Created
January 6, 2020 22:14
-
-
Save chaimleib/354573c40f6c4ab8e3bfcb52fca748e8 to your computer and use it in GitHub Desktop.
Haikunator CLI (node)
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 | |
/* | |
Requirements: | |
node v7.6.0 | |
node-getopt | |
haikunator | |
*/ | |
const path = require('path'); | |
const Haikunator = require('haikunator'); | |
// command-line interface | |
if (require.main === module) { | |
const Getopt = require('node-getopt'); | |
function main() { | |
try { | |
const haikunator = new Haikunator() | |
const gotten = getopts(); | |
const cfg = buildConfig(gotten); | |
const nameComponents = [...cfg.argv, haikunator.haikunate(cfg)]; | |
const name = nameComponents | |
.filter(s => s !== "") | |
.join("-"); | |
console.log(name); | |
} catch (err) { | |
console.error(err); | |
process.exit(1); | |
} | |
} | |
function getopts() { | |
let optConfig = new Getopt([ | |
['d', 'delimiter=ARG', 'word separator. Default: "-"'], | |
['l', 'token-length=ARG', 'how many random chars to suffix. Default: 4'], | |
['c', 'token-chars=ARG', 'set of characters for the random suffix. Default: "0123456789"'], | |
['x', 'token-hex', 'same as token-chars="0123456789abcdef". If true, chars in token-chars are ignored. Default: false'], | |
['h', 'help', 'display this help'], | |
]).bindHelp(); | |
optConfig.setHelp( | |
"Usage: node "+path.basename(__filename)+" [OPTION]\n"+ | |
"Generate Heroku-like random names.\n"+ | |
"\n"+ | |
"[[OPTIONS]]\n" | |
); | |
const gotten = optConfig.parseSystem(); | |
const opts = gotten.options; | |
if (opts.help) { | |
optConfig.showHelp(); | |
process.exit(0); | |
} | |
return gotten; | |
} | |
function buildConfig(gotten) { | |
const argv = gotten.argv; | |
const opts = gotten.options; | |
const cfg = {}; | |
for (let key of Object.keys(opts)) { | |
let newKey = key; | |
if (key.includes('-')) { | |
let keyParts = key.split('-'); | |
let capitalized = keyParts | |
.slice(1) | |
.map(part => { | |
if (part.length == 0) return ''; | |
return part.charAt(0).toUpperCase() + part.slice(1); | |
}) | |
.join(''); | |
newKey = keyParts[0] + capitalized; | |
} | |
cfg[newKey] = opts[key]; | |
} | |
cfg.argv = gotten.argv; | |
return cfg; | |
} | |
main(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment