Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WIP (well, abandoned)
// @flow strict
function terminate(help, error) {
console.error('%s\n\n%s', help, error);
process.exit(1);
}
/**
* Goal of this parser is to create less awkward tool for working with command line. You just
* have to write a help screen and the rest is responsibility of this parser.
*
* It is just an experiment.
*/
export default function cmdParser(rawHelp: string, args?: $ReadOnlyArray<string>) {
const help = rawHelp.trim();
const options = new Map<string, null | string>();
// $FlowPullRequest: https://github.com/facebook/flow/pull/7812
const relevantLines = help.matchAll(/^[ \t]+--?\w[\w-]*.*$/gm);
for (const line of relevantLines) {
const matchedOptions = line[0].matchAll(/(?<optionName>--?\w[\w-]*)[ ,|]*/g);
for (const matchedOption of matchedOptions) {
options.set(matchedOption.groups.optionName, null);
}
}
const argv = args ?? process.argv.splice(2);
for (const arg of argv) {
if (options.has(arg) === false) {
terminate(help, `Unexpected parameter ${arg}`);
}
}
return options;
}
// @flow strict
import cmdParser from '../cmdParser';
it('parses provided help correctly', () => {
expect(
cmdParser(
`
Usage:
node some-command [options]
Options:
-a
-b description
--param
--param description
--param-with-dash
--param-with-dash description
-x --xxx
-y | --yyy
-z, --zzz
`,
[], // overwrite process.argv
),
).toMatchInlineSnapshot(`
Map {
"-a" => null,
"-b" => null,
"--param" => null,
"--param-with-dash" => null,
"-x" => null,
"--xxx" => null,
"-y" => null,
"--yyy" => null,
"-z" => null,
"--zzz" => null,
}
`);
});
it('throws when unknown arguments are used', () => {
expect(() => cmdParser('-p', ['--unknown'])).toThrowErrorMatchingInlineSnapshot(
`"Unexpected parameter --unknown"`,
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.