CLI Args Parser With Subcommands
Parse CLI arguments with subcommands flags and positional args using a declarative spec for consistent tooling.
Code
export function cliParser(spec){function parse(argv){const[subcommand,...rest]=argv;if(!spec[subcommand])throw new Error('unknown subcommand: '+subcommand);const cmdSpec=spec[subcommand];const args={};const positional=[];let i=0;while(i<rest.length){const arg=rest[i];if(arg.startsWith('--')){const key=arg.slice(2);const val=rest[i+1]?.startsWith('--')?true:rest[++i];args[key]=cmdSpec.flags?.[key]?.type==='number'?Number(val):val;}else positional.push(arg);i++;}return{subcommand,args,positional};}return{parse};}Report a problem with this exampleOpens a pre-filled issue on GitHub.