arg Simple argument parsing开源项目

我要开发同款
匿名用户2021年11月17日
64阅读
开发技术JavaScript
所属分类应用工具、终端/远程登录
授权协议MIT License

作品详情

Arg

argisanunopinionated,no-frillsCLIargumentparser.

InstallationnpminstallargUsage

arg()takeseither1or2arguments:

Commandlinespecificationobject(seebelow)Parseoptions(Optional,defaultsto{permissive:false,argv:process.argv.slice(2),stopAtPositional:false})

Itreturnsanobjectwithanyvaluespresentonthecommand-line(missingoptionsarethusmissingfromtheresultingobject).Argperformsnovalidation/requirementchecking-weleavethatuptotheapplication.

Allparametersthataren'tconsumedbyoptions(commonlyreferredtoas"extra"parameters)areaddedtoresult._,whichisalwaysanarray(evenifnoextraparametersarepassed,inwhichcaseanemptyarrayisreturned).

constarg=require('arg');//`options`isanoptionalparameterconstargs=arg(spec,(options={permissive:false,argv:process.argv.slice(2)}));

Forexample:

$node./hello.js--verbose-vvv--port=1234-n'Myname'foobar--tagqux--tag=qix----foobar//hello.jsconstarg=require('arg');constargs=arg({//Types'--help':Boolean,'--version':Boolean,'--verbose':arg.COUNT,//Countsthenumberoftimes--verboseispassed'--port':Number,//--port<number>or--port=<number>'--name':String,//--name<string>or--name=<string>'--tag':[String],//--tag<string>or--tag=<string>//Aliases'-v':'--verbose','-n':'--name',//-n<string>;resultisstoredin--name'--label':'--name'//--label<string>or--label=<string>;//resultisstoredin--name});console.log(args);/*{_:["foo","bar","--foobar"],'--port':1234,'--verbose':4,'--name':"Myname",'--tag':["qux","qix"]}*/

Thevaluesforeachkey=>valuepairiseitheratype(functionor[function])orastring(indicatinganalias).

Inthecaseofafunction,thestringvalueoftheargument'svalueispassedtoit,andthereturnvalueisusedastheultimatevalue.

Inthecaseofanarray,theonlyelementmustbeatypefunction.Arraytypesindicatethattheargumentmaybepassedmultipletimes,andassuchtheresultingvalueinthereturnedobjectisanarraywithallofthevaluesthatwerepassedusingthespecifiedflag.

Inthecaseofastring,analiasisestablished.Ifaflagispassedthatmatchesthekey,thenthevalueissubstitutedinitsplace.

Typefunctionsarepassedthreearguments:

Theparametervalue(alwaysastring)Theparametername(e.g.--label)Thepreviousvalueforthedestination(usefulforreduce-likeoperationsorforsupporting-vmultipletimes,etc.)

Thismeansthebuilt-inString,Number,andBooleantypeconstructors"justwork"astypefunctions.

NotethatBooleanand[Boolean]havespecialtreatment-anoptionargumentisnotconsumedorpassed,butinsteadtrueisreturned.Theseoptionsarecalled"flags".

Forcustomhandlersthatwishtobehaveasflags,youmaypassthefunctionthrougharg.flag():

constarg=require('arg');constargv=['--foo','bar','-ff','baz','--foo','--foo','qux','-fff','qix'];functionmyHandler(value,argName,previousValue){/*`value`isalways`true`*/return'na'+(previousValue||'batman!');}constargs=arg({'--foo':arg.flag(myHandler),'-f':'--foo'},{argv});console.log(args);/*{_:['bar','baz','qux','qix'],'--foo':'nanananananananabatman!'}*/

Aswell,argsuppliesahelperargumenthandlercalledarg.COUNT,whichequivalenttoa[Boolean]argument's.lengthproperty-effectivelycountingthenumberoftimesthebooleanflag,denotedbythekey,ispassedonthecommandline..Forexample,thisishowyoucouldimplementssh'smultiplelevelsofverbosity(-vvvvbeingthemostverbose).

constarg=require('arg');constargv=['-AAAA','-BBBB'];constargs=arg({'-A':arg.COUNT,'-B':[Boolean]},{argv});console.log(args);/*{_:[],'-A':4,'-B':[true,true,true,true]}*/Options

Ifasecondparameterisspecifiedandisanobject,itspecifiesparsingoptionstomodifythebehaviorofarg().

argv

Ifyouhavealreadyslicedorgeneratedanumberofrawargumentstobeparsed(asopposedtolettingargslicethemfromprocess.argv)youmayspecifythemintheargvoption.

Forexample:

constargs=arg({'--foo':String},{argv:['hello','--foo','world']});

resultsin:

constargs={_:['hello'],'--foo':'world'};permissive

Whenpermissivesettotrue,argwillpushanyunknownargumentsontothe"extra"argumentarray(result._)insteadofthrowinganerroraboutanunknownflag.

Forexample:

constarg=require('arg');constargv=['--foo','hello','--qux','qix','--bar','12345','helloagain'];constargs=arg({'--foo':String,'--bar':Number},{argv,permissive:true});

resultsin:

constargs={_:['--qux','qix','helloagain'],'--foo':'hello','--bar':12345};stopAtPositional

WhenstopAtPositionalissettotrue,argwillhaltparsingatthefirstpositionalargument.

Forexample:

constarg=require('arg');constargv=['--foo','hello','--bar'];constargs=arg({'--foo':Boolean,'--bar':Boolean},{argv,stopAtPositional:true});

resultsin:

constargs={_:['hello','--bar'],'--foo':true};Errors

Someerrorsthatargthrowsprovidea.codepropertyinordertoaidinrecoveringfromusererror,ortodifferentiatebetweenusererroranddevelopererror(bug).

ARG_UNKNOWN_OPTION

Ifanunknownoption(notdefinedinthespecobject)ispassed,anerrorwithcodeARG_UNKNOWN_OPTIONwillbethrown:

//cli.jstry{require('arg')({'--hi':String});}catch(err){if(err.code==='ARG_UNKNOWN_OPTION'){console.log(err.message);}else{throwerr;}}nodecli.js--extraneoustrueUnknownorunexpectedoption:--extraneousFAQ

Afewquestionsandanswersthathavebeenaskedbefore:

HowdoIrequireanargumentwitharg?

Dotheassertionyourself,suchas:

constargs=arg({'--name':String});if(!args['--name'])thrownewError('missingrequiredargument:--name');License

ReleasedundertheMITLicense.

声明:本文仅代表作者观点,不代表本站立场。如果侵犯到您的合法权益,请联系我们删除侵权资源!如果遇到资源链接失效,请您通过评论或工单的方式通知管理员。未经允许,不得转载,本站所有资源文章禁止商业使用运营!
下载安装【程序员客栈】APP
实时对接需求、及时收发消息、丰富的开放项目需求、随时随地查看项目状态

评论