@protostr/libcli
v0.1.0
Published
Command-line argument parsing
Downloads
13
Readme
@protostr/libcli
Command-line argument parsing
Examples
import { processArgv, stringOpt, booleanOpt } from "@protostr/libcli";
let gPathInstall = null;
let gIsProduction = true;
let gIsWatch = false;
const argHandlers = [
stringOpt('install', 'Install built files into this directory', p => {
gPathInstall = path.resolve(p);
}),
booleanOpt('dev', 'Disables minification and generates sourcemaps', p => { gIsProduction = !p; }),
booleanOpt('watch', 'Watch mode', p => { gIsWatch = p; }),
];
const result = processArgv(argHandlers);
stringOpt
, booleanOpt
and numberOpt
are shorthand for frequent kinds of parameters; you can write your own handlers if you need any custom functionality:
import { processArgv, checkOrPrintHelp, isMissingParameter } from "@protostr/libcli";
let gPathInstall = null;
let gIsProduction = true;
let gIsWatch = false;
const argHandlers = [
(arg, arrArgs, idxArg) => {
if (!checkOrPrintHelp(arg, '--install', 'path', 'Install built files into this directory')) {
return 'next';
}
if (isMissingParameter(idxArg, arrArgs)) return new Error('--install requires a parameter');
gPathInstall = path.resolve(__dirname, arrArgs[idxArg + 1]);
return idxArg + 2;
},
(arg) => {
if (!checkOrPrintHelp(arg, '--dev', 'Disables minification and generates sourcemaps')) {
return 'next';
}
gIsProduction = false;
},
(arg) => {
if (!checkOrPrintHelp(arg, '--watch', 'Watch mode')) {
return 'next';
}
gIsWatch = true;
},
];
const result = processArgv(argHandlers);
processArgv
takes the arguments from process.argv.slice(2)
which is a Node-specific thing.
You can use any argument vector with preprocessArgs
and processArgs
:
const res = processArgs(preprocessArgs(myArgv), argHandlers);
If you don't like the default argument format (--flag
and --key=value
) then you can write your own preprocessArgs
-like function.
It only has to return an array of [string] | [string, string]
values.