Last active
May 8, 2023 14:52
-
-
Save udovichenko/ea7d1d2895bd7e2dfecf8f0217004d4f to your computer and use it in GitHub Desktop.
Script for sorting ~/.ssh/config by host alphabetically
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const fs = require('fs') | |
const os = require('os') | |
const readline = require('readline') | |
const home = `${os.homedir()}` | |
const configFile = `${home}/.ssh/config` | |
const lines = fs.readFileSync(configFile, 'utf-8').split('\n') | |
const blocks = [] | |
let block = '' | |
for (const line of lines) { | |
if (line.startsWith('Host ')) { | |
if (block) { | |
blocks.push(block) | |
block = '' | |
} | |
} | |
block += `${line}\n` | |
} | |
if (block) { | |
blocks.push(block) | |
} | |
blocks.sort((a, b) => { | |
const aHost = a.match(/^Host (.*)/m)[1] | |
const bHost = b.match(/^Host (.*)/m)[1] | |
return aHost.localeCompare(bHost) | |
}) | |
const sortedConfig = blocks.join('') | |
console.log(sortedConfig) | |
const rl = readline.createInterface({ | |
input: process.stdin, | |
output: process.stdout | |
}) | |
rl.question('Are you sure you want to write this output to ~/.ssh/config? (y/n): ', (answer) => { | |
if (answer.toLowerCase() === 'y' || answer.toLowerCase() === 'yes') { | |
fs.writeFileSync(configFile, sortedConfig) | |
console.log('Config file written to ~/.ssh/config') | |
fs.copyFileSync(configFile, `${configFile}.bak`) | |
console.log('Backup file written to ~/.ssh/config.bak') | |
} else { | |
console.log('Cancelled by user') | |
} | |
rl.close() | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment