Create a simpler argument parse -- no validation, just returns a more usable object than the default argv

This commit is contained in:
n loewen 2023-08-29 22:23:36 -04:00
parent 6ca7bb2a71
commit 32d3d87d71
2 changed files with 44 additions and 0 deletions

41
arg-parser-simpler.js Normal file
View File

@ -0,0 +1,41 @@
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 output = {};
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 grouped short flags (eg `ps -aux`)
// (Let's not let grouped ones have values) //... FIXME, maybe?
if (arg.startsWith('-')) {
if (arg.length < 2) {
// It's not grouped; just remove the '-' and treat it like the rest, later
arg = arg.substring(1);
} else {
arg = arg.substring(1);
let ungrouped = arg.split('');
ungrouped.forEach(a => output[a] = true);
return;
}
}
let split = arg.split('=')
if (split.length > 2) { throw new Error(`Too many '=' in argument ${arg}`); }
if (split.length === 2) {
let [key, value] = split;
output[key] = value;
return;
}
output[arg] = true;
});
return output;
}

3
tests-simpler.js Normal file
View File

@ -0,0 +1,3 @@
const args = require('./arg-parser-simpler.js')(process.argv);
console.log(args);