Created
October 24, 2019 00:59
-
-
Save mrtnzlml/9a7e70460947f2f150f5b9307e242594 to your computer and use it in GitHub Desktop.
WIP (well, abandoned)
This file contains 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
// @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; | |
} |
This file contains 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
// @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