64 lines
1.7 KiB
JavaScript
64 lines
1.7 KiB
JavaScript
module.exports = parse;
|
|
|
|
// Inspired a bit by
|
|
// https://github.com/eveningkid/args-parser/blob/master/parse.js
|
|
|
|
function parse(argv) {
|
|
argv = process.argv.slice(2);
|
|
let finalOutput = {};
|
|
|
|
argv.forEach((arg) => {
|
|
// We'll treat `--long` flags and flags without dash prefixes the same,
|
|
// so just discard double-dash prefixes
|
|
if (arg.startsWith('--')) { arg = arg.substring(2); }
|
|
|
|
// Handle short flags, including
|
|
// un-grouping grouped ones (eg `ps -aux`)
|
|
if (arg.startsWith('-')) {
|
|
console.log('startswith -; length:', arg.length);
|
|
console.log('lose first char:', arg.substring(1));
|
|
console.log('split keys vals:', arg.split('='));
|
|
|
|
// If there's a key=value assignment,
|
|
// don't treat it like a group
|
|
if (arg.split('=').length > 1) {
|
|
let [key, value] = processArg(arg);
|
|
finalOutput[key] = value;
|
|
return;
|
|
}
|
|
|
|
if (arg.length < 2) {
|
|
// It's not grouped; just remove the '-' and treat it like the rest, later
|
|
arg = arg.substring(1);
|
|
let [key, value] = processArg(arg);
|
|
finalOutput[key] = value;
|
|
return;
|
|
} else {
|
|
arg = arg.substring(1);
|
|
let ungrouped = arg.split('');
|
|
ungrouped.forEach(a => output[a] = true);
|
|
console.log('ungr', ungrouped);
|
|
return;
|
|
}
|
|
}
|
|
|
|
console.log('out:', output);
|
|
|
|
|
|
output[arg] = true;
|
|
});
|
|
|
|
return finalOutput;
|
|
}
|
|
|
|
function processArg(a) {
|
|
let out = {};
|
|
let split = a.split('=')
|
|
if (split.length > 2) { throw new Error(`Too many '=' in argument ${a}`); }
|
|
let [key, value] = split;
|
|
if (split.length === 2) {
|
|
return [key, value];
|
|
} else {
|
|
return [key, true];
|
|
}
|
|
} |