CommandLine.java 787 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602
  1. /*
  2. Copyright 2017 Remko Popma
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package picocli;
  14. import java.io.*;
  15. import java.lang.annotation.Annotation;
  16. import java.lang.annotation.ElementType;
  17. import java.lang.annotation.Retention;
  18. import java.lang.annotation.RetentionPolicy;
  19. import java.lang.annotation.Target;
  20. import java.lang.reflect.*;
  21. import java.math.BigDecimal;
  22. import java.math.BigInteger;
  23. import java.net.InetAddress;
  24. import java.net.MalformedURLException;
  25. import java.net.NetworkInterface;
  26. import java.net.URI;
  27. import java.net.URISyntaxException;
  28. import java.net.URL;
  29. import java.nio.ByteOrder;
  30. import java.nio.charset.Charset;
  31. import java.text.BreakIterator;
  32. import java.text.ParseException;
  33. import java.text.SimpleDateFormat;
  34. import java.util.*;
  35. import java.util.concurrent.Callable;
  36. import java.util.regex.Pattern;
  37. import picocli.CommandLine.Help.Ansi.IStyle;
  38. import picocli.CommandLine.Help.Ansi.Style;
  39. import picocli.CommandLine.Help.Ansi.Text;
  40. import picocli.CommandLine.Model.*;
  41. import picocli.CommandLine.ParseResult.MatchedGroup;
  42. import static java.util.Locale.ENGLISH;
  43. import static picocli.CommandLine.Help.Column.Overflow.SPAN;
  44. import static picocli.CommandLine.Help.Column.Overflow.TRUNCATE;
  45. import static picocli.CommandLine.Help.Column.Overflow.WRAP;
  46. /**
  47. * <p>
  48. * CommandLine interpreter that uses reflection to initialize an annotated domain object with values obtained from the
  49. * command line arguments.
  50. * </p><h2>Example</h2>
  51. * <pre>import static picocli.CommandLine.*;
  52. *
  53. * &#064;Command(mixinStandardHelpOptions = true, version = "v3.0.0",
  54. * header = "Encrypt FILE(s), or standard input, to standard output or to the output file.")
  55. * public class Encrypt {
  56. *
  57. * &#064;Parameters(type = File.class, description = "Any number of input files")
  58. * private List&lt;File&gt; files = new ArrayList&lt;File&gt;();
  59. *
  60. * &#064;Option(names = { "-o", "--out" }, description = "Output file (default: print to console)")
  61. * private File outputFile;
  62. *
  63. * &#064;Option(names = { "-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.")
  64. * private boolean[] verbose;
  65. * }
  66. * </pre>
  67. * <p>
  68. * Use {@code CommandLine} to initialize a domain object as follows:
  69. * </p><pre>
  70. * public static void main(String... args) {
  71. * Encrypt encrypt = new Encrypt();
  72. * try {
  73. * ParseResult parseResult = new CommandLine(encrypt).parseArgs(args);
  74. * if (!CommandLine.printHelpIfRequested(parseResult)) {
  75. * runProgram(encrypt);
  76. * }
  77. * } catch (ParameterException ex) { // command line arguments could not be parsed
  78. * System.err.println(ex.getMessage());
  79. * ex.getCommandLine().usage(System.err);
  80. * }
  81. * }
  82. * </pre><p>
  83. * Invoke the above program with some command line arguments. The below are all equivalent:
  84. * </p>
  85. * <pre>
  86. * --verbose --out=outfile in1 in2
  87. * --verbose --out outfile in1 in2
  88. * -v --out=outfile in1 in2
  89. * -v -o outfile in1 in2
  90. * -v -o=outfile in1 in2
  91. * -vo outfile in1 in2
  92. * -vo=outfile in1 in2
  93. * -v -ooutfile in1 in2
  94. * -vooutfile in1 in2
  95. * </pre>
  96. * <p>
  97. * Another example that implements {@code Callable} and uses the {@link #call(Callable, String...) CommandLine.call} convenience API to run in a single line of code:
  98. * </p>
  99. * <pre>
  100. * &#064;Command(description = "Prints the checksum (MD5 by default) of a file to STDOUT.",
  101. * name = "checksum", mixinStandardHelpOptions = true, version = "checksum 3.0")
  102. * class CheckSum implements Callable&lt;Void&gt; {
  103. *
  104. * &#064;Parameters(index = "0", description = "The file whose checksum to calculate.")
  105. * private File file;
  106. *
  107. * &#064;Option(names = {"-a", "--algorithm"}, description = "MD5, SHA-1, SHA-256, ...")
  108. * private String algorithm = "MD5";
  109. *
  110. * public static void main(String[] args) throws Exception {
  111. * // CheckSum implements Callable, so parsing, error handling and handling user
  112. * // requests for usage help or version help can be done with one line of code.
  113. * CommandLine.call(new CheckSum(), args);
  114. * }
  115. *
  116. * &#064;Override
  117. * public Void call() throws Exception {
  118. * // your business logic goes here...
  119. * byte[] fileContents = Files.readAllBytes(file.toPath());
  120. * byte[] digest = MessageDigest.getInstance(algorithm).digest(fileContents);
  121. * System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(digest));
  122. * return null;
  123. * }
  124. * }
  125. * </pre>
  126. * <h2>Classes and Interfaces for Defining a CommandSpec Model</h2>
  127. * <p>
  128. * <img src="doc-files/class-diagram-definition.png" alt="Classes and Interfaces for Defining a CommandSpec Model">
  129. * </p>
  130. * <h2>Classes Related to Parsing Command Line Arguments</h2>
  131. * <p>
  132. * <img src="doc-files/class-diagram-parsing.png" alt="Classes Related to Parsing Command Line Arguments">
  133. * </p>
  134. */
  135. public class CommandLine {
  136. /** This is picocli version {@value}. */
  137. public static final String VERSION = "4.0.0-alpha-2-SNAPSHOT";
  138. private final Tracer tracer = new Tracer();
  139. private final CommandSpec commandSpec;
  140. private final Interpreter interpreter;
  141. private final IFactory factory;
  142. /**
  143. * Constructs a new {@code CommandLine} interpreter with the specified object (which may be an annotated user object or a {@link CommandSpec CommandSpec}) and a default subcommand factory.
  144. * <p>The specified object may be a {@link CommandSpec CommandSpec} object, or it may be a {@code @Command}-annotated
  145. * user object with {@code @Option} and {@code @Parameters}-annotated fields, in which case picocli automatically
  146. * constructs a {@code CommandSpec} from this user object.
  147. * </p><p>
  148. * When the {@link #parse(String...)} method is called, the {@link CommandSpec CommandSpec} object will be
  149. * initialized based on command line arguments. If the commandSpec is created from an annotated user object, this
  150. * user object will be initialized based on the command line arguments.</p>
  151. * @param command an annotated user object or a {@code CommandSpec} object to initialize from the command line arguments
  152. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  153. */
  154. public CommandLine(Object command) {
  155. this(command, new DefaultFactory());
  156. }
  157. /**
  158. * Constructs a new {@code CommandLine} interpreter with the specified object (which may be an annotated user object or a {@link CommandSpec CommandSpec}) and object factory.
  159. * <p>The specified object may be a {@link CommandSpec CommandSpec} object, or it may be a {@code @Command}-annotated
  160. * user object with {@code @Option} and {@code @Parameters}-annotated fields, in which case picocli automatically
  161. * constructs a {@code CommandSpec} from this user object.
  162. * </p><p> If the specified command object is an interface {@code Class} with {@code @Option} and {@code @Parameters}-annotated methods,
  163. * picocli creates a {@link java.lang.reflect.Proxy Proxy} whose methods return the matched command line values.
  164. * If the specified command object is a concrete {@code Class}, picocli delegates to the {@linkplain IFactory factory} to get an instance.
  165. * </p><p>
  166. * When the {@link #parse(String...)} method is called, the {@link CommandSpec CommandSpec} object will be
  167. * initialized based on command line arguments. If the commandSpec is created from an annotated user object, this
  168. * user object will be initialized based on the command line arguments.</p>
  169. * @param command an annotated user object or a {@code CommandSpec} object to initialize from the command line arguments
  170. * @param factory the factory used to create instances of {@linkplain Command#subcommands() subcommands}, {@linkplain Option#converter() converters}, etc., that are registered declaratively with annotation attributes
  171. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  172. * @since 2.2 */
  173. public CommandLine(Object command, IFactory factory) {
  174. this.factory = Assert.notNull(factory, "factory");
  175. interpreter = new Interpreter();
  176. commandSpec = CommandSpec.forAnnotatedObject(command, factory);
  177. commandSpec.commandLine(this);
  178. commandSpec.validate();
  179. if (commandSpec.unmatchedArgsBindings().size() > 0) { setUnmatchedArgumentsAllowed(true); }
  180. }
  181. /**
  182. * Returns the {@code CommandSpec} model that this {@code CommandLine} was constructed with.
  183. * @return the {@code CommandSpec} model
  184. * @since 3.0 */
  185. public CommandSpec getCommandSpec() { return commandSpec; }
  186. /**
  187. * Adds the options and positional parameters in the specified mixin to this command.
  188. * <p>The specified object may be a {@link CommandSpec CommandSpec} object, or it may be a user object with
  189. * {@code @Option} and {@code @Parameters}-annotated fields, in which case picocli automatically
  190. * constructs a {@code CommandSpec} from this user object.
  191. * </p>
  192. * @param name the name by which the mixin object may later be retrieved
  193. * @param mixin an annotated user object or a {@link CommandSpec CommandSpec} object whose options and positional parameters to add to this command
  194. * @return this CommandLine object, to allow method chaining
  195. * @since 3.0 */
  196. public CommandLine addMixin(String name, Object mixin) {
  197. getCommandSpec().addMixin(name, CommandSpec.forAnnotatedObject(mixin, factory));
  198. return this;
  199. }
  200. /**
  201. * Returns a map of user objects whose options and positional parameters were added to ("mixed in" with) this command.
  202. * @return a new Map containing the user objects mixed in with this command. If {@code CommandSpec} objects without
  203. * user objects were programmatically added, use the {@link CommandSpec#mixins() underlying model} directly.
  204. * @since 3.0 */
  205. public Map<String, Object> getMixins() {
  206. Map<String, CommandSpec> mixins = getCommandSpec().mixins();
  207. Map<String, Object> result = new LinkedHashMap<String, Object>();
  208. for (String name : mixins.keySet()) { result.put(name, mixins.get(name).userObject); }
  209. return result;
  210. }
  211. /** Registers a subcommand with the specified name. For example:
  212. * <pre>
  213. * CommandLine commandLine = new CommandLine(new Git())
  214. * .addSubcommand("status", new GitStatus())
  215. * .addSubcommand("commit", new GitCommit();
  216. * .addSubcommand("add", new GitAdd())
  217. * .addSubcommand("branch", new GitBranch())
  218. * .addSubcommand("checkout", new GitCheckout())
  219. * //...
  220. * ;
  221. * </pre>
  222. *
  223. * <p>The specified object can be an annotated object or a
  224. * {@code CommandLine} instance with its own nested subcommands. For example:</p>
  225. * <pre>
  226. * CommandLine commandLine = new CommandLine(new MainCommand())
  227. * .addSubcommand("cmd1", new ChildCommand1()) // subcommand
  228. * .addSubcommand("cmd2", new ChildCommand2())
  229. * .addSubcommand("cmd3", new CommandLine(new ChildCommand3()) // subcommand with nested sub-subcommands
  230. * .addSubcommand("cmd3sub1", new GrandChild3Command1())
  231. * .addSubcommand("cmd3sub2", new GrandChild3Command2())
  232. * .addSubcommand("cmd3sub3", new CommandLine(new GrandChild3Command3()) // deeper nesting
  233. * .addSubcommand("cmd3sub3sub1", new GreatGrandChild3Command3_1())
  234. * .addSubcommand("cmd3sub3sub2", new GreatGrandChild3Command3_2())
  235. * )
  236. * );
  237. * </pre>
  238. * <p>The default type converters are available on all subcommands and nested sub-subcommands, but custom type
  239. * converters are registered only with the subcommand hierarchy as it existed when the custom type was registered.
  240. * To ensure a custom type converter is available to all subcommands, register the type converter last, after
  241. * adding subcommands.</p>
  242. * <p>See also the {@link Command#subcommands()} annotation to register subcommands declaratively.</p>
  243. *
  244. * @param name the string to recognize on the command line as a subcommand
  245. * @param command the object to initialize with command line arguments following the subcommand name.
  246. * This may be a {@code CommandLine} instance with its own (nested) subcommands
  247. * @return this CommandLine object, to allow method chaining
  248. * @see #registerConverter(Class, ITypeConverter)
  249. * @since 0.9.7
  250. * @see Command#subcommands()
  251. */
  252. public CommandLine addSubcommand(String name, Object command) {
  253. return addSubcommand(name, command, new String[0]);
  254. }
  255. /** Registers a subcommand with the specified name and all specified aliases. See also {@link #addSubcommand(String, Object)}.
  256. *
  257. *
  258. * @param name the string to recognize on the command line as a subcommand
  259. * @param command the object to initialize with command line arguments following the subcommand name.
  260. * This may be a {@code CommandLine} instance with its own (nested) subcommands
  261. * @param aliases zero or more alias names that are also recognized on the command line as this subcommand
  262. * @return this CommandLine object, to allow method chaining
  263. * @since 3.1
  264. * @see #addSubcommand(String, Object)
  265. */
  266. public CommandLine addSubcommand(String name, Object command, String... aliases) {
  267. CommandLine subcommandLine = toCommandLine(command, factory);
  268. subcommandLine.getCommandSpec().aliases.addAll(Arrays.asList(aliases));
  269. getCommandSpec().addSubcommand(name, subcommandLine);
  270. CommandLine.Model.CommandReflection.initParentCommand(subcommandLine.getCommandSpec().userObject(), getCommandSpec().userObject());
  271. return this;
  272. }
  273. /** Returns a map with the subcommands {@linkplain #addSubcommand(String, Object) registered} on this instance.
  274. * @return a map with the registered subcommands
  275. * @since 0.9.7
  276. */
  277. public Map<String, CommandLine> getSubcommands() {
  278. return new LinkedHashMap<String, CommandLine>(getCommandSpec().subcommands());
  279. }
  280. /**
  281. * Returns the command that this is a subcommand of, or {@code null} if this is a top-level command.
  282. * @return the command that this is a subcommand of, or {@code null} if this is a top-level command
  283. * @see #addSubcommand(String, Object)
  284. * @see Command#subcommands()
  285. * @since 0.9.8
  286. */
  287. public CommandLine getParent() {
  288. CommandSpec parent = getCommandSpec().parent();
  289. return parent == null ? null : parent.commandLine();
  290. }
  291. /** Returns the annotated user object that this {@code CommandLine} instance was constructed with.
  292. * @param <T> the type of the variable that the return value is being assigned to
  293. * @return the annotated object that this {@code CommandLine} instance was constructed with
  294. * @since 0.9.7
  295. */
  296. @SuppressWarnings("unchecked")
  297. public <T> T getCommand() {
  298. return (T) getCommandSpec().userObject();
  299. }
  300. /** Returns {@code true} if an option annotated with {@link Option#usageHelp()} was specified on the command line.
  301. * @return whether the parser encountered an option annotated with {@link Option#usageHelp()}.
  302. * @since 0.9.8 */
  303. public boolean isUsageHelpRequested() { return interpreter.parseResultBuilder != null && interpreter.parseResultBuilder.usageHelpRequested; }
  304. /** Returns {@code true} if an option annotated with {@link Option#versionHelp()} was specified on the command line.
  305. * @return whether the parser encountered an option annotated with {@link Option#versionHelp()}.
  306. * @since 0.9.8 */
  307. public boolean isVersionHelpRequested() { return interpreter.parseResultBuilder != null && interpreter.parseResultBuilder.versionHelpRequested; }
  308. /** Returns the {@code IHelpFactory} that is used to construct the usage help message.
  309. * @see #setHelpFactory(IHelpFactory)
  310. * @since 3.9
  311. */
  312. public IHelpFactory getHelpFactory() {
  313. return getCommandSpec().usageMessage().helpFactory();
  314. }
  315. /** Sets a new {@code IHelpFactory} to customize the usage help message.
  316. * @param helpFactory the new help factory. Must be non-{@code null}.
  317. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  318. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  319. * later will have the default setting. To ensure a setting is applied to all
  320. * subcommands, call the setter last, after adding subcommands.</p>
  321. * @return this {@code CommandLine} object, to allow method chaining
  322. * @since 3.9
  323. */
  324. public CommandLine setHelpFactory(IHelpFactory helpFactory) {
  325. getCommandSpec().usageMessage().helpFactory(helpFactory);
  326. for (CommandLine command : getCommandSpec().subcommands().values()) {
  327. command.setHelpFactory(helpFactory);
  328. }
  329. return this;
  330. }
  331. /**
  332. * Returns the section keys in the order that the usage help message should render the sections.
  333. * This ordering may be modified with {@link #setHelpSectionKeys(List) setSectionKeys}. The default keys are (in order):
  334. * <ol>
  335. * <li>{@link UsageMessageSpec#SECTION_KEY_HEADER_HEADING SECTION_KEY_HEADER_HEADING}</li>
  336. * <li>{@link UsageMessageSpec#SECTION_KEY_HEADER SECTION_KEY_HEADER}</li>
  337. * <li>{@link UsageMessageSpec#SECTION_KEY_SYNOPSIS_HEADING SECTION_KEY_SYNOPSIS_HEADING}</li>
  338. * <li>{@link UsageMessageSpec#SECTION_KEY_SYNOPSIS SECTION_KEY_SYNOPSIS}</li>
  339. * <li>{@link UsageMessageSpec#SECTION_KEY_DESCRIPTION_HEADING SECTION_KEY_DESCRIPTION_HEADING}</li>
  340. * <li>{@link UsageMessageSpec#SECTION_KEY_DESCRIPTION SECTION_KEY_DESCRIPTION}</li>
  341. * <li>{@link UsageMessageSpec#SECTION_KEY_PARAMETER_LIST_HEADING SECTION_KEY_PARAMETER_LIST_HEADING}</li>
  342. * <li>{@link UsageMessageSpec#SECTION_KEY_PARAMETER_LIST SECTION_KEY_PARAMETER_LIST}</li>
  343. * <li>{@link UsageMessageSpec#SECTION_KEY_OPTION_LIST_HEADING SECTION_KEY_OPTION_LIST_HEADING}</li>
  344. * <li>{@link UsageMessageSpec#SECTION_KEY_OPTION_LIST SECTION_KEY_OPTION_LIST}</li>
  345. * <li>{@link UsageMessageSpec#SECTION_KEY_COMMAND_LIST_HEADING SECTION_KEY_COMMAND_LIST_HEADING}</li>
  346. * <li>{@link UsageMessageSpec#SECTION_KEY_COMMAND_LIST SECTION_KEY_COMMAND_LIST}</li>
  347. * <li>{@link UsageMessageSpec#SECTION_KEY_FOOTER_HEADING SECTION_KEY_FOOTER_HEADING}</li>
  348. * <li>{@link UsageMessageSpec#SECTION_KEY_FOOTER SECTION_KEY_FOOTER}</li>
  349. * </ol>
  350. * @since 3.9
  351. */
  352. public List<String> getHelpSectionKeys() { return getCommandSpec().usageMessage().sectionKeys(); }
  353. /**
  354. * Sets the section keys in the order that the usage help message should render the sections.
  355. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  356. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  357. * later will have the default setting. To ensure a setting is applied to all
  358. * subcommands, call the setter last, after adding subcommands.</p>
  359. * <p>Use {@link UsageMessageSpec#sectionKeys(List)} to customize a command without affecting its subcommands.</p>
  360. * @see #getHelpSectionKeys
  361. * @since 3.9
  362. */
  363. public CommandLine setHelpSectionKeys(List<String> keys) {
  364. getCommandSpec().usageMessage().sectionKeys(keys);
  365. for (CommandLine command : getCommandSpec().subcommands().values()) {
  366. command.setHelpSectionKeys(keys);
  367. }
  368. return this;
  369. }
  370. /**
  371. * Returns the map of section keys and renderers used to construct the usage help message.
  372. * The usage help message can be customized by adding, replacing and removing section renderers from this map.
  373. * Sections can be reordered with {@link #setHelpSectionKeys(List) setSectionKeys}.
  374. * Sections that are either not in this map or not in the list returned by {@link #getHelpSectionKeys() getSectionKeys} are omitted.
  375. * <p>
  376. * NOTE: By modifying the returned {@code Map}, only the usage help message <em>of this command</em> is affected.
  377. * Use {@link #setHelpSectionMap(Map)} to customize the usage help message for this command <em>and all subcommands</em>.
  378. * </p>
  379. * @since 3.9
  380. */
  381. public Map<String, IHelpSectionRenderer> getHelpSectionMap() { return getCommandSpec().usageMessage().sectionMap(); }
  382. /**
  383. * Sets the map of section keys and renderers used to construct the usage help message.
  384. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  385. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  386. * later will have the default setting. To ensure a setting is applied to all
  387. * subcommands, call the setter last, after adding subcommands.</p>
  388. * <p>Use {@link UsageMessageSpec#sectionMap(Map)} to customize a command without affecting its subcommands.</p>
  389. * @see #getHelpSectionMap
  390. * @since 3.9
  391. */
  392. public CommandLine setHelpSectionMap(Map<String, IHelpSectionRenderer> map) {
  393. getCommandSpec().usageMessage().sectionMap(map);
  394. for (CommandLine command : getCommandSpec().subcommands().values()) {
  395. command.setHelpSectionMap(map);
  396. }
  397. return this;
  398. }
  399. /** Returns whether the value of boolean flag options should be "toggled" when the option is matched.
  400. * By default, flags are toggled, so if the value is {@code true} it is set to {@code false}, and when the value is
  401. * {@code false} it is set to {@code true}. If toggling is off, flags are simply set to {@code true}.
  402. * @return {@code true} the value of boolean flag options should be "toggled" when the option is matched, {@code false} otherwise
  403. * @since 3.0
  404. */
  405. public boolean isToggleBooleanFlags() {
  406. return getCommandSpec().parser().toggleBooleanFlags();
  407. }
  408. /** Sets whether the value of boolean flag options should be "toggled" when the option is matched. The default is {@code true}.
  409. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  410. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  411. * later will have the default setting. To ensure a setting is applied to all
  412. * subcommands, call the setter last, after adding subcommands.</p>
  413. * @param newValue the new setting
  414. * @return this {@code CommandLine} object, to allow method chaining
  415. * @since 3.0
  416. */
  417. public CommandLine setToggleBooleanFlags(boolean newValue) {
  418. getCommandSpec().parser().toggleBooleanFlags(newValue);
  419. for (CommandLine command : getCommandSpec().subcommands().values()) {
  420. command.setToggleBooleanFlags(newValue);
  421. }
  422. return this;
  423. }
  424. /** Returns whether options for single-value fields can be specified multiple times on the command line.
  425. * The default is {@code false} and a {@link OverwrittenOptionException} is thrown if this happens.
  426. * When {@code true}, the last specified value is retained.
  427. * @return {@code true} if options for single-value fields can be specified multiple times on the command line, {@code false} otherwise
  428. * @since 0.9.7
  429. */
  430. public boolean isOverwrittenOptionsAllowed() {
  431. return getCommandSpec().parser().overwrittenOptionsAllowed();
  432. }
  433. /** Sets whether options for single-value fields can be specified multiple times on the command line without a {@link OverwrittenOptionException} being thrown.
  434. * The default is {@code false}.
  435. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  436. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  437. * later will have the default setting. To ensure a setting is applied to all
  438. * subcommands, call the setter last, after adding subcommands.</p>
  439. * @param newValue the new setting
  440. * @return this {@code CommandLine} object, to allow method chaining
  441. * @since 0.9.7
  442. */
  443. public CommandLine setOverwrittenOptionsAllowed(boolean newValue) {
  444. getCommandSpec().parser().overwrittenOptionsAllowed(newValue);
  445. for (CommandLine command : getCommandSpec().subcommands().values()) {
  446. command.setOverwrittenOptionsAllowed(newValue);
  447. }
  448. return this;
  449. }
  450. /** Returns whether the parser accepts clustered short options. The default is {@code true}.
  451. * @return {@code true} if short options like {@code -x -v -f SomeFile} can be clustered together like {@code -xvfSomeFile}, {@code false} otherwise
  452. * @since 3.0 */
  453. public boolean isPosixClusteredShortOptionsAllowed() { return getCommandSpec().parser().posixClusteredShortOptionsAllowed(); }
  454. /** Sets whether short options like {@code -x -v -f SomeFile} can be clustered together like {@code -xvfSomeFile}. The default is {@code true}.
  455. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  456. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  457. * later will have the default setting. To ensure a setting is applied to all
  458. * subcommands, call the setter last, after adding subcommands.</p>
  459. * @param newValue the new setting
  460. * @return this {@code CommandLine} object, to allow method chaining
  461. * @since 3.0
  462. */
  463. public CommandLine setPosixClusteredShortOptionsAllowed(boolean newValue) {
  464. getCommandSpec().parser().posixClusteredShortOptionsAllowed(newValue);
  465. for (CommandLine command : getCommandSpec().subcommands().values()) {
  466. command.setPosixClusteredShortOptionsAllowed(newValue);
  467. }
  468. return this;
  469. }
  470. /** Returns whether the parser should ignore case when converting arguments to {@code enum} values. The default is {@code false}.
  471. * @return {@code true} if enum values can be specified that don't match the {@code toString()} value of the enum constant, {@code false} otherwise;
  472. * e.g., for an option of type <a href="https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html">java.time.DayOfWeek</a>,
  473. * values {@code MonDaY}, {@code monday} and {@code MONDAY} are all recognized if {@code true}.
  474. * @since 3.4 */
  475. public boolean isCaseInsensitiveEnumValuesAllowed() { return getCommandSpec().parser().caseInsensitiveEnumValuesAllowed(); }
  476. /** Sets whether the parser should ignore case when converting arguments to {@code enum} values. The default is {@code false}.
  477. * When set to true, for example, for an option of type <a href="https://docs.oracle.com/javase/8/docs/api/java/time/DayOfWeek.html">java.time.DayOfWeek</a>,
  478. * values {@code MonDaY}, {@code monday} and {@code MONDAY} are all recognized if {@code true}.
  479. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  480. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  481. * later will have the default setting. To ensure a setting is applied to all
  482. * subcommands, call the setter last, after adding subcommands.</p>
  483. * @param newValue the new setting
  484. * @return this {@code CommandLine} object, to allow method chaining
  485. * @since 3.4
  486. */
  487. public CommandLine setCaseInsensitiveEnumValuesAllowed(boolean newValue) {
  488. getCommandSpec().parser().caseInsensitiveEnumValuesAllowed(newValue);
  489. for (CommandLine command : getCommandSpec().subcommands().values()) {
  490. command.setCaseInsensitiveEnumValuesAllowed(newValue);
  491. }
  492. return this;
  493. }
  494. /** Returns whether the parser should trim quotes from command line arguments before processing them. The default is
  495. * read from the system property "picocli.trimQuotes" and will be {@code true} if the property is present and empty,
  496. * or if its value is "true".
  497. * @return {@code true} if the parser should trim quotes from command line arguments before processing them, {@code false} otherwise;
  498. * @since 3.7 */
  499. public boolean isTrimQuotes() { return getCommandSpec().parser().trimQuotes(); }
  500. /** Sets whether the parser should trim quotes from command line arguments before processing them. The default is
  501. * read from the system property "picocli.trimQuotes" and will be {@code true} if the property is set and empty, or
  502. * if its value is "true".
  503. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  504. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  505. * later will have the default setting. To ensure a setting is applied to all
  506. * subcommands, call the setter last, after adding subcommands.</p>
  507. * <p>Calling this method will cause the "picocli.trimQuotes" property to have no effect.</p>
  508. * @param newValue the new setting
  509. * @return this {@code CommandLine} object, to allow method chaining
  510. * @since 3.7
  511. */
  512. public CommandLine setTrimQuotes(boolean newValue) {
  513. getCommandSpec().parser().trimQuotes(newValue);
  514. for (CommandLine command : getCommandSpec().subcommands().values()) {
  515. command.setTrimQuotes(newValue);
  516. }
  517. return this;
  518. }
  519. /** Returns whether the parser is allowed to split quoted Strings or not. The default is {@code false},
  520. * so quoted strings are treated as a single value that cannot be split.
  521. * @return {@code true} if the parser is allowed to split quoted Strings, {@code false} otherwise;
  522. * @see ArgSpec#splitRegex()
  523. * @since 3.7 */
  524. public boolean isSplitQuotedStrings() { return getCommandSpec().parser().splitQuotedStrings(); }
  525. /** Sets whether the parser is allowed to split quoted Strings. The default is {@code false}.
  526. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  527. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  528. * later will have the default setting. To ensure a setting is applied to all
  529. * subcommands, call the setter last, after adding subcommands.</p>
  530. * @param newValue the new setting
  531. * @return this {@code CommandLine} object, to allow method chaining
  532. * @see ArgSpec#splitRegex()
  533. * @since 3.7
  534. */
  535. public CommandLine setSplitQuotedStrings(boolean newValue) {
  536. getCommandSpec().parser().splitQuotedStrings(newValue);
  537. for (CommandLine command : getCommandSpec().subcommands().values()) {
  538. command.setSplitQuotedStrings(newValue);
  539. }
  540. return this;
  541. }
  542. /** Returns the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.
  543. * @return the end-of-options delimiter. The default is {@code "--"}.
  544. * @since 3.5 */
  545. public String getEndOfOptionsDelimiter() { return getCommandSpec().parser().endOfOptionsDelimiter(); }
  546. /** Sets the end-of-options delimiter that signals that the remaining command line arguments should be treated as positional parameters.
  547. * @param delimiter the end-of-options delimiter; must not be {@code null}. The default is {@code "--"}.
  548. * @return this {@code CommandLine} object, to allow method chaining
  549. * @since 3.5 */
  550. public CommandLine setEndOfOptionsDelimiter(String delimiter) {
  551. getCommandSpec().parser().endOfOptionsDelimiter(delimiter);
  552. for (CommandLine command : getCommandSpec().subcommands().values()) {
  553. command.setEndOfOptionsDelimiter(delimiter);
  554. }
  555. return this;
  556. }
  557. /** Returns the default value provider for the command, or {@code null} if none has been set.
  558. * @return the default value provider for this command, or {@code null}
  559. * @since 3.6
  560. * @see Command#defaultValueProvider()
  561. * @see CommandSpec#defaultValueProvider()
  562. * @see ArgSpec#defaultValueString()
  563. */
  564. public IDefaultValueProvider getDefaultValueProvider() {
  565. return getCommandSpec().defaultValueProvider();
  566. }
  567. /** Sets a default value provider for the command and sub-commands
  568. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  569. * sub-commands and nested sub-subcommands <em>at the moment this method is called</em>. Sub-commands added
  570. * later will have the default setting. To ensure a setting is applied to all
  571. * sub-commands, call the setter last, after adding sub-commands.</p>
  572. * @param newValue the default value provider to use
  573. * @return this {@code CommandLine} object, to allow method chaining
  574. * @since 3.6
  575. */
  576. public CommandLine setDefaultValueProvider(IDefaultValueProvider newValue) {
  577. getCommandSpec().defaultValueProvider(newValue);
  578. for (CommandLine command : getCommandSpec().subcommands().values()) {
  579. command.setDefaultValueProvider(newValue);
  580. }
  581. return this;
  582. }
  583. /** Returns whether the parser interprets the first positional parameter as "end of options" so the remaining
  584. * arguments are all treated as positional parameters. The default is {@code false}.
  585. * @return {@code true} if all values following the first positional parameter should be treated as positional parameters, {@code false} otherwise
  586. * @since 2.3
  587. */
  588. public boolean isStopAtPositional() {
  589. return getCommandSpec().parser().stopAtPositional();
  590. }
  591. /** Sets whether the parser interprets the first positional parameter as "end of options" so the remaining
  592. * arguments are all treated as positional parameters. The default is {@code false}.
  593. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  594. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  595. * later will have the default setting. To ensure a setting is applied to all
  596. * subcommands, call the setter last, after adding subcommands.</p>
  597. * @param newValue {@code true} if all values following the first positional parameter should be treated as positional parameters, {@code false} otherwise
  598. * @return this {@code CommandLine} object, to allow method chaining
  599. * @since 2.3
  600. */
  601. public CommandLine setStopAtPositional(boolean newValue) {
  602. getCommandSpec().parser().stopAtPositional(newValue);
  603. for (CommandLine command : getCommandSpec().subcommands().values()) {
  604. command.setStopAtPositional(newValue);
  605. }
  606. return this;
  607. }
  608. /** Returns whether the parser should stop interpreting options and positional parameters as soon as it encounters an
  609. * unmatched option. Unmatched options are arguments that look like an option but are not one of the known options, or
  610. * positional arguments for which there is no available slots (the command has no positional parameters or their size is limited).
  611. * The default is {@code false}.
  612. * <p>Setting this flag to {@code true} automatically sets the {@linkplain #isUnmatchedArgumentsAllowed() unmatchedArgumentsAllowed} flag to {@code true} also.</p>
  613. * @return {@code true} when an unmatched option should result in the remaining command line arguments to be added to the
  614. * {@linkplain #getUnmatchedArguments() unmatchedArguments list}
  615. * @since 2.3
  616. */
  617. public boolean isStopAtUnmatched() {
  618. return getCommandSpec().parser().stopAtUnmatched();
  619. }
  620. /** Sets whether the parser should stop interpreting options and positional parameters as soon as it encounters an
  621. * unmatched option. Unmatched options are arguments that look like an option but are not one of the known options, or
  622. * positional arguments for which there is no available slots (the command has no positional parameters or their size is limited).
  623. * The default is {@code false}.
  624. * <p>Setting this flag to {@code true} automatically sets the {@linkplain #setUnmatchedArgumentsAllowed(boolean) unmatchedArgumentsAllowed} flag to {@code true} also.</p>
  625. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  626. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  627. * later will have the default setting. To ensure a setting is applied to all
  628. * subcommands, call the setter last, after adding subcommands.</p>
  629. * @param newValue {@code true} when an unmatched option should result in the remaining command line arguments to be added to the
  630. * {@linkplain #getUnmatchedArguments() unmatchedArguments list}
  631. * @return this {@code CommandLine} object, to allow method chaining
  632. * @since 2.3
  633. */
  634. public CommandLine setStopAtUnmatched(boolean newValue) {
  635. getCommandSpec().parser().stopAtUnmatched(newValue);
  636. for (CommandLine command : getCommandSpec().subcommands().values()) {
  637. command.setStopAtUnmatched(newValue);
  638. }
  639. if (newValue) { setUnmatchedArgumentsAllowed(true); }
  640. return this;
  641. }
  642. /** Returns whether arguments on the command line that resemble an option should be treated as positional parameters.
  643. * The default is {@code false} and the parser behaviour depends on {@link #isUnmatchedArgumentsAllowed()}.
  644. * @return {@code true} arguments on the command line that resemble an option should be treated as positional parameters, {@code false} otherwise
  645. * @see #getUnmatchedArguments()
  646. * @since 3.0
  647. */
  648. public boolean isUnmatchedOptionsArePositionalParams() {
  649. return getCommandSpec().parser().unmatchedOptionsArePositionalParams();
  650. }
  651. /** Sets whether arguments on the command line that resemble an option should be treated as positional parameters.
  652. * The default is {@code false}.
  653. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  654. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  655. * later will have the default setting. To ensure a setting is applied to all
  656. * subcommands, call the setter last, after adding subcommands.</p>
  657. * @param newValue the new setting. When {@code true}, arguments on the command line that resemble an option should be treated as positional parameters.
  658. * @return this {@code CommandLine} object, to allow method chaining
  659. * @since 3.0
  660. * @see #getUnmatchedArguments()
  661. * @see #isUnmatchedArgumentsAllowed
  662. */
  663. public CommandLine setUnmatchedOptionsArePositionalParams(boolean newValue) {
  664. getCommandSpec().parser().unmatchedOptionsArePositionalParams(newValue);
  665. for (CommandLine command : getCommandSpec().subcommands().values()) {
  666. command.setUnmatchedOptionsArePositionalParams(newValue);
  667. }
  668. return this;
  669. }
  670. /** Returns whether the end user may specify arguments on the command line that are not matched to any option or parameter fields.
  671. * The default is {@code false} and a {@link UnmatchedArgumentException} is thrown if this happens.
  672. * When {@code true}, the last unmatched arguments are available via the {@link #getUnmatchedArguments()} method.
  673. * @return {@code true} if the end use may specify unmatched arguments on the command line, {@code false} otherwise
  674. * @see #getUnmatchedArguments()
  675. * @since 0.9.7
  676. */
  677. public boolean isUnmatchedArgumentsAllowed() {
  678. return getCommandSpec().parser().unmatchedArgumentsAllowed();
  679. }
  680. /** Sets whether the end user may specify unmatched arguments on the command line without a {@link UnmatchedArgumentException} being thrown.
  681. * The default is {@code false}.
  682. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  683. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  684. * later will have the default setting. To ensure a setting is applied to all
  685. * subcommands, call the setter last, after adding subcommands.</p>
  686. * @param newValue the new setting. When {@code true}, the last unmatched arguments are available via the {@link #getUnmatchedArguments()} method.
  687. * @return this {@code CommandLine} object, to allow method chaining
  688. * @since 0.9.7
  689. * @see #getUnmatchedArguments()
  690. */
  691. public CommandLine setUnmatchedArgumentsAllowed(boolean newValue) {
  692. getCommandSpec().parser().unmatchedArgumentsAllowed(newValue);
  693. for (CommandLine command : getCommandSpec().subcommands().values()) {
  694. command.setUnmatchedArgumentsAllowed(newValue);
  695. }
  696. return this;
  697. }
  698. /** Returns the list of unmatched command line arguments, if any.
  699. * @return the list of unmatched command line arguments or an empty list
  700. * @see #isUnmatchedArgumentsAllowed()
  701. * @since 0.9.7
  702. */
  703. public List<String> getUnmatchedArguments() {
  704. return interpreter.parseResultBuilder == null ? Collections.<String>emptyList() : UnmatchedArgumentException.stripErrorMessage(interpreter.parseResultBuilder.unmatched);
  705. }
  706. /**
  707. * <p>
  708. * Convenience method that initializes the specified annotated object from the specified command line arguments.
  709. * </p><p>
  710. * This is equivalent to
  711. * </p><pre>
  712. * CommandLine cli = new CommandLine(command);
  713. * cli.parse(args);
  714. * return command;
  715. * </pre>
  716. *
  717. * @param command the object to initialize. This object contains fields annotated with
  718. * {@code @Option} or {@code @Parameters}.
  719. * @param args the command line arguments to parse
  720. * @param <T> the type of the annotated object
  721. * @return the specified annotated object
  722. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  723. * @throws ParameterException if the specified command line arguments are invalid
  724. * @since 0.9.7
  725. */
  726. public static <T> T populateCommand(T command, String... args) {
  727. CommandLine cli = toCommandLine(command, new DefaultFactory());
  728. cli.parse(args);
  729. return command;
  730. }
  731. /**
  732. * <p>
  733. * Convenience method that derives the command specification from the specified interface class, and returns an
  734. * instance of the specified interface. The interface is expected to have annotated getter methods. Picocli will
  735. * instantiate the interface and the getter methods will return the option and positional parameter values matched on the command line.
  736. * </p><p>
  737. * This is equivalent to
  738. * </p><pre>
  739. * CommandLine cli = new CommandLine(spec);
  740. * cli.parse(args);
  741. * return cli.getCommand();
  742. * </pre>
  743. *
  744. * @param spec the interface that defines the command specification. This object contains getter methods annotated with
  745. * {@code @Option} or {@code @Parameters}.
  746. * @param args the command line arguments to parse
  747. * @param <T> the type of the annotated object
  748. * @return an instance of the specified annotated interface
  749. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  750. * @throws ParameterException if the specified command line arguments are invalid
  751. * @since 3.1
  752. */
  753. public static <T> T populateSpec(Class<T> spec, String... args) {
  754. CommandLine cli = toCommandLine(spec, new DefaultFactory());
  755. cli.parse(args);
  756. return cli.getCommand();
  757. }
  758. /** Parses the specified command line arguments and returns a list of {@code CommandLine} objects representing the
  759. * top-level command and any subcommands (if any) that were recognized and initialized during the parsing process.
  760. * <p>
  761. * If parsing succeeds, the first element in the returned list is always {@code this CommandLine} object. The
  762. * returned list may contain more elements if subcommands were {@linkplain #addSubcommand(String, Object) registered}
  763. * and these subcommands were initialized by matching command line arguments. If parsing fails, a
  764. * {@link ParameterException} is thrown.
  765. * </p>
  766. *
  767. * @param args the command line arguments to parse
  768. * @return a list with the top-level command and any subcommands initialized by this method
  769. * @throws ParameterException if the specified command line arguments are invalid; use
  770. * {@link ParameterException#getCommandLine()} to get the command or subcommand whose user input was invalid
  771. */
  772. public List<CommandLine> parse(String... args) {
  773. return interpreter.parse(args);
  774. }
  775. /** Parses the specified command line arguments and returns a list of {@code ParseResult} with the options, positional
  776. * parameters, and subcommands (if any) that were recognized and initialized during the parsing process.
  777. * <p>If parsing fails, a {@link ParameterException} is thrown.</p>
  778. *
  779. * @param args the command line arguments to parse
  780. * @return a list with the top-level command and any subcommands initialized by this method
  781. * @throws ParameterException if the specified command line arguments are invalid; use
  782. * {@link ParameterException#getCommandLine()} to get the command or subcommand whose user input was invalid
  783. */
  784. public ParseResult parseArgs(String... args) {
  785. interpreter.parse(args);
  786. return getParseResult();
  787. }
  788. public ParseResult getParseResult() { return interpreter.parseResultBuilder == null ? null : interpreter.parseResultBuilder.build(); }
  789. /**
  790. * Represents a function that can process a List of {@code CommandLine} objects resulting from successfully
  791. * {@linkplain #parse(String...) parsing} the command line arguments. This is a
  792. * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html">functional interface</a>
  793. * whose functional method is {@link #handleParseResult(List, PrintStream, CommandLine.Help.Ansi)}.
  794. * <p>
  795. * Implementations of this functions can be passed to the {@link #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) CommandLine::parseWithHandler}
  796. * methods to take some next step after the command line was successfully parsed.
  797. * </p>
  798. * @see RunFirst
  799. * @see RunLast
  800. * @see RunAll
  801. * @deprecated Use {@link IParseResultHandler2} instead.
  802. * @since 2.0 */
  803. @Deprecated public static interface IParseResultHandler {
  804. /** Processes a List of {@code CommandLine} objects resulting from successfully
  805. * {@linkplain #parse(String...) parsing} the command line arguments and optionally returns a list of results.
  806. * @param parsedCommands the {@code CommandLine} objects that resulted from successfully parsing the command line arguments
  807. * @param out the {@code PrintStream} to print help to if requested
  808. * @param ansi for printing help messages using ANSI styles and colors
  809. * @return a list of results, or an empty list if there are no results
  810. * @throws ParameterException if a help command was invoked for an unknown subcommand. Any {@code ParameterExceptions}
  811. * thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler}
  812. * @throws ExecutionException if a problem occurred while processing the parse results; use
  813. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  814. */
  815. List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) throws ExecutionException;
  816. }
  817. /**
  818. * Represents a function that can process the {@code ParseResult} object resulting from successfully
  819. * {@linkplain #parseArgs(String...) parsing} the command line arguments. This is a
  820. * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html">functional interface</a>
  821. * whose functional method is {@link IParseResultHandler2#handleParseResult(CommandLine.ParseResult)}.
  822. * <p>
  823. * Implementations of this function can be passed to the {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...) CommandLine::parseWithHandlers}
  824. * methods to take some next step after the command line was successfully parsed.
  825. * </p><p>
  826. * This interface replaces the {@link IParseResultHandler} interface; it takes the parse result as a {@code ParseResult}
  827. * object instead of a List of {@code CommandLine} objects, and it has the freedom to select the {@link Help.Ansi} style
  828. * to use and what {@code PrintStreams} to print to.
  829. * </p>
  830. * @param <R> the return type of this handler
  831. * @see RunFirst
  832. * @see RunLast
  833. * @see RunAll
  834. * @since 3.0 */
  835. public static interface IParseResultHandler2<R> {
  836. /** Processes the {@code ParseResult} object resulting from successfully
  837. * {@linkplain CommandLine#parseArgs(String...) parsing} the command line arguments and returns a return value.
  838. * @param parseResult the {@code ParseResult} that resulted from successfully parsing the command line arguments
  839. * @throws ParameterException if a help command was invoked for an unknown subcommand. Any {@code ParameterExceptions}
  840. * thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler2}
  841. * @throws ExecutionException if a problem occurred while processing the parse results; use
  842. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  843. */
  844. R handleParseResult(ParseResult parseResult) throws ExecutionException;
  845. }
  846. /**
  847. * Represents a function that can handle a {@code ParameterException} that occurred while
  848. * {@linkplain #parse(String...) parsing} the command line arguments. This is a
  849. * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/function/package-summary.html">functional interface</a>
  850. * whose functional method is {@link #handleException(CommandLine.ParameterException, PrintStream, CommandLine.Help.Ansi, String...)}.
  851. * <p>
  852. * Implementations of this function can be passed to the {@link #parseWithHandlers(IParseResultHandler, PrintStream, Help.Ansi, IExceptionHandler, String...) CommandLine::parseWithHandlers}
  853. * methods to handle situations when the command line could not be parsed.
  854. * </p>
  855. * @deprecated Use {@link IExceptionHandler2} instead.
  856. * @see DefaultExceptionHandler
  857. * @since 2.0 */
  858. @Deprecated public static interface IExceptionHandler {
  859. /** Handles a {@code ParameterException} that occurred while {@linkplain #parse(String...) parsing} the command
  860. * line arguments and optionally returns a list of results.
  861. * @param ex the ParameterException describing the problem that occurred while parsing the command line arguments,
  862. * and the CommandLine representing the command or subcommand whose input was invalid
  863. * @param out the {@code PrintStream} to print help to if requested
  864. * @param ansi for printing help messages using ANSI styles and colors
  865. * @param args the command line arguments that could not be parsed
  866. * @return a list of results, or an empty list if there are no results
  867. */
  868. List<Object> handleException(ParameterException ex, PrintStream out, Help.Ansi ansi, String... args);
  869. }
  870. /**
  871. * Classes implementing this interface know how to handle {@code ParameterExceptions} (usually from invalid user input)
  872. * and {@code ExecutionExceptions} that occurred while executing the {@code Runnable} or {@code Callable} command.
  873. * <p>
  874. * Implementations of this interface can be passed to the
  875. * {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...) CommandLine::parseWithHandlers} method.
  876. * </p><p>
  877. * This interface replaces the {@link IParseResultHandler} interface.
  878. * </p>
  879. * @param <R> the return type of this handler
  880. * @see DefaultExceptionHandler
  881. * @since 3.0 */
  882. public static interface IExceptionHandler2<R> {
  883. /** Handles a {@code ParameterException} that occurred while {@linkplain #parseArgs(String...) parsing} the command
  884. * line arguments and optionally returns a list of results.
  885. * @param ex the ParameterException describing the problem that occurred while parsing the command line arguments,
  886. * and the CommandLine representing the command or subcommand whose input was invalid
  887. * @param args the command line arguments that could not be parsed
  888. * @return an object resulting from handling the exception
  889. */
  890. R handleParseException(ParameterException ex, String[] args);
  891. /** Handles a {@code ExecutionException} that occurred while executing the {@code Runnable} or
  892. * {@code Callable} command and optionally returns a list of results.
  893. * @param ex the ExecutionException describing the problem that occurred while executing the {@code Runnable} or
  894. * {@code Callable} command, and the CommandLine representing the command or subcommand that was being executed
  895. * @param parseResult the result of parsing the command line arguments
  896. * @return an object resulting from handling the exception
  897. */
  898. R handleExecutionException(ExecutionException ex, ParseResult parseResult);
  899. }
  900. /** Abstract superclass for {@link IParseResultHandler2} and {@link IExceptionHandler2} implementations.
  901. * <p>Note that {@code AbstractHandler} is a generic type. This, along with the abstract {@code self} method,
  902. * allows method chaining to work properly in subclasses, without the need for casts. An example subclass can look like this:</p>
  903. * <pre>{@code
  904. * class MyResultHandler extends AbstractHandler<MyReturnType, MyResultHandler> implements IParseResultHandler2<MyReturnType> {
  905. *
  906. * public MyReturnType handleParseResult(ParseResult parseResult) { ... }
  907. *
  908. * protected MyResultHandler self() { return this; }
  909. * }
  910. * }</pre>
  911. * @param <R> the return type of this handler
  912. * @param <T> The type of the handler subclass; for fluent API method chaining
  913. * @since 3.0 */
  914. public static abstract class AbstractHandler<R, T extends AbstractHandler<R, T>> {
  915. private Help.Ansi ansi = Help.Ansi.AUTO;
  916. private Integer exitCode;
  917. private PrintStream out = System.out;
  918. private PrintStream err = System.err;
  919. /** Returns the stream to print command output to. Defaults to {@code System.out}, unless {@link #useOut(PrintStream)}
  920. * was called with a different stream.
  921. * <p>{@code IParseResultHandler2} implementations should use this stream.
  922. * By <a href="http://www.gnu.org/prep/standards/html_node/_002d_002dhelp.html">convention</a>, when the user requests
  923. * help with a {@code --help} or similar option, the usage help message is printed to the standard output stream so that it can be easily searched and paged.</p> */
  924. public PrintStream out() { return out; }
  925. /** Returns the stream to print diagnostic messages to. Defaults to {@code System.err}, unless {@link #useErr(PrintStream)}
  926. * was called with a different stream. <p>{@code IExceptionHandler2} implementations should use this stream to print error
  927. * messages (which may include a usage help message) when an unexpected error occurs.</p> */
  928. public PrintStream err() { return err; }
  929. /** Returns the ANSI style to use. Defaults to {@code Help.Ansi.AUTO}, unless {@link #useAnsi(CommandLine.Help.Ansi)} was called with a different setting. */
  930. public Help.Ansi ansi() { return ansi; }
  931. /** Returns the exit code to use as the termination status, or {@code null} (the default) if the handler should
  932. * not call {@link System#exit(int)} after processing completes.
  933. * @see #andExit(int) */
  934. public Integer exitCode() { return exitCode; }
  935. /** Returns {@code true} if an exit code was set with {@link #andExit(int)}, or {@code false} (the default) if
  936. * the handler should not call {@link System#exit(int)} after processing completes. */
  937. public boolean hasExitCode() { return exitCode != null; }
  938. /** Convenience method for subclasses that returns the specified result object if no exit code was set,
  939. * or otherwise, if an exit code {@linkplain #andExit(int) was set}, calls {@code System.exit} with the configured
  940. * exit code to terminate the currently running Java virtual machine. */
  941. protected R returnResultOrExit(R result) {
  942. if (hasExitCode()) { exit(exitCode()); }
  943. return result;
  944. }
  945. /** Convenience method for subclasses that throws the specified ExecutionException if no exit code was set,
  946. * or otherwise, if an exit code {@linkplain #andExit(int) was set}, prints the stacktrace of the specified exception
  947. * to the diagnostic error stream and calls {@code System.exit} with the configured
  948. * exit code to terminate the currently running Java virtual machine. */
  949. protected R throwOrExit(ExecutionException ex) {
  950. if (hasExitCode()) {
  951. ex.printStackTrace(this.err());
  952. exit(exitCode());
  953. }
  954. throw ex;
  955. }
  956. /** Calls {@code System.exit(int)} with the specified exit code. */
  957. protected void exit(int exitCode) { System.exit(exitCode); }
  958. /** Returns {@code this} to allow method chaining when calling the setters for a fluent API. */
  959. protected abstract T self();
  960. /** Sets the stream to print command output to. For use by {@code IParseResultHandler2} implementations.
  961. * @see #out() */
  962. public T useOut(PrintStream out) { this.out = Assert.notNull(out, "out"); return self(); }
  963. /** Sets the stream to print diagnostic messages to. For use by {@code IExceptionHandler2} implementations.
  964. * @see #err()*/
  965. public T useErr(PrintStream err) { this.err = Assert.notNull(err, "err"); return self(); }
  966. /** Sets the ANSI style to use.
  967. * @see #ansi() */
  968. public T useAnsi(Help.Ansi ansi) { this.ansi = Assert.notNull(ansi, "ansi"); return self(); }
  969. /** Indicates that the handler should call {@link System#exit(int)} after processing completes and sets the exit code to use as the termination status. */
  970. public T andExit(int exitCode) { this.exitCode = exitCode; return self(); }
  971. }
  972. /**
  973. * Default exception handler that handles invalid user input by printing the exception message, followed by the usage
  974. * message for the command or subcommand whose input was invalid.
  975. * <p>{@code ParameterExceptions} (invalid user input) is handled like this:</p>
  976. * <pre>
  977. * err().println(paramException.getMessage());
  978. * paramException.getCommandLine().usage(err(), ansi());
  979. * if (hasExitCode()) System.exit(exitCode()); else return returnValue;
  980. * </pre>
  981. * <p>{@code ExecutionExceptions} that occurred while executing the {@code Runnable} or {@code Callable} command are simply rethrown and not handled.</p>
  982. * @since 2.0 */
  983. @SuppressWarnings("deprecation")
  984. public static class DefaultExceptionHandler<R> extends AbstractHandler<R, DefaultExceptionHandler<R>> implements IExceptionHandler, IExceptionHandler2<R> {
  985. public List<Object> handleException(ParameterException ex, PrintStream out, Help.Ansi ansi, String... args) {
  986. internalHandleParseException(ex, out, ansi, args); return Collections.<Object>emptyList(); }
  987. /** Prints the message of the specified exception, followed by the usage message for the command or subcommand
  988. * whose input was invalid, to the stream returned by {@link #err()}.
  989. * @param ex the ParameterException describing the problem that occurred while parsing the command line arguments,
  990. * and the CommandLine representing the command or subcommand whose input was invalid
  991. * @param args the command line arguments that could not be parsed
  992. * @return the empty list
  993. * @since 3.0 */
  994. public R handleParseException(ParameterException ex, String[] args) {
  995. internalHandleParseException(ex, err(), ansi(), args); return returnResultOrExit(null); }
  996. private void internalHandleParseException(ParameterException ex, PrintStream out, Help.Ansi ansi, String[] args) {
  997. out.println(ex.getMessage());
  998. if (!UnmatchedArgumentException.printSuggestions(ex, out)) {
  999. ex.getCommandLine().usage(out, ansi);
  1000. }
  1001. }
  1002. /** This implementation always simply rethrows the specified exception.
  1003. * @param ex the ExecutionException describing the problem that occurred while executing the {@code Runnable} or {@code Callable} command
  1004. * @param parseResult the result of parsing the command line arguments
  1005. * @return nothing: this method always rethrows the specified exception
  1006. * @throws ExecutionException always rethrows the specified exception
  1007. * @since 3.0 */
  1008. public R handleExecutionException(ExecutionException ex, ParseResult parseResult) { return throwOrExit(ex); }
  1009. @Override protected DefaultExceptionHandler<R> self() { return this; }
  1010. }
  1011. /** Convenience method that returns {@code new DefaultExceptionHandler<List<Object>>()}. */
  1012. public static DefaultExceptionHandler<List<Object>> defaultExceptionHandler() { return new DefaultExceptionHandler<List<Object>>(); }
  1013. /** @deprecated use {@link #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)} instead
  1014. * @since 2.0 */
  1015. @Deprecated public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) {
  1016. return printHelpIfRequested(parsedCommands, out, out, ansi);
  1017. }
  1018. /** Delegates to {@link #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)} with
  1019. * {@code parseResult.asCommandLineList(), System.out, System.err, Help.Ansi.AUTO}.
  1020. * @since 3.0 */
  1021. public static boolean printHelpIfRequested(ParseResult parseResult) {
  1022. return printHelpIfRequested(parseResult.asCommandLineList(), System.out, System.err, Help.Ansi.AUTO);
  1023. }
  1024. /**
  1025. * Helper method that may be useful when processing the list of {@code CommandLine} objects that result from successfully
  1026. * {@linkplain #parse(String...) parsing} command line arguments. This method prints out
  1027. * {@linkplain #usage(PrintStream, Help.Ansi) usage help} if {@linkplain #isUsageHelpRequested() requested}
  1028. * or {@linkplain #printVersionHelp(PrintStream, Help.Ansi) version help} if {@linkplain #isVersionHelpRequested() requested}
  1029. * and returns {@code true}. If the command is a {@link Command#helpCommand()} and {@code runnable} or {@code callable},
  1030. * that command is executed and this method returns {@code true}.
  1031. * Otherwise, if none of the specified {@code CommandLine} objects have help requested,
  1032. * this method returns {@code false}.<p>
  1033. * Note that this method <em>only</em> looks at the {@link Option#usageHelp() usageHelp} and
  1034. * {@link Option#versionHelp() versionHelp} attributes. The {@link Option#help() help} attribute is ignored.
  1035. * </p><p><b>Implementation note:</b></p><p>
  1036. * When an error occurs while processing the help request, it is recommended custom Help commands throw a
  1037. * {@link ParameterException} with a reference to the parent command. This will print the error message and the
  1038. * usage for the parent command, and will use the exit code of the exception handler if one was set.
  1039. * </p>
  1040. * @param parsedCommands the list of {@code CommandLine} objects to check if help was requested
  1041. * @param out the {@code PrintStream} to print help to if requested
  1042. * @param err the error string to print diagnostic messages to, in addition to the output from the exception handler
  1043. * @param ansi for printing help messages using ANSI styles and colors
  1044. * @return {@code true} if help was printed, {@code false} otherwise
  1045. * @see IHelpCommandInitializable
  1046. * @since 3.0 */
  1047. public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, Help.Ansi ansi) {
  1048. return printHelpIfRequested(parsedCommands, out, err, Help.defaultColorScheme(ansi));
  1049. }
  1050. /**
  1051. * Helper method that may be useful when processing the list of {@code CommandLine} objects that result from successfully
  1052. * {@linkplain #parse(String...) parsing} command line arguments. This method prints out
  1053. * {@linkplain #usage(PrintStream, Help.ColorScheme) usage help} if {@linkplain #isUsageHelpRequested() requested}
  1054. * or {@linkplain #printVersionHelp(PrintStream, Help.Ansi) version help} if {@linkplain #isVersionHelpRequested() requested}
  1055. * and returns {@code true}. If the command is a {@link Command#helpCommand()} and {@code runnable} or {@code callable},
  1056. * that command is executed and this method returns {@code true}.
  1057. * Otherwise, if none of the specified {@code CommandLine} objects have help requested,
  1058. * this method returns {@code false}.<p>
  1059. * Note that this method <em>only</em> looks at the {@link Option#usageHelp() usageHelp} and
  1060. * {@link Option#versionHelp() versionHelp} attributes. The {@link Option#help() help} attribute is ignored.
  1061. * </p><p><b>Implementation note:</b></p><p>
  1062. * When an error occurs while processing the help request, it is recommended custom Help commands throw a
  1063. * {@link ParameterException} with a reference to the parent command. This will print the error message and the
  1064. * usage for the parent command, and will use the exit code of the exception handler if one was set.
  1065. * </p>
  1066. * @param parsedCommands the list of {@code CommandLine} objects to check if help was requested
  1067. * @param out the {@code PrintStream} to print help to if requested
  1068. * @param err the error string to print diagnostic messages to, in addition to the output from the exception handler
  1069. * @param colorScheme for printing help messages using ANSI styles and colors
  1070. * @return {@code true} if help was printed, {@code false} otherwise
  1071. * @see IHelpCommandInitializable
  1072. * @since 3.6 */
  1073. public static boolean printHelpIfRequested(List<CommandLine> parsedCommands, PrintStream out, PrintStream err, Help.ColorScheme colorScheme) {
  1074. for (int i = 0; i < parsedCommands.size(); i++) {
  1075. CommandLine parsed = parsedCommands.get(i);
  1076. if (parsed.isUsageHelpRequested()) {
  1077. parsed.usage(out, colorScheme);
  1078. return true;
  1079. } else if (parsed.isVersionHelpRequested()) {
  1080. parsed.printVersionHelp(out, colorScheme.ansi);
  1081. return true;
  1082. } else if (parsed.getCommandSpec().helpCommand()) {
  1083. if (parsed.getCommand() instanceof IHelpCommandInitializable) {
  1084. ((IHelpCommandInitializable) parsed.getCommand()).init(parsed, colorScheme.ansi, out, err);
  1085. }
  1086. execute(parsed, new ArrayList<Object>());
  1087. return true;
  1088. }
  1089. }
  1090. return false;
  1091. }
  1092. private static List<Object> execute(CommandLine parsed, List<Object> executionResult) {
  1093. Object command = parsed.getCommand();
  1094. if (command instanceof Runnable) {
  1095. try {
  1096. ((Runnable) command).run();
  1097. executionResult.add(null); // for compatibility with picocli 2.x
  1098. return executionResult;
  1099. } catch (ParameterException ex) {
  1100. throw ex;
  1101. } catch (ExecutionException ex) {
  1102. throw ex;
  1103. } catch (Exception ex) {
  1104. throw new ExecutionException(parsed, "Error while running command (" + command + "): " + ex, ex);
  1105. }
  1106. } else if (command instanceof Callable) {
  1107. try {
  1108. @SuppressWarnings("unchecked") Callable<Object> callable = (Callable<Object>) command;
  1109. executionResult.add(callable.call());
  1110. return executionResult;
  1111. } catch (ParameterException ex) {
  1112. throw ex;
  1113. } catch (ExecutionException ex) {
  1114. throw ex;
  1115. } catch (Exception ex) {
  1116. throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + ex, ex);
  1117. }
  1118. } else if (command instanceof Method) {
  1119. try {
  1120. if (Modifier.isStatic(((Method) command).getModifiers())) {
  1121. // invoke static method
  1122. executionResult.add(((Method) command).invoke(null, parsed.getCommandSpec().argValues()));
  1123. return executionResult;
  1124. } else if (parsed.getCommandSpec().parent() != null) {
  1125. executionResult.add(((Method) command).invoke(parsed.getCommandSpec().parent().userObject(), parsed.getCommandSpec().argValues()));
  1126. return executionResult;
  1127. } else {
  1128. for (Constructor<?> constructor : ((Method) command).getDeclaringClass().getDeclaredConstructors()) {
  1129. if (constructor.getParameterTypes().length == 0) {
  1130. executionResult.add(((Method) command).invoke(constructor.newInstance(), parsed.getCommandSpec().argValues()));
  1131. return executionResult;
  1132. }
  1133. }
  1134. throw new UnsupportedOperationException("Invoking non-static method without default constructor not implemented");
  1135. }
  1136. } catch (InvocationTargetException ex) {
  1137. Throwable t = ex.getTargetException();
  1138. if (t instanceof ParameterException) {
  1139. throw (ParameterException) t;
  1140. } else if (t instanceof ExecutionException) {
  1141. throw (ExecutionException) t;
  1142. } else {
  1143. throw new ExecutionException(parsed, "Error while calling command (" + command + "): " + t, t);
  1144. }
  1145. } catch (Exception ex) {
  1146. throw new ExecutionException(parsed, "Unhandled error while calling command (" + command + "): " + ex, ex);
  1147. }
  1148. }
  1149. throw new ExecutionException(parsed, "Parsed command (" + command + ") is not Method, Runnable or Callable");
  1150. }
  1151. /** Command line parse result handler that returns a value. This handler prints help if requested, and otherwise calls
  1152. * {@link #handle(CommandLine.ParseResult)} with the parse result. Facilitates implementation of the {@link IParseResultHandler2} interface.
  1153. * <p>Note that {@code AbstractParseResultHandler} is a generic type. This, along with the abstract {@code self} method,
  1154. * allows method chaining to work properly in subclasses, without the need for casts. An example subclass can look like this:</p>
  1155. * <pre>{@code
  1156. * class MyResultHandler extends AbstractParseResultHandler<MyReturnType> {
  1157. *
  1158. * protected MyReturnType handle(ParseResult parseResult) throws ExecutionException { ... }
  1159. *
  1160. * protected MyResultHandler self() { return this; }
  1161. * }
  1162. * }</pre>
  1163. * @since 3.0 */
  1164. public abstract static class AbstractParseResultHandler<R> extends AbstractHandler<R, AbstractParseResultHandler<R>> implements IParseResultHandler2<R> {
  1165. /** Prints help if requested, and otherwise calls {@link #handle(CommandLine.ParseResult)}.
  1166. * Finally, either a list of result objects is returned, or the JVM is terminated if an exit code {@linkplain #andExit(int) was set}.
  1167. *
  1168. * @param parseResult the {@code ParseResult} that resulted from successfully parsing the command line arguments
  1169. * @return the result of {@link #handle(ParseResult) processing parse results}
  1170. * @throws ParameterException if the {@link HelpCommand HelpCommand} was invoked for an unknown subcommand. Any {@code ParameterExceptions}
  1171. * thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler2}
  1172. * @throws ExecutionException if a problem occurred while processing the parse results; client code can use
  1173. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1174. */
  1175. public R handleParseResult(ParseResult parseResult) throws ExecutionException {
  1176. if (printHelpIfRequested(parseResult.asCommandLineList(), out(), err(), ansi())) {
  1177. return returnResultOrExit(null);
  1178. }
  1179. return returnResultOrExit(handle(parseResult));
  1180. }
  1181. /** Processes the specified {@code ParseResult} and returns the result as a list of objects.
  1182. * Implementations are responsible for catching any exceptions thrown in the {@code handle} method, and
  1183. * rethrowing an {@code ExecutionException} that details the problem and captures the offending {@code CommandLine} object.
  1184. *
  1185. * @param parseResult the {@code ParseResult} that resulted from successfully parsing the command line arguments
  1186. * @return the result of processing parse results
  1187. * @throws ExecutionException if a problem occurred while processing the parse results; client code can use
  1188. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1189. */
  1190. protected abstract R handle(ParseResult parseResult) throws ExecutionException;
  1191. }
  1192. /**
  1193. * Command line parse result handler that prints help if requested, and otherwise executes the top-level
  1194. * {@code Runnable} or {@code Callable} command.
  1195. * For use in the {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...) parseWithHandler} methods.
  1196. * @since 2.0 */
  1197. public static class RunFirst extends AbstractParseResultHandler<List<Object>> implements IParseResultHandler {
  1198. /** Prints help if requested, and otherwise executes the top-level {@code Runnable} or {@code Callable} command.
  1199. * Finally, either a list of result objects is returned, or the JVM is terminated if an exit code {@linkplain #andExit(int) was set}.
  1200. * If the top-level command does not implement either {@code Runnable} or {@code Callable}, an {@code ExecutionException}
  1201. * is thrown detailing the problem and capturing the offending {@code CommandLine} object.
  1202. *
  1203. * @param parsedCommands the {@code CommandLine} objects that resulted from successfully parsing the command line arguments
  1204. * @param out the {@code PrintStream} to print help to if requested
  1205. * @param ansi for printing help messages using ANSI styles and colors
  1206. * @return an empty list if help was requested, or a list containing a single element: the result of calling the
  1207. * {@code Callable}, or a {@code null} element if the top-level command was a {@code Runnable}
  1208. * @throws ParameterException if the {@link HelpCommand HelpCommand} was invoked for an unknown subcommand. Any {@code ParameterExceptions}
  1209. * thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler}
  1210. * @throws ExecutionException if a problem occurred while processing the parse results; use
  1211. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1212. */
  1213. public List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) {
  1214. if (printHelpIfRequested(parsedCommands, out, err(), ansi)) { return returnResultOrExit(Collections.emptyList()); }
  1215. return returnResultOrExit(execute(parsedCommands.get(0), new ArrayList<Object>()));
  1216. }
  1217. /** Executes the top-level {@code Runnable} or {@code Callable} subcommand.
  1218. * If the top-level command does not implement either {@code Runnable} or {@code Callable}, an {@code ExecutionException}
  1219. * is thrown detailing the problem and capturing the offending {@code CommandLine} object.
  1220. *
  1221. * @param parseResult the {@code ParseResult} that resulted from successfully parsing the command line arguments
  1222. * @return an empty list if help was requested, or a list containing a single element: the result of calling the
  1223. * {@code Callable}, or a {@code null} element if the last (sub)command was a {@code Runnable}
  1224. * @throws ExecutionException if a problem occurred while processing the parse results; use
  1225. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1226. * @since 3.0 */
  1227. protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
  1228. return execute(parseResult.commandSpec().commandLine(), new ArrayList<Object>()); // first
  1229. }
  1230. @Override protected RunFirst self() { return this; }
  1231. }
  1232. /**
  1233. * Command line parse result handler that prints help if requested, and otherwise executes the most specific
  1234. * {@code Runnable} or {@code Callable} subcommand.
  1235. * For use in the {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...) parseWithHandler} methods.
  1236. * <p>
  1237. * Something like this:</p>
  1238. * <pre>{@code
  1239. * // RunLast implementation: print help if requested, otherwise execute the most specific subcommand
  1240. * List<CommandLine> parsedCommands = parseResult.asCommandLineList();
  1241. * if (CommandLine.printHelpIfRequested(parsedCommands, out(), err(), ansi())) {
  1242. * return emptyList();
  1243. * }
  1244. * CommandLine last = parsedCommands.get(parsedCommands.size() - 1);
  1245. * Object command = last.getCommand();
  1246. * Object result = null;
  1247. * if (command instanceof Runnable) {
  1248. * try {
  1249. * ((Runnable) command).run();
  1250. * } catch (Exception ex) {
  1251. * throw new ExecutionException(last, "Error in runnable " + command, ex);
  1252. * }
  1253. * } else if (command instanceof Callable) {
  1254. * try {
  1255. * result = ((Callable) command).call();
  1256. * } catch (Exception ex) {
  1257. * throw new ExecutionException(last, "Error in callable " + command, ex);
  1258. * }
  1259. * } else {
  1260. * throw new ExecutionException(last, "Parsed command (" + command + ") is not Runnable or Callable");
  1261. * }
  1262. * if (hasExitCode()) { System.exit(exitCode()); }
  1263. * return Arrays.asList(result);
  1264. * }</pre>
  1265. * <p>
  1266. * From picocli v2.0, {@code RunLast} is used to implement the {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...) run}
  1267. * and {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...) call} convenience methods.
  1268. * </p>
  1269. * @since 2.0 */
  1270. public static class RunLast extends AbstractParseResultHandler<List<Object>> implements IParseResultHandler {
  1271. /** Prints help if requested, and otherwise executes the most specific {@code Runnable} or {@code Callable} subcommand.
  1272. * Finally, either a list of result objects is returned, or the JVM is terminated if an exit code {@linkplain #andExit(int) was set}.
  1273. * If the last (sub)command does not implement either {@code Runnable} or {@code Callable}, an {@code ExecutionException}
  1274. * is thrown detailing the problem and capturing the offending {@code CommandLine} object.
  1275. *
  1276. * @param parsedCommands the {@code CommandLine} objects that resulted from successfully parsing the command line arguments
  1277. * @param out the {@code PrintStream} to print help to if requested
  1278. * @param ansi for printing help messages using ANSI styles and colors
  1279. * @return an empty list if help was requested, or a list containing a single element: the result of calling the
  1280. * {@code Callable}, or a {@code null} element if the last (sub)command was a {@code Runnable}
  1281. * @throws ParameterException if the {@link HelpCommand HelpCommand} was invoked for an unknown subcommand. Any {@code ParameterExceptions}
  1282. * thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler}
  1283. * @throws ExecutionException if a problem occurred while processing the parse results; use
  1284. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1285. */
  1286. public List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) {
  1287. if (printHelpIfRequested(parsedCommands, out, err(), ansi)) { return returnResultOrExit(Collections.emptyList()); }
  1288. return returnResultOrExit(execute(parsedCommands.get(parsedCommands.size() - 1), new ArrayList<Object>()));
  1289. }
  1290. /** Executes the most specific {@code Runnable} or {@code Callable} subcommand.
  1291. * If the last (sub)command does not implement either {@code Runnable} or {@code Callable}, an {@code ExecutionException}
  1292. * is thrown detailing the problem and capturing the offending {@code CommandLine} object.
  1293. *
  1294. * @param parseResult the {@code ParseResult} that resulted from successfully parsing the command line arguments
  1295. * @return an empty list if help was requested, or a list containing a single element: the result of calling the
  1296. * {@code Callable}, or a {@code null} element if the last (sub)command was a {@code Runnable}
  1297. * @throws ExecutionException if a problem occurred while processing the parse results; use
  1298. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1299. * @since 3.0 */
  1300. protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
  1301. List<CommandLine> parsedCommands = parseResult.asCommandLineList();
  1302. return execute(parsedCommands.get(parsedCommands.size() - 1), new ArrayList<Object>());
  1303. }
  1304. @Override protected RunLast self() { return this; }
  1305. }
  1306. /**
  1307. * Command line parse result handler that prints help if requested, and otherwise executes the top-level command and
  1308. * all subcommands as {@code Runnable} or {@code Callable}.
  1309. * For use in the {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...) parseWithHandler} methods.
  1310. * @since 2.0 */
  1311. public static class RunAll extends AbstractParseResultHandler<List<Object>> implements IParseResultHandler {
  1312. /** Prints help if requested, and otherwise executes the top-level command and all subcommands as {@code Runnable}
  1313. * or {@code Callable}. Finally, either a list of result objects is returned, or the JVM is terminated if an exit
  1314. * code {@linkplain #andExit(int) was set}. If any of the {@code CommandLine} commands does not implement either
  1315. * {@code Runnable} or {@code Callable}, an {@code ExecutionException}
  1316. * is thrown detailing the problem and capturing the offending {@code CommandLine} object.
  1317. *
  1318. * @param parsedCommands the {@code CommandLine} objects that resulted from successfully parsing the command line arguments
  1319. * @param out the {@code PrintStream} to print help to if requested
  1320. * @param ansi for printing help messages using ANSI styles and colors
  1321. * @return an empty list if help was requested, or a list containing the result of executing all commands:
  1322. * the return values from calling the {@code Callable} commands, {@code null} elements for commands that implement {@code Runnable}
  1323. * @throws ParameterException if the {@link HelpCommand HelpCommand} was invoked for an unknown subcommand. Any {@code ParameterExceptions}
  1324. * thrown from this method are treated as if this exception was thrown during parsing and passed to the {@link IExceptionHandler}
  1325. * @throws ExecutionException if a problem occurred while processing the parse results; use
  1326. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1327. */
  1328. public List<Object> handleParseResult(List<CommandLine> parsedCommands, PrintStream out, Help.Ansi ansi) {
  1329. if (printHelpIfRequested(parsedCommands, out, err(), ansi)) { return returnResultOrExit(Collections.emptyList()); }
  1330. List<Object> result = new ArrayList<Object>();
  1331. for (CommandLine parsed : parsedCommands) {
  1332. execute(parsed, result);
  1333. }
  1334. return returnResultOrExit(result);
  1335. }
  1336. /** Executes the top-level command and all subcommands as {@code Runnable} or {@code Callable}.
  1337. * If any of the {@code CommandLine} commands does not implement either {@code Runnable} or {@code Callable}, an {@code ExecutionException}
  1338. * is thrown detailing the problem and capturing the offending {@code CommandLine} object.
  1339. *
  1340. * @param parseResult the {@code ParseResult} that resulted from successfully parsing the command line arguments
  1341. * @return an empty list if help was requested, or a list containing the result of executing all commands:
  1342. * the return values from calling the {@code Callable} commands, {@code null} elements for commands that implement {@code Runnable}
  1343. * @throws ExecutionException if a problem occurred while processing the parse results; use
  1344. * {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1345. * @since 3.0 */
  1346. protected List<Object> handle(ParseResult parseResult) throws ExecutionException {
  1347. List<Object> result = new ArrayList<Object>();
  1348. execute(parseResult.commandSpec().commandLine(), result);
  1349. while (parseResult.hasSubcommand()) {
  1350. parseResult = parseResult.subcommand();
  1351. execute(parseResult.commandSpec().commandLine(), result);
  1352. }
  1353. return returnResultOrExit(result);
  1354. }
  1355. @Override protected RunAll self() { return this; }
  1356. }
  1357. /** @deprecated use {@link #parseWithHandler(IParseResultHandler2, String[])} instead
  1358. * @since 2.0 */
  1359. @Deprecated public List<Object> parseWithHandler(IParseResultHandler handler, PrintStream out, String... args) {
  1360. return parseWithHandlers(handler, out, Help.Ansi.AUTO, defaultExceptionHandler(), args);
  1361. }
  1362. /**
  1363. * Returns the result of calling {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)} with
  1364. * a new {@link DefaultExceptionHandler} in addition to the specified parse result handler and the specified command line arguments.
  1365. * <p>
  1366. * This is a convenience method intended to offer the same ease of use as the {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...) run}
  1367. * and {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...) call} methods, but with more flexibility and better
  1368. * support for nested subcommands.
  1369. * </p>
  1370. * <p>Calling this method roughly expands to:</p>
  1371. * <pre>{@code
  1372. * try {
  1373. * ParseResult parseResult = parseArgs(args);
  1374. * return handler.handleParseResult(parseResult);
  1375. * } catch (ParameterException ex) {
  1376. * return new DefaultExceptionHandler<R>().handleParseException(ex, args);
  1377. * }
  1378. * }</pre>
  1379. * <p>
  1380. * Picocli provides some default handlers that allow you to accomplish some common tasks with very little code.
  1381. * The following handlers are available:</p>
  1382. * <ul>
  1383. * <li>{@link RunLast} handler prints help if requested, and otherwise gets the last specified command or subcommand
  1384. * and tries to execute it as a {@code Runnable} or {@code Callable}.</li>
  1385. * <li>{@link RunFirst} handler prints help if requested, and otherwise executes the top-level command as a {@code Runnable} or {@code Callable}.</li>
  1386. * <li>{@link RunAll} handler prints help if requested, and otherwise executes all recognized commands and subcommands as {@code Runnable} or {@code Callable} tasks.</li>
  1387. * <li>{@link DefaultExceptionHandler} prints the error message followed by usage help</li>
  1388. * </ul>
  1389. * @param <R> the return type of this handler
  1390. * @param handler the function that will handle the result of successfully parsing the command line arguments
  1391. * @param args the command line arguments
  1392. * @return an object resulting from handling the parse result or the exception that occurred while parsing the input
  1393. * @throws ExecutionException if the command line arguments were parsed successfully but a problem occurred while processing the
  1394. * parse results; use {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1395. * @see RunLast
  1396. * @see RunAll
  1397. * @since 3.0 */
  1398. public <R> R parseWithHandler(IParseResultHandler2<R> handler, String[] args) {
  1399. return parseWithHandlers(handler, new DefaultExceptionHandler<R>(), args);
  1400. }
  1401. /** @deprecated use {@link #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)} instead
  1402. * @since 2.0 */
  1403. @Deprecated public List<Object> parseWithHandlers(IParseResultHandler handler, PrintStream out, Help.Ansi ansi, IExceptionHandler exceptionHandler, String... args) {
  1404. try {
  1405. List<CommandLine> result = parse(args);
  1406. return handler.handleParseResult(result, out, ansi);
  1407. } catch (ParameterException ex) {
  1408. return exceptionHandler.handleException(ex, out, ansi, args);
  1409. }
  1410. }
  1411. /**
  1412. * Tries to {@linkplain #parseArgs(String...) parse} the specified command line arguments, and if successful, delegates
  1413. * the processing of the resulting {@code ParseResult} object to the specified {@linkplain IParseResultHandler2 handler}.
  1414. * If the command line arguments were invalid, the {@code ParameterException} thrown from the {@code parse} method
  1415. * is caught and passed to the specified {@link IExceptionHandler2}.
  1416. * <p>
  1417. * This is a convenience method intended to offer the same ease of use as the {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...) run}
  1418. * and {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...) call} methods, but with more flexibility and better
  1419. * support for nested subcommands.
  1420. * </p>
  1421. * <p>Calling this method roughly expands to:</p>
  1422. * <pre>
  1423. * ParseResult parseResult = null;
  1424. * try {
  1425. * parseResult = parseArgs(args);
  1426. * return handler.handleParseResult(parseResult);
  1427. * } catch (ParameterException ex) {
  1428. * return exceptionHandler.handleParseException(ex, (String[]) args);
  1429. * } catch (ExecutionException ex) {
  1430. * return exceptionHandler.handleExecutionException(ex, parseResult);
  1431. * }
  1432. * </pre>
  1433. * <p>
  1434. * Picocli provides some default handlers that allow you to accomplish some common tasks with very little code.
  1435. * The following handlers are available:</p>
  1436. * <ul>
  1437. * <li>{@link RunLast} handler prints help if requested, and otherwise gets the last specified command or subcommand
  1438. * and tries to execute it as a {@code Runnable} or {@code Callable}.</li>
  1439. * <li>{@link RunFirst} handler prints help if requested, and otherwise executes the top-level command as a {@code Runnable} or {@code Callable}.</li>
  1440. * <li>{@link RunAll} handler prints help if requested, and otherwise executes all recognized commands and subcommands as {@code Runnable} or {@code Callable} tasks.</li>
  1441. * <li>{@link DefaultExceptionHandler} prints the error message followed by usage help</li>
  1442. * </ul>
  1443. *
  1444. * @param handler the function that will handle the result of successfully parsing the command line arguments
  1445. * @param exceptionHandler the function that can handle the {@code ParameterException} thrown when the command line arguments are invalid
  1446. * @param args the command line arguments
  1447. * @return an object resulting from handling the parse result or the exception that occurred while parsing the input
  1448. * @throws ExecutionException if the command line arguments were parsed successfully but a problem occurred while processing the parse
  1449. * result {@code ParseResult} object; use {@link ExecutionException#getCommandLine()} to get the command or subcommand where processing failed
  1450. * @param <R> the return type of the result handler and exception handler
  1451. * @see RunLast
  1452. * @see RunAll
  1453. * @see DefaultExceptionHandler
  1454. * @since 3.0 */
  1455. public <R> R parseWithHandlers(IParseResultHandler2<R> handler, IExceptionHandler2<R> exceptionHandler, String... args) {
  1456. ParseResult parseResult = null;
  1457. try {
  1458. parseResult = parseArgs(args);
  1459. return handler.handleParseResult(parseResult);
  1460. } catch (ParameterException ex) {
  1461. return exceptionHandler.handleParseException(ex, args);
  1462. } catch (ExecutionException ex) {
  1463. return exceptionHandler.handleExecutionException(ex, parseResult);
  1464. }
  1465. }
  1466. static String versionString() {
  1467. return String.format("%s, JVM: %s (%s %s %s), OS: %s %s %s", VERSION,
  1468. System.getProperty("java.version"), System.getProperty("java.vendor"), System.getProperty("java.vm.name"), System.getProperty("java.vm.version"),
  1469. System.getProperty("os.name"), System.getProperty("os.version"), System.getProperty("os.arch"));
  1470. }
  1471. /**
  1472. * Equivalent to {@code new CommandLine(command).usage(out)}. See {@link #usage(PrintStream)} for details.
  1473. * @param command the object annotated with {@link Command}, {@link Option} and {@link Parameters}
  1474. * @param out the print stream to print the help message to
  1475. * @throws IllegalArgumentException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1476. */
  1477. public static void usage(Object command, PrintStream out) {
  1478. toCommandLine(command, new DefaultFactory()).usage(out);
  1479. }
  1480. /**
  1481. * Equivalent to {@code new CommandLine(command).usage(out, ansi)}.
  1482. * See {@link #usage(PrintStream, Help.Ansi)} for details.
  1483. * @param command the object annotated with {@link Command}, {@link Option} and {@link Parameters}
  1484. * @param out the print stream to print the help message to
  1485. * @param ansi whether the usage message should contain ANSI escape codes or not
  1486. * @throws IllegalArgumentException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1487. */
  1488. public static void usage(Object command, PrintStream out, Help.Ansi ansi) {
  1489. toCommandLine(command, new DefaultFactory()).usage(out, ansi);
  1490. }
  1491. /**
  1492. * Equivalent to {@code new CommandLine(command).usage(out, colorScheme)}.
  1493. * See {@link #usage(PrintStream, Help.ColorScheme)} for details.
  1494. * @param command the object annotated with {@link Command}, {@link Option} and {@link Parameters}
  1495. * @param out the print stream to print the help message to
  1496. * @param colorScheme the {@code ColorScheme} defining the styles for options, parameters and commands when ANSI is enabled
  1497. * @throws IllegalArgumentException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1498. */
  1499. public static void usage(Object command, PrintStream out, Help.ColorScheme colorScheme) {
  1500. toCommandLine(command, new DefaultFactory()).usage(out, colorScheme);
  1501. }
  1502. /**
  1503. * Delegates to {@link #usage(PrintStream, Help.Ansi)} with the {@linkplain Help.Ansi#AUTO platform default}.
  1504. * @param out the printStream to print to
  1505. * @see #usage(PrintStream, Help.ColorScheme)
  1506. */
  1507. public void usage(PrintStream out) { usage(out, Help.Ansi.AUTO); }
  1508. /**
  1509. * Delegates to {@link #usage(PrintWriter, Help.Ansi)} with the {@linkplain Help.Ansi#AUTO platform default}.
  1510. * @param writer the PrintWriter to print to
  1511. * @see #usage(PrintWriter, Help.ColorScheme)
  1512. * @since 3.0 */
  1513. public void usage(PrintWriter writer) { usage(writer, Help.Ansi.AUTO); }
  1514. /**
  1515. * Delegates to {@link #usage(PrintStream, Help.ColorScheme)} with the {@linkplain Help#defaultColorScheme(CommandLine.Help.Ansi) default color scheme}.
  1516. * @param out the printStream to print to
  1517. * @param ansi whether the usage message should include ANSI escape codes or not
  1518. * @see #usage(PrintStream, Help.ColorScheme)
  1519. */
  1520. public void usage(PrintStream out, Help.Ansi ansi) { usage(out, Help.defaultColorScheme(ansi)); }
  1521. /** Similar to {@link #usage(PrintStream, Help.Ansi)} but with the specified {@code PrintWriter} instead of a {@code PrintStream}.
  1522. * @since 3.0 */
  1523. public void usage(PrintWriter writer, Help.Ansi ansi) { usage(writer, Help.defaultColorScheme(ansi)); }
  1524. /**
  1525. * Prints a usage help message for the annotated command class to the specified {@code PrintStream}.
  1526. * Delegates construction of the usage help message to the {@link Help} inner class and is equivalent to:
  1527. * <pre>
  1528. * Help.ColorScheme colorScheme = Help.defaultColorScheme(Help.Ansi.AUTO);
  1529. * Help help = getHelpFactory().create(getCommandSpec(), colorScheme)
  1530. * StringBuilder sb = new StringBuilder();
  1531. * for (String key : getHelpSectionKeys()) {
  1532. * IHelpSectionRenderer renderer = getHelpSectionMap().get(key);
  1533. * if (renderer != null) { sb.append(renderer.render(help)); }
  1534. * }
  1535. * out.print(sb);
  1536. * </pre>
  1537. * <p>Annotate your class with {@link Command} to control many aspects of the usage help message, including
  1538. * the program name, text of section headings and section contents, and some aspects of the auto-generated sections
  1539. * of the usage help message.
  1540. * <p>To customize the auto-generated sections of the usage help message, like how option details are displayed,
  1541. * instantiate a {@link Help} object and use a {@link Help.TextTable} with more of fewer columns, a custom
  1542. * {@linkplain Help.Layout layout}, and/or a custom option {@linkplain Help.IOptionRenderer renderer}
  1543. * for ultimate control over which aspects of an Option or Field are displayed where.</p>
  1544. * @param out the {@code PrintStream} to print the usage help message to
  1545. * @param colorScheme the {@code ColorScheme} defining the styles for options, parameters and commands when ANSI is enabled
  1546. * @see UsageMessageSpec
  1547. */
  1548. public void usage(PrintStream out, Help.ColorScheme colorScheme) {
  1549. out.print(usage(new StringBuilder(), getHelpFactory().create(getCommandSpec(), colorScheme)));
  1550. }
  1551. /** Similar to {@link #usage(PrintStream, Help.ColorScheme)}, but with the specified {@code PrintWriter} instead of a {@code PrintStream}.
  1552. * @since 3.0 */
  1553. public void usage(PrintWriter writer, Help.ColorScheme colorScheme) {
  1554. writer.print(usage(new StringBuilder(), getHelpFactory().create(getCommandSpec(), colorScheme)));
  1555. }
  1556. /** Similar to {@link #usage(PrintStream)}, but returns the usage help message as a String instead of printing it to the {@code PrintStream}.
  1557. * @since 3.2 */
  1558. public String getUsageMessage() {
  1559. return usage(new StringBuilder(), getHelpFactory().create(getCommandSpec(), Help.defaultColorScheme(Help.Ansi.AUTO))).toString();
  1560. }
  1561. /** Similar to {@link #usage(PrintStream, Help.Ansi)}, but returns the usage help message as a String instead of printing it to the {@code PrintStream}.
  1562. * @since 3.2 */
  1563. public String getUsageMessage(Help.Ansi ansi) {
  1564. return usage(new StringBuilder(), getHelpFactory().create(getCommandSpec(), Help.defaultColorScheme(ansi))).toString();
  1565. }
  1566. /** Similar to {@link #usage(PrintStream, Help.ColorScheme)}, but returns the usage help message as a String instead of printing it to the {@code PrintStream}.
  1567. * @since 3.2 */
  1568. public String getUsageMessage(Help.ColorScheme colorScheme) {
  1569. return usage(new StringBuilder(), getHelpFactory().create(getCommandSpec(), colorScheme)).toString();
  1570. }
  1571. private StringBuilder usage(StringBuilder sb, Help help) {
  1572. for (String key : getHelpSectionKeys()) {
  1573. IHelpSectionRenderer renderer = getHelpSectionMap().get(key);
  1574. if (renderer != null) { sb.append(renderer.render(help)); }
  1575. }
  1576. return sb;
  1577. }
  1578. /**
  1579. * Delegates to {@link #printVersionHelp(PrintStream, Help.Ansi)} with the {@linkplain Help.Ansi#AUTO platform default}.
  1580. * @param out the printStream to print to
  1581. * @see #printVersionHelp(PrintStream, Help.Ansi)
  1582. * @since 0.9.8
  1583. */
  1584. public void printVersionHelp(PrintStream out) { printVersionHelp(out, Help.Ansi.AUTO); }
  1585. /**
  1586. * Prints version information from the {@link Command#version()} annotation to the specified {@code PrintStream}.
  1587. * Each element of the array of version strings is printed on a separate line. Version strings may contain
  1588. * <a href="http://picocli.info/#_usage_help_with_styles_and_colors">markup for colors and style</a>.
  1589. * @param out the printStream to print to
  1590. * @param ansi whether the usage message should include ANSI escape codes or not
  1591. * @see Command#version()
  1592. * @see Option#versionHelp()
  1593. * @see #isVersionHelpRequested()
  1594. * @since 0.9.8
  1595. */
  1596. public void printVersionHelp(PrintStream out, Help.Ansi ansi) {
  1597. for (String versionInfo : getCommandSpec().version()) {
  1598. out.println(ansi.new Text(versionInfo));
  1599. }
  1600. }
  1601. /**
  1602. * Prints version information from the {@link Command#version()} annotation to the specified {@code PrintStream}.
  1603. * Each element of the array of version strings is {@linkplain String#format(String, Object...) formatted} with the
  1604. * specified parameters, and printed on a separate line. Both version strings and parameters may contain
  1605. * <a href="http://picocli.info/#_usage_help_with_styles_and_colors">markup for colors and style</a>.
  1606. * @param out the printStream to print to
  1607. * @param ansi whether the usage message should include ANSI escape codes or not
  1608. * @param params Arguments referenced by the format specifiers in the version strings
  1609. * @see Command#version()
  1610. * @see Option#versionHelp()
  1611. * @see #isVersionHelpRequested()
  1612. * @since 1.0.0
  1613. */
  1614. public void printVersionHelp(PrintStream out, Help.Ansi ansi, Object... params) {
  1615. for (String versionInfo : getCommandSpec().version()) {
  1616. out.println(ansi.new Text(format(versionInfo, params)));
  1617. }
  1618. }
  1619. /**
  1620. * Delegates to {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.out} for
  1621. * requested usage help messages, {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1622. * @param callable the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1623. * @param args the command line arguments to parse
  1624. * @param <C> the annotated object must implement Callable
  1625. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1626. * @see #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)
  1627. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1628. * @throws ExecutionException if the Callable throws an exception
  1629. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1630. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1631. * @since 3.0
  1632. */
  1633. public static <C extends Callable<T>, T> T call(C callable, String... args) {
  1634. return call(callable, System.out, System.err, Help.Ansi.AUTO, args);
  1635. }
  1636. /**
  1637. * Delegates to {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.err} for
  1638. * diagnostic error messages and {@link Help.Ansi#AUTO}.
  1639. * @param callable the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1640. * @param out the printStream to print the usage help message to when the user requested help
  1641. * @param args the command line arguments to parse
  1642. * @param <C> the annotated object must implement Callable
  1643. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1644. * @see #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)
  1645. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1646. * @throws ExecutionException if the Callable throws an exception
  1647. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1648. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1649. * @see RunLast
  1650. */
  1651. public static <C extends Callable<T>, T> T call(C callable, PrintStream out, String... args) {
  1652. return call(callable, out, System.err, Help.Ansi.AUTO, args);
  1653. }
  1654. /**
  1655. * Delegates to {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.err} for diagnostic error messages.
  1656. * @param callable the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1657. * @param out the printStream to print the usage help message to when the user requested help
  1658. * @param ansi the ANSI style to use
  1659. * @param args the command line arguments to parse
  1660. * @param <C> the annotated object must implement Callable
  1661. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1662. * @see #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)
  1663. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1664. * @throws ExecutionException if the Callable throws an exception
  1665. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1666. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1667. * @see RunLast
  1668. */
  1669. public static <C extends Callable<T>, T> T call(C callable, PrintStream out, Help.Ansi ansi, String... args) {
  1670. return call(callable, out, System.err, ansi, args);
  1671. }
  1672. /**
  1673. * Convenience method to allow command line application authors to avoid some boilerplate code in their application.
  1674. * The annotated object needs to implement {@link Callable}. Calling this method is equivalent to:
  1675. * <pre>{@code
  1676. * CommandLine cmd = new CommandLine(callable);
  1677. * List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi),
  1678. * new DefaultExceptionHandler().useErr(err).useAnsi(ansi),
  1679. * args);
  1680. * T result = results == null || results.isEmpty() ? null : (T) results.get(0);
  1681. * return result;
  1682. * }</pre>
  1683. * <p>
  1684. * If the specified Callable command has subcommands, the {@linkplain RunLast last} subcommand specified on the
  1685. * command line is executed.
  1686. * Commands with subcommands may be interested in calling the {@link #parseWithHandler(IParseResultHandler2, String[]) parseWithHandler}
  1687. * method with the {@link RunAll} handler or a custom handler.
  1688. * </p><p>
  1689. * Use {@link #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...) call(Class, IFactory, ...)} instead of this method
  1690. * if you want to use a factory that performs Dependency Injection.
  1691. * </p>
  1692. * @param callable the command to call when {@linkplain #parse(String...) parsing} succeeds.
  1693. * @param out the printStream to print the usage help message to when the user requested help
  1694. * @param err the printStream to print diagnostic messages to
  1695. * @param ansi whether the usage message should include ANSI escape codes or not
  1696. * @param args the command line arguments to parse
  1697. * @param <C> the annotated object must implement Callable
  1698. * @param <T> the return type of the specified {@code Callable}
  1699. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1700. * @throws ExecutionException if the Callable throws an exception
  1701. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1702. * @see #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1703. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1704. * @see RunLast
  1705. * @since 3.0
  1706. */
  1707. public static <C extends Callable<T>, T> T call(C callable, PrintStream out, PrintStream err, Help.Ansi ansi, String... args) {
  1708. CommandLine cmd = new CommandLine(callable);
  1709. List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
  1710. @SuppressWarnings("unchecked") T result = (results == null || results.isEmpty()) ? null : (T) results.get(0);
  1711. return result;
  1712. }
  1713. /**
  1714. * Delegates to {@link #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.out} for
  1715. * requested usage help messages, {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1716. * @param callableClass class of the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1717. * @param factory the factory responsible for instantiating the specified callable class and potentially inject other components
  1718. * @param args the command line arguments to parse
  1719. * @param <C> the annotated class must implement Callable
  1720. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1721. * @see #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1722. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1723. * @throws ExecutionException if the Callable throws an exception
  1724. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1725. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1726. * @since 3.2
  1727. */
  1728. public static <C extends Callable<T>, T> T call(Class<C> callableClass, IFactory factory, String... args) {
  1729. return call(callableClass, factory, System.out, System.err, Help.Ansi.AUTO, args);
  1730. }
  1731. /**
  1732. * Delegates to {@link #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)} with
  1733. * {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1734. * @param callableClass class of the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1735. * @param factory the factory responsible for instantiating the specified callable class and potentially injecting other components
  1736. * @param out the printStream to print the usage help message to when the user requested help
  1737. * @param args the command line arguments to parse
  1738. * @param <C> the annotated class must implement Callable
  1739. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1740. * @see #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1741. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1742. * @throws ExecutionException if the Callable throws an exception
  1743. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1744. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1745. * @since 3.2
  1746. */
  1747. public static <C extends Callable<T>, T> T call(Class<C> callableClass, IFactory factory, PrintStream out, String... args) {
  1748. return call(callableClass, factory, out, System.err, Help.Ansi.AUTO, args);
  1749. }
  1750. /**
  1751. * Delegates to {@link #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)} with
  1752. * {@code System.err} for diagnostic error messages.
  1753. * @param callableClass class of the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1754. * @param factory the factory responsible for instantiating the specified callable class and potentially injecting other components
  1755. * @param out the printStream to print the usage help message to when the user requested help
  1756. * @param ansi the ANSI style to use
  1757. * @param args the command line arguments to parse
  1758. * @param <C> the annotated class must implement Callable
  1759. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1760. * @see #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1761. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1762. * @throws ExecutionException if the Callable throws an exception
  1763. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1764. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1765. * @since 3.2
  1766. */
  1767. public static <C extends Callable<T>, T> T call(Class<C> callableClass, IFactory factory, PrintStream out, Help.Ansi ansi, String... args) {
  1768. return call(callableClass, factory, out, System.err, ansi, args);
  1769. }
  1770. /**
  1771. * Convenience method to allow command line application authors to avoid some boilerplate code in their application.
  1772. * The specified {@linkplain IFactory factory} will create an instance of the specified {@code callableClass};
  1773. * use this method instead of {@link #call(Callable, PrintStream, PrintStream, Help.Ansi, String...) call(Callable, ...)}
  1774. * if you want to use a factory that performs Dependency Injection.
  1775. * The annotated class needs to implement {@link Callable}. Calling this method is equivalent to:
  1776. * <pre>{@code
  1777. * CommandLine cmd = new CommandLine(callableClass, factory);
  1778. * List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi),
  1779. * new DefaultExceptionHandler().useErr(err).useAnsi(ansi),
  1780. * args);
  1781. * T result = results == null || results.isEmpty() ? null : (T) results.get(0);
  1782. * return result;
  1783. * }</pre>
  1784. * <p>
  1785. * If the specified Callable command has subcommands, the {@linkplain RunLast last} subcommand specified on the
  1786. * command line is executed.
  1787. * Commands with subcommands may be interested in calling the {@link #parseWithHandler(IParseResultHandler2, String[]) parseWithHandler}
  1788. * method with the {@link RunAll} handler or a custom handler.
  1789. * </p>
  1790. * @param callableClass class of the command to call when {@linkplain #parseArgs(String...) parsing} succeeds.
  1791. * @param factory the factory responsible for instantiating the specified callable class and potentially injecting other components
  1792. * @param out the printStream to print the usage help message to when the user requested help
  1793. * @param err the printStream to print diagnostic messages to
  1794. * @param ansi the ANSI style to use
  1795. * @param args the command line arguments to parse
  1796. * @param <C> the annotated class must implement Callable
  1797. * @param <T> the return type of the most specific command (must implement {@code Callable})
  1798. * @see #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1799. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1800. * @throws ExecutionException if the Callable throws an exception
  1801. * @return {@code null} if an error occurred while parsing the command line options, or if help was requested and printed. Otherwise returns the result of calling the Callable
  1802. * @see #call(Callable, PrintStream, PrintStream, Help.Ansi, String...)
  1803. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1804. * @since 3.2
  1805. */
  1806. public static <C extends Callable<T>, T> T call(Class<C> callableClass, IFactory factory, PrintStream out, PrintStream err, Help.Ansi ansi, String... args) {
  1807. CommandLine cmd = new CommandLine(callableClass, factory);
  1808. List<Object> results = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
  1809. @SuppressWarnings("unchecked") T result = (results == null || results.isEmpty()) ? null : (T) results.get(0);
  1810. return result;
  1811. }
  1812. /**
  1813. * Delegates to {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.out} for
  1814. * requested usage help messages, {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1815. * @param runnable the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1816. * @param args the command line arguments to parse
  1817. * @param <R> the annotated object must implement Runnable
  1818. * @see #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)
  1819. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1820. * @throws ExecutionException if the Runnable throws an exception
  1821. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1822. * @see RunLast
  1823. * @since 3.0
  1824. */
  1825. public static <R extends Runnable> void run(R runnable, String... args) {
  1826. run(runnable, System.out, System.err, Help.Ansi.AUTO, args);
  1827. }
  1828. /**
  1829. * Delegates to {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.err} for diagnostic error messages and {@link Help.Ansi#AUTO}.
  1830. * @param runnable the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1831. * @param out the printStream to print the usage help message to when the user requested help
  1832. * @param args the command line arguments to parse
  1833. * @param <R> the annotated object must implement Runnable
  1834. * @see #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)
  1835. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1836. * @throws ExecutionException if the Runnable throws an exception
  1837. * @see #parseWithHandler(IParseResultHandler2, String[])
  1838. * @see RunLast
  1839. */
  1840. public static <R extends Runnable> void run(R runnable, PrintStream out, String... args) {
  1841. run(runnable, out, System.err, Help.Ansi.AUTO, args);
  1842. }
  1843. /**
  1844. * Delegates to {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.err} for diagnostic error messages.
  1845. * @param runnable the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1846. * @param out the printStream to print the usage help message to when the user requested help
  1847. * @param ansi whether the usage message should include ANSI escape codes or not
  1848. * @param args the command line arguments to parse
  1849. * @param <R> the annotated object must implement Runnable
  1850. * @see #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)
  1851. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1852. * @throws ExecutionException if the Runnable throws an exception
  1853. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1854. * @see RunLast
  1855. */
  1856. public static <R extends Runnable> void run(R runnable, PrintStream out, Help.Ansi ansi, String... args) {
  1857. run(runnable, out, System.err, ansi, args);
  1858. }
  1859. /**
  1860. * Convenience method to allow command line application authors to avoid some boilerplate code in their application.
  1861. * The annotated object needs to implement {@link Runnable}. Calling this method is equivalent to:
  1862. * <pre>{@code
  1863. * CommandLine cmd = new CommandLine(runnable);
  1864. * cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi),
  1865. * new DefaultExceptionHandler().useErr(err).useAnsi(ansi),
  1866. * args);
  1867. * }</pre>
  1868. * <p>
  1869. * If the specified Runnable command has subcommands, the {@linkplain RunLast last} subcommand specified on the
  1870. * command line is executed.
  1871. * Commands with subcommands may be interested in calling the {@link #parseWithHandler(IParseResultHandler2, String[]) parseWithHandler}
  1872. * method with the {@link RunAll} handler or a custom handler.
  1873. * </p><p>
  1874. * From picocli v2.0, this method prints usage help or version help if {@linkplain #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi) requested},
  1875. * and any exceptions thrown by the {@code Runnable} are caught and rethrown wrapped in an {@code ExecutionException}.
  1876. * </p><p>
  1877. * Use {@link #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...) run(Class, IFactory, ...)} instead of this method
  1878. * if you want to use a factory that performs Dependency Injection.
  1879. * </p>
  1880. * @param runnable the command to run when {@linkplain #parse(String...) parsing} succeeds.
  1881. * @param out the printStream to print the usage help message to when the user requested help
  1882. * @param err the printStream to print diagnostic messages to
  1883. * @param ansi whether the usage message should include ANSI escape codes or not
  1884. * @param args the command line arguments to parse
  1885. * @param <R> the annotated object must implement Runnable
  1886. * @throws InitializationException if the specified command object does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1887. * @throws ExecutionException if the Runnable throws an exception
  1888. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1889. * @see RunLast
  1890. * @see #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1891. * @since 3.0
  1892. */
  1893. public static <R extends Runnable> void run(R runnable, PrintStream out, PrintStream err, Help.Ansi ansi, String... args) {
  1894. CommandLine cmd = new CommandLine(runnable);
  1895. cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
  1896. }
  1897. /**
  1898. * Delegates to {@link #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.out} for
  1899. * requested usage help messages, {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1900. * @param runnableClass class of the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1901. * @param factory the factory responsible for instantiating the specified Runnable class and potentially injecting other components
  1902. * @param args the command line arguments to parse
  1903. * @param <R> the annotated class must implement Runnable
  1904. * @see #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1905. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1906. * @throws ExecutionException if the Runnable throws an exception
  1907. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1908. * @see RunLast
  1909. * @since 3.2
  1910. */
  1911. public static <R extends Runnable> void run(Class<R> runnableClass, IFactory factory, String... args) {
  1912. run(runnableClass, factory, System.out, System.err, Help.Ansi.AUTO, args);
  1913. }
  1914. /**
  1915. * Delegates to {@link #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)} with
  1916. * {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1917. * @param runnableClass class of the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1918. * @param factory the factory responsible for instantiating the specified Runnable class and potentially injecting other components
  1919. * @param out the printStream to print the usage help message to when the user requested help
  1920. * @param args the command line arguments to parse
  1921. * @param <R> the annotated class must implement Runnable
  1922. * @see #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1923. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1924. * @throws ExecutionException if the Runnable throws an exception
  1925. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1926. * @see RunLast
  1927. * @since 3.2
  1928. */
  1929. public static <R extends Runnable> void run(Class<R> runnableClass, IFactory factory, PrintStream out, String... args) {
  1930. run(runnableClass, factory, out, System.err, Help.Ansi.AUTO, args);
  1931. }
  1932. /**
  1933. * Delegates to {@link #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)} with
  1934. * {@code System.err} for diagnostic error messages.
  1935. * @param runnableClass class of the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1936. * @param factory the factory responsible for instantiating the specified Runnable class and potentially injecting other components
  1937. * @param out the printStream to print the usage help message to when the user requested help
  1938. * @param ansi whether the usage message should include ANSI escape codes or not
  1939. * @param args the command line arguments to parse
  1940. * @param <R> the annotated class must implement Runnable
  1941. * @see #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1942. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1943. * @throws ExecutionException if the Runnable throws an exception
  1944. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1945. * @see RunLast
  1946. * @since 3.2
  1947. */
  1948. public static <R extends Runnable> void run(Class<R> runnableClass, IFactory factory, PrintStream out, Help.Ansi ansi, String... args) {
  1949. run(runnableClass, factory, out, System.err, ansi, args);
  1950. }
  1951. /**
  1952. * Convenience method to allow command line application authors to avoid some boilerplate code in their application.
  1953. * The specified {@linkplain IFactory factory} will create an instance of the specified {@code runnableClass};
  1954. * use this method instead of {@link #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...) run(Runnable, ...)}
  1955. * if you want to use a factory that performs Dependency Injection.
  1956. * The annotated class needs to implement {@link Runnable}. Calling this method is equivalent to:
  1957. * <pre>{@code
  1958. * CommandLine cmd = new CommandLine(runnableClass, factory);
  1959. * cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi),
  1960. * new DefaultExceptionHandler().useErr(err).useAnsi(ansi),
  1961. * args);
  1962. * }</pre>
  1963. * <p>
  1964. * If the specified Runnable command has subcommands, the {@linkplain RunLast last} subcommand specified on the
  1965. * command line is executed.
  1966. * Commands with subcommands may be interested in calling the {@link #parseWithHandler(IParseResultHandler2, String[]) parseWithHandler}
  1967. * method with the {@link RunAll} handler or a custom handler.
  1968. * </p><p>
  1969. * This method prints usage help or version help if {@linkplain #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi) requested},
  1970. * and any exceptions thrown by the {@code Runnable} are caught and rethrown wrapped in an {@code ExecutionException}.
  1971. * </p>
  1972. * @param runnableClass class of the command to run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1973. * @param factory the factory responsible for instantiating the specified Runnable class and potentially injecting other components
  1974. * @param out the printStream to print the usage help message to when the user requested help
  1975. * @param err the printStream to print diagnostic messages to
  1976. * @param ansi whether the usage message should include ANSI escape codes or not
  1977. * @param args the command line arguments to parse
  1978. * @param <R> the annotated class must implement Runnable
  1979. * @see #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  1980. * @throws InitializationException if the specified class cannot be instantiated by the factory, or does not have a {@link Command}, {@link Option} or {@link Parameters} annotation
  1981. * @throws ExecutionException if the Runnable throws an exception
  1982. * @see #run(Runnable, PrintStream, PrintStream, Help.Ansi, String...)
  1983. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  1984. * @see RunLast
  1985. * @since 3.2
  1986. */
  1987. public static <R extends Runnable> void run(Class<R> runnableClass, IFactory factory, PrintStream out, PrintStream err, Help.Ansi ansi, String... args) {
  1988. CommandLine cmd = new CommandLine(runnableClass, factory);
  1989. cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
  1990. }
  1991. /**
  1992. * Delegates to {@link #invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)} with {@code System.out} for
  1993. * requested usage help messages, {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  1994. * @param methodName the {@code @Command}-annotated method to build a {@link CommandSpec} model from,
  1995. * and run when {@linkplain #parseArgs(String...) parsing} succeeds.
  1996. * @param cls the class where the {@code @Command}-annotated method is declared, or a subclass
  1997. * @param args the command line arguments to parse
  1998. * @see #invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
  1999. * @throws InitializationException if the specified method does not have a {@link Command} annotation,
  2000. * or if the specified class contains multiple {@code @Command}-annotated methods with the specified name
  2001. * @throws ExecutionException if the Runnable throws an exception
  2002. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  2003. * @since 3.6
  2004. */
  2005. public static Object invoke(String methodName, Class<?> cls, String... args) {
  2006. return invoke(methodName, cls, System.out, System.err, Help.Ansi.AUTO, args);
  2007. }
  2008. /**
  2009. * Delegates to {@link #invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)} with the specified stream for
  2010. * requested usage help messages, {@code System.err} for diagnostic error messages, and {@link Help.Ansi#AUTO}.
  2011. * @param methodName the {@code @Command}-annotated method to build a {@link CommandSpec} model from,
  2012. * and run when {@linkplain #parseArgs(String...) parsing} succeeds.
  2013. * @param cls the class where the {@code @Command}-annotated method is declared, or a subclass
  2014. * @param out the printstream to print requested help message to
  2015. * @param args the command line arguments to parse
  2016. * @see #invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
  2017. * @throws InitializationException if the specified method does not have a {@link Command} annotation,
  2018. * or if the specified class contains multiple {@code @Command}-annotated methods with the specified name
  2019. * @throws ExecutionException if the Runnable throws an exception
  2020. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  2021. * @since 3.6
  2022. */
  2023. public static Object invoke(String methodName, Class<?> cls, PrintStream out, String... args) {
  2024. return invoke(methodName, cls, out, System.err, Help.Ansi.AUTO, args);
  2025. }
  2026. /**
  2027. * Delegates to {@link #invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)} with the specified stream for
  2028. * requested usage help messages, {@code System.err} for diagnostic error messages, and the specified Ansi mode.
  2029. * @param methodName the {@code @Command}-annotated method to build a {@link CommandSpec} model from,
  2030. * and run when {@linkplain #parseArgs(String...) parsing} succeeds.
  2031. * @param cls the class where the {@code @Command}-annotated method is declared, or a subclass
  2032. * @param out the printstream to print requested help message to
  2033. * @param ansi whether the usage message should include ANSI escape codes or not
  2034. * @param args the command line arguments to parse
  2035. * @see #invoke(String, Class, PrintStream, PrintStream, Help.Ansi, String...)
  2036. * @throws InitializationException if the specified method does not have a {@link Command} annotation,
  2037. * or if the specified class contains multiple {@code @Command}-annotated methods with the specified name
  2038. * @throws ExecutionException if the Runnable throws an exception
  2039. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  2040. * @since 3.6
  2041. */
  2042. public static Object invoke(String methodName, Class<?> cls, PrintStream out, Help.Ansi ansi, String... args) {
  2043. return invoke(methodName, cls, out, System.err, ansi, args);
  2044. }
  2045. /**
  2046. * Convenience method to allow command line application authors to avoid some boilerplate code in their application.
  2047. * Constructs a {@link CommandSpec} model from the {@code @Option} and {@code @Parameters}-annotated method parameters
  2048. * of the {@code @Command}-annotated method, parses the specified command line arguments and invokes the specified method.
  2049. * Calling this method is equivalent to:
  2050. * <pre>{@code
  2051. * Method commandMethod = getCommandMethods(cls, methodName).get(0);
  2052. * CommandLine cmd = new CommandLine(commandMethod);
  2053. * List<Object> list = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi),
  2054. * new DefaultExceptionHandler().useErr(err).useAnsi(ansi),
  2055. * args);
  2056. * return list == null ? null : list.get(0);
  2057. * }</pre>
  2058. * @param methodName the {@code @Command}-annotated method to build a {@link CommandSpec} model from,
  2059. * and run when {@linkplain #parseArgs(String...) parsing} succeeds.
  2060. * @param cls the class where the {@code @Command}-annotated method is declared, or a subclass
  2061. * @param out the printStream to print the usage help message to when the user requested help
  2062. * @param err the printStream to print diagnostic messages to
  2063. * @param ansi whether the usage message should include ANSI escape codes or not
  2064. * @param args the command line arguments to parse
  2065. * @throws InitializationException if the specified method does not have a {@link Command} annotation,
  2066. * or if the specified class contains multiple {@code @Command}-annotated methods with the specified name
  2067. * @throws ExecutionException if the method throws an exception
  2068. * @see #parseWithHandlers(IParseResultHandler2, IExceptionHandler2, String...)
  2069. * @since 3.6
  2070. */
  2071. public static Object invoke(String methodName, Class<?> cls, PrintStream out, PrintStream err, Help.Ansi ansi, String... args) {
  2072. List<Method> candidates = getCommandMethods(cls, methodName);
  2073. if (candidates.size() != 1) { throw new InitializationException("Expected exactly one @Command-annotated method for " + cls.getName() + "::" + methodName + "(...), but got: " + candidates); }
  2074. Method method = candidates.get(0);
  2075. CommandLine cmd = new CommandLine(method);
  2076. List<Object> list = cmd.parseWithHandlers(new RunLast().useOut(out).useAnsi(ansi), new DefaultExceptionHandler<List<Object>>().useErr(err).useAnsi(ansi), args);
  2077. return list == null ? null : list.get(0);
  2078. }
  2079. /**
  2080. * Helper to get methods of a class annotated with {@link Command @Command} via reflection, optionally filtered by method name (not {@link Command#name() @Command.name}).
  2081. * Methods have to be either public (inherited) members or be declared by {@code cls}, that is "inherited" static or protected methods will not be picked up.
  2082. *
  2083. * @param cls the class to search for methods annotated with {@code @Command}
  2084. * @param methodName if not {@code null}, return only methods whose method name (not {@link Command#name() @Command.name}) equals this string. Ignored if {@code null}.
  2085. * @return the matching command methods, or an empty list
  2086. * @see #invoke(String, Class, String...)
  2087. * @since 3.6.0
  2088. */
  2089. public static List<Method> getCommandMethods(Class<?> cls, String methodName) {
  2090. Set<Method> candidates = new HashSet<Method>();
  2091. // traverse public member methods (excludes static/non-public, includes inherited)
  2092. candidates.addAll(Arrays.asList(Assert.notNull(cls, "class").getMethods()));
  2093. // traverse directly declared methods (includes static/non-public, excludes inherited)
  2094. candidates.addAll(Arrays.asList(Assert.notNull(cls, "class").getDeclaredMethods()));
  2095. List<Method> result = new ArrayList<Method>();
  2096. for (Method method : candidates) {
  2097. if (method.isAnnotationPresent(Command.class)) {
  2098. if (methodName == null || methodName.equals(method.getName())) { result.add(method); }
  2099. }
  2100. }
  2101. Collections.sort(result, new Comparator<Method>() {
  2102. public int compare(Method o1, Method o2) { return o1.getName().compareTo(o2.getName()); }
  2103. });
  2104. return result;
  2105. }
  2106. /**
  2107. * Registers the specified type converter for the specified class. When initializing fields annotated with
  2108. * {@link Option}, the field's type is used as a lookup key to find the associated type converter, and this
  2109. * type converter converts the original command line argument string value to the correct type.
  2110. * <p>
  2111. * Java 8 lambdas make it easy to register custom type converters:
  2112. * </p>
  2113. * <pre>
  2114. * commandLine.registerConverter(java.nio.file.Path.class, s -&gt; java.nio.file.Paths.get(s));
  2115. * commandLine.registerConverter(java.time.Duration.class, s -&gt; java.time.Duration.parse(s));</pre>
  2116. * <p>
  2117. * Built-in type converters are pre-registered for the following java 1.5 types:
  2118. * </p>
  2119. * <ul>
  2120. * <li>all primitive types</li>
  2121. * <li>all primitive wrapper types: Boolean, Byte, Character, Double, Float, Integer, Long, Short</li>
  2122. * <li>any enum</li>
  2123. * <li>java.io.File</li>
  2124. * <li>java.math.BigDecimal</li>
  2125. * <li>java.math.BigInteger</li>
  2126. * <li>java.net.InetAddress</li>
  2127. * <li>java.net.URI</li>
  2128. * <li>java.net.URL</li>
  2129. * <li>java.nio.charset.Charset</li>
  2130. * <li>java.sql.Time</li>
  2131. * <li>java.util.Date</li>
  2132. * <li>java.util.UUID</li>
  2133. * <li>java.util.regex.Pattern</li>
  2134. * <li>StringBuilder</li>
  2135. * <li>CharSequence</li>
  2136. * <li>String</li>
  2137. * </ul>
  2138. * <p>The specified converter will be registered with this {@code CommandLine} and the full hierarchy of its
  2139. * subcommands and nested sub-subcommands <em>at the moment the converter is registered</em>. Subcommands added
  2140. * later will not have this converter added automatically. To ensure a custom type converter is available to all
  2141. * subcommands, register the type converter last, after adding subcommands.</p>
  2142. *
  2143. * @param cls the target class to convert parameter string values to
  2144. * @param converter the class capable of converting string values to the specified target type
  2145. * @param <K> the target type
  2146. * @return this CommandLine object, to allow method chaining
  2147. * @see #addSubcommand(String, Object)
  2148. */
  2149. public <K> CommandLine registerConverter(Class<K> cls, ITypeConverter<K> converter) {
  2150. interpreter.converterRegistry.put(Assert.notNull(cls, "class"), Assert.notNull(converter, "converter"));
  2151. for (CommandLine command : getCommandSpec().commands.values()) {
  2152. command.registerConverter(cls, converter);
  2153. }
  2154. return this;
  2155. }
  2156. /** Returns the String that separates option names from option values when parsing command line options.
  2157. * @return the String the parser uses to separate option names from option values
  2158. * @see ParserSpec#separator() */
  2159. public String getSeparator() { return getCommandSpec().parser().separator(); }
  2160. /** Sets the String the parser uses to separate option names from option values to the specified value.
  2161. * The separator may also be set declaratively with the {@link CommandLine.Command#separator()} annotation attribute.
  2162. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  2163. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  2164. * later will have the default setting. To ensure a setting is applied to all
  2165. * subcommands, call the setter last, after adding subcommands.</p>
  2166. * @param separator the String that separates option names from option values
  2167. * @see ParserSpec#separator(String)
  2168. * @return this {@code CommandLine} object, to allow method chaining */
  2169. public CommandLine setSeparator(String separator) {
  2170. getCommandSpec().parser().separator(Assert.notNull(separator, "separator"));
  2171. for (CommandLine command : getCommandSpec().subcommands().values()) {
  2172. command.setSeparator(separator);
  2173. }
  2174. return this;
  2175. }
  2176. /** Returns the ResourceBundle of this command or {@code null} if no resource bundle is set.
  2177. * @see Command#resourceBundle()
  2178. * @see CommandSpec#resourceBundle()
  2179. * @since 3.6 */
  2180. public ResourceBundle getResourceBundle() { return getCommandSpec().resourceBundle(); }
  2181. /** Sets the ResourceBundle containing usage help message strings.
  2182. * <p>The specified bundle will be registered with this {@code CommandLine} and the full hierarchy of its
  2183. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  2184. * later will not be impacted. To ensure a setting is applied to all
  2185. * subcommands, call the setter last, after adding subcommands.</p>
  2186. * @param bundle the ResourceBundle containing usage help message strings
  2187. * @return this {@code CommandLine} object, to allow method chaining
  2188. * @see Command#resourceBundle()
  2189. * @see CommandSpec#resourceBundle(ResourceBundle)
  2190. * @since 3.6 */
  2191. public CommandLine setResourceBundle(ResourceBundle bundle) {
  2192. getCommandSpec().resourceBundle(bundle);
  2193. for (CommandLine command : getCommandSpec().subcommands().values()) {
  2194. command.getCommandSpec().resourceBundle(bundle);
  2195. }
  2196. return this;
  2197. }
  2198. /** Returns the maximum width of the usage help message. The default is 80.
  2199. * @see UsageMessageSpec#width() */
  2200. public int getUsageHelpWidth() { return getCommandSpec().usageMessage().width(); }
  2201. /** Sets the maximum width of the usage help message. Longer lines are wrapped.
  2202. * <p>The specified setting will be registered with this {@code CommandLine} and the full hierarchy of its
  2203. * subcommands and nested sub-subcommands <em>at the moment this method is called</em>. Subcommands added
  2204. * later will have the default setting. To ensure a setting is applied to all
  2205. * subcommands, call the setter last, after adding subcommands.</p>
  2206. * @param width the maximum width of the usage help message
  2207. * @see UsageMessageSpec#width(int)
  2208. * @return this {@code CommandLine} object, to allow method chaining */
  2209. public CommandLine setUsageHelpWidth(int width) {
  2210. getCommandSpec().usageMessage().width(width);
  2211. for (CommandLine command : getCommandSpec().subcommands().values()) {
  2212. command.setUsageHelpWidth(width);
  2213. }
  2214. return this;
  2215. }
  2216. /** Returns the command name (also called program name) displayed in the usage help synopsis.
  2217. * @return the command name (also called program name) displayed in the usage
  2218. * @see CommandSpec#name()
  2219. * @since 2.0 */
  2220. public String getCommandName() { return getCommandSpec().name(); }
  2221. /** Sets the command name (also called program name) displayed in the usage help synopsis to the specified value.
  2222. * Note that this method only modifies the usage help message, it does not impact parsing behaviour.
  2223. * The command name may also be set declaratively with the {@link CommandLine.Command#name()} annotation attribute.
  2224. * @param commandName command name (also called program name) displayed in the usage help synopsis
  2225. * @return this {@code CommandLine} object, to allow method chaining
  2226. * @see CommandSpec#name(String)
  2227. * @since 2.0 */
  2228. public CommandLine setCommandName(String commandName) {
  2229. getCommandSpec().name(Assert.notNull(commandName, "commandName"));
  2230. return this;
  2231. }
  2232. /** Returns whether arguments starting with {@code '@'} should be treated as the path to an argument file and its
  2233. * contents should be expanded into separate arguments for each line in the specified file.
  2234. * This property is {@code true} by default.
  2235. * @return whether "argument files" or {@code @files} should be expanded into their content
  2236. * @since 2.1 */
  2237. public boolean isExpandAtFiles() { return getCommandSpec().parser().expandAtFiles(); }
  2238. /** Sets whether arguments starting with {@code '@'} should be treated as the path to an argument file and its
  2239. * contents should be expanded into separate arguments for each line in the specified file. ({@code true} by default.)
  2240. * @param expandAtFiles whether "argument files" or {@code @files} should be expanded into their content
  2241. * @return this {@code CommandLine} object, to allow method chaining
  2242. * @since 2.1 */
  2243. public CommandLine setExpandAtFiles(boolean expandAtFiles) {
  2244. getCommandSpec().parser().expandAtFiles(expandAtFiles);
  2245. return this;
  2246. }
  2247. /** Returns the character that starts a single-line comment or {@code null} if all content of argument files should
  2248. * be interpreted as arguments (without comments).
  2249. * If specified, all characters from the comment character to the end of the line are ignored.
  2250. * @return the character that starts a single-line comment or {@code null}. The default is {@code '#'}.
  2251. * @since 3.5 */
  2252. public Character getAtFileCommentChar() { return getCommandSpec().parser().atFileCommentChar(); }
  2253. /** Sets the character that starts a single-line comment or {@code null} if all content of argument files should
  2254. * be interpreted as arguments (without comments).
  2255. * If specified, all characters from the comment character to the end of the line are ignored.
  2256. * @param atFileCommentChar the character that starts a single-line comment or {@code null}. The default is {@code '#'}.
  2257. * @return this {@code CommandLine} object, to allow method chaining
  2258. * @since 3.5 */
  2259. public CommandLine setAtFileCommentChar(Character atFileCommentChar) {
  2260. getCommandSpec().parser().atFileCommentChar(atFileCommentChar);
  2261. for (CommandLine command : getCommandSpec().subcommands().values()) {
  2262. command.setAtFileCommentChar(atFileCommentChar);
  2263. }
  2264. return this;
  2265. }
  2266. /** Returns whether to use a simplified argument file format that is compatible with JCommander.
  2267. * In this format, every line (except empty lines and comment lines)
  2268. * is interpreted as a single argument. Arguments containing whitespace do not need to be quoted.
  2269. * When system property {@code "picocli.useSimplifiedAtFiles"} is defined, the system property value overrides the programmatically set value.
  2270. * @return whether to use a simplified argument file format. The default is {@code false}.
  2271. * @since 3.9 */
  2272. public boolean isUseSimplifiedAtFiles() { return getCommandSpec().parser().useSimplifiedAtFiles(); }
  2273. /** Sets whether to use a simplified argument file format that is compatible with JCommander.
  2274. * In this format, every line (except empty lines and comment lines)
  2275. * is interpreted as a single argument. Arguments containing whitespace do not need to be quoted.
  2276. * When system property {@code "picocli.useSimplifiedAtFiles"} is defined, the system property value overrides the programmatically set value.
  2277. * @param simplifiedAtFiles whether to use a simplified argument file format. The default is {@code false}.
  2278. * @return this {@code CommandLine} object, to allow method chaining
  2279. * @since 3.9 */
  2280. public CommandLine setUseSimplifiedAtFiles(boolean simplifiedAtFiles) {
  2281. getCommandSpec().parser().useSimplifiedAtFiles(simplifiedAtFiles);
  2282. for (CommandLine command : getCommandSpec().subcommands().values()) {
  2283. command.setUseSimplifiedAtFiles(simplifiedAtFiles);
  2284. }
  2285. return this;
  2286. }
  2287. private static boolean empty(String str) { return str == null || str.trim().length() == 0; }
  2288. private static boolean empty(Object[] array) { return array == null || array.length == 0; }
  2289. private static String str(String[] arr, int i) { return (arr == null || arr.length <= i) ? "" : arr[i]; }
  2290. private static boolean isBoolean(Class<?> type) { return type == Boolean.class || type == Boolean.TYPE; }
  2291. private static CommandLine toCommandLine(Object obj, IFactory factory) { return obj instanceof CommandLine ? (CommandLine) obj : new CommandLine(obj, factory);}
  2292. private static boolean isMultiValue(Class<?> cls) { return cls.isArray() || Collection.class.isAssignableFrom(cls) || Map.class.isAssignableFrom(cls); }
  2293. private static String format(String formatString, Object... params) {
  2294. try {
  2295. return formatString == null ? "" : String.format(formatString, params);
  2296. } catch (IllegalFormatException ex) {
  2297. new Tracer().warn("Could not format '%s' (Underlying error: %s). " +
  2298. "Using raw String: '%%n' format strings have not been replaced with newlines. " +
  2299. "Please ensure to escape '%%' characters with another '%%'.%n", formatString, ex.getMessage());
  2300. return formatString;
  2301. }
  2302. }
  2303. private static class NoCompletionCandidates implements Iterable<String> {
  2304. public Iterator<String> iterator() { throw new UnsupportedOperationException(); }
  2305. }
  2306. /**
  2307. * <p>
  2308. * Annotate fields in your class with {@code @Option} and picocli will initialize these fields when matching
  2309. * arguments are specified on the command line. In the case of command methods (annotated with {@code @Command}),
  2310. * command options can be defined by annotating method parameters with {@code @Option}.
  2311. * </p><p>
  2312. * Command class example:
  2313. * </p>
  2314. * <pre>
  2315. * import static picocli.CommandLine.*;
  2316. *
  2317. * public class MyClass {
  2318. * &#064;Parameters(description = "Any number of input files")
  2319. * private List&lt;File&gt; files = new ArrayList&lt;File&gt;();
  2320. *
  2321. * &#064;Option(names = { "-o", "--out" }, description = "Output file (default: print to console)")
  2322. * private File outputFile;
  2323. *
  2324. * &#064;Option(names = { "-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.")
  2325. * private boolean[] verbose;
  2326. *
  2327. * &#064;Option(names = { "-h", "--help", "-?", "-help"}, usageHelp = true, description = "Display this help and exit")
  2328. * private boolean help;
  2329. * }
  2330. * </pre>
  2331. * <p>
  2332. * A field cannot be annotated with both {@code @Parameters} and {@code @Option} or a
  2333. * {@code ParameterException} is thrown.
  2334. * </p>
  2335. */
  2336. @Retention(RetentionPolicy.RUNTIME)
  2337. @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
  2338. public @interface Option {
  2339. /**
  2340. * One or more option names. At least one option name is required.
  2341. * <p>
  2342. * Different environments have different conventions for naming options, but usually options have a prefix
  2343. * that sets them apart from parameters.
  2344. * Picocli supports all of the below styles. The default separator is {@code '='}, but this can be configured.
  2345. * </p><p>
  2346. * <b>*nix</b>
  2347. * </p><p>
  2348. * In Unix and Linux, options have a short (single-character) name, a long name or both.
  2349. * Short options
  2350. * (<a href="http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap12.html#tag_12_02">POSIX
  2351. * style</a> are single-character and are preceded by the {@code '-'} character, e.g., {@code `-v'}.
  2352. * <a href="https://www.gnu.org/software/tar/manual/html_node/Long-Options.html">GNU-style</a> long
  2353. * (or <em>mnemonic</em>) options start with two dashes in a row, e.g., {@code `--file'}.
  2354. * </p><p>Picocli supports the POSIX convention that short options can be grouped, with the last option
  2355. * optionally taking a parameter, which may be attached to the option name or separated by a space or
  2356. * a {@code '='} character. The below examples are all equivalent:
  2357. * </p><pre>
  2358. * -xvfFILE
  2359. * -xvf FILE
  2360. * -xvf=FILE
  2361. * -xv --file FILE
  2362. * -xv --file=FILE
  2363. * -x -v --file FILE
  2364. * -x -v --file=FILE
  2365. * </pre><p>
  2366. * <b>DOS</b>
  2367. * </p><p>
  2368. * DOS options mostly have upper case single-character names and start with a single slash {@code '/'} character.
  2369. * Option parameters are separated by a {@code ':'} character. Options cannot be grouped together but
  2370. * must be specified separately. For example:
  2371. * </p><pre>
  2372. * DIR /S /A:D /T:C
  2373. * </pre><p>
  2374. * <b>PowerShell</b>
  2375. * </p><p>
  2376. * Windows PowerShell options generally are a word preceded by a single {@code '-'} character, e.g., {@code `-Help'}.
  2377. * Option parameters are separated by a space or by a {@code ':'} character.
  2378. * </p>
  2379. * @return one or more option names
  2380. */
  2381. String[] names();
  2382. /**
  2383. * Indicates whether this option is required. By default this is false.
  2384. * <p>If an option is required, but a user invokes the program without specifying the required option,
  2385. * a {@link MissingParameterException} is thrown from the {@link #parse(String...)} method.</p>
  2386. * <p>Required options that are part of a {@linkplain ArgGroup group} are required <em>within the group</em>, not required within the command:
  2387. * the group's {@linkplain ArgGroup#multiplicity() multiplicity} determines whether the group itself is required or optional.</p>
  2388. * @return whether this option is required
  2389. */
  2390. boolean required() default false;
  2391. /**
  2392. * Set {@code help=true} if this option should disable validation of the remaining arguments:
  2393. * If the {@code help} option is specified, no error message is generated for missing required options.
  2394. * <p>
  2395. * This attribute is useful for special options like help ({@code -h} and {@code --help} on unix,
  2396. * {@code -?} and {@code -Help} on Windows) or version ({@code -V} and {@code --version} on unix,
  2397. * {@code -Version} on Windows).
  2398. * </p>
  2399. * <p>
  2400. * Note that the {@link #parse(String...)} method will not print help documentation. It will only set
  2401. * the value of the annotated field. It is the responsibility of the caller to inspect the annotated fields
  2402. * and take the appropriate action.
  2403. * </p>
  2404. * @return whether this option disables validation of the other arguments
  2405. * @deprecated Use {@link #usageHelp()} and {@link #versionHelp()} instead. See {@link #printHelpIfRequested(List, PrintStream, CommandLine.Help.Ansi)}
  2406. */
  2407. @Deprecated boolean help() default false;
  2408. /**
  2409. * Set {@code usageHelp=true} for the {@code --help} option that triggers display of the usage help message.
  2410. * The <a href="http://picocli.info/#_printing_help_automatically">convenience methods</a> {@code Commandline.call},
  2411. * {@code Commandline.run}, and {@code Commandline.parseWithHandler(s)} will automatically print usage help
  2412. * when an option with {@code usageHelp=true} was specified on the command line.
  2413. * <p>
  2414. * By default, <em>all</em> options and positional parameters are included in the usage help message
  2415. * <em>except when explicitly marked {@linkplain #hidden() hidden}.</em>
  2416. * </p><p>
  2417. * If this option is specified on the command line, picocli will not validate the remaining arguments (so no "missing required
  2418. * option" errors) and the {@link CommandLine#isUsageHelpRequested()} method will return {@code true}.
  2419. * </p><p>
  2420. * Alternatively, consider annotating your command with {@linkplain Command#mixinStandardHelpOptions() @Command(mixinStandardHelpOptions = true)}.
  2421. * </p>
  2422. * @return whether this option allows the user to request usage help
  2423. * @since 0.9.8
  2424. * @see #hidden()
  2425. * @see #run(Runnable, String...)
  2426. * @see #call(Callable, String...)
  2427. * @see #parseWithHandler(IParseResultHandler2, String[])
  2428. * @see #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)
  2429. */
  2430. boolean usageHelp() default false;
  2431. /**
  2432. * Set {@code versionHelp=true} for the {@code --version} option that triggers display of the version information.
  2433. * The <a href="http://picocli.info/#_printing_help_automatically">convenience methods</a> {@code Commandline.call},
  2434. * {@code Commandline.run}, and {@code Commandline.parseWithHandler(s)} will automatically print version information
  2435. * when an option with {@code versionHelp=true} was specified on the command line.
  2436. * <p>
  2437. * The version information string is obtained from the command's {@linkplain Command#version() version} annotation
  2438. * or from the {@linkplain Command#versionProvider() version provider}.
  2439. * </p><p>
  2440. * If this option is specified on the command line, picocli will not validate the remaining arguments (so no "missing required
  2441. * option" errors) and the {@link CommandLine#isUsageHelpRequested()} method will return {@code true}.
  2442. * </p><p>
  2443. * Alternatively, consider annotating your command with {@linkplain Command#mixinStandardHelpOptions() @Command(mixinStandardHelpOptions = true)}.
  2444. * </p>
  2445. * @return whether this option allows the user to request version information
  2446. * @since 0.9.8
  2447. * @see #hidden()
  2448. * @see #run(Runnable, String...)
  2449. * @see #call(Callable, String...)
  2450. * @see #parseWithHandler(IParseResultHandler2, String[])
  2451. * @see #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)
  2452. */
  2453. boolean versionHelp() default false;
  2454. /**
  2455. * Description of this option, used when generating the usage documentation. Each element of the array is rendered on a separate line.
  2456. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.
  2457. * </p><p>
  2458. * The description may contain variables that are rendered when help is requested.
  2459. * The string {@code ${DEFAULT-VALUE}} is replaced with the default value of the option. This is regardless of
  2460. * the command's {@link Command#showDefaultValues() showDefaultValues} setting or the option's {@link #showDefaultValue() showDefaultValue} setting.
  2461. * The string {@code ${COMPLETION-CANDIDATES}} is replaced with the completion candidates generated by
  2462. * {@link #completionCandidates()} in the description for this option.
  2463. * Also, embedded {@code %n} newline markers are converted to actual newlines.
  2464. * </p>
  2465. * @return the description of this option
  2466. */
  2467. String[] description() default {};
  2468. /**
  2469. * Specifies the minimum number of required parameters and the maximum number of accepted parameters.
  2470. * If an option declares a positive arity, and the user specifies an insufficient number of parameters on the
  2471. * command line, a {@link MissingParameterException} is thrown by the {@link #parse(String...)} method.
  2472. * <p>
  2473. * In many cases picocli can deduce the number of required parameters from the field's type.
  2474. * By default, flags (boolean options) have arity zero,
  2475. * and single-valued type fields (String, int, Integer, double, Double, File, Date, etc) have arity one.
  2476. * Generally, fields with types that cannot hold multiple values can omit the {@code arity} attribute.
  2477. * </p><p>
  2478. * Fields used to capture options with arity two or higher should have a type that can hold multiple values,
  2479. * like arrays or Collections. See {@link #type()} for strongly-typed Collection fields.
  2480. * </p><p>
  2481. * For example, if an option has 2 required parameters and any number of optional parameters,
  2482. * specify {@code @Option(names = "-example", arity = "2..*")}.
  2483. * </p>
  2484. * <b>A note on boolean options</b>
  2485. * <p>
  2486. * By default picocli does not expect boolean options (also called "flags" or "switches") to have a parameter.
  2487. * You can make a boolean option take a required parameter by annotating your field with {@code arity="1"}.
  2488. * For example: </p>
  2489. * <pre>&#064;Option(names = "-v", arity = "1") boolean verbose;</pre>
  2490. * <p>
  2491. * Because this boolean field is defined with arity 1, the user must specify either {@code <program> -v false}
  2492. * or {@code <program> -v true}
  2493. * on the command line, or a {@link MissingParameterException} is thrown by the {@link #parse(String...)}
  2494. * method.
  2495. * </p><p>
  2496. * To make the boolean parameter possible but optional, define the field with {@code arity = "0..1"}.
  2497. * For example: </p>
  2498. * <pre>&#064;Option(names="-v", arity="0..1") boolean verbose;</pre>
  2499. * <p>This will accept any of the below without throwing an exception:</p>
  2500. * <pre>
  2501. * -v
  2502. * -v true
  2503. * -v false
  2504. * </pre>
  2505. * @return how many arguments this option requires
  2506. */
  2507. String arity() default "";
  2508. /**
  2509. * Specify a {@code paramLabel} for the option parameter to be used in the usage help message. If omitted,
  2510. * picocli uses the field name in fish brackets ({@code '<'} and {@code '>'}) by default. Example:
  2511. * <pre>class Example {
  2512. * &#064;Option(names = {"-o", "--output"}, paramLabel="FILE", description="path of the output file")
  2513. * private File out;
  2514. * &#064;Option(names = {"-j", "--jobs"}, arity="0..1", description="Allow N jobs at once; infinite jobs with no arg.")
  2515. * private int maxJobs = -1;
  2516. * }</pre>
  2517. * <p>By default, the above gives a usage help message like the following:</p><pre>
  2518. * Usage: &lt;main class&gt; [OPTIONS]
  2519. * -o, --output FILE path of the output file
  2520. * -j, --jobs [&lt;maxJobs&gt;] Allow N jobs at once; infinite jobs with no arg.
  2521. * </pre>
  2522. * @return name of the option parameter used in the usage help message
  2523. */
  2524. String paramLabel() default "";
  2525. /** Returns whether usage syntax decorations around the {@linkplain #paramLabel() paramLabel} should be suppressed.
  2526. * The default is {@code false}: by default, the paramLabel is surrounded with {@code '['} and {@code ']'} characters
  2527. * if the value is optional and followed by ellipses ("...") when multiple values can be specified.
  2528. * @since 3.6.0 */
  2529. boolean hideParamSyntax() default false;
  2530. /** <p>
  2531. * Optionally specify a {@code type} to control exactly what Class the option parameter should be converted
  2532. * to. This may be useful when the field type is an interface or an abstract class. For example, a field can
  2533. * be declared to have type {@code java.lang.Number}, and annotating {@code @Option(type=Short.class)}
  2534. * ensures that the option parameter value is converted to a {@code Short} before setting the field value.
  2535. * </p><p>
  2536. * For array fields whose <em>component</em> type is an interface or abstract class, specify the concrete <em>component</em> type.
  2537. * For example, a field with type {@code Number[]} may be annotated with {@code @Option(type=Short.class)}
  2538. * to ensure that option parameter values are converted to {@code Short} before adding an element to the array.
  2539. * </p><p>
  2540. * Picocli will use the {@link ITypeConverter} that is
  2541. * {@linkplain #registerConverter(Class, ITypeConverter) registered} for the specified type to convert
  2542. * the raw String values before modifying the field value.
  2543. * </p><p>
  2544. * Prior to 2.0, the {@code type} attribute was necessary for {@code Collection} and {@code Map} fields,
  2545. * but starting from 2.0 picocli will infer the component type from the generic type's type arguments.
  2546. * For example, for a field of type {@code Map<TimeUnit, Long>} picocli will know the option parameter
  2547. * should be split up in key=value pairs, where the key should be converted to a {@code java.util.concurrent.TimeUnit}
  2548. * enum value, and the value should be converted to a {@code Long}. No {@code @Option(type=...)} type attribute
  2549. * is required for this. For generic types with wildcards, picocli will take the specified upper or lower bound
  2550. * as the Class to convert to, unless the {@code @Option} annotation specifies an explicit {@code type} attribute.
  2551. * </p><p>
  2552. * If the field type is a raw collection or a raw map, and you want it to contain other values than Strings,
  2553. * or if the generic type's type arguments are interfaces or abstract classes, you may
  2554. * specify a {@code type} attribute to control the Class that the option parameter should be converted to.
  2555. * @return the type(s) to convert the raw String values
  2556. */
  2557. Class<?>[] type() default {};
  2558. /**
  2559. * Optionally specify one or more {@link ITypeConverter} classes to use to convert the command line argument into
  2560. * a strongly typed value (or key-value pair for map fields). This is useful when a particular field should
  2561. * use a custom conversion that is different from the normal conversion for the field's type.
  2562. * <p>For example, for a specific field you may want to use a converter that maps the constant names defined
  2563. * in {@link java.sql.Types java.sql.Types} to the {@code int} value of these constants, but any other {@code int} fields should
  2564. * not be affected by this and should continue to use the standard int converter that parses numeric values.</p>
  2565. * @return the type converter(s) to use to convert String values to strongly typed values for this field
  2566. * @see CommandLine#registerConverter(Class, ITypeConverter)
  2567. */
  2568. Class<? extends ITypeConverter<?>>[] converter() default {};
  2569. /**
  2570. * Specify a regular expression to use to split option parameter values before applying them to the field.
  2571. * All elements resulting from the split are added to the array or Collection. Ignored for single-value fields.
  2572. * @return a regular expression to split option parameter values or {@code ""} if the value should not be split
  2573. * @see String#split(String)
  2574. */
  2575. String split() default "";
  2576. /**
  2577. * Set {@code hidden=true} if this option should not be included in the usage help message.
  2578. * @return whether this option should be excluded from the usage documentation
  2579. */
  2580. boolean hidden() default false;
  2581. /** Returns the default value of this option, before splitting and type conversion.
  2582. * @return a String that (after type conversion) will be used as the value for this option if no value was specified on the command line
  2583. * @since 3.2 */
  2584. String defaultValue() default "__no_default_value__";
  2585. /** Use this attribute to control for a specific option whether its default value should be shown in the usage
  2586. * help message. If not specified, the default value is only shown when the {@link Command#showDefaultValues()}
  2587. * is set {@code true} on the command. Use this attribute to specify whether the default value
  2588. * for this specific option should always be shown or never be shown, regardless of the command setting.
  2589. * <p>Note that picocli 3.2 allows {@linkplain #description() embedding default values} anywhere in the description that ignores this setting.</p>
  2590. * @return whether this option's default value should be shown in the usage help message
  2591. */
  2592. Help.Visibility showDefaultValue() default Help.Visibility.ON_DEMAND;
  2593. /** Use this attribute to specify an {@code Iterable<String>} class that generates completion candidates for this option.
  2594. * For map fields, completion candidates should be in {@code key=value} form.
  2595. * <p>
  2596. * Completion candidates are used in bash completion scripts generated by the {@code picocli.AutoComplete} class.
  2597. * Bash has special completion options to generate file names and host names, and the bash completion scripts
  2598. * generated by {@code AutoComplete} delegate to these bash built-ins for {@code @Options} whose {@code type} is
  2599. * {@code java.io.File}, {@code java.nio.file.Path} or {@code java.net.InetAddress}.
  2600. * </p><p>
  2601. * For {@code @Options} whose {@code type} is a Java {@code enum}, {@code AutoComplete} can generate completion
  2602. * candidates from the type. For other types, use this attribute to specify completion candidates.
  2603. * </p>
  2604. *
  2605. * @return a class whose instances can iterate over the completion candidates for this option
  2606. * @see picocli.CommandLine.IFactory
  2607. * @since 3.2 */
  2608. Class<? extends Iterable<String>> completionCandidates() default NoCompletionCandidates.class;
  2609. /**
  2610. * Set {@code interactive=true} if this option will prompt the end user for a value (like a password).
  2611. * Only supported for single-value options (not arrays, collections or maps).
  2612. * When running on Java 6 or greater, this will use the {@link Console#readPassword()} API to get a value without echoing input to the console.
  2613. * @return whether this option prompts the end user for a value to be entered on the command line
  2614. * @since 3.5
  2615. */
  2616. boolean interactive() default false;
  2617. /** ResourceBundle key for this option. If not specified, (and a ResourceBundle {@linkplain Command#resourceBundle() exists for this command}) an attempt
  2618. * is made to find the option description using any of the option names (without leading hyphens) as key.
  2619. * @see OptionSpec#description()
  2620. * @since 3.6
  2621. */
  2622. String descriptionKey() default "";
  2623. /**
  2624. * When {@link Command#sortOptions() @Command(sortOptions = false)} is specified, this attribute can be used to control the order in which options are listed in the usage help message.
  2625. * @return the position in the options list at which this option should be shown. Options with a lower number are shown before options with a higher number. Gaps are allowed.
  2626. * @since 3.9
  2627. */
  2628. int order() default -1;
  2629. /**
  2630. * Specify the name of one or more options that this option is mutually exclusive with.
  2631. * Picocli will internally create a mutually exclusive {@linkplain ArgGroup group} with all specified options (and
  2632. * any options that the specified options are mutually exclusive with).
  2633. * <p>
  2634. * Options cannot be part of multiple groups to avoid ambiguity for the parser. Constructions
  2635. * where an option is part of multiple groups must be simplified so that the option is in just one group.
  2636. * For example: {@code (-a | -b) | (-a -x)} can be simplified to {@code (-a [-x] | -b)}.
  2637. * </p>
  2638. * @return the name or names of the option(s) that this option is mutually exclusive with.
  2639. * @since 4.0
  2640. */
  2641. String[] excludes() default {};
  2642. /**
  2643. * Specify the name of one or more options that this option must co-occur with.
  2644. * Picocli will internally create a co-occurring {@linkplain ArgGroup group} with all specified options (and
  2645. * any options that the specified options must co-occur with).
  2646. * <p>
  2647. * Options cannot be part of multiple groups to avoid ambiguity for the parser. Constructions
  2648. * where an option is part of multiple groups must be simplified so that the option is in just one group.
  2649. * For example: {@code (-a -x) | (-a -y)} can be simplified to {@code (-a [-x | -y])}.
  2650. * </p>
  2651. * @return the name or names of the option(s) that this option must co-occur with.
  2652. * @since 4.0
  2653. */
  2654. String[] needs() default {};
  2655. }
  2656. /**
  2657. * <p>
  2658. * Fields annotated with {@code @Parameters} will be initialized with positional parameters. By specifying the
  2659. * {@link #index()} attribute you can pick the exact position or a range of positional parameters to apply. If no
  2660. * index is specified, the field will get all positional parameters (and so it should be an array or a collection).
  2661. * </p><p>
  2662. * In the case of command methods (annotated with {@code @Command}), method parameters may be annotated with {@code @Parameters},
  2663. * but are are considered positional parameters by default, unless they are annotated with {@code @Option}.
  2664. * </p><p>
  2665. * Command class example:
  2666. * </p>
  2667. * <pre>
  2668. * import static picocli.CommandLine.*;
  2669. *
  2670. * public class MyCalcParameters {
  2671. * &#064;Parameters(description = "Any number of input numbers")
  2672. * private List&lt;BigDecimal&gt; files = new ArrayList&lt;BigDecimal&gt;();
  2673. *
  2674. * &#064;Option(names = { "-h", "--help" }, usageHelp = true, description = "Display this help and exit")
  2675. * private boolean help;
  2676. * }
  2677. * </pre><p>
  2678. * A field cannot be annotated with both {@code @Parameters} and {@code @Option} or a {@code ParameterException}
  2679. * is thrown.</p>
  2680. */
  2681. @Retention(RetentionPolicy.RUNTIME)
  2682. @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
  2683. public @interface Parameters {
  2684. /** Specify an index ("0", or "1", etc.) to pick which of the command line arguments should be assigned to this
  2685. * field. For array or Collection fields, you can also specify an index range ("0..3", or "2..*", etc.) to assign
  2686. * a subset of the command line arguments to this field. The default is "*", meaning all command line arguments.
  2687. * @return an index or range specifying which of the command line arguments should be assigned to this field
  2688. */
  2689. String index() default "";
  2690. /** Description of the parameter(s), used when generating the usage documentation. Each element of the array is rendered on a separate line.
  2691. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.
  2692. * </p><p>
  2693. * The description may contain variables that are rendered when help is requested.
  2694. * The string {@code ${DEFAULT-VALUE}} is replaced with the default value of the positional parameter. This is regardless of
  2695. * the command's {@link Command#showDefaultValues() showDefaultValues} setting or the positional parameter's {@link #showDefaultValue() showDefaultValue} setting.
  2696. * The string {@code ${COMPLETION-CANDIDATES}} is replaced with the completion candidates generated by
  2697. * {@link #completionCandidates()} in the description for this positional parameter.
  2698. * Also, embedded {@code %n} newline markers are converted to actual newlines.
  2699. * </p>
  2700. * @return the description of the parameter(s)
  2701. */
  2702. String[] description() default {};
  2703. /**
  2704. * Specifies the minimum number of required parameters and the maximum number of accepted parameters. If a
  2705. * positive arity is declared, and the user specifies an insufficient number of parameters on the command line,
  2706. * {@link MissingParameterException} is thrown by the {@link #parse(String...)} method.
  2707. * <p>The default depends on the type of the parameter: booleans require no parameters, arrays and Collections
  2708. * accept zero to any number of parameters, and any other type accepts one parameter.</p>
  2709. * <p>For single-value parameters, setting {@code arity = "0..1"} makes a positional parameter optional, while setting {@code arity = "1"} makes it required.</p>
  2710. * <p>Required parameters that are part of a {@linkplain ArgGroup group} are required <em>within the group</em>, not required within the command:
  2711. * the group's {@linkplain ArgGroup#multiplicity() multiplicity} determines whether the group itself is required or optional.</p>
  2712. * @return the range of minimum and maximum parameters accepted by this command
  2713. */
  2714. String arity() default "";
  2715. /**
  2716. * Specify a {@code paramLabel} for the parameter to be used in the usage help message. If omitted,
  2717. * picocli uses the field name in fish brackets ({@code '<'} and {@code '>'}) by default. Example:
  2718. * <pre>class Example {
  2719. * &#064;Parameters(paramLabel="FILE", description="path of the input FILE(s)")
  2720. * private File[] inputFiles;
  2721. * }</pre>
  2722. * <p>By default, the above gives a usage help message like the following:</p><pre>
  2723. * Usage: &lt;main class&gt; [FILE...]
  2724. * [FILE...] path of the input FILE(s)
  2725. * </pre>
  2726. * @return name of the positional parameter used in the usage help message
  2727. */
  2728. String paramLabel() default "";
  2729. /** Returns whether usage syntax decorations around the {@linkplain #paramLabel() paramLabel} should be suppressed.
  2730. * The default is {@code false}: by default, the paramLabel is surrounded with {@code '['} and {@code ']'} characters
  2731. * if the value is optional and followed by ellipses ("...") when multiple values can be specified.
  2732. * @since 3.6.0 */
  2733. boolean hideParamSyntax() default false;
  2734. /**
  2735. * <p>
  2736. * Optionally specify a {@code type} to control exactly what Class the positional parameter should be converted
  2737. * to. This may be useful when the field type is an interface or an abstract class. For example, a field can
  2738. * be declared to have type {@code java.lang.Number}, and annotating {@code @Parameters(type=Short.class)}
  2739. * ensures that the positional parameter value is converted to a {@code Short} before setting the field value.
  2740. * </p><p>
  2741. * For array fields whose <em>component</em> type is an interface or abstract class, specify the concrete <em>component</em> type.
  2742. * For example, a field with type {@code Number[]} may be annotated with {@code @Parameters(type=Short.class)}
  2743. * to ensure that positional parameter values are converted to {@code Short} before adding an element to the array.
  2744. * </p><p>
  2745. * Picocli will use the {@link ITypeConverter} that is
  2746. * {@linkplain #registerConverter(Class, ITypeConverter) registered} for the specified type to convert
  2747. * the raw String values before modifying the field value.
  2748. * </p><p>
  2749. * Prior to 2.0, the {@code type} attribute was necessary for {@code Collection} and {@code Map} fields,
  2750. * but starting from 2.0 picocli will infer the component type from the generic type's type arguments.
  2751. * For example, for a field of type {@code Map<TimeUnit, Long>} picocli will know the positional parameter
  2752. * should be split up in key=value pairs, where the key should be converted to a {@code java.util.concurrent.TimeUnit}
  2753. * enum value, and the value should be converted to a {@code Long}. No {@code @Parameters(type=...)} type attribute
  2754. * is required for this. For generic types with wildcards, picocli will take the specified upper or lower bound
  2755. * as the Class to convert to, unless the {@code @Parameters} annotation specifies an explicit {@code type} attribute.
  2756. * </p><p>
  2757. * If the field type is a raw collection or a raw map, and you want it to contain other values than Strings,
  2758. * or if the generic type's type arguments are interfaces or abstract classes, you may
  2759. * specify a {@code type} attribute to control the Class that the positional parameter should be converted to.
  2760. * @return the type(s) to convert the raw String values
  2761. */
  2762. Class<?>[] type() default {};
  2763. /**
  2764. * Optionally specify one or more {@link ITypeConverter} classes to use to convert the command line argument into
  2765. * a strongly typed value (or key-value pair for map fields). This is useful when a particular field should
  2766. * use a custom conversion that is different from the normal conversion for the field's type.
  2767. * <p>For example, for a specific field you may want to use a converter that maps the constant names defined
  2768. * in {@link java.sql.Types java.sql.Types} to the {@code int} value of these constants, but any other {@code int} fields should
  2769. * not be affected by this and should continue to use the standard int converter that parses numeric values.</p>
  2770. * @return the type converter(s) to use to convert String values to strongly typed values for this field
  2771. * @see CommandLine#registerConverter(Class, ITypeConverter)
  2772. */
  2773. Class<? extends ITypeConverter<?>>[] converter() default {};
  2774. /**
  2775. * Specify a regular expression to use to split positional parameter values before applying them to the field.
  2776. * All elements resulting from the split are added to the array or Collection. Ignored for single-value fields.
  2777. * @return a regular expression to split operand values or {@code ""} if the value should not be split
  2778. * @see String#split(String)
  2779. */
  2780. String split() default "";
  2781. /**
  2782. * Set {@code hidden=true} if this parameter should not be included in the usage message.
  2783. * @return whether this parameter should be excluded from the usage message
  2784. */
  2785. boolean hidden() default false;
  2786. /** Returns the default value of this positional parameter, before splitting and type conversion.
  2787. * @return a String that (after type conversion) will be used as the value for this positional parameter if no value was specified on the command line
  2788. * @since 3.2 */
  2789. String defaultValue() default "__no_default_value__";
  2790. /** Use this attribute to control for a specific positional parameter whether its default value should be shown in the usage
  2791. * help message. If not specified, the default value is only shown when the {@link Command#showDefaultValues()}
  2792. * is set {@code true} on the command. Use this attribute to specify whether the default value
  2793. * for this specific positional parameter should always be shown or never be shown, regardless of the command setting.
  2794. * <p>Note that picocli 3.2 allows {@linkplain #description() embedding default values} anywhere in the description that ignores this setting.</p>
  2795. * @return whether this positional parameter's default value should be shown in the usage help message
  2796. */
  2797. Help.Visibility showDefaultValue() default Help.Visibility.ON_DEMAND;
  2798. /** Use this attribute to specify an {@code Iterable<String>} class that generates completion candidates for
  2799. * this positional parameter. For map fields, completion candidates should be in {@code key=value} form.
  2800. * <p>
  2801. * Completion candidates are used in bash completion scripts generated by the {@code picocli.AutoComplete} class.
  2802. * Unfortunately, {@code picocli.AutoComplete} is not very good yet at generating completions for positional parameters.
  2803. * </p>
  2804. *
  2805. * @return a class whose instances can iterate over the completion candidates for this positional parameter
  2806. * @see picocli.CommandLine.IFactory
  2807. * @since 3.2 */
  2808. Class<? extends Iterable<String>> completionCandidates() default NoCompletionCandidates.class;
  2809. /**
  2810. * Set {@code interactive=true} if this positional parameter will prompt the end user for a value (like a password).
  2811. * Only supported for single-value positional parameters (not arrays, collections or maps).
  2812. * When running on Java 6 or greater, this will use the {@link Console#readPassword()} API to get a value without echoing input to the console.
  2813. * @return whether this positional parameter prompts the end user for a value to be entered on the command line
  2814. * @since 3.5
  2815. */
  2816. boolean interactive() default false;
  2817. /** ResourceBundle key for this option. If not specified, (and a ResourceBundle {@linkplain Command#resourceBundle() exists for this command}) an attempt
  2818. * is made to find the positional parameter description using {@code paramLabel() + "[" + index() + "]"} as key.
  2819. *
  2820. * @see PositionalParamSpec#description()
  2821. * @since 3.6
  2822. */
  2823. String descriptionKey() default "";
  2824. /**
  2825. * Specify the name of one or more options that this positional parameter is mutually exclusive with.
  2826. * Picocli will internally create a mutually exclusive {@linkplain ArgGroup group} with all specified options (and
  2827. * any options and positional parameters that the specified options are mutually exclusive with).
  2828. * <p>
  2829. * An option or positional parameter cannot be part of multiple groups to avoid ambiguity for the parser. Constructions
  2830. * where an option is part of multiple groups must be simplified so that the option is in just one group.
  2831. * For example: {@code (-a | -b) | (-a -x)} can be simplified to {@code (-a [-x] | -b)}.
  2832. * </p>
  2833. * @return the name or names of the option(s) that this positional parameter is mutually exclusive with.
  2834. * @since 4.0
  2835. */
  2836. String[] excludes() default {};
  2837. /**
  2838. * Specify the name of one or more options that this option must co-occur with.
  2839. * Picocli will internally create a co-occurring {@linkplain ArgGroup group} with all specified options (and
  2840. * any options that the specified options must co-occur with).
  2841. * <p>
  2842. * Options cannot be part of multiple groups to avoid ambiguity for the parser. Constructions
  2843. * where an option is part of multiple groups must be simplified so that the option is in just one group.
  2844. * For example: {@code (-a -x) | (-a -y)} can be simplified to {@code (-a [-x | -y])}.
  2845. * </p>
  2846. * @return the name or names of the option(s) that this option must co-occur with.
  2847. * @since 4.0
  2848. */
  2849. String[] needs() default {};
  2850. }
  2851. /**
  2852. * <p>
  2853. * Fields annotated with {@code @ParentCommand} will be initialized with the parent command of the current subcommand.
  2854. * If the current command does not have a parent command, this annotation has no effect.
  2855. * </p><p>
  2856. * Parent commands often define options that apply to all the subcommands.
  2857. * This annotation offers a convenient way to inject a reference to the parent command into a subcommand, so the
  2858. * subcommand can access its parent options. For example:
  2859. * </p><pre>
  2860. * &#064;Command(name = "top", subcommands = Sub.class)
  2861. * class Top implements Runnable {
  2862. *
  2863. * &#064;Option(names = {"-d", "--directory"}, description = "this option applies to all subcommands")
  2864. * File baseDirectory;
  2865. *
  2866. * public void run() { System.out.println("Hello from top"); }
  2867. * }
  2868. *
  2869. * &#064;Command(name = "sub")
  2870. * class Sub implements Runnable {
  2871. *
  2872. * &#064;ParentCommand
  2873. * private Top parent;
  2874. *
  2875. * public void run() {
  2876. * System.out.println("Subcommand: parent command 'directory' is " + parent.baseDirectory);
  2877. * }
  2878. * }
  2879. * </pre>
  2880. * @since 2.2
  2881. */
  2882. @Retention(RetentionPolicy.RUNTIME)
  2883. @Target(ElementType.FIELD)
  2884. public @interface ParentCommand { }
  2885. /**
  2886. * Fields annotated with {@code @Unmatched} will be initialized with the list of unmatched command line arguments, if any.
  2887. * If this annotation is found, picocli automatically sets {@linkplain CommandLine#setUnmatchedArgumentsAllowed(boolean) unmatchedArgumentsAllowed} to {@code true}.
  2888. * @see CommandLine#isUnmatchedArgumentsAllowed()
  2889. * @since 3.0
  2890. */
  2891. @Retention(RetentionPolicy.RUNTIME)
  2892. @Target(ElementType.FIELD)
  2893. public @interface Unmatched { }
  2894. /**
  2895. * <p>
  2896. * Fields annotated with {@code @Mixin} are "expanded" into the current command: {@link Option @Option} and
  2897. * {@link Parameters @Parameters} in the mixin class are added to the options and positional parameters of this command.
  2898. * A {@link DuplicateOptionAnnotationsException} is thrown if any of the options in the mixin has the same name as
  2899. * an option in this command.
  2900. * </p><p>
  2901. * The {@code Mixin} annotation provides a way to reuse common options and parameters without subclassing. For example:
  2902. * </p><pre>
  2903. * class HelloWorld implements Runnable {
  2904. *
  2905. * // adds the --help and --version options to this command
  2906. * &#064;Mixin
  2907. * private HelpOptions = new HelpOptions();
  2908. *
  2909. * &#064;Option(names = {"-u", "--userName"}, required = true, description = "The user name")
  2910. * String userName;
  2911. *
  2912. * public void run() { System.out.println("Hello, " + userName); }
  2913. * }
  2914. *
  2915. * // Common reusable help options.
  2916. * class HelpOptions {
  2917. *
  2918. * &#064;Option(names = { "-h", "--help"}, usageHelp = true, description = "Display this help and exit")
  2919. * private boolean help;
  2920. *
  2921. * &#064;Option(names = { "-V", "--version"}, versionHelp = true, description = "Display version info and exit")
  2922. * private boolean versionHelp;
  2923. * }
  2924. * </pre>
  2925. * @since 3.0
  2926. */
  2927. @Retention(RetentionPolicy.RUNTIME)
  2928. @Target({ElementType.FIELD, ElementType.PARAMETER})
  2929. public @interface Mixin {
  2930. /** Optionally specify a name that the mixin object can be retrieved with from the {@code CommandSpec}.
  2931. * If not specified the name of the annotated field is used.
  2932. * @return a String to register the mixin object with, or an empty String if the name of the annotated field should be used */
  2933. String name() default "";
  2934. }
  2935. /**
  2936. * Fields annotated with {@code @Spec} will be initialized with the {@code CommandSpec} for the command the field is part of. Example usage:
  2937. * <pre>
  2938. * class InjectSpecExample implements Runnable {
  2939. * &#064;Spec CommandSpec commandSpec;
  2940. * //...
  2941. * public void run() {
  2942. * // do something with the injected objects
  2943. * }
  2944. * }
  2945. * </pre>
  2946. * @since 3.2
  2947. */
  2948. @Retention(RetentionPolicy.RUNTIME)
  2949. @Target({ElementType.FIELD, ElementType.METHOD})
  2950. public @interface Spec { }
  2951. /**
  2952. * <p>Annotate your class with {@code @Command} when you want more control over the format of the generated help
  2953. * message. From 3.6, methods can also be annotated with {@code @Command}, where the method parameters define the
  2954. * command options and positional parameters.
  2955. * </p><pre>
  2956. * &#064;Command(name = "Encrypt", mixinStandardHelpOptions = true,
  2957. * description = "Encrypt FILE(s), or standard input, to standard output or to the output file.",
  2958. * version = "Encrypt version 1.0",
  2959. * footer = "Copyright (c) 2017")
  2960. * public class Encrypt {
  2961. * &#064;Parameters(paramLabel = "FILE", description = "Any number of input files")
  2962. * private List&lt;File&gt; files = new ArrayList&lt;File&gt;();
  2963. *
  2964. * &#064;Option(names = { "-o", "--out" }, description = "Output file (default: print to console)")
  2965. * private File outputFile;
  2966. *
  2967. * &#064;Option(names = { "-v", "--verbose"}, description = "Verbose mode. Helpful for troubleshooting. Multiple -v options increase the verbosity.")
  2968. * private boolean[] verbose;
  2969. * }</pre>
  2970. * <p>
  2971. * The structure of a help message looks like this:
  2972. * </p><ul>
  2973. * <li>[header]</li>
  2974. * <li>[synopsis]: {@code Usage: <commandName> [OPTIONS] [FILE...]}</li>
  2975. * <li>[description]</li>
  2976. * <li>[parameter list]: {@code [FILE...] Any number of input files}</li>
  2977. * <li>[option list]: {@code -h, --help prints this help message and exits}</li>
  2978. * <li>[footer]</li>
  2979. * </ul> */
  2980. @Retention(RetentionPolicy.RUNTIME)
  2981. @Target({ElementType.TYPE, ElementType.LOCAL_VARIABLE, ElementType.FIELD, ElementType.PACKAGE, ElementType.METHOD})
  2982. public @interface Command {
  2983. /** Program name to show in the synopsis. If omitted, {@code "<main class>"} is used.
  2984. * For {@linkplain #subcommands() declaratively added} subcommands, this attribute is also used
  2985. * by the parser to recognize subcommands in the command line arguments.
  2986. * @return the program name to show in the synopsis
  2987. * @see CommandSpec#name()
  2988. * @see Help#commandName() */
  2989. String name() default "<main class>";
  2990. /** Alternative command names by which this subcommand is recognized on the command line.
  2991. * @return one or more alternative command names
  2992. * @since 3.1 */
  2993. String[] aliases() default {};
  2994. /** A list of classes to instantiate and register as subcommands. When registering subcommands declaratively
  2995. * like this, you don't need to call the {@link CommandLine#addSubcommand(String, Object)} method. For example, this:
  2996. * <pre>
  2997. * &#064;Command(subcommands = {
  2998. * GitStatus.class,
  2999. * GitCommit.class,
  3000. * GitBranch.class })
  3001. * public class Git { ... }
  3002. *
  3003. * CommandLine commandLine = new CommandLine(new Git());
  3004. * </pre> is equivalent to this:
  3005. * <pre>
  3006. * // alternative: programmatically add subcommands.
  3007. * // NOTE: in this case there should be no `subcommands` attribute on the @Command annotation.
  3008. * &#064;Command public class Git { ... }
  3009. *
  3010. * CommandLine commandLine = new CommandLine(new Git())
  3011. * .addSubcommand("status", new GitStatus())
  3012. * .addSubcommand("commit", new GitCommit())
  3013. * .addSubcommand("branch", new GitBranch());
  3014. * </pre>
  3015. * @return the declaratively registered subcommands of this command, or an empty array if none
  3016. * @see CommandLine#addSubcommand(String, Object)
  3017. * @see HelpCommand
  3018. * @since 0.9.8
  3019. */
  3020. Class<?>[] subcommands() default {};
  3021. /** Specify whether methods annotated with {@code @Command} should be registered as subcommands of their
  3022. * enclosing {@code @Command} class.
  3023. * The default is {@code true}. For example:
  3024. * <pre>
  3025. * &#064;Command
  3026. * public class Git {
  3027. * &#064;Command
  3028. * void status() { ... }
  3029. * }
  3030. *
  3031. * CommandLine git = new CommandLine(new Git());
  3032. * </pre> is equivalent to this:
  3033. * <pre>
  3034. * // don't add command methods as subcommands automatically
  3035. * &#064;Command(addMethodSubcommands = false)
  3036. * public class Git {
  3037. * &#064;Command
  3038. * void status() { ... }
  3039. * }
  3040. *
  3041. * // add command methods as subcommands programmatically
  3042. * CommandLine git = new CommandLine(new Git());
  3043. * CommandLine status = new CommandLine(CommandLine.getCommandMethods(Git.class, "status").get(0));
  3044. * git.addSubcommand("status", status);
  3045. * </pre>
  3046. * @return whether methods annotated with {@code @Command} should be registered as subcommands
  3047. * @see CommandLine#addSubcommand(String, Object)
  3048. * @see CommandLine#getCommandMethods(Class, String)
  3049. * @see CommandSpec#addMethodSubcommands()
  3050. * @since 3.6.0 */
  3051. boolean addMethodSubcommands() default true;
  3052. /** String that separates options from option parameters. Default is {@code "="}. Spaces are also accepted.
  3053. * @return the string that separates options from option parameters, used both when parsing and when generating usage help
  3054. * @see CommandLine#setSeparator(String) */
  3055. String separator() default "=";
  3056. /** Version information for this command, to print to the console when the user specifies an
  3057. * {@linkplain Option#versionHelp() option} to request version help. Each element of the array is rendered on a separate line.
  3058. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3059. * <p>This is not part of the usage help message.</p>
  3060. *
  3061. * @return a string or an array of strings with version information about this command (each string in the array is displayed on a separate line).
  3062. * @since 0.9.8
  3063. * @see CommandLine#printVersionHelp(PrintStream)
  3064. */
  3065. String[] version() default {};
  3066. /** Class that can provide version information dynamically at runtime. An implementation may return version
  3067. * information obtained from the JAR manifest, a properties file or some other source.
  3068. * @return a Class that can provide version information dynamically at runtime
  3069. * @since 2.2 */
  3070. Class<? extends IVersionProvider> versionProvider() default NoVersionProvider.class;
  3071. /**
  3072. * Adds the standard {@code -h} and {@code --help} {@linkplain Option#usageHelp() usageHelp} options and {@code -V}
  3073. * and {@code --version} {@linkplain Option#versionHelp() versionHelp} options to the options of this command.
  3074. * <p>
  3075. * Note that if no {@link #version()} or {@link #versionProvider()} is specified, the {@code --version} option will not print anything.
  3076. * </p><p>
  3077. * For {@linkplain #resourceBundle() internationalization}: the help option has {@code descriptionKey = "mixinStandardHelpOptions.help"},
  3078. * and the version option has {@code descriptionKey = "mixinStandardHelpOptions.version"}.
  3079. * </p>
  3080. * @return whether the auto-help mixin should be added to this command
  3081. * @since 3.0 */
  3082. boolean mixinStandardHelpOptions() default false;
  3083. /** Set this attribute to {@code true} if this subcommand is a help command, and required options and positional
  3084. * parameters of the parent command should not be validated. If a subcommand marked as {@code helpCommand} is
  3085. * specified on the command line, picocli will not validate the parent arguments (so no "missing required
  3086. * option" errors) and the {@link CommandLine#printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi)} method will return {@code true}.
  3087. * @return {@code true} if this subcommand is a help command and picocli should not check for missing required
  3088. * options and positional parameters on the parent command
  3089. * @since 3.0 */
  3090. boolean helpCommand() default false;
  3091. /** Set the heading preceding the header section.
  3092. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3093. * @return the heading preceding the header section
  3094. * @see UsageMessageSpec#headerHeading()
  3095. * @see Help#headerHeading(Object...) */
  3096. String headerHeading() default "";
  3097. /** Optional summary description of the command, shown before the synopsis. Each element of the array is rendered on a separate line.
  3098. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3099. * @return summary description of the command
  3100. * @see UsageMessageSpec#header()
  3101. * @see Help#header(Object...) */
  3102. String[] header() default {};
  3103. /** Set the heading preceding the synopsis text. The default heading is {@code "Usage: "} (without a line break between the heading and the synopsis text).
  3104. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3105. * @return the heading preceding the synopsis text
  3106. * @see Help#synopsisHeading(Object...) */
  3107. String synopsisHeading() default "Usage: ";
  3108. /** Specify {@code true} to generate an abbreviated synopsis like {@code "<main> [OPTIONS] [PARAMETERS...]"}.
  3109. * By default, a detailed synopsis with individual option names and parameters is generated.
  3110. * @return whether the synopsis should be abbreviated
  3111. * @see Help#abbreviatedSynopsis()
  3112. * @see Help#detailedSynopsis(Comparator, boolean) */
  3113. boolean abbreviateSynopsis() default false;
  3114. /** Specify one or more custom synopsis lines to display instead of an auto-generated synopsis. Each element of the array is rendered on a separate line.
  3115. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3116. * @return custom synopsis text to replace the auto-generated synopsis
  3117. * @see Help#customSynopsis(Object...) */
  3118. String[] customSynopsis() default {};
  3119. /** Set the heading preceding the description section.
  3120. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3121. * @return the heading preceding the description section
  3122. * @see Help#descriptionHeading(Object...) */
  3123. String descriptionHeading() default "";
  3124. /** Optional text to display between the synopsis line(s) and the list of options. Each element of the array is rendered on a separate line.
  3125. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3126. * @return description of this command
  3127. * @see Help#description(Object...) */
  3128. String[] description() default {};
  3129. /** Set the heading preceding the parameters list.
  3130. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3131. * @return the heading preceding the parameters list
  3132. * @see Help#parameterListHeading(Object...) */
  3133. String parameterListHeading() default "";
  3134. /** Set the heading preceding the options list.
  3135. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3136. * @return the heading preceding the options list
  3137. * @see Help#optionListHeading(Object...) */
  3138. String optionListHeading() default "";
  3139. /** Specify {@code false} to show Options in declaration order. The default is to sort alphabetically.
  3140. * @return whether options should be shown in alphabetic order. */
  3141. boolean sortOptions() default true;
  3142. /** Prefix required options with this character in the options list. The default is no marker: the synopsis
  3143. * indicates which options and parameters are required.
  3144. * @return the character to show in the options list to mark required options */
  3145. char requiredOptionMarker() default ' ';
  3146. /** Class that can provide default values dynamically at runtime. An implementation may return default
  3147. * value obtained from a configuration file like a properties file or some other source.
  3148. * @return a Class that can provide default values dynamically at runtime
  3149. * @since 3.6 */
  3150. Class<? extends IDefaultValueProvider> defaultValueProvider() default NoDefaultProvider.class;
  3151. /** Specify {@code true} to show default values in the description column of the options list (except for
  3152. * boolean options). False by default.
  3153. * <p>Note that picocli 3.2 allows {@linkplain Option#description() embedding default values} anywhere in the
  3154. * option or positional parameter description that ignores this setting.</p>
  3155. * @return whether the default values for options and parameters should be shown in the description column */
  3156. boolean showDefaultValues() default false;
  3157. /** Set the heading preceding the subcommands list. The default heading is {@code "Commands:%n"} (with a line break at the end).
  3158. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3159. * @return the heading preceding the subcommands list
  3160. * @see Help#commandListHeading(Object...) */
  3161. String commandListHeading() default "Commands:%n";
  3162. /** Set the heading preceding the footer section.
  3163. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3164. * @return the heading preceding the footer section
  3165. * @see Help#footerHeading(Object...) */
  3166. String footerHeading() default "";
  3167. /** Optional text to display after the list of options. Each element of the array is rendered on a separate line.
  3168. * <p>May contain embedded {@linkplain java.util.Formatter format specifiers} like {@code %n} line separators. Literal percent {@code '%'} characters must be escaped with another {@code %}.</p>
  3169. * @return text to display after the list of options
  3170. * @see Help#footer(Object...) */
  3171. String[] footer() default {};
  3172. /**
  3173. * Set {@code hidden=true} if this command should not be included in the list of commands in the usage help of the parent command.
  3174. * @return whether this command should be excluded from the usage message
  3175. * @since 3.0
  3176. */
  3177. boolean hidden() default false;
  3178. /** Set the base name of the ResourceBundle to find option and positional parameters descriptions, as well as
  3179. * usage help message sections and section headings. <p>See {@link Messages} for more details and an example.</p>
  3180. * @return the base name of the ResourceBundle for usage help strings
  3181. * @see ArgSpec#messages()
  3182. * @see UsageMessageSpec#messages()
  3183. * @see CommandSpec#resourceBundle()
  3184. * @see CommandLine#setResourceBundle(ResourceBundle)
  3185. * @since 3.6
  3186. */
  3187. String resourceBundle() default "";
  3188. /** Set the {@link UsageMessageSpec#width(int) usage help message width}. The default is 80.
  3189. * @since 3.7
  3190. */
  3191. int usageHelpWidth() default 80;
  3192. }
  3193. /** A {@code Command} may define one or more {@code ArgGroups}: a group of options, positional parameters or a mixture of the two.
  3194. * Groups can be used to:
  3195. * <ul>
  3196. * <li>define <b>mutually exclusive</b> arguments. By default, options and positional parameters
  3197. * in a group are mutually exclusive. This can be controlled with the {@link #exclusive() exclusive} attribute.
  3198. * Picocli will throw a {@link MutuallyExclusiveArgsException} if the command line contains multiple arguments that are mutually exclusive.</li>
  3199. * <li>define a set of arguments that <b>must co-occur</b>. Set {@link #exclusive() exclusive = false}
  3200. * to define a group of options and positional parameters that must always be specified together.
  3201. * Picocli will throw a {@link MissingParameterException MissingParameterException} if not all the options and positional parameters in a co-occurring group are specified together.</li>
  3202. * <li>create an <b>option section</b> in the usage help message.
  3203. * To be shown in the usage help message, a group needs to have a {@link #heading() heading} (which may come from a {@linkplain #headingKey() resource bundle}).
  3204. * Groups without a heading are only used for validation.
  3205. * Set {@link #validate() validate = false} for groups whose purpose is only to customize the usage help message.</li>
  3206. * <li>define <b>composite repeating argument groups</b>. Groups may contain other groups to create composite groups.</li>
  3207. * </ul>
  3208. * <p>Groups may be optional ({@code multiplicity = "0..1"}), required ({@code multiplicity = "1"}), or repeating groups ({@code multiplicity = "0..*"} or {@code multiplicity = "1..*"}).
  3209. * For a group of mutually exclusive arguments, making the group required means that one of the arguments in the group must appear on the command line, or a {@link MissingParameterException MissingParameterException} is thrown.
  3210. * For a group of co-occurring arguments, all arguments in the group must appear on the command line.
  3211. * </p>
  3212. * <p>Groups can be composed for validation purposes:</p>
  3213. * <ul>
  3214. * <li>When the parent group is mutually exclusive, only one of the subgroups may be present.</li>
  3215. * <li>When the parent group is a co-occurring group, all subgroups must be present.</li>
  3216. * <li>When the parent group is required, at least one subgroup must be present.</li>
  3217. * </ul>
  3218. * <p>
  3219. * Below is an example of an {@code ArgGroup} defining a set of dependent options that must occur together.
  3220. * All options are required <em>within the group</em>, while the group itself is optional:</p>
  3221. * <pre>
  3222. * public class DependentOptions {
  3223. * &#064;ArgGroup(exclusive = false, multiplicity = "0..1")
  3224. * Dependent group;
  3225. *
  3226. * static class Dependent {
  3227. * &#064;Option(names = "-a", required = true) int a;
  3228. * &#064;Option(names = "-b", required = true) int b;
  3229. * &#064;Option(names = "-c", required = true) int c;
  3230. * }
  3231. * }</pre>
  3232. * @see ArgGroupSpec
  3233. * @since 4.0 */
  3234. @Retention(RetentionPolicy.RUNTIME)
  3235. @Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
  3236. public @interface ArgGroup {
  3237. /** The heading of this group, used when generating the usage documentation.
  3238. * When neither a {@link #heading() heading} nor a {@link #headingKey() headingKey} are specified,
  3239. * this group is used for validation only and does not change the usage help message. */
  3240. String heading() default "__no_heading__";
  3241. /** ResourceBundle key for this group's usage help message section heading.
  3242. * When neither a {@link #heading() heading} nor a {@link #headingKey() headingKey} are specified,
  3243. * this group is used for validation only and does not change the usage help message. */
  3244. String headingKey() default "__no_heading_key__";
  3245. /** Determines whether this is a mutually exclusive group; {@code true} by default.
  3246. * If {@code false}, this is a co-occurring group. Ignored if {@link #validate()} is {@code false}. */
  3247. boolean exclusive() default true;
  3248. /** Determines how often this group can be specified on the command line; {@code "0..1"} (optional) by default.
  3249. * For a group of mutually exclusive arguments, making the group required {@code multiplicity = "1"} means that
  3250. * one of the arguments in the group must appear on the command line, or a MissingParameterException is thrown.
  3251. * For a group of co-occurring arguments, making the group required means that all arguments in the group must appear on the command line.
  3252. * Ignored if {@link #validate()} is {@code false}. */
  3253. String multiplicity() default "0..1";
  3254. /** Determines whether picocli should validate the rules of this group ({@code true} by default).
  3255. * For a mutually exclusive group validation means verifying that no more than one elements of the group is specified on the command line;
  3256. * for a co-ocurring group validation means verifying that all elements of the group are specified on the command line.
  3257. * Set {@link #validate() validate = false} for groups whose purpose is only to customize the usage help message.
  3258. * @see #multiplicity()
  3259. * @see #heading() */
  3260. boolean validate() default true;
  3261. /** Determines the position in the options list in the usage help message at which this group should be shown.
  3262. * Options with a lower number are shown before options with a higher number.
  3263. * This attribute is only honored if {@link UsageMessageSpec#sortOptions()} is {@code false} for this command.*/
  3264. int order() default -1;
  3265. }
  3266. /**
  3267. * <p>
  3268. * When parsing command line arguments and initializing
  3269. * fields annotated with {@link Option @Option} or {@link Parameters @Parameters},
  3270. * String values can be converted to any type for which a {@code ITypeConverter} is registered.
  3271. * </p><p>
  3272. * This interface defines the contract for classes that know how to convert a String into some domain object.
  3273. * Custom converters can be registered with the {@link #registerConverter(Class, ITypeConverter)} method.
  3274. * </p><p>
  3275. * Java 8 lambdas make it easy to register custom type converters:
  3276. * </p>
  3277. * <pre>
  3278. * commandLine.registerConverter(java.nio.file.Path.class, s -&gt; java.nio.file.Paths.get(s));
  3279. * commandLine.registerConverter(java.time.Duration.class, s -&gt; java.time.Duration.parse(s));</pre>
  3280. * <p>
  3281. * Built-in type converters are pre-registered for the following java 1.5 types:
  3282. * </p>
  3283. * <ul>
  3284. * <li>all primitive types</li>
  3285. * <li>all primitive wrapper types: Boolean, Byte, Character, Double, Float, Integer, Long, Short</li>
  3286. * <li>any enum</li>
  3287. * <li>java.io.File</li>
  3288. * <li>java.math.BigDecimal</li>
  3289. * <li>java.math.BigInteger</li>
  3290. * <li>java.net.InetAddress</li>
  3291. * <li>java.net.URI</li>
  3292. * <li>java.net.URL</li>
  3293. * <li>java.nio.charset.Charset</li>
  3294. * <li>java.sql.Time</li>
  3295. * <li>java.util.Date</li>
  3296. * <li>java.util.UUID</li>
  3297. * <li>java.util.regex.Pattern</li>
  3298. * <li>StringBuilder</li>
  3299. * <li>CharSequence</li>
  3300. * <li>String</li>
  3301. * </ul>
  3302. * @param <K> the type of the object that is the result of the conversion
  3303. */
  3304. public interface ITypeConverter<K> {
  3305. /**
  3306. * Converts the specified command line argument value to some domain object.
  3307. * @param value the command line argument String value
  3308. * @return the resulting domain object
  3309. * @throws Exception an exception detailing what went wrong during the conversion
  3310. */
  3311. K convert(String value) throws Exception;
  3312. }
  3313. /**
  3314. * Provides version information for a command. Commands may configure a provider with the
  3315. * {@link Command#versionProvider()} annotation attribute.
  3316. * @since 2.2 */
  3317. public interface IVersionProvider {
  3318. /**
  3319. * Returns version information for a command.
  3320. * @return version information (each string in the array is displayed on a separate line)
  3321. * @throws Exception an exception detailing what went wrong when obtaining version information
  3322. */
  3323. String[] getVersion() throws Exception;
  3324. }
  3325. private static class NoVersionProvider implements IVersionProvider {
  3326. public String[] getVersion() throws Exception { throw new UnsupportedOperationException(); }
  3327. }
  3328. /**
  3329. * Provides default value for a command. Commands may configure a provider with the
  3330. * {@link Command#defaultValueProvider()} annotation attribute.
  3331. * @since 3.6 */
  3332. public interface IDefaultValueProvider {
  3333. /** Returns the default value for an option or positional parameter or {@code null}.
  3334. * The returned value is converted to the type of the option/positional parameter
  3335. * via the same type converter used when populating this option/positional
  3336. * parameter from a command line argument.
  3337. * @param argSpec the option or positional parameter, never {@code null}
  3338. * @return the default value for the option or positional parameter, or {@code null} if
  3339. * this provider has no default value for the specified option or positional parameter
  3340. * @throws Exception when there was a problem obtaining the default value
  3341. */
  3342. String defaultValue(ArgSpec argSpec) throws Exception;
  3343. }
  3344. private static class NoDefaultProvider implements IDefaultValueProvider {
  3345. public String defaultValue(ArgSpec argSpec) { throw new UnsupportedOperationException(); }
  3346. }
  3347. /**
  3348. * Creates the {@link Help} instance used to render the usage help message.
  3349. * @since 3.9
  3350. */
  3351. public interface IHelpFactory {
  3352. /** Returns a {@code Help} instance to assist in rendering the usage help message
  3353. * @param commandSpec the command to create usage help for
  3354. * @param colorScheme the color scheme to use when rendering usage help
  3355. * @return a {@code Help} instance
  3356. */
  3357. Help create(CommandSpec commandSpec, Help.ColorScheme colorScheme);
  3358. }
  3359. private static class DefaultHelpFactory implements IHelpFactory {
  3360. public Help create(CommandSpec commandSpec, Help.ColorScheme colorScheme) {
  3361. return new Help(commandSpec, colorScheme);
  3362. }
  3363. }
  3364. /**
  3365. * Factory for instantiating classes that are registered declaratively with annotation attributes, like
  3366. * {@link Command#subcommands()}, {@link Option#converter()}, {@link Parameters#converter()} and {@link Command#versionProvider()}.
  3367. * <p>The default factory implementation simply creates a new instance of the specified class when {@link #create(Class)} is invoked.
  3368. * </p><p>
  3369. * You may provide a custom implementation of this interface.
  3370. * For example, a custom factory implementation could delegate to a dependency injection container that provides the requested instance.
  3371. * </p>
  3372. * @see picocli.CommandLine#CommandLine(Object, IFactory)
  3373. * @see #call(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  3374. * @see #run(Class, IFactory, PrintStream, PrintStream, Help.Ansi, String...)
  3375. * @since 2.2 */
  3376. public interface IFactory {
  3377. /**
  3378. * Returns an instance of the specified class.
  3379. * @param cls the class of the object to return
  3380. * @param <K> the type of the object to return
  3381. * @return the instance
  3382. * @throws Exception an exception detailing what went wrong when creating or obtaining the instance
  3383. */
  3384. <K> K create(Class<K> cls) throws Exception;
  3385. }
  3386. /** Returns a default {@link IFactory} implementation. Package-protected for testing purposes. */
  3387. static IFactory defaultFactory() { return new DefaultFactory(); }
  3388. private static class DefaultFactory implements IFactory {
  3389. public <T> T create(Class<T> cls) throws Exception {
  3390. if (cls.isInterface() && Collection.class.isAssignableFrom(cls)) {
  3391. if (List.class.isAssignableFrom(cls)) {
  3392. return cls.cast(new ArrayList<Object>());
  3393. } else if (SortedSet.class.isAssignableFrom(cls)) {
  3394. return cls.cast(new TreeSet<Object>());
  3395. } else if (Set.class.isAssignableFrom(cls)) {
  3396. return cls.cast(new LinkedHashSet<Object>());
  3397. } else if (Queue.class.isAssignableFrom(cls)) {
  3398. return cls.cast(new LinkedList<Object>()); // ArrayDeque is only available since 1.6
  3399. }
  3400. return cls.cast(new ArrayList<Object>());
  3401. }
  3402. if (Map.class.isAssignableFrom(cls)) {
  3403. try { // if it is an implementation class, instantiate it
  3404. return cls.cast(cls.getDeclaredConstructor().newInstance());
  3405. } catch (Exception ignored) { }
  3406. return cls.cast(new LinkedHashMap<Object, Object>());
  3407. }
  3408. try {
  3409. return cls.getDeclaredConstructor().newInstance();
  3410. } catch (Exception ex) {
  3411. Constructor<T> constructor = cls.getDeclaredConstructor();
  3412. constructor.setAccessible(true);
  3413. return constructor.newInstance();
  3414. }
  3415. }
  3416. private static ITypeConverter<?>[] createConverter(IFactory factory, Class<? extends ITypeConverter<?>>[] classes) {
  3417. ITypeConverter<?>[] result = new ITypeConverter<?>[classes.length];
  3418. for (int i = 0; i < classes.length; i++) { result[i] = create(factory, classes[i]); }
  3419. return result;
  3420. }
  3421. static IVersionProvider createVersionProvider(IFactory factory, Class<? extends IVersionProvider> cls) {
  3422. return create(factory, cls);
  3423. }
  3424. static IDefaultValueProvider createDefaultValueProvider(IFactory factory, Class<? extends IDefaultValueProvider> cls) {
  3425. return create(factory, cls);
  3426. }
  3427. static Iterable<String> createCompletionCandidates(IFactory factory, Class<? extends Iterable<String>> cls) {
  3428. return create(factory, cls);
  3429. }
  3430. static <T> T create(IFactory factory, Class<T> cls) {
  3431. try { return factory.create(cls); }
  3432. catch (Exception ex) { throw new InitializationException("Could not instantiate " + cls + ": " + ex, ex); }
  3433. }
  3434. }
  3435. /** Describes the number of parameters required and accepted by an option or a positional parameter.
  3436. * @since 0.9.7
  3437. */
  3438. public static class Range implements Comparable<Range> {
  3439. /** Required number of parameters for an option or positional parameter. */
  3440. public final int min;
  3441. /** Maximum accepted number of parameters for an option or positional parameter. */
  3442. public final int max;
  3443. public final boolean isVariable;
  3444. private final boolean isUnspecified;
  3445. private final String originalValue;
  3446. /** Constructs a new Range object with the specified parameters.
  3447. * @param min minimum number of required parameters
  3448. * @param max maximum number of allowed parameters (or Integer.MAX_VALUE if variable)
  3449. * @param variable {@code true} if any number or parameters is allowed, {@code false} otherwise
  3450. * @param unspecified {@code true} if no arity was specified on the option/parameter (value is based on type)
  3451. * @param originalValue the original value that was specified on the option or parameter
  3452. */
  3453. public Range(int min, int max, boolean variable, boolean unspecified, String originalValue) {
  3454. if (min < 0 || max < 0) { throw new InitializationException("Invalid negative range (min=" + min + ", max=" + max + ")"); }
  3455. if (min > max) { throw new InitializationException("Invalid range (min=" + min + ", max=" + max + ")"); }
  3456. this.min = min;
  3457. this.max = max;
  3458. this.isVariable = variable;
  3459. this.isUnspecified = unspecified;
  3460. this.originalValue = originalValue;
  3461. }
  3462. /** Returns a new {@code Range} based on the {@link Option#arity()} annotation on the specified field,
  3463. * or the field type's default arity if no arity was specified.
  3464. * @param field the field whose Option annotation to inspect
  3465. * @return a new {@code Range} based on the Option arity annotation on the specified field */
  3466. public static Range optionArity(Field field) { return optionArity(new TypedMember(field)); }
  3467. private static Range optionArity(IAnnotatedElement member) {
  3468. return member.isAnnotationPresent(Option.class)
  3469. ? adjustForType(Range.valueOf(member.getAnnotation(Option.class).arity()), member)
  3470. : new Range(0, 0, false, true, "0");
  3471. }
  3472. /** Returns a new {@code Range} based on the {@link Parameters#arity()} annotation on the specified field,
  3473. * or the field type's default arity if no arity was specified.
  3474. * @param field the field whose Parameters annotation to inspect
  3475. * @return a new {@code Range} based on the Parameters arity annotation on the specified field */
  3476. public static Range parameterArity(Field field) { return parameterArity(new TypedMember(field)); }
  3477. private static Range parameterArity(IAnnotatedElement member) {
  3478. if (member.isAnnotationPresent(Parameters.class)) {
  3479. return adjustForType(Range.valueOf(member.getAnnotation(Parameters.class).arity()), member);
  3480. } else {
  3481. return member.isMethodParameter()
  3482. ? adjustForType(Range.valueOf(""), member)
  3483. : new Range(0, 0, false, true, "0");
  3484. }
  3485. }
  3486. /** Returns a new {@code Range} based on the {@link Parameters#index()} annotation on the specified field.
  3487. * @param field the field whose Parameters annotation to inspect
  3488. * @return a new {@code Range} based on the Parameters index annotation on the specified field */
  3489. public static Range parameterIndex(Field field) { return parameterIndex(new TypedMember(field)); }
  3490. private static Range parameterIndex(IAnnotatedElement member) {
  3491. if (member.isAnnotationPresent(Parameters.class)) {
  3492. Range result = Range.valueOf(member.getAnnotation(Parameters.class).index());
  3493. if (!result.isUnspecified) { return result; }
  3494. }
  3495. if (member.isMethodParameter()) {
  3496. int min = member.getMethodParamPosition();
  3497. int max = member.isMultiValue() ? Integer.MAX_VALUE : min;
  3498. return new Range(min, max, member.isMultiValue(), false, "");
  3499. }
  3500. return Range.valueOf("*"); // the default
  3501. }
  3502. static Range adjustForType(Range result, IAnnotatedElement member) {
  3503. return result.isUnspecified ? defaultArity(member) : result;
  3504. }
  3505. /** Returns the default arity {@code Range}: for {@link Option options} this is 0 for booleans and 1 for
  3506. * other types, for {@link Parameters parameters} booleans have arity 0, arrays or Collections have
  3507. * arity "0..*", and other types have arity 1.
  3508. * @param field the field whose default arity to return
  3509. * @return a new {@code Range} indicating the default arity of the specified field
  3510. * @since 2.0 */
  3511. public static Range defaultArity(Field field) { return defaultArity(new TypedMember(field)); }
  3512. private static Range defaultArity(IAnnotatedElement member) {
  3513. ITypeInfo info = member.getTypeInfo();
  3514. if (member.isAnnotationPresent(Option.class)) {
  3515. boolean zeroArgs = info.isBoolean() || (info.isMultiValue() && info.getAuxiliaryTypeInfos().get(0).isBoolean());
  3516. return zeroArgs ? Range.valueOf("0").unspecified(true)
  3517. : Range.valueOf("1").unspecified(true);
  3518. }
  3519. if (info.isMultiValue()) {
  3520. return Range.valueOf("0..1").unspecified(true);
  3521. }
  3522. return Range.valueOf("1").unspecified(true);// for single-valued fields (incl. boolean positional parameters)
  3523. }
  3524. /** Returns the default arity {@code Range} for {@link Option options}: booleans have arity 0, other types have arity 1.
  3525. * @param type the type whose default arity to return
  3526. * @return a new {@code Range} indicating the default arity of the specified type
  3527. * @deprecated use {@link #defaultArity(Field)} instead */
  3528. @Deprecated public static Range defaultArity(Class<?> type) {
  3529. return isBoolean(type) ? Range.valueOf("0").unspecified(true) : Range.valueOf("1").unspecified(true);
  3530. }
  3531. private int size() { return 1 + max - min; }
  3532. static Range parameterCapacity(IAnnotatedElement member) {
  3533. Range arity = parameterArity(member);
  3534. if (!member.isMultiValue()) { return arity; }
  3535. Range index = parameterIndex(member);
  3536. return parameterCapacity(arity, index);
  3537. }
  3538. private static Range parameterCapacity(Range arity, Range index) {
  3539. if (arity.max == 0) { return arity; }
  3540. if (index.size() == 1) { return arity; }
  3541. if (index.isVariable) { return Range.valueOf(arity.min + "..*"); }
  3542. if (arity.size() == 1) { return Range.valueOf(arity.min * index.size() + ""); }
  3543. if (arity.isVariable) { return Range.valueOf(arity.min * index.size() + "..*"); }
  3544. return Range.valueOf(arity.min * index.size() + ".." + arity.max * index.size());
  3545. }
  3546. /** Leniently parses the specified String as an {@code Range} value and return the result. A range string can
  3547. * be a fixed integer value or a range of the form {@code MIN_VALUE + ".." + MAX_VALUE}. If the
  3548. * {@code MIN_VALUE} string is not numeric, the minimum is zero. If the {@code MAX_VALUE} is not numeric, the
  3549. * range is taken to be variable and the maximum is {@code Integer.MAX_VALUE}.
  3550. * @param range the value range string to parse
  3551. * @return a new {@code Range} value */
  3552. public static Range valueOf(String range) {
  3553. range = range.trim();
  3554. boolean unspecified = range.length() == 0 || range.startsWith(".."); // || range.endsWith("..");
  3555. int min = -1, max = -1;
  3556. boolean variable = false;
  3557. int dots = -1;
  3558. if ((dots = range.indexOf("..")) >= 0) {
  3559. min = parseInt(range.substring(0, dots), 0);
  3560. max = parseInt(range.substring(dots + 2), Integer.MAX_VALUE);
  3561. variable = max == Integer.MAX_VALUE;
  3562. } else {
  3563. max = parseInt(range, Integer.MAX_VALUE);
  3564. variable = max == Integer.MAX_VALUE;
  3565. min = variable ? 0 : max;
  3566. }
  3567. Range result = new Range(min, max, variable, unspecified, range);
  3568. return result;
  3569. }
  3570. private static int parseInt(String str, int defaultValue) {
  3571. try {
  3572. return Integer.parseInt(str);
  3573. } catch (Exception ex) {
  3574. return defaultValue;
  3575. }
  3576. }
  3577. /** Returns a new Range object with the {@code min} value replaced by the specified value.
  3578. * The {@code max} of the returned Range is guaranteed not to be less than the new {@code min} value.
  3579. * @param newMin the {@code min} value of the returned Range object
  3580. * @return a new Range object with the specified {@code min} value */
  3581. public Range min(int newMin) { return new Range(newMin, Math.max(newMin, max), isVariable, isUnspecified, originalValue); }
  3582. /** Returns a new Range object with the {@code max} value replaced by the specified value.
  3583. * The {@code min} of the returned Range is guaranteed not to be greater than the new {@code max} value.
  3584. * @param newMax the {@code max} value of the returned Range object
  3585. * @return a new Range object with the specified {@code max} value */
  3586. public Range max(int newMax) { return new Range(Math.min(min, newMax), newMax, isVariable, isUnspecified, originalValue); }
  3587. /** Returns a new Range object with the {@code isUnspecified} value replaced by the specified value.
  3588. * @param unspecified the {@code unspecified} value of the returned Range object
  3589. * @return a new Range object with the specified {@code unspecified} value */
  3590. public Range unspecified(boolean unspecified) { return new Range(min, max, isVariable, unspecified, originalValue); }
  3591. /** Returns {@code true} if this Range is a default value, {@code false} if the user specified this value.
  3592. * @since 4.0 */
  3593. public boolean isUnspecified() { return isUnspecified; }
  3594. /**
  3595. * Returns {@code true} if this Range includes the specified value, {@code false} otherwise.
  3596. * @param value the value to check
  3597. * @return {@code true} if the specified value is not less than the minimum and not greater than the maximum of this Range
  3598. */
  3599. public boolean contains(int value) { return min <= value && max >= value; }
  3600. public boolean equals(Object object) {
  3601. if (!(object instanceof Range)) { return false; }
  3602. Range other = (Range) object;
  3603. return other.max == this.max && other.min == this.min && other.isVariable == this.isVariable;
  3604. }
  3605. public int hashCode() {
  3606. return ((17 * 37 + max) * 37 + min) * 37 + (isVariable ? 1 : 0);
  3607. }
  3608. public String toString() {
  3609. return min == max ? String.valueOf(min) : min + ".." + (isVariable ? "*" : max);
  3610. }
  3611. public int compareTo(Range other) {
  3612. int result = min - other.min;
  3613. return (result == 0) ? max - other.max : result;
  3614. }
  3615. boolean overlaps(Range index) {
  3616. return contains(index.min) || contains(index.max) || index.contains(min) || index.contains(max);
  3617. }
  3618. }
  3619. private static void validatePositionalParameters(List<PositionalParamSpec> positionalParametersFields) {
  3620. int min = 0;
  3621. for (PositionalParamSpec positional : positionalParametersFields) {
  3622. Range index = positional.index();
  3623. if (index.min > min) {
  3624. throw new ParameterIndexGapException("Command definition should have a positional parameter with index=" + min +
  3625. ". Nearest positional parameter '" + positional.paramLabel() + "' has index=" + index.min);
  3626. }
  3627. min = Math.max(min, index.max);
  3628. min = min == Integer.MAX_VALUE ? min : min + 1;
  3629. }
  3630. }
  3631. @SuppressWarnings("unchecked") private static Stack<String> copy(Stack<String> stack) { return (Stack<String>) stack.clone(); }
  3632. private static <T> Stack<T> reverse(Stack<T> stack) {
  3633. Collections.reverse(stack);
  3634. return stack;
  3635. }
  3636. private static <T> List<T> reverseList(List<T> list) {
  3637. Collections.reverse(list);
  3638. return list;
  3639. }
  3640. /** This class provides a namespace for classes and interfaces that model concepts and attributes of command line interfaces in picocli.
  3641. * @since 3.0 */
  3642. public static final class Model {
  3643. private Model() {}
  3644. /** The scope of a binding is the context where the current value should be gotten from or set to.
  3645. * For a field, the scope is the object whose field value to get/set. For a method binding, it is the
  3646. * object on which the method should be invoked.
  3647. * <p>The getter and setter of the scope allow you to change the object onto which the option and positional parameter getters and setters should be applied.</p>
  3648. * @since 4.0
  3649. */
  3650. public interface IScope extends IGetter, ISetter {}
  3651. /** Customizable getter for obtaining the current value of an option or positional parameter.
  3652. * When an option or positional parameter is matched on the command line, its getter or setter is invoked to capture the value.
  3653. * For example, an option can be bound to a field or a method, and when the option is matched on the command line, the
  3654. * field's value is set or the method is invoked with the option parameter value.
  3655. * @since 3.0 */
  3656. public static interface IGetter {
  3657. /** Returns the current value of the binding. For multi-value options and positional parameters,
  3658. * this method returns an array, collection or map to add values to.
  3659. * @throws PicocliException if a problem occurred while obtaining the current value
  3660. * @throws Exception internally, picocli call sites will catch any exceptions thrown from here and rethrow them wrapped in a PicocliException */
  3661. <T> T get() throws Exception;
  3662. }
  3663. /** Customizable setter for modifying the value of an option or positional parameter.
  3664. * When an option or positional parameter is matched on the command line, its setter is invoked to capture the value.
  3665. * For example, an option can be bound to a field or a method, and when the option is matched on the command line, the
  3666. * field's value is set or the method is invoked with the option parameter value.
  3667. * @since 3.0 */
  3668. public static interface ISetter {
  3669. /** Sets the new value of the option or positional parameter.
  3670. *
  3671. * @param value the new value of the option or positional parameter
  3672. * @param <T> type of the value
  3673. * @return the previous value of the binding (if supported by this binding)
  3674. * @throws PicocliException if a problem occurred while setting the new value
  3675. * @throws Exception internally, picocli call sites will catch any exceptions thrown from here and rethrow them wrapped in a PicocliException */
  3676. <T> T set(T value) throws Exception;
  3677. }
  3678. /** The {@code CommandSpec} class models a command specification, including the options, positional parameters and subcommands
  3679. * supported by the command, as well as attributes for the version help message and the usage help message of the command.
  3680. * <p>
  3681. * Picocli views a command line application as a hierarchy of commands: there is a top-level command (usually the Java
  3682. * class with the {@code main} method) with optionally a set of command line options, positional parameters and subcommands.
  3683. * Subcommands themselves can have options, positional parameters and nested sub-subcommands to any level of depth.
  3684. * </p><p>
  3685. * The object model has a corresponding hierarchy of {@code CommandSpec} objects, each with a set of {@link OptionSpec},
  3686. * {@link PositionalParamSpec} and {@linkplain CommandLine subcommands} associated with it.
  3687. * This object model is used by the picocli command line interpreter and help message generator.
  3688. * </p><p>Picocli can construct a {@code CommandSpec} automatically from classes with {@link Command @Command}, {@link Option @Option} and
  3689. * {@link Parameters @Parameters} annotations. Alternatively a {@code CommandSpec} can be constructed programmatically.
  3690. * </p>
  3691. * @since 3.0 */
  3692. public static class CommandSpec {
  3693. /** Constant String holding the default program name: {@code "<main class>" }. */
  3694. static final String DEFAULT_COMMAND_NAME = "<main class>";
  3695. /** Constant Boolean holding the default setting for whether this is a help command: <code>{@value}</code>.*/
  3696. static final Boolean DEFAULT_IS_HELP_COMMAND = Boolean.FALSE;
  3697. /** Constant Boolean holding the default setting for whether method commands should be added as subcommands: <code>{@value}</code>.*/
  3698. static final Boolean DEFAULT_IS_ADD_METHOD_SUBCOMMANDS = Boolean.TRUE;
  3699. private final Map<String, CommandLine> commands = new LinkedHashMap<String, CommandLine>();
  3700. private final Map<String, OptionSpec> optionsByNameMap = new LinkedHashMap<String, OptionSpec>();
  3701. private final Map<Character, OptionSpec> posixOptionsByKeyMap = new LinkedHashMap<Character, OptionSpec>();
  3702. private final Map<String, CommandSpec> mixins = new LinkedHashMap<String, CommandSpec>();
  3703. private final List<ArgSpec> requiredArgs = new ArrayList<ArgSpec>();
  3704. private final List<ArgSpec> args = new ArrayList<ArgSpec>();
  3705. private final List<OptionSpec> options = new ArrayList<OptionSpec>();
  3706. private final List<PositionalParamSpec> positionalParameters = new ArrayList<PositionalParamSpec>();
  3707. private final List<UnmatchedArgsBinding> unmatchedArgs = new ArrayList<UnmatchedArgsBinding>();
  3708. private final List<ArgGroupSpec> groups = new ArrayList<ArgGroupSpec>();
  3709. private final ParserSpec parser = new ParserSpec();
  3710. private final UsageMessageSpec usageMessage = new UsageMessageSpec();
  3711. private final Object userObject;
  3712. private CommandLine commandLine;
  3713. private CommandSpec parent;
  3714. private Boolean isAddMethodSubcommands;
  3715. private String name;
  3716. private Set<String> aliases = new LinkedHashSet<String>();
  3717. private Boolean isHelpCommand;
  3718. private IVersionProvider versionProvider;
  3719. private IDefaultValueProvider defaultValueProvider;
  3720. private String[] version;
  3721. private String toString;
  3722. private CommandSpec(Object userObject) { this.userObject = userObject; }
  3723. /** Creates and returns a new {@code CommandSpec} without any associated user object. */
  3724. public static CommandSpec create() { return wrapWithoutInspection(null); }
  3725. /** Creates and returns a new {@code CommandSpec} with the specified associated user object.
  3726. * The specified user object is <em>not</em> inspected for annotations.
  3727. * @param userObject the associated user object. May be any object, may be {@code null}.
  3728. */
  3729. public static CommandSpec wrapWithoutInspection(Object userObject) { return new CommandSpec(userObject); }
  3730. /** Creates and returns a new {@code CommandSpec} initialized from the specified associated user object. The specified
  3731. * user object must have at least one {@link Command}, {@link Option} or {@link Parameters} annotation.
  3732. * @param userObject the user object annotated with {@link Command}, {@link Option} and/or {@link Parameters} annotations.
  3733. * @throws InitializationException if the specified object has no picocli annotations or has invalid annotations
  3734. */
  3735. public static CommandSpec forAnnotatedObject(Object userObject) { return forAnnotatedObject(userObject, new DefaultFactory()); }
  3736. /** Creates and returns a new {@code CommandSpec} initialized from the specified associated user object. The specified
  3737. * user object must have at least one {@link Command}, {@link Option} or {@link Parameters} annotation.
  3738. * @param userObject the user object annotated with {@link Command}, {@link Option} and/or {@link Parameters} annotations.
  3739. * @param factory the factory used to create instances of {@linkplain Command#subcommands() subcommands}, {@linkplain Option#converter() converters}, etc., that are registered declaratively with annotation attributes
  3740. * @throws InitializationException if the specified object has no picocli annotations or has invalid annotations
  3741. */
  3742. public static CommandSpec forAnnotatedObject(Object userObject, IFactory factory) { return CommandReflection.extractCommandSpec(userObject, factory, true); }
  3743. /** Creates and returns a new {@code CommandSpec} initialized from the specified associated user object. If the specified
  3744. * user object has no {@link Command}, {@link Option} or {@link Parameters} annotations, an empty {@code CommandSpec} is returned.
  3745. * @param userObject the user object annotated with {@link Command}, {@link Option} and/or {@link Parameters} annotations.
  3746. * @throws InitializationException if the specified object has invalid annotations
  3747. */
  3748. public static CommandSpec forAnnotatedObjectLenient(Object userObject) { return forAnnotatedObjectLenient(userObject, new DefaultFactory()); }
  3749. /** Creates and returns a new {@code CommandSpec} initialized from the specified associated user object. If the specified
  3750. * user object has no {@link Command}, {@link Option} or {@link Parameters} annotations, an empty {@code CommandSpec} is returned.
  3751. * @param userObject the user object annotated with {@link Command}, {@link Option} and/or {@link Parameters} annotations.
  3752. * @param factory the factory used to create instances of {@linkplain Command#subcommands() subcommands}, {@linkplain Option#converter() converters}, etc., that are registered declaratively with annotation attributes
  3753. * @throws InitializationException if the specified object has invalid annotations
  3754. */
  3755. public static CommandSpec forAnnotatedObjectLenient(Object userObject, IFactory factory) { return CommandReflection.extractCommandSpec(userObject, factory, false); }
  3756. /** Ensures all attributes of this {@code CommandSpec} have a valid value; throws an {@link InitializationException} if this cannot be achieved. */
  3757. void validate() {
  3758. Collections.sort(positionalParameters, new PositionalParametersSorter());
  3759. validatePositionalParameters(positionalParameters);
  3760. List<String> wrongUsageHelpAttr = new ArrayList<String>();
  3761. List<String> wrongVersionHelpAttr = new ArrayList<String>();
  3762. List<String> usageHelpAttr = new ArrayList<String>();
  3763. List<String> versionHelpAttr = new ArrayList<String>();
  3764. for (OptionSpec option : options()) {
  3765. if (option.usageHelp()) {
  3766. usageHelpAttr.add(option.longestName());
  3767. if (!isBoolean(option.type())) { wrongUsageHelpAttr.add(option.longestName()); }
  3768. }
  3769. if (option.versionHelp()) {
  3770. versionHelpAttr.add(option.longestName());
  3771. if (!isBoolean(option.type())) { wrongVersionHelpAttr.add(option.longestName()); }
  3772. }
  3773. }
  3774. String wrongType = "Non-boolean options like %s should not be marked as '%s=true'. Usually a command has one %s boolean flag that triggers display of the %s. Alternatively, consider using @Command(mixinStandardHelpOptions = true) on your command instead.";
  3775. String multiple = "Multiple options %s are marked as '%s=true'. Usually a command has only one %s option that triggers display of the %s. Alternatively, consider using @Command(mixinStandardHelpOptions = true) on your command instead.%n";
  3776. if (!wrongUsageHelpAttr.isEmpty()) {
  3777. throw new InitializationException(String.format(wrongType, wrongUsageHelpAttr, "usageHelp", "--help", "usage help message"));
  3778. }
  3779. if (!wrongVersionHelpAttr.isEmpty()) {
  3780. throw new InitializationException(String.format(wrongType, wrongVersionHelpAttr, "versionHelp", "--version", "version information"));
  3781. }
  3782. if (usageHelpAttr.size() > 1) { new Tracer().warn(multiple, usageHelpAttr, "usageHelp", "--help", "usage help message"); }
  3783. if (versionHelpAttr.size() > 1) { new Tracer().warn(multiple, versionHelpAttr, "versionHelp", "--version", "version information"); }
  3784. }
  3785. /** Returns the user object associated with this command.
  3786. * @see CommandLine#getCommand() */
  3787. public Object userObject() { return userObject; }
  3788. /** Returns the CommandLine constructed with this {@code CommandSpec} model. */
  3789. public CommandLine commandLine() { return commandLine;}
  3790. /** Sets the CommandLine constructed with this {@code CommandSpec} model. */
  3791. protected CommandSpec commandLine(CommandLine commandLine) {
  3792. this.commandLine = commandLine;
  3793. for (CommandSpec mixedInSpec : mixins.values()) {
  3794. mixedInSpec.commandLine(commandLine);
  3795. }
  3796. for (CommandLine sub : commands.values()) {
  3797. sub.getCommandSpec().parent(this);
  3798. }
  3799. return this;
  3800. }
  3801. /** Returns the parser specification for this command. */
  3802. public ParserSpec parser() { return parser; }
  3803. /** Initializes the parser specification for this command from the specified settings and returns this commandSpec.*/
  3804. public CommandSpec parser(ParserSpec settings) { parser.initFrom(settings); return this; }
  3805. /** Returns the usage help message specification for this command. */
  3806. public UsageMessageSpec usageMessage() { return usageMessage; }
  3807. /** Initializes the usageMessage specification for this command from the specified settings and returns this commandSpec.*/
  3808. public CommandSpec usageMessage(UsageMessageSpec settings) { usageMessage.initFrom(settings, this); return this; }
  3809. /** Returns the resource bundle base name for this command.
  3810. * @return the resource bundle base name from the {@linkplain UsageMessageSpec#messages()}
  3811. * @since 4.0 */
  3812. public String resourceBundleBaseName() { return Messages.resourceBundleBaseName(usageMessage.messages()); }
  3813. /** Initializes the resource bundle for this command: sets the {@link UsageMessageSpec#messages(Messages) UsageMessageSpec.messages} to
  3814. * a {@link Messages Messages} object created from this command spec and the specified bundle, and then sets the
  3815. * {@link ArgSpec#messages(Messages) ArgSpec.messages} of all options and positional parameters in this command
  3816. * to the same {@code Messages} instance. Subcommands are not modified.
  3817. * <p>This method is preferable to {@link #resourceBundle(ResourceBundle)} for pre-Java 8</p>
  3818. * @param resourceBundleBaseName the base name of the ResourceBundle to set, may be {@code null}
  3819. * @return this commandSpec
  3820. * @see #addSubcommand(String, CommandLine)
  3821. * @since 4.0 */
  3822. public CommandSpec resourceBundleBaseName(String resourceBundleBaseName) {
  3823. ResourceBundle bundle = empty(resourceBundleBaseName) ? null : ResourceBundle.getBundle(resourceBundleBaseName);
  3824. setBundle(resourceBundleBaseName, bundle);
  3825. return this;
  3826. }
  3827. /** Returns the resource bundle for this command.
  3828. * @return the resource bundle from the {@linkplain UsageMessageSpec#messages()}
  3829. * @since 3.6 */
  3830. public ResourceBundle resourceBundle() { return Messages.resourceBundle(usageMessage.messages()); }
  3831. /** Initializes the resource bundle for this command: sets the {@link UsageMessageSpec#messages(Messages) UsageMessageSpec.messages} to
  3832. * a {@link Messages Messages} object created from this command spec and the specified bundle, and then sets the
  3833. * {@link ArgSpec#messages(Messages) ArgSpec.messages} of all options and positional parameters in this command
  3834. * to the same {@code Messages} instance. Subcommands are not modified.
  3835. * @param bundle the ResourceBundle to set, may be {@code null}
  3836. * @return this commandSpec
  3837. * @see #addSubcommand(String, CommandLine)
  3838. * @since 3.6 */
  3839. public CommandSpec resourceBundle(ResourceBundle bundle) {
  3840. setBundle(Messages.extractName(bundle), bundle);
  3841. return this;
  3842. }
  3843. private void setBundle(String bundleBaseName, ResourceBundle bundle) {
  3844. usageMessage().messages(new Messages(this, bundleBaseName, bundle));
  3845. updateArgSpecMessages();
  3846. }
  3847. private void updateArgSpecMessages() {
  3848. for (OptionSpec opt : options()) { opt.messages(usageMessage().messages()); }
  3849. for (PositionalParamSpec pos : positionalParameters()) { pos.messages(usageMessage().messages()); }
  3850. }
  3851. /** Returns a read-only view of the subcommand map. */
  3852. public Map<String, CommandLine> subcommands() { return Collections.unmodifiableMap(commands); }
  3853. /** Adds the specified subcommand with the specified name.
  3854. * If the specified subcommand does not have a ResourceBundle set, it is initialized to the ResourceBundle of this command spec.
  3855. * @param name subcommand name - when this String is encountered in the command line arguments the subcommand is invoked
  3856. * @param subcommand describes the subcommand to envoke when the name is encountered on the command line
  3857. * @return this {@code CommandSpec} object for method chaining */
  3858. public CommandSpec addSubcommand(String name, CommandSpec subcommand) {
  3859. return addSubcommand(name, new CommandLine(subcommand));
  3860. }
  3861. /** Adds the specified subcommand with the specified name.
  3862. * If the specified subcommand does not have a ResourceBundle set, it is initialized to the ResourceBundle of this command spec.
  3863. * @param name subcommand name - when this String is encountered in the command line arguments the subcommand is invoked
  3864. * @param subCommandLine the subcommand to envoke when the name is encountered on the command line
  3865. * @return this {@code CommandSpec} object for method chaining */
  3866. public CommandSpec addSubcommand(String name, CommandLine subCommandLine) {
  3867. Tracer t = new Tracer();
  3868. if (t.isDebug()) {t.debug("Adding subcommand '%s' to '%s'%n", name, this.qualifiedName());}
  3869. CommandLine previous = commands.put(name, subCommandLine);
  3870. if (previous != null && previous != subCommandLine) { throw new InitializationException("Another subcommand named '" + name + "' already exists for command '" + this.name() + "'"); }
  3871. CommandSpec subSpec = subCommandLine.getCommandSpec();
  3872. if (subSpec.name == null) { subSpec.name(name); }
  3873. subSpec.parent(this);
  3874. for (String alias : subSpec.aliases()) {
  3875. if (t.isDebug()) {t.debug("Adding alias '%s' for subcommand '%s' to '%s'%n", alias, name, this.qualifiedName());}
  3876. previous = commands.put(alias, subCommandLine);
  3877. if (previous != null && previous != subCommandLine) { throw new InitializationException("Alias '" + alias + "' for subcommand '" + name + "' is already used by another subcommand of '" + this.name() + "'"); }
  3878. }
  3879. subSpec.initCommandHierarchyWithResourceBundle(resourceBundleBaseName(), resourceBundle());
  3880. return this;
  3881. }
  3882. private void initCommandHierarchyWithResourceBundle(String bundleBaseName, ResourceBundle rb) {
  3883. if (resourceBundle() == null) {
  3884. setBundle(bundleBaseName, rb);
  3885. }
  3886. for (CommandLine sub : commands.values()) { // percolate down the hierarchy
  3887. sub.getCommandSpec().initCommandHierarchyWithResourceBundle(bundleBaseName, rb);
  3888. }
  3889. }
  3890. /** Returns whether method commands should be added as subcommands. Used by the annotation processor.
  3891. * @since 4.0 */
  3892. public boolean isAddMethodSubcommands() { return (isAddMethodSubcommands == null) ? DEFAULT_IS_ADD_METHOD_SUBCOMMANDS : isAddMethodSubcommands; }
  3893. /** Sets whether method commands should be added as subcommands. Used by the annotation processor.
  3894. * @since 4.0 */
  3895. public CommandSpec setAddMethodSubcommands(Boolean addMethodSubcommands) { isAddMethodSubcommands = addMethodSubcommands; return this; }
  3896. /** Reflects on the class of the {@linkplain #userObject() user object} and registers any command methods
  3897. * (class methods annotated with {@code @Command}) as subcommands.
  3898. *
  3899. * @return this {@link CommandSpec} object for method chaining
  3900. * @see #addMethodSubcommands(IFactory)
  3901. * @see #addSubcommand(String, CommandLine)
  3902. * @since 3.6.0
  3903. */
  3904. public CommandSpec addMethodSubcommands() { return addMethodSubcommands(new DefaultFactory()); }
  3905. /** Reflects on the class of the {@linkplain #userObject() user object} and registers any command methods
  3906. * (class methods annotated with {@code @Command}) as subcommands.
  3907. * @param factory the factory used to create instances of subcommands, converters, etc., that are registered declaratively with annotation attributes
  3908. * @return this {@link CommandSpec} object for method chaining
  3909. * @see #addSubcommand(String, CommandLine)
  3910. * @since 3.7.0
  3911. */
  3912. public CommandSpec addMethodSubcommands(IFactory factory) {
  3913. if (userObject() instanceof Method) {
  3914. throw new InitializationException("Cannot discover subcommand methods of this Command Method: " + userObject());
  3915. }
  3916. for (CommandLine sub : createMethodSubcommands(userObject().getClass(), factory)) {
  3917. addSubcommand(sub.getCommandName(), sub);
  3918. }
  3919. isAddMethodSubcommands = true;
  3920. return this;
  3921. }
  3922. static List<CommandLine> createMethodSubcommands(Class<?> cls, IFactory factory) {
  3923. List<CommandLine> result = new ArrayList<CommandLine>();
  3924. for (Method method : getCommandMethods(cls, null)) {
  3925. result.add(new CommandLine(method, factory));
  3926. }
  3927. return result;
  3928. }
  3929. /** Returns the parent command of this subcommand, or {@code null} if this is a top-level command. */
  3930. public CommandSpec parent() { return parent; }
  3931. /** Sets the parent command of this subcommand.
  3932. * @return this CommandSpec for method chaining */
  3933. public CommandSpec parent(CommandSpec parent) { this.parent = parent; return this; }
  3934. /** Adds the specified option spec or positional parameter spec to the list of configured arguments to expect.
  3935. * @param arg the option spec or positional parameter spec to add
  3936. * @return this CommandSpec for method chaining */
  3937. public CommandSpec add(ArgSpec arg) { return arg.isOption() ? addOption((OptionSpec) arg) : addPositional((PositionalParamSpec) arg); }
  3938. /** Adds the specified option spec to the list of configured arguments to expect.
  3939. * The option's {@linkplain OptionSpec#description()} may now return Strings from this
  3940. * CommandSpec's {@linkplain UsageMessageSpec#messages() messages}.
  3941. * The option parameter's {@linkplain OptionSpec#defaultValueString()} may
  3942. * now return Strings from this CommandSpec's {@link CommandSpec#defaultValueProvider()} IDefaultValueProvider}.
  3943. * @param option the option spec to add
  3944. * @return this CommandSpec for method chaining
  3945. * @throws DuplicateOptionAnnotationsException if any of the names of the specified option is the same as the name of another option */
  3946. public CommandSpec addOption(OptionSpec option) {
  3947. for (String name : option.names()) { // cannot be null or empty
  3948. OptionSpec existing = optionsByNameMap.put(name, option);
  3949. if (existing != null) { /* was: && !existing.equals(option)) {*/ // since 4.0 ArgGroups: an option cannot be in multiple groups
  3950. throw DuplicateOptionAnnotationsException.create(name, option, existing);
  3951. }
  3952. if (name.length() == 2 && name.startsWith("-")) { posixOptionsByKeyMap.put(name.charAt(1), option); }
  3953. }
  3954. options.add(option);
  3955. return addArg(option);
  3956. }
  3957. /** Adds the specified positional parameter spec to the list of configured arguments to expect.
  3958. * The positional parameter's {@linkplain PositionalParamSpec#description()} may
  3959. * now return Strings from this CommandSpec's {@linkplain UsageMessageSpec#messages() messages}.
  3960. * The positional parameter's {@linkplain PositionalParamSpec#defaultValueString()} may
  3961. * now return Strings from this CommandSpec's {@link CommandSpec#defaultValueProvider()} IDefaultValueProvider}.
  3962. * @param positional the positional parameter spec to add
  3963. * @return this CommandSpec for method chaining */
  3964. public CommandSpec addPositional(PositionalParamSpec positional) {
  3965. positionalParameters.add(positional);
  3966. return addArg(positional);
  3967. }
  3968. private CommandSpec addArg(ArgSpec arg) {
  3969. args.add(arg);
  3970. if (arg.required() && arg.group() == null) { requiredArgs.add(arg); }
  3971. arg.messages(usageMessage().messages());
  3972. arg.commandSpec = this;
  3973. return this;
  3974. }
  3975. /** Adds the specified {@linkplain ArgGroupSpec argument group} to the groups in this command.
  3976. * @param group the group spec to add
  3977. * @return this CommandSpec for method chaining
  3978. * @throws InitializationException if the specified group or one of its {@linkplain ArgGroupSpec#parentGroup() ancestors} has already been added
  3979. * @since 4.0 */
  3980. public CommandSpec addArgGroup(ArgGroupSpec group) {
  3981. Assert.notNull(group, "group");
  3982. if (group.parentGroup() != null) {
  3983. throw new InitializationException("Groups that are part of another group should not be added to a command. Add only the top-level group.");
  3984. }
  3985. check(group, flatten(groups, new HashSet<ArgGroupSpec>()));
  3986. this.groups.add(group);
  3987. addGroupArgsToCommand(group, new HashMap<String, ArgGroupSpec>());
  3988. return this;
  3989. }
  3990. private void addGroupArgsToCommand(ArgGroupSpec group, Map<String, ArgGroupSpec> added) {
  3991. for (ArgSpec arg : group.args()) {
  3992. if (arg.isOption()) {
  3993. for (String name : ((OptionSpec) arg).names()) {
  3994. if (added.containsKey(name)) {
  3995. throw new DuplicateNameException("An option cannot be in multiple groups but " + name + " is in " + group.synopsis() + " and " + added.get(name).synopsis() + ". Refactor to avoid this. For example, (-a | (-a -b)) can be rewritten as (-a [-b]), and (-a -b | -a -c) can be rewritten as (-a (-b | -c)).");
  3996. }
  3997. }
  3998. for (String name : ((OptionSpec) arg).names()) { added.put(name, group); }
  3999. }
  4000. add(arg);
  4001. }
  4002. for (ArgGroupSpec sub : group.subgroups()) { addGroupArgsToCommand(sub, added); }
  4003. }
  4004. private Set<ArgGroupSpec> flatten(Collection<ArgGroupSpec> groups, Set<ArgGroupSpec> result) {
  4005. for (ArgGroupSpec group : groups) { flatten(group, result); } return result;
  4006. }
  4007. private Set<ArgGroupSpec> flatten(ArgGroupSpec group, Set<ArgGroupSpec> result) {
  4008. result.add(group);
  4009. for (ArgGroupSpec sub : group.subgroups()) { flatten(sub, result); }
  4010. return result;
  4011. }
  4012. private void check(ArgGroupSpec group, Set<ArgGroupSpec> existing) {
  4013. if (existing.contains(group)) {
  4014. throw new InitializationException("The specified group " + group.synopsis() + " has already been added to the " + qualifiedName() + " command.");
  4015. }
  4016. for (ArgGroupSpec sub : group.subgroups()) { check(sub, existing); }
  4017. }
  4018. /** Adds the specified mixin {@code CommandSpec} object to the map of mixins for this command.
  4019. * @param name the name that can be used to later retrieve the mixin
  4020. * @param mixin the mixin whose options and positional parameters and other attributes to add to this command
  4021. * @return this CommandSpec for method chaining */
  4022. public CommandSpec addMixin(String name, CommandSpec mixin) {
  4023. mixins.put(name, mixin);
  4024. parser.initSeparator(mixin.parser.separator());
  4025. initName(mixin.name());
  4026. initVersion(mixin.version());
  4027. initHelpCommand(mixin.helpCommand());
  4028. initVersionProvider(mixin.versionProvider());
  4029. initDefaultValueProvider(mixin.defaultValueProvider());
  4030. usageMessage.initFromMixin(mixin.usageMessage, this);
  4031. for (Map.Entry<String, CommandLine> entry : mixin.subcommands().entrySet()) {
  4032. addSubcommand(entry.getKey(), entry.getValue());
  4033. }
  4034. for (OptionSpec optionSpec : mixin.options()) { addOption(optionSpec); }
  4035. for (PositionalParamSpec paramSpec : mixin.positionalParameters()) { addPositional(paramSpec); }
  4036. return this;
  4037. }
  4038. /** Adds the specified {@code UnmatchedArgsBinding} to the list of model objects to capture unmatched arguments for this command.
  4039. * @param spec the unmatched arguments binding to capture unmatched arguments
  4040. * @return this CommandSpec for method chaining */
  4041. public CommandSpec addUnmatchedArgsBinding(UnmatchedArgsBinding spec) { unmatchedArgs.add(spec); parser().unmatchedArgumentsAllowed(true); return this; }
  4042. /** Returns a map of the mixin names to mixin {@code CommandSpec} objects configured for this command.
  4043. * @return an immutable map of mixins added to this command. */
  4044. public Map<String, CommandSpec> mixins() { return Collections.unmodifiableMap(mixins); }
  4045. /** Returns the list of options configured for this command.
  4046. * @return an immutable list of options that this command recognizes. */
  4047. public List<OptionSpec> options() { return Collections.unmodifiableList(options); }
  4048. /** Returns the list of positional parameters configured for this command.
  4049. * @return an immutable list of positional parameters that this command recognizes. */
  4050. public List<PositionalParamSpec> positionalParameters() { return Collections.unmodifiableList(positionalParameters); }
  4051. /** Returns the {@linkplain ArgGroupSpec argument groups} in this command.
  4052. * @return an immutable list of groups of options and positional parameters in this command
  4053. * @since 4.0 */
  4054. public List<ArgGroupSpec> argGroups() { return Collections.unmodifiableList(groups); }
  4055. /** Returns a map of the option names to option spec objects configured for this command.
  4056. * @return an immutable map of options that this command recognizes. */
  4057. public Map<String, OptionSpec> optionsMap() { return Collections.unmodifiableMap(optionsByNameMap); }
  4058. /** Returns a map of the short (single character) option names to option spec objects configured for this command.
  4059. * @return an immutable map of options that this command recognizes. */
  4060. public Map<Character, OptionSpec> posixOptionsMap() { return Collections.unmodifiableMap(posixOptionsByKeyMap); }
  4061. /** Returns the list of required options and positional parameters configured for this command.
  4062. * This does not include options and positional parameters that are part of a {@linkplain ArgGroupSpec group}.
  4063. * @return an immutable list of the required options and positional parameters for this command. */
  4064. public List<ArgSpec> requiredArgs() { return Collections.unmodifiableList(requiredArgs); }
  4065. /** Returns the list of {@link UnmatchedArgsBinding UnmatchedArgumentsBindings} configured for this command;
  4066. * each {@code UnmatchedArgsBinding} captures the arguments that could not be matched to any options or positional parameters. */
  4067. public List<UnmatchedArgsBinding> unmatchedArgsBindings() { return Collections.unmodifiableList(unmatchedArgs); }
  4068. /** Returns name of this command. Used in the synopsis line of the help message.
  4069. * {@link #DEFAULT_COMMAND_NAME} by default, initialized from {@link Command#name()} if defined.
  4070. * @see #qualifiedName() */
  4071. public String name() { return (name == null) ? DEFAULT_COMMAND_NAME : name; }
  4072. /** Returns the alias command names of this subcommand.
  4073. * @since 3.1 */
  4074. public String[] aliases() { return aliases.toArray(new String[0]); }
  4075. /** Returns all names of this command, including {@link #name()} and {@link #aliases()}.
  4076. * @since 3.9 */
  4077. public Set<String> names() {
  4078. Set<String> result = new LinkedHashSet<String>();
  4079. result.add(name());
  4080. result.addAll(Arrays.asList(aliases()));
  4081. return result;
  4082. }
  4083. /** Returns the list of all options and positional parameters configured for this command.
  4084. * @return an immutable list of all options and positional parameters for this command. */
  4085. public List<ArgSpec> args() { return Collections.unmodifiableList(args); }
  4086. Object[] argValues() {
  4087. Map<Class<?>, CommandSpec> allMixins = null;
  4088. int argsLength = args.size();
  4089. int shift = 0;
  4090. for (Map.Entry<String, CommandSpec> mixinEntry : mixins.entrySet()) {
  4091. if (mixinEntry.getKey().equals(AutoHelpMixin.KEY)) {
  4092. shift = 2;
  4093. argsLength -= shift;
  4094. continue;
  4095. }
  4096. CommandSpec mixin = mixinEntry.getValue();
  4097. int mixinArgs = mixin.args.size();
  4098. argsLength -= (mixinArgs - 1); // subtract 1 because that's the mixin
  4099. if (allMixins == null) {
  4100. allMixins = new IdentityHashMap<Class<?>, CommandSpec>(mixins.size());
  4101. }
  4102. allMixins.put(mixin.userObject.getClass(), mixin);
  4103. }
  4104. Object[] values = new Object[argsLength];
  4105. if (allMixins == null) {
  4106. for (int i = 0; i < values.length; i++) { values[i] = args.get(i + shift).getValue(); }
  4107. } else {
  4108. int argIndex = shift;
  4109. Class<?>[] methodParams = ((Method) userObject).getParameterTypes();
  4110. for (int i = 0; i < methodParams.length; i++) {
  4111. final Class<?> param = methodParams[i];
  4112. CommandSpec mixin = allMixins.remove(param);
  4113. if (mixin == null) {
  4114. values[i] = args.get(argIndex++).getValue();
  4115. } else {
  4116. values[i] = mixin.userObject;
  4117. argIndex += mixin.args.size();
  4118. }
  4119. }
  4120. }
  4121. return values;
  4122. }
  4123. /** Returns the String to use as the program name in the synopsis line of the help message:
  4124. * this command's {@link #name() name}, preceded by the qualified name of the parent command, if any, separated by a space.
  4125. * @return {@link #DEFAULT_COMMAND_NAME} by default, initialized from {@link Command#name()} and the parent command if defined.
  4126. * @since 3.0.1 */
  4127. public String qualifiedName() { return qualifiedName(" "); }
  4128. /** Returns this command's fully qualified name, which is its {@link #name() name}, preceded by the qualified name of the parent command, if this command has a parent command.
  4129. * @return {@link #DEFAULT_COMMAND_NAME} by default, initialized from {@link Command#name()} and the parent command if any.
  4130. * @param separator the string to put between the names of the commands in the hierarchy
  4131. * @since 3.6 */
  4132. public String qualifiedName(String separator) {
  4133. String result = name();
  4134. if (parent() != null) { result = parent().qualifiedName(separator) + separator + result; }
  4135. return result;
  4136. }
  4137. /** Returns version information for this command, to print to the console when the user specifies an
  4138. * {@linkplain OptionSpec#versionHelp() option} to request version help. This is not part of the usage help message.
  4139. * @return the version strings generated by the {@link #versionProvider() version provider} if one is set, otherwise the {@linkplain #version(String...) version literals}*/
  4140. public String[] version() {
  4141. if (versionProvider != null) {
  4142. try {
  4143. return versionProvider.getVersion();
  4144. } catch (Exception ex) {
  4145. String msg = "Could not get version info from " + versionProvider + ": " + ex;
  4146. throw new ExecutionException(this.commandLine, msg, ex);
  4147. }
  4148. }
  4149. return version == null ? UsageMessageSpec.DEFAULT_MULTI_LINE : version;
  4150. }
  4151. /** Returns the version provider for this command, to generate the {@link #version()} strings.
  4152. * @return the version provider or {@code null} if the version strings should be returned from the {@linkplain #version(String...) version literals}.*/
  4153. public IVersionProvider versionProvider() { return versionProvider; }
  4154. /** Returns whether this subcommand is a help command, and required options and positional
  4155. * parameters of the parent command should not be validated.
  4156. * @return {@code true} if this subcommand is a help command and picocli should not check for missing required
  4157. * options and positional parameters on the parent command
  4158. * @see Command#helpCommand() */
  4159. public boolean helpCommand() { return (isHelpCommand == null) ? DEFAULT_IS_HELP_COMMAND : isHelpCommand; }
  4160. /** Returns {@code true} if the standard help options have been mixed in with this command, {@code false} otherwise. */
  4161. public boolean mixinStandardHelpOptions() { return mixins.containsKey(AutoHelpMixin.KEY); }
  4162. /** Returns a string representation of this command, used in error messages and trace messages. */
  4163. public String toString() { return toString; }
  4164. /** Sets the String to use as the program name in the synopsis line of the help message.
  4165. * @return this CommandSpec for method chaining */
  4166. public CommandSpec name(String name) { this.name = name; return this; }
  4167. /** Sets the alternative names by which this subcommand is recognized on the command line.
  4168. * @return this CommandSpec for method chaining
  4169. * @since 3.1 */
  4170. public CommandSpec aliases(String... aliases) {
  4171. this.aliases = new LinkedHashSet<String>(Arrays.asList(aliases == null ? new String[0] : aliases));
  4172. return this;
  4173. }
  4174. /** Returns the default value provider for this command.
  4175. * @return the default value provider or {@code null}
  4176. * @since 3.6 */
  4177. public IDefaultValueProvider defaultValueProvider() { return defaultValueProvider; }
  4178. /** Sets default value provider for this command.
  4179. * @param defaultValueProvider the default value provider to use, or {@code null}.
  4180. * @return this CommandSpec for method chaining
  4181. * @since 3.6 */
  4182. public CommandSpec defaultValueProvider(IDefaultValueProvider defaultValueProvider) { this.defaultValueProvider = defaultValueProvider; return this; }
  4183. /** Sets version information literals for this command, to print to the console when the user specifies an
  4184. * {@linkplain OptionSpec#versionHelp() option} to request version help. Only used if no {@link #versionProvider() versionProvider} is set.
  4185. * @return this CommandSpec for method chaining */
  4186. public CommandSpec version(String... version) { this.version = version; return this; }
  4187. /** Sets version provider for this command, to generate the {@link #version()} strings.
  4188. * @param versionProvider the version provider to use to generate the version strings, or {@code null} if the {@linkplain #version(String...) version literals} should be used.
  4189. * @return this CommandSpec for method chaining */
  4190. public CommandSpec versionProvider(IVersionProvider versionProvider) { this.versionProvider = versionProvider; return this; }
  4191. /** Sets whether this is a help command and required parameter checking should be suspended.
  4192. * @return this CommandSpec for method chaining
  4193. * @see Command#helpCommand() */
  4194. public CommandSpec helpCommand(boolean newValue) {isHelpCommand = newValue; return this;}
  4195. /** Sets whether the standard help options should be mixed in with this command.
  4196. * @return this CommandSpec for method chaining
  4197. * @see Command#mixinStandardHelpOptions() */
  4198. public CommandSpec mixinStandardHelpOptions(boolean newValue) {
  4199. if (newValue) {
  4200. CommandSpec mixin = CommandSpec.forAnnotatedObject(new AutoHelpMixin(), new DefaultFactory());
  4201. addMixin(AutoHelpMixin.KEY, mixin);
  4202. } else {
  4203. CommandSpec helpMixin = mixins.remove(AutoHelpMixin.KEY);
  4204. if (helpMixin != null) {
  4205. options.removeAll(helpMixin.options);
  4206. for (OptionSpec option : helpMixin.options()) {
  4207. for (String name : option.names) {
  4208. optionsByNameMap.remove(name);
  4209. if (name.length() == 2 && name.startsWith("-")) { posixOptionsByKeyMap.remove(name.charAt(1)); }
  4210. }
  4211. }
  4212. }
  4213. }
  4214. return this;
  4215. }
  4216. /** Sets the string representation of this command, used in error messages and trace messages.
  4217. * @param newValue the string representation
  4218. * @return this CommandSpec for method chaining */
  4219. public CommandSpec withToString(String newValue) { this.toString = newValue; return this; }
  4220. /**
  4221. * Updates the following attributes from the specified {@code @Command} annotation:
  4222. * aliases, {@link ParserSpec#separator() parser separator}, command name, version, help command,
  4223. * version provider, default provider and {@link UsageMessageSpec usage message spec}.
  4224. * @param cmd the {@code @Command} annotation to get attribute values from
  4225. * @param factory factory used to instantiate classes
  4226. * @since 3.7
  4227. */
  4228. public void updateCommandAttributes(Command cmd, IFactory factory) {
  4229. aliases(cmd.aliases());
  4230. parser().updateSeparator(cmd.separator());
  4231. updateName(cmd.name());
  4232. updateVersion(cmd.version());
  4233. updateHelpCommand(cmd.helpCommand());
  4234. updateAddMethodSubcommands(cmd.addMethodSubcommands());
  4235. usageMessage().updateFromCommand(cmd, this);
  4236. if (factory != null) {
  4237. updateVersionProvider(cmd.versionProvider(), factory);
  4238. initDefaultValueProvider(cmd.defaultValueProvider(), factory);
  4239. }
  4240. }
  4241. void initName(String value) { if (initializable(name, value, DEFAULT_COMMAND_NAME)) {name = value;} }
  4242. void initHelpCommand(boolean value) { if (initializable(isHelpCommand, value, DEFAULT_IS_HELP_COMMAND)) {isHelpCommand = value;} }
  4243. void initVersion(String[] value) { if (initializable(version, value, UsageMessageSpec.DEFAULT_MULTI_LINE)) {version = value.clone();} }
  4244. void initVersionProvider(IVersionProvider value) { if (versionProvider == null) { versionProvider = value; } }
  4245. void initDefaultValueProvider(IDefaultValueProvider value) { if (defaultValueProvider == null) { defaultValueProvider = value; } }
  4246. void initDefaultValueProvider(Class<? extends IDefaultValueProvider> value, IFactory factory) {
  4247. if (initializable(defaultValueProvider, value, NoDefaultProvider.class)) { defaultValueProvider = (DefaultFactory.createDefaultValueProvider(factory, value)); }
  4248. }
  4249. void updateName(String value) { if (isNonDefault(value, DEFAULT_COMMAND_NAME)) {name = value;} }
  4250. void updateHelpCommand(boolean value) { if (isNonDefault(value, DEFAULT_IS_HELP_COMMAND)) {isHelpCommand = value;} }
  4251. void updateAddMethodSubcommands(boolean value) { if (isNonDefault(value, DEFAULT_IS_ADD_METHOD_SUBCOMMANDS)) {isAddMethodSubcommands = value;} }
  4252. void updateVersion(String[] value) { if (isNonDefault(value, UsageMessageSpec.DEFAULT_MULTI_LINE)) {version = value.clone();} }
  4253. void updateVersionProvider(Class<? extends IVersionProvider> value, IFactory factory) {
  4254. if (isNonDefault(value, NoVersionProvider.class)) { versionProvider = (DefaultFactory.createVersionProvider(factory, value)); }
  4255. }
  4256. /** Returns the option with the specified short name, or {@code null} if no option with that name is defined for this command. */
  4257. public OptionSpec findOption(char shortName) { return findOption(shortName, options()); }
  4258. /** Returns the option with the specified name, or {@code null} if no option with that name is defined for this command.
  4259. * @param name used to search the options. May include option name prefix characters or not. */
  4260. public OptionSpec findOption(String name) { return findOption(name, options()); }
  4261. static OptionSpec findOption(char shortName, Iterable<OptionSpec> options) {
  4262. for (OptionSpec option : options) {
  4263. for (String name : option.names()) {
  4264. if (name.length() == 2 && name.charAt(0) == '-' && name.charAt(1) == shortName) { return option; }
  4265. if (name.length() == 1 && name.charAt(0) == shortName) { return option; }
  4266. }
  4267. }
  4268. return null;
  4269. }
  4270. static OptionSpec findOption(String name, List<OptionSpec> options) {
  4271. for (OptionSpec option : options) {
  4272. for (String prefixed : option.names()) {
  4273. if (prefixed.equals(name) || stripPrefix(prefixed).equals(name)) { return option; }
  4274. }
  4275. }
  4276. return null;
  4277. }
  4278. static String stripPrefix(String prefixed) {
  4279. for (int i = 0; i < prefixed.length(); i++) {
  4280. if (Character.isJavaIdentifierPart(prefixed.charAt(i))) { return prefixed.substring(i); }
  4281. }
  4282. return prefixed;
  4283. }
  4284. List<String> findOptionNamesWithPrefix(String prefix) {
  4285. List<String> result = new ArrayList<String>();
  4286. for (OptionSpec option : options()) {
  4287. for (String name : option.names()) {
  4288. if (stripPrefix(name).startsWith(prefix)) { result.add(name); }
  4289. }
  4290. }
  4291. return result;
  4292. }
  4293. boolean resemblesOption(String arg, Tracer tracer) {
  4294. if (parser().unmatchedOptionsArePositionalParams()) {
  4295. if (tracer != null && tracer.isDebug()) {tracer.debug("Parser is configured to treat all unmatched options as positional parameter%n", arg);}
  4296. return false;
  4297. }
  4298. if (arg.length() == 1) {
  4299. if (tracer != null && tracer.isDebug()) {tracer.debug("Single-character arguments that don't match known options are considered positional parameters%n", arg);}
  4300. return false;
  4301. }
  4302. if (options().isEmpty()) {
  4303. boolean result = arg.startsWith("-");
  4304. if (tracer != null && tracer.isDebug()) {tracer.debug("'%s' %s an option%n", arg, (result ? "resembles" : "doesn't resemble"));}
  4305. return result;
  4306. }
  4307. int count = 0;
  4308. for (String optionName : optionsMap().keySet()) {
  4309. for (int i = 0; i < arg.length(); i++) {
  4310. if (optionName.length() > i && arg.charAt(i) == optionName.charAt(i)) { count++; } else { break; }
  4311. }
  4312. }
  4313. boolean result = count > 0 && count * 10 >= optionsMap().size() * 9; // at least one prefix char in common with 9 out of 10 options
  4314. if (tracer != null && tracer.isDebug()) {tracer.debug("'%s' %s an option: %d matching prefix chars out of %d option names%n", arg, (result ? "resembles" : "doesn't resemble"), count, optionsMap().size());}
  4315. return result;
  4316. }
  4317. }
  4318. private static boolean initializable(Object current, Object candidate, Object defaultValue) {
  4319. return current == null && isNonDefault(candidate, defaultValue);
  4320. }
  4321. private static boolean initializable(Object current, Object[] candidate, Object[] defaultValue) {
  4322. return current == null && isNonDefault(candidate, defaultValue);
  4323. }
  4324. private static boolean isNonDefault(Object candidate, Object defaultValue) {
  4325. return !Assert.notNull(defaultValue, "defaultValue").equals(candidate);
  4326. }
  4327. private static boolean isNonDefault(Object[] candidate, Object[] defaultValue) {
  4328. return !Arrays.equals(Assert.notNull(defaultValue, "defaultValue"), candidate);
  4329. }
  4330. /** Models the usage help message specification and can be used to customize the usage help message.
  4331. * <p>
  4332. * This class provides two ways to customize the usage help message:
  4333. * </p>
  4334. * <ul>
  4335. * <li>Change the text of the predefined sections (this may also be done declaratively using the annotations)</li>
  4336. * <li>Add custom sections, or remove or re-order predefined sections</li>
  4337. * </ul>
  4338. * <p>
  4339. * The pre-defined sections have getters and setters that return a String (or array of Strings). For example:
  4340. * {@link #description()} and {@link #description(String...)} or {@link #header()} and {@link #header(String...)}.
  4341. * </p><p>
  4342. * Changing the section order, or adding custom sections can be accomplished with {@link #sectionKeys(List)} and {@link #sectionMap(Map)}.
  4343. * This gives complete freedom on how a usage help message section is rendered, but it also means that the {@linkplain IHelpSectionRenderer section renderer}
  4344. * is responsible for all aspects of rendering the section, including layout and emitting ANSI escape codes.
  4345. * The {@link Help.TextTable} and {@link Help.Ansi.Text} classes, and the {@link CommandLine.Help.Ansi#string(String)} and {@link CommandLine.Help.Ansi#text(String)} methods may be useful.
  4346. * </p><p>
  4347. * The usage help message is created more or less like this:
  4348. * </p>
  4349. * <pre>
  4350. * // CommandLine.usage(...) or CommandLine.getUsageMessage(...)
  4351. * Help.ColorScheme colorScheme = Help.defaultColorScheme(Help.Ansi.AUTO);
  4352. * Help help = getHelpFactory().create(getCommandSpec(), colorScheme)
  4353. * StringBuilder result = new StringBuilder();
  4354. * for (String key : getHelpSectionKeys()) {
  4355. * IHelpSectionRenderer renderer = getHelpSectionMap().get(key);
  4356. * if (renderer != null) { result.append(renderer.render(help)); }
  4357. * }
  4358. * // return or print result
  4359. * </pre>
  4360. * <p>
  4361. * Where the default {@linkplain #sectionMap() help section map} is constructed like this:</p>
  4362. * <pre>{@code
  4363. * // The default section renderers delegate to methods in Help for their implementation
  4364. * // (using Java 8 lambda notation for brevity):
  4365. * Map<String, IHelpSectionRenderer> sectionMap = new HashMap<>();
  4366. * sectionMap.put(SECTION_KEY_HEADER_HEADING, help -> help.headerHeading());
  4367. * sectionMap.put(SECTION_KEY_HEADER, help -> help.header());
  4368. * sectionMap.put(SECTION_KEY_SYNOPSIS_HEADING, help -> help.synopsisHeading()); //e.g. Usage:
  4369. * sectionMap.put(SECTION_KEY_SYNOPSIS, help -> help.synopsis(help.synopsisHeadingLength())); //e.g. <cmd> [OPTIONS] <subcmd> [COMMAND-OPTIONS] [ARGUMENTS]
  4370. * sectionMap.put(SECTION_KEY_DESCRIPTION_HEADING, help -> help.descriptionHeading()); //e.g. %nDescription:%n%n
  4371. * sectionMap.put(SECTION_KEY_DESCRIPTION, help -> help.description()); //e.g. {"Converts foos to bars.", "Use options to control conversion mode."}
  4372. * sectionMap.put(SECTION_KEY_PARAMETER_LIST_HEADING, help -> help.parameterListHeading()); //e.g. %nPositional parameters:%n%n
  4373. * sectionMap.put(SECTION_KEY_PARAMETER_LIST, help -> help.parameterList()); //e.g. [FILE...] the files to convert
  4374. * sectionMap.put(SECTION_KEY_OPTION_LIST_HEADING, help -> help.optionListHeading()); //e.g. %nOptions:%n%n
  4375. * sectionMap.put(SECTION_KEY_OPTION_LIST, help -> help.optionList()); //e.g. -h, --help displays this help and exits
  4376. * sectionMap.put(SECTION_KEY_COMMAND_LIST_HEADING, help -> help.commandListHeading()); //e.g. %nCommands:%n%n
  4377. * sectionMap.put(SECTION_KEY_COMMAND_LIST, help -> help.commandList()); //e.g. add adds the frup to the frooble
  4378. * sectionMap.put(SECTION_KEY_FOOTER_HEADING, help -> help.footerHeading());
  4379. * sectionMap.put(SECTION_KEY_FOOTER, help -> help.footer());
  4380. * }</pre>
  4381. *
  4382. * @since 3.0 */
  4383. public static class UsageMessageSpec {
  4384. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Header Heading section.
  4385. * The default renderer for this section calls {@link Help#headerHeading(Object...)}.
  4386. * @since 3.9 */
  4387. public static final String SECTION_KEY_HEADER_HEADING = "headerHeading";
  4388. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Header section.
  4389. * The default renderer for this section calls {@link Help#header(Object...)}.
  4390. * @since 3.9 */
  4391. public static final String SECTION_KEY_HEADER = "header";
  4392. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Synopsis Heading section.
  4393. * The default renderer for this section calls {@link Help#synopsisHeading(Object...)}.
  4394. * @since 3.9 */
  4395. public static final String SECTION_KEY_SYNOPSIS_HEADING = "synopsisHeading";
  4396. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Synopsis section.
  4397. * The default renderer for this section calls {@link Help#synopsis(int)}.
  4398. * @since 3.9 */
  4399. public static final String SECTION_KEY_SYNOPSIS = "synopsis";
  4400. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Description Heading section.
  4401. * The default renderer for this section calls {@link Help#descriptionHeading(Object...)}.
  4402. * @since 3.9 */
  4403. public static final String SECTION_KEY_DESCRIPTION_HEADING = "descriptionHeading";
  4404. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Description section.
  4405. * The default renderer for this section calls {@link Help#description(Object...)}.
  4406. * @since 3.9 */
  4407. public static final String SECTION_KEY_DESCRIPTION = "description";
  4408. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Parameter List Heading section.
  4409. * The default renderer for this section calls {@link Help#parameterListHeading(Object...)}.
  4410. * @since 3.9 */
  4411. public static final String SECTION_KEY_PARAMETER_LIST_HEADING = "parameterListHeading";
  4412. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Parameter List section.
  4413. * The default renderer for this section calls {@link Help#parameterList()}.
  4414. * @since 3.9 */
  4415. public static final String SECTION_KEY_PARAMETER_LIST = "parameterList";
  4416. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Option List Heading section.
  4417. * The default renderer for this section calls {@link Help#optionListHeading(Object...)}.
  4418. * @since 3.9 */
  4419. public static final String SECTION_KEY_OPTION_LIST_HEADING = "optionListHeading";
  4420. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Option List section.
  4421. * The default renderer for this section calls {@link Help#optionList()}.
  4422. * @since 3.9 */
  4423. public static final String SECTION_KEY_OPTION_LIST = "optionList";
  4424. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Subcommand List Heading section.
  4425. * The default renderer for this section calls {@link Help#commandListHeading(Object...)}.
  4426. * @since 3.9 */
  4427. public static final String SECTION_KEY_COMMAND_LIST_HEADING = "commandListHeading";
  4428. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Subcommand List section.
  4429. * The default renderer for this section calls {@link Help#commandList()}.
  4430. * @since 3.9 */
  4431. public static final String SECTION_KEY_COMMAND_LIST = "commandList";
  4432. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Footer Heading section.
  4433. * The default renderer for this section calls {@link Help#footerHeading(Object...)}.
  4434. * @since 3.9 */
  4435. public static final String SECTION_KEY_FOOTER_HEADING = "footerHeading";
  4436. /** {@linkplain #sectionKeys() Section key} to {@linkplain #sectionMap() control} the {@linkplain IHelpSectionRenderer section renderer} for the Footer section.
  4437. * The default renderer for this section calls {@link Help#footer(Object...)}.
  4438. * @since 3.9 */
  4439. public static final String SECTION_KEY_FOOTER = "footer";
  4440. /** Constant holding the default usage message width: <code>{@value}</code>. */
  4441. public final static int DEFAULT_USAGE_WIDTH = 80;
  4442. private final static int MINIMUM_USAGE_WIDTH = 55;
  4443. /** Constant String holding the default synopsis heading: <code>{@value}</code>. */
  4444. static final String DEFAULT_SYNOPSIS_HEADING = "Usage: ";
  4445. /** Constant String holding the default command list heading: <code>{@value}</code>. */
  4446. static final String DEFAULT_COMMAND_LIST_HEADING = "Commands:%n";
  4447. /** Constant String holding the default string that separates options from option parameters: {@code ' '} ({@value}). */
  4448. static final char DEFAULT_REQUIRED_OPTION_MARKER = ' ';
  4449. /** Constant Boolean holding the default setting for whether to abbreviate the synopsis: <code>{@value}</code>.*/
  4450. static final Boolean DEFAULT_ABBREVIATE_SYNOPSIS = Boolean.FALSE;
  4451. /** Constant Boolean holding the default setting for whether to sort the options alphabetically: <code>{@value}</code>.*/
  4452. static final Boolean DEFAULT_SORT_OPTIONS = Boolean.TRUE;
  4453. /** Constant Boolean holding the default setting for whether to show default values in the usage help message: <code>{@value}</code>.*/
  4454. static final Boolean DEFAULT_SHOW_DEFAULT_VALUES = Boolean.FALSE;
  4455. /** Constant Boolean holding the default setting for whether this command should be listed in the usage help of the parent command: <code>{@value}</code>.*/
  4456. static final Boolean DEFAULT_HIDDEN = Boolean.FALSE;
  4457. static final String DEFAULT_SINGLE_VALUE = "";
  4458. static final String[] DEFAULT_MULTI_LINE = {};
  4459. private IHelpFactory helpFactory;
  4460. private List<String> sectionKeys = Collections.unmodifiableList(Arrays.asList(
  4461. SECTION_KEY_HEADER_HEADING,
  4462. SECTION_KEY_HEADER,
  4463. SECTION_KEY_SYNOPSIS_HEADING,
  4464. SECTION_KEY_SYNOPSIS,
  4465. SECTION_KEY_DESCRIPTION_HEADING,
  4466. SECTION_KEY_DESCRIPTION,
  4467. SECTION_KEY_PARAMETER_LIST_HEADING,
  4468. SECTION_KEY_PARAMETER_LIST,
  4469. SECTION_KEY_OPTION_LIST_HEADING,
  4470. SECTION_KEY_OPTION_LIST,
  4471. SECTION_KEY_COMMAND_LIST_HEADING,
  4472. SECTION_KEY_COMMAND_LIST,
  4473. SECTION_KEY_FOOTER_HEADING,
  4474. SECTION_KEY_FOOTER));
  4475. private Map<String, IHelpSectionRenderer> helpSectionRendererMap = createHelpSectionRendererMap();
  4476. private String[] description;
  4477. private String[] customSynopsis;
  4478. private String[] header;
  4479. private String[] footer;
  4480. private Boolean abbreviateSynopsis;
  4481. private Boolean sortOptions;
  4482. private Boolean showDefaultValues;
  4483. private Boolean hidden;
  4484. private Character requiredOptionMarker;
  4485. private String headerHeading;
  4486. private String synopsisHeading;
  4487. private String descriptionHeading;
  4488. private String parameterListHeading;
  4489. private String optionListHeading;
  4490. private String commandListHeading;
  4491. private String footerHeading;
  4492. private int width = DEFAULT_USAGE_WIDTH;
  4493. private Messages messages;
  4494. /**
  4495. * Sets the maximum usage help message width to the specified value. Longer values are wrapped.
  4496. * @param newValue the new maximum usage help message width. Must be 55 or greater.
  4497. * @return this {@code UsageMessageSpec} for method chaining
  4498. * @throws IllegalArgumentException if the specified width is less than 55
  4499. */
  4500. public UsageMessageSpec width(int newValue) {
  4501. if (newValue < MINIMUM_USAGE_WIDTH) {
  4502. throw new InitializationException("Invalid usage message width " + newValue + ". Minimum value is " + MINIMUM_USAGE_WIDTH);
  4503. }
  4504. width = newValue; return this;
  4505. }
  4506. private static int getSysPropertyWidthOrDefault(int defaultWidth) {
  4507. String userValue = System.getProperty("picocli.usage.width");
  4508. if (userValue == null) { return defaultWidth; }
  4509. try {
  4510. int width = Integer.parseInt(userValue);
  4511. if (width < MINIMUM_USAGE_WIDTH) {
  4512. new Tracer().warn("Invalid picocli.usage.width value %d. Using minimum usage width %d.%n", width, MINIMUM_USAGE_WIDTH);
  4513. return MINIMUM_USAGE_WIDTH;
  4514. }
  4515. return width;
  4516. } catch (NumberFormatException ex) {
  4517. new Tracer().warn("Invalid picocli.usage.width value '%s'. Using usage width %d.%n", userValue, defaultWidth);
  4518. return defaultWidth;
  4519. }
  4520. }
  4521. /** Returns the maximum usage help message width. Derived from system property {@code "picocli.usage.width"}
  4522. * if set, otherwise returns the value set via the {@link #width(int)} method, or if not set, the {@linkplain #DEFAULT_USAGE_WIDTH default width}.
  4523. * @return the maximum usage help message width. Never returns less than 55. */
  4524. public int width() { return getSysPropertyWidthOrDefault(width); }
  4525. /** Returns the help section renderers for the predefined section keys. see: {@link #sectionKeys()} */
  4526. private Map<String, IHelpSectionRenderer> createHelpSectionRendererMap() {
  4527. Map<String, IHelpSectionRenderer> result = new HashMap<String, IHelpSectionRenderer>();
  4528. result.put(SECTION_KEY_HEADER_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.headerHeading(); } });
  4529. result.put(SECTION_KEY_HEADER, new IHelpSectionRenderer() { public String render(Help help) { return help.header(); } });
  4530. //e.g. Usage:
  4531. result.put(SECTION_KEY_SYNOPSIS_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.synopsisHeading(); } });
  4532. //e.g. &lt;main class&gt; [OPTIONS] &lt;command&gt; [COMMAND-OPTIONS] [ARGUMENTS]
  4533. result.put(SECTION_KEY_SYNOPSIS, new IHelpSectionRenderer() { public String render(Help help) { return help.synopsis(help.synopsisHeadingLength()); } });
  4534. //e.g. %nDescription:%n%n
  4535. result.put(SECTION_KEY_DESCRIPTION_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.descriptionHeading(); } });
  4536. //e.g. {"Converts foos to bars.", "Use options to control conversion mode."}
  4537. result.put(SECTION_KEY_DESCRIPTION, new IHelpSectionRenderer() { public String render(Help help) { return help.description(); } });
  4538. //e.g. %nPositional parameters:%n%n
  4539. result.put(SECTION_KEY_PARAMETER_LIST_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.parameterListHeading(); } });
  4540. //e.g. [FILE...] the files to convert
  4541. result.put(SECTION_KEY_PARAMETER_LIST, new IHelpSectionRenderer() { public String render(Help help) { return help.parameterList(); } });
  4542. //e.g. %nOptions:%n%n
  4543. result.put(SECTION_KEY_OPTION_LIST_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.optionListHeading(); } });
  4544. //e.g. -h, --help displays this help and exits
  4545. result.put(SECTION_KEY_OPTION_LIST, new IHelpSectionRenderer() { public String render(Help help) { return help.optionList(); } });
  4546. //e.g. %nCommands:%n%n
  4547. result.put(SECTION_KEY_COMMAND_LIST_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.commandListHeading(); } });
  4548. //e.g. add adds the frup to the frooble
  4549. result.put(SECTION_KEY_COMMAND_LIST, new IHelpSectionRenderer() { public String render(Help help) { return help.commandList(); } });
  4550. result.put(SECTION_KEY_FOOTER_HEADING, new IHelpSectionRenderer() { public String render(Help help) { return help.footerHeading(); } });
  4551. result.put(SECTION_KEY_FOOTER, new IHelpSectionRenderer() { public String render(Help help) { return help.footer(); } });
  4552. return result;
  4553. }
  4554. /**
  4555. * Returns the section keys in the order that the usage help message should render the sections.
  4556. * This ordering may be modified with the {@link #sectionKeys(List) sectionKeys setter}. The default keys are (in order):
  4557. * <ol>
  4558. * <li>{@link UsageMessageSpec#SECTION_KEY_HEADER_HEADING SECTION_KEY_HEADER_HEADING}</li>
  4559. * <li>{@link UsageMessageSpec#SECTION_KEY_HEADER SECTION_KEY_HEADER}</li>
  4560. * <li>{@link UsageMessageSpec#SECTION_KEY_SYNOPSIS_HEADING SECTION_KEY_SYNOPSIS_HEADING}</li>
  4561. * <li>{@link UsageMessageSpec#SECTION_KEY_SYNOPSIS SECTION_KEY_SYNOPSIS}</li>
  4562. * <li>{@link UsageMessageSpec#SECTION_KEY_DESCRIPTION_HEADING SECTION_KEY_DESCRIPTION_HEADING}</li>
  4563. * <li>{@link UsageMessageSpec#SECTION_KEY_DESCRIPTION SECTION_KEY_DESCRIPTION}</li>
  4564. * <li>{@link UsageMessageSpec#SECTION_KEY_PARAMETER_LIST_HEADING SECTION_KEY_PARAMETER_LIST_HEADING}</li>
  4565. * <li>{@link UsageMessageSpec#SECTION_KEY_PARAMETER_LIST SECTION_KEY_PARAMETER_LIST}</li>
  4566. * <li>{@link UsageMessageSpec#SECTION_KEY_OPTION_LIST_HEADING SECTION_KEY_OPTION_LIST_HEADING}</li>
  4567. * <li>{@link UsageMessageSpec#SECTION_KEY_OPTION_LIST SECTION_KEY_OPTION_LIST}</li>
  4568. * <li>{@link UsageMessageSpec#SECTION_KEY_COMMAND_LIST_HEADING SECTION_KEY_COMMAND_LIST_HEADING}</li>
  4569. * <li>{@link UsageMessageSpec#SECTION_KEY_COMMAND_LIST SECTION_KEY_COMMAND_LIST}</li>
  4570. * <li>{@link UsageMessageSpec#SECTION_KEY_FOOTER_HEADING SECTION_KEY_FOOTER_HEADING}</li>
  4571. * <li>{@link UsageMessageSpec#SECTION_KEY_FOOTER SECTION_KEY_FOOTER}</li>
  4572. * </ol>
  4573. * @since 3.9
  4574. */
  4575. public List<String> sectionKeys() { return sectionKeys; }
  4576. /**
  4577. * Sets the section keys in the order that the usage help message should render the sections.
  4578. * @see #sectionKeys
  4579. * @since 3.9
  4580. */
  4581. public UsageMessageSpec sectionKeys(List<String> keys) { sectionKeys = Collections.unmodifiableList(new ArrayList<String>(keys)); return this; }
  4582. /**
  4583. * Returns the map of section keys and renderers used to construct the usage help message.
  4584. * The usage help message can be customized by adding, replacing and removing section renderers from this map.
  4585. * Sections can be reordered with the {@link #sectionKeys(List) sectionKeys setter}.
  4586. * Sections that are either not in this map or not in the list returned by {@link #sectionKeys() sectionKeys} are omitted.
  4587. * @see #sectionKeys
  4588. * @since 3.9
  4589. */
  4590. public Map<String, IHelpSectionRenderer> sectionMap() { return helpSectionRendererMap; }
  4591. /**
  4592. * Sets the map of section keys and renderers used to construct the usage help message to a copy of the specified map.
  4593. * @param map the mapping of section keys to their renderers, must be non-{@code null}.
  4594. * @return this UsageMessageSpec for method chaining
  4595. * @see #sectionKeys
  4596. * @see #setHelpSectionMap(Map)
  4597. * @since 3.9
  4598. */
  4599. public UsageMessageSpec sectionMap(Map<String, IHelpSectionRenderer> map) { this.helpSectionRendererMap = new HashMap<String, IHelpSectionRenderer>(map); return this; }
  4600. /** Returns the {@code IHelpFactory} that is used to construct the usage help message.
  4601. * @see #setHelpFactory(IHelpFactory)
  4602. * @since 3.9
  4603. */
  4604. public IHelpFactory helpFactory() {
  4605. if (helpFactory == null) {
  4606. helpFactory = new DefaultHelpFactory();
  4607. }
  4608. return helpFactory;
  4609. }
  4610. /** Sets a new {@code IHelpFactory} to customize the usage help message.
  4611. * @param helpFactory the new help factory. Must be non-{@code null}.
  4612. * @return this {@code UsageMessageSpec} object, to allow method chaining
  4613. */
  4614. public UsageMessageSpec helpFactory(IHelpFactory helpFactory) {
  4615. this.helpFactory = Assert.notNull(helpFactory, "helpFactory");
  4616. return this;
  4617. }
  4618. private String str(String localized, String value, String defaultValue) {
  4619. return localized != null ? localized : (value != null ? value : defaultValue);
  4620. }
  4621. private String[] arr(String[] localized, String[] value, String[] defaultValue) {
  4622. return localized != null ? localized : (value != null ? value.clone() : defaultValue);
  4623. }
  4624. private String resourceStr(String key) { return messages == null ? null : messages.getString(key, null); }
  4625. private String[] resourceArr(String key) { return messages == null ? null : messages.getStringArray(key, null); }
  4626. /** Returns the optional heading preceding the header section. Initialized from {@link Command#headerHeading()}, or null. */
  4627. public String headerHeading() { return str(resourceStr("usage.headerHeading"), headerHeading, DEFAULT_SINGLE_VALUE); }
  4628. /** Returns the optional header lines displayed at the top of the help message. For subcommands, the first header line is
  4629. * displayed in the list of commands. Values are initialized from {@link Command#header()}
  4630. * if the {@code Command} annotation is present, otherwise this is an empty array and the help message has no
  4631. * header. Applications may programmatically set this field to create a custom help message. */
  4632. public String[] header() { return arr(resourceArr("usage.header"), header, DEFAULT_MULTI_LINE); }
  4633. /** Returns the optional heading preceding the synopsis. Initialized from {@link Command#synopsisHeading()}, {@code "Usage: "} by default. */
  4634. public String synopsisHeading() { return str(resourceStr("usage.synopsisHeading"), synopsisHeading, DEFAULT_SYNOPSIS_HEADING); }
  4635. /** Returns whether the synopsis line(s) should show an abbreviated synopsis without detailed option names. */
  4636. public boolean abbreviateSynopsis() { return (abbreviateSynopsis == null) ? DEFAULT_ABBREVIATE_SYNOPSIS : abbreviateSynopsis; }
  4637. /** Returns the optional custom synopsis lines to use instead of the auto-generated synopsis.
  4638. * Initialized from {@link Command#customSynopsis()} if the {@code Command} annotation is present,
  4639. * otherwise this is an empty array and the synopsis is generated.
  4640. * Applications may programmatically set this field to create a custom help message. */
  4641. public String[] customSynopsis() { return arr(resourceArr("usage.customSynopsis"), customSynopsis, DEFAULT_MULTI_LINE); }
  4642. /** Returns the optional heading preceding the description section. Initialized from {@link Command#descriptionHeading()}, or null. */
  4643. public String descriptionHeading() { return str(resourceStr("usage.descriptionHeading"), descriptionHeading, DEFAULT_SINGLE_VALUE); }
  4644. /** Returns the optional text lines to use as the description of the help message, displayed between the synopsis and the
  4645. * options list. Initialized from {@link Command#description()} if the {@code Command} annotation is present,
  4646. * otherwise this is an empty array and the help message has no description.
  4647. * Applications may programmatically set this field to create a custom help message. */
  4648. public String[] description() { return arr(resourceArr("usage.description"), description, DEFAULT_MULTI_LINE); }
  4649. /** Returns the optional heading preceding the parameter list. Initialized from {@link Command#parameterListHeading()}, or null. */
  4650. public String parameterListHeading() { return str(resourceStr("usage.parameterListHeading"), parameterListHeading, DEFAULT_SINGLE_VALUE); }
  4651. /** Returns the optional heading preceding the options list. Initialized from {@link Command#optionListHeading()}, or null. */
  4652. public String optionListHeading() { return str(resourceStr("usage.optionListHeading"), optionListHeading, DEFAULT_SINGLE_VALUE); }
  4653. /** Returns whether the options list in the usage help message should be sorted alphabetically. */
  4654. public boolean sortOptions() { return (sortOptions == null) ? DEFAULT_SORT_OPTIONS : sortOptions; }
  4655. /** Returns the character used to prefix required options in the options list. */
  4656. public char requiredOptionMarker() { return (requiredOptionMarker == null) ? DEFAULT_REQUIRED_OPTION_MARKER : requiredOptionMarker; }
  4657. /** Returns whether the options list in the usage help message should show default values for all non-boolean options. */
  4658. public boolean showDefaultValues() { return (showDefaultValues == null) ? DEFAULT_SHOW_DEFAULT_VALUES : showDefaultValues; }
  4659. /**
  4660. * Returns whether this command should be hidden from the usage help message of the parent command.
  4661. * @return {@code true} if this command should not appear in the usage help message of the parent command
  4662. */
  4663. public boolean hidden() { return (hidden == null) ? DEFAULT_HIDDEN : hidden; }
  4664. /** Returns the optional heading preceding the subcommand list. Initialized from {@link Command#commandListHeading()}. {@code "Commands:%n"} by default. */
  4665. public String commandListHeading() { return str(resourceStr("usage.commandListHeading"), commandListHeading, DEFAULT_COMMAND_LIST_HEADING); }
  4666. /** Returns the optional heading preceding the footer section. Initialized from {@link Command#footerHeading()}, or null. */
  4667. public String footerHeading() { return str(resourceStr("usage.footerHeading"), footerHeading, DEFAULT_SINGLE_VALUE); }
  4668. /** Returns the optional footer text lines displayed at the bottom of the help message. Initialized from
  4669. * {@link Command#footer()} if the {@code Command} annotation is present, otherwise this is an empty array and
  4670. * the help message has no footer.
  4671. * Applications may programmatically set this field to create a custom help message. */
  4672. public String[] footer() { return arr(resourceArr("usage.footer"), footer, DEFAULT_MULTI_LINE); }
  4673. /** Sets the heading preceding the header section. Initialized from {@link Command#headerHeading()}, or null.
  4674. * @return this UsageMessageSpec for method chaining */
  4675. public UsageMessageSpec headerHeading(String headerHeading) { this.headerHeading = headerHeading; return this; }
  4676. /** Sets the optional header lines displayed at the top of the help message. For subcommands, the first header line is
  4677. * displayed in the list of commands.
  4678. * @return this UsageMessageSpec for method chaining */
  4679. public UsageMessageSpec header(String... header) { this.header = header; return this; }
  4680. /** Sets the optional heading preceding the synopsis.
  4681. * @return this UsageMessageSpec for method chaining */
  4682. public UsageMessageSpec synopsisHeading(String newValue) {synopsisHeading = newValue; return this;}
  4683. /** Sets whether the synopsis line(s) should show an abbreviated synopsis without detailed option names.
  4684. * @return this UsageMessageSpec for method chaining */
  4685. public UsageMessageSpec abbreviateSynopsis(boolean newValue) {abbreviateSynopsis = newValue; return this;}
  4686. /** Sets the optional custom synopsis lines to use instead of the auto-generated synopsis.
  4687. * @return this UsageMessageSpec for method chaining */
  4688. public UsageMessageSpec customSynopsis(String... customSynopsis) { this.customSynopsis = customSynopsis; return this; }
  4689. /** Sets the heading preceding the description section.
  4690. * @return this UsageMessageSpec for method chaining */
  4691. public UsageMessageSpec descriptionHeading(String newValue) {descriptionHeading = newValue; return this;}
  4692. /** Sets the optional text lines to use as the description of the help message, displayed between the synopsis and the
  4693. * options list.
  4694. * @return this UsageMessageSpec for method chaining */
  4695. public UsageMessageSpec description(String... description) { this.description = description; return this; }
  4696. /** Sets the optional heading preceding the parameter list.
  4697. * @return this UsageMessageSpec for method chaining */
  4698. public UsageMessageSpec parameterListHeading(String newValue) {parameterListHeading = newValue; return this;}
  4699. /** Sets the heading preceding the options list.
  4700. * @return this UsageMessageSpec for method chaining */
  4701. public UsageMessageSpec optionListHeading(String newValue) {optionListHeading = newValue; return this;}
  4702. /** Sets whether the options list in the usage help message should be sorted alphabetically.
  4703. * @return this UsageMessageSpec for method chaining */
  4704. public UsageMessageSpec sortOptions(boolean newValue) {sortOptions = newValue; return this;}
  4705. /** Sets the character used to prefix required options in the options list.
  4706. * @return this UsageMessageSpec for method chaining */
  4707. public UsageMessageSpec requiredOptionMarker(char newValue) {requiredOptionMarker = newValue; return this;}
  4708. /** Sets whether the options list in the usage help message should show default values for all non-boolean options.
  4709. * @return this UsageMessageSpec for method chaining */
  4710. public UsageMessageSpec showDefaultValues(boolean newValue) {showDefaultValues = newValue; return this;}
  4711. /**
  4712. * Set the hidden flag on this command to control whether to show or hide it in the help usage text of the parent command.
  4713. * @param value enable or disable the hidden flag
  4714. * @return this UsageMessageSpec for method chaining
  4715. * @see Command#hidden() */
  4716. public UsageMessageSpec hidden(boolean value) { hidden = value; return this; }
  4717. /** Sets the optional heading preceding the subcommand list.
  4718. * @return this UsageMessageSpec for method chaining */
  4719. public UsageMessageSpec commandListHeading(String newValue) {commandListHeading = newValue; return this;}
  4720. /** Sets the optional heading preceding the footer section.
  4721. * @return this UsageMessageSpec for method chaining */
  4722. public UsageMessageSpec footerHeading(String newValue) {footerHeading = newValue; return this;}
  4723. /** Sets the optional footer text lines displayed at the bottom of the help message.
  4724. * @return this UsageMessageSpec for method chaining */
  4725. public UsageMessageSpec footer(String... footer) { this.footer = footer; return this; }
  4726. /** Returns the Messages for this usage help message specification, or {@code null}.
  4727. * @return the Messages object that encapsulates this {@linkplain CommandSpec#resourceBundle() command's resource bundle}
  4728. * @since 3.6 */
  4729. public Messages messages() { return messages; }
  4730. /** Sets the Messages for this usageMessage specification, and returns this UsageMessageSpec.
  4731. * @param msgs the new Messages value that encapsulates this {@linkplain CommandSpec#resourceBundle() command's resource bundle}, may be {@code null}
  4732. * @since 3.6 */
  4733. public UsageMessageSpec messages(Messages msgs) { messages = msgs; return this; }
  4734. void updateFromCommand(Command cmd, CommandSpec commandSpec) {
  4735. if (isNonDefault(cmd.synopsisHeading(), DEFAULT_SYNOPSIS_HEADING)) {synopsisHeading = cmd.synopsisHeading();}
  4736. if (isNonDefault(cmd.commandListHeading(), DEFAULT_COMMAND_LIST_HEADING)) {commandListHeading = cmd.commandListHeading();}
  4737. if (isNonDefault(cmd.requiredOptionMarker(), DEFAULT_REQUIRED_OPTION_MARKER)) {requiredOptionMarker = cmd.requiredOptionMarker();}
  4738. if (isNonDefault(cmd.abbreviateSynopsis(), DEFAULT_ABBREVIATE_SYNOPSIS)) {abbreviateSynopsis = cmd.abbreviateSynopsis();}
  4739. if (isNonDefault(cmd.sortOptions(), DEFAULT_SORT_OPTIONS)) {sortOptions = cmd.sortOptions();}
  4740. if (isNonDefault(cmd.showDefaultValues(), DEFAULT_SHOW_DEFAULT_VALUES)) {showDefaultValues = cmd.showDefaultValues();}
  4741. if (isNonDefault(cmd.hidden(), DEFAULT_HIDDEN)) {hidden = cmd.hidden();}
  4742. if (isNonDefault(cmd.customSynopsis(), DEFAULT_MULTI_LINE)) {customSynopsis = cmd.customSynopsis().clone();}
  4743. if (isNonDefault(cmd.description(), DEFAULT_MULTI_LINE)) {description = cmd.description().clone();}
  4744. if (isNonDefault(cmd.descriptionHeading(), DEFAULT_SINGLE_VALUE)) {descriptionHeading = cmd.descriptionHeading();}
  4745. if (isNonDefault(cmd.header(), DEFAULT_MULTI_LINE)) {header = cmd.header().clone();}
  4746. if (isNonDefault(cmd.headerHeading(), DEFAULT_SINGLE_VALUE)) {headerHeading = cmd.headerHeading();}
  4747. if (isNonDefault(cmd.footer(), DEFAULT_MULTI_LINE)) {footer = cmd.footer().clone();}
  4748. if (isNonDefault(cmd.footerHeading(), DEFAULT_SINGLE_VALUE)) {footerHeading = cmd.footerHeading();}
  4749. if (isNonDefault(cmd.parameterListHeading(), DEFAULT_SINGLE_VALUE)) {parameterListHeading = cmd.parameterListHeading();}
  4750. if (isNonDefault(cmd.optionListHeading(), DEFAULT_SINGLE_VALUE)) {optionListHeading = cmd.optionListHeading();}
  4751. if (isNonDefault(cmd.usageHelpWidth(), DEFAULT_USAGE_WIDTH)) {width(cmd.usageHelpWidth());} // validate
  4752. if (!empty(cmd.resourceBundle())) { // else preserve superclass bundle
  4753. messages(new Messages(commandSpec, cmd.resourceBundle()));
  4754. }
  4755. }
  4756. void initFromMixin(UsageMessageSpec mixin, CommandSpec commandSpec) {
  4757. if (initializable(synopsisHeading, mixin.synopsisHeading(), DEFAULT_SYNOPSIS_HEADING)) {synopsisHeading = mixin.synopsisHeading();}
  4758. if (initializable(commandListHeading, mixin.commandListHeading(), DEFAULT_COMMAND_LIST_HEADING)) {commandListHeading = mixin.commandListHeading();}
  4759. if (initializable(requiredOptionMarker, mixin.requiredOptionMarker(), DEFAULT_REQUIRED_OPTION_MARKER)) {requiredOptionMarker = mixin.requiredOptionMarker();}
  4760. if (initializable(abbreviateSynopsis, mixin.abbreviateSynopsis(), DEFAULT_ABBREVIATE_SYNOPSIS)) {abbreviateSynopsis = mixin.abbreviateSynopsis();}
  4761. if (initializable(sortOptions, mixin.sortOptions(), DEFAULT_SORT_OPTIONS)) {sortOptions = mixin.sortOptions();}
  4762. if (initializable(showDefaultValues, mixin.showDefaultValues(), DEFAULT_SHOW_DEFAULT_VALUES)) {showDefaultValues = mixin.showDefaultValues();}
  4763. if (initializable(hidden, mixin.hidden(), DEFAULT_HIDDEN)) {hidden = mixin.hidden();}
  4764. if (initializable(customSynopsis, mixin.customSynopsis(), DEFAULT_MULTI_LINE)) {customSynopsis = mixin.customSynopsis().clone();}
  4765. if (initializable(description, mixin.description(), DEFAULT_MULTI_LINE)) {description = mixin.description().clone();}
  4766. if (initializable(descriptionHeading, mixin.descriptionHeading(), DEFAULT_SINGLE_VALUE)) {descriptionHeading = mixin.descriptionHeading();}
  4767. if (initializable(header, mixin.header(), DEFAULT_MULTI_LINE)) {header = mixin.header().clone();}
  4768. if (initializable(headerHeading, mixin.headerHeading(), DEFAULT_SINGLE_VALUE)) {headerHeading = mixin.headerHeading();}
  4769. if (initializable(footer, mixin.footer(), DEFAULT_MULTI_LINE)) {footer = mixin.footer().clone();}
  4770. if (initializable(footerHeading, mixin.footerHeading(), DEFAULT_SINGLE_VALUE)) {footerHeading = mixin.footerHeading();}
  4771. if (initializable(parameterListHeading, mixin.parameterListHeading(), DEFAULT_SINGLE_VALUE)) {parameterListHeading = mixin.parameterListHeading();}
  4772. if (initializable(optionListHeading, mixin.optionListHeading(), DEFAULT_SINGLE_VALUE)) {optionListHeading = mixin.optionListHeading();}
  4773. if (Messages.empty(messages)) { messages(Messages.copy(commandSpec, mixin.messages())); }
  4774. }
  4775. void initFrom(UsageMessageSpec settings, CommandSpec commandSpec) {
  4776. description = settings.description;
  4777. customSynopsis = settings.customSynopsis;
  4778. header = settings.header;
  4779. footer = settings.footer;
  4780. abbreviateSynopsis = settings.abbreviateSynopsis;
  4781. sortOptions = settings.sortOptions;
  4782. showDefaultValues = settings.showDefaultValues;
  4783. hidden = settings.hidden;
  4784. requiredOptionMarker = settings.requiredOptionMarker;
  4785. headerHeading = settings.headerHeading;
  4786. synopsisHeading = settings.synopsisHeading;
  4787. descriptionHeading = settings.descriptionHeading;
  4788. parameterListHeading = settings.parameterListHeading;
  4789. optionListHeading = settings.optionListHeading;
  4790. commandListHeading = settings.commandListHeading;
  4791. footerHeading = settings.footerHeading;
  4792. width = settings.width;
  4793. messages = Messages.copy(commandSpec, settings.messages());
  4794. }
  4795. }
  4796. /** Models parser configuration specification.
  4797. * @since 3.0 */
  4798. public static class ParserSpec {
  4799. /** Constant String holding the default separator between options and option parameters: <code>{@value}</code>.*/
  4800. static final String DEFAULT_SEPARATOR = "=";
  4801. private String separator;
  4802. private boolean stopAtUnmatched = false;
  4803. private boolean stopAtPositional = false;
  4804. private String endOfOptionsDelimiter = "--";
  4805. private boolean toggleBooleanFlags = true;
  4806. private boolean overwrittenOptionsAllowed = false;
  4807. private boolean unmatchedArgumentsAllowed = false;
  4808. private boolean expandAtFiles = true;
  4809. private boolean useSimplifiedAtFiles = false;
  4810. private Character atFileCommentChar = '#';
  4811. private boolean posixClusteredShortOptionsAllowed = true;
  4812. private boolean unmatchedOptionsArePositionalParams = false;
  4813. private boolean limitSplit = false;
  4814. private boolean aritySatisfiedByAttachedOptionParam = false;
  4815. private boolean collectErrors = false;
  4816. private boolean caseInsensitiveEnumValuesAllowed = false;
  4817. private boolean trimQuotes = shouldTrimQuotes();
  4818. private boolean splitQuotedStrings = false;
  4819. /** Returns the String to use as the separator between options and option parameters. {@code "="} by default,
  4820. * initialized from {@link Command#separator()} if defined.*/
  4821. public String separator() { return (separator == null) ? DEFAULT_SEPARATOR : separator; }
  4822. /** @see CommandLine#isStopAtUnmatched() */
  4823. public boolean stopAtUnmatched() { return stopAtUnmatched; }
  4824. /** @see CommandLine#isStopAtPositional() */
  4825. public boolean stopAtPositional() { return stopAtPositional; }
  4826. /** @see CommandLine#getEndOfOptionsDelimiter()
  4827. * @since 3.5 */
  4828. public String endOfOptionsDelimiter() { return endOfOptionsDelimiter; }
  4829. /** @see CommandLine#isToggleBooleanFlags() */
  4830. public boolean toggleBooleanFlags() { return toggleBooleanFlags; }
  4831. /** @see CommandLine#isOverwrittenOptionsAllowed() */
  4832. public boolean overwrittenOptionsAllowed() { return overwrittenOptionsAllowed; }
  4833. /** @see CommandLine#isUnmatchedArgumentsAllowed() */
  4834. public boolean unmatchedArgumentsAllowed() { return unmatchedArgumentsAllowed; }
  4835. /** @see CommandLine#isExpandAtFiles() */
  4836. public boolean expandAtFiles() { return expandAtFiles; }
  4837. /** @see CommandLine#getAtFileCommentChar()
  4838. * @since 3.5 */
  4839. public Character atFileCommentChar() { return atFileCommentChar; }
  4840. /** @see CommandLine#isUseSimplifiedAtFiles()
  4841. * @since 3.9 */
  4842. public boolean useSimplifiedAtFiles() {
  4843. String value = System.getProperty("picocli.useSimplifiedAtFiles");
  4844. if (value != null) {
  4845. return "".equals(value) || Boolean.valueOf(value);
  4846. }
  4847. return useSimplifiedAtFiles;
  4848. }
  4849. /** @see CommandLine#isPosixClusteredShortOptionsAllowed() */
  4850. public boolean posixClusteredShortOptionsAllowed() { return posixClusteredShortOptionsAllowed; }
  4851. /** @see CommandLine#isCaseInsensitiveEnumValuesAllowed()
  4852. * @since 3.4 */
  4853. public boolean caseInsensitiveEnumValuesAllowed() { return caseInsensitiveEnumValuesAllowed; }
  4854. /** @see CommandLine#isTrimQuotes()
  4855. * @since 3.7 */
  4856. public boolean trimQuotes() { return trimQuotes; }
  4857. /** @see CommandLine#isSplitQuotedStrings()
  4858. * @since 3.7 */
  4859. public boolean splitQuotedStrings() { return splitQuotedStrings; }
  4860. /** @see CommandLine#isUnmatchedOptionsArePositionalParams() */
  4861. public boolean unmatchedOptionsArePositionalParams() { return unmatchedOptionsArePositionalParams; }
  4862. private boolean splitFirst() { return limitSplit(); }
  4863. /** Returns true if arguments should be split first before any further processing and the number of
  4864. * parts resulting from the split is limited to the max arity of the argument. */
  4865. public boolean limitSplit() { return limitSplit; }
  4866. /** Returns true if options with attached arguments should not consume subsequent arguments and should not validate arity. The default is {@code false}. */
  4867. public boolean aritySatisfiedByAttachedOptionParam() { return aritySatisfiedByAttachedOptionParam; }
  4868. /** Returns true if exceptions during parsing should be collected instead of thrown.
  4869. * Multiple errors may be encountered during parsing. These can be obtained from {@link ParseResult#errors()}.
  4870. * @since 3.2 */
  4871. public boolean collectErrors() { return collectErrors; }
  4872. /** Sets the String to use as the separator between options and option parameters.
  4873. * @return this ParserSpec for method chaining */
  4874. public ParserSpec separator(String separator) { this.separator = separator; return this; }
  4875. /** @see CommandLine#setStopAtUnmatched(boolean) */
  4876. public ParserSpec stopAtUnmatched(boolean stopAtUnmatched) { this.stopAtUnmatched = stopAtUnmatched; return this; }
  4877. /** @see CommandLine#setStopAtPositional(boolean) */
  4878. public ParserSpec stopAtPositional(boolean stopAtPositional) { this.stopAtPositional = stopAtPositional; return this; }
  4879. /** @see CommandLine#setEndOfOptionsDelimiter(String)
  4880. * @since 3.5 */
  4881. public ParserSpec endOfOptionsDelimiter(String delimiter) { this.endOfOptionsDelimiter = Assert.notNull(delimiter, "end-of-options delimiter"); return this; }
  4882. /** @see CommandLine#setToggleBooleanFlags(boolean) */
  4883. public ParserSpec toggleBooleanFlags(boolean toggleBooleanFlags) { this.toggleBooleanFlags = toggleBooleanFlags; return this; }
  4884. /** @see CommandLine#setOverwrittenOptionsAllowed(boolean) */
  4885. public ParserSpec overwrittenOptionsAllowed(boolean overwrittenOptionsAllowed) { this.overwrittenOptionsAllowed = overwrittenOptionsAllowed; return this; }
  4886. /** @see CommandLine#setUnmatchedArgumentsAllowed(boolean) */
  4887. public ParserSpec unmatchedArgumentsAllowed(boolean unmatchedArgumentsAllowed) { this.unmatchedArgumentsAllowed = unmatchedArgumentsAllowed; return this; }
  4888. /** @see CommandLine#setExpandAtFiles(boolean) */
  4889. public ParserSpec expandAtFiles(boolean expandAtFiles) { this.expandAtFiles = expandAtFiles; return this; }
  4890. /** @see CommandLine#setAtFileCommentChar(Character)
  4891. * @since 3.5 */
  4892. public ParserSpec atFileCommentChar(Character atFileCommentChar) { this.atFileCommentChar = atFileCommentChar; return this; }
  4893. /** @see CommandLine#setUseSimplifiedAtFiles(boolean)
  4894. * @since 3.9 */
  4895. public ParserSpec useSimplifiedAtFiles(boolean useSimplifiedAtFiles) { this.useSimplifiedAtFiles = useSimplifiedAtFiles; return this; }
  4896. /** @see CommandLine#setPosixClusteredShortOptionsAllowed(boolean) */
  4897. public ParserSpec posixClusteredShortOptionsAllowed(boolean posixClusteredShortOptionsAllowed) { this.posixClusteredShortOptionsAllowed = posixClusteredShortOptionsAllowed; return this; }
  4898. /** @see CommandLine#setCaseInsensitiveEnumValuesAllowed(boolean)
  4899. * @since 3.4 */
  4900. public ParserSpec caseInsensitiveEnumValuesAllowed(boolean caseInsensitiveEnumValuesAllowed) { this.caseInsensitiveEnumValuesAllowed = caseInsensitiveEnumValuesAllowed; return this; }
  4901. /** @see CommandLine#setTrimQuotes(boolean)
  4902. * @since 3.7 */
  4903. public ParserSpec trimQuotes(boolean trimQuotes) { this.trimQuotes = trimQuotes; return this; }
  4904. /** @see CommandLine#setSplitQuotedStrings(boolean)
  4905. * @since 3.7 */
  4906. public ParserSpec splitQuotedStrings(boolean splitQuotedStrings) { this.splitQuotedStrings = splitQuotedStrings; return this; }
  4907. /** @see CommandLine#setUnmatchedOptionsArePositionalParams(boolean) */
  4908. public ParserSpec unmatchedOptionsArePositionalParams(boolean unmatchedOptionsArePositionalParams) { this.unmatchedOptionsArePositionalParams = unmatchedOptionsArePositionalParams; return this; }
  4909. /** Sets whether exceptions during parsing should be collected instead of thrown.
  4910. * Multiple errors may be encountered during parsing. These can be obtained from {@link ParseResult#errors()}.
  4911. * @since 3.2 */
  4912. public ParserSpec collectErrors(boolean collectErrors) { this.collectErrors = collectErrors; return this; }
  4913. /** Returns true if options with attached arguments should not consume subsequent arguments and should not validate arity. The default is {@code false}.*/
  4914. public ParserSpec aritySatisfiedByAttachedOptionParam(boolean newValue) { aritySatisfiedByAttachedOptionParam = newValue; return this; }
  4915. /** Sets whether arguments should be {@linkplain ArgSpec#splitRegex() split} first before any further processing.
  4916. * If true, the original argument will only be split into as many parts as allowed by max arity. */
  4917. public ParserSpec limitSplit(boolean limitSplit) { this.limitSplit = limitSplit; return this; }
  4918. private boolean shouldTrimQuotes() {
  4919. String value = System.getProperty("picocli.trimQuotes");
  4920. if ("".equals(value)) { value = "true"; }
  4921. return Boolean.valueOf(value);
  4922. }
  4923. void initSeparator(String value) { if (initializable(separator, value, DEFAULT_SEPARATOR)) {separator = value;} }
  4924. void updateSeparator(String value) { if (isNonDefault(value, DEFAULT_SEPARATOR)) {separator = value;} }
  4925. public String toString() {
  4926. return String.format("posixClusteredShortOptionsAllowed=%s, stopAtPositional=%s, stopAtUnmatched=%s, " +
  4927. "separator=%s, overwrittenOptionsAllowed=%s, unmatchedArgumentsAllowed=%s, expandAtFiles=%s, " +
  4928. "atFileCommentChar=%s, useSimplifiedAtFiles=%s, endOfOptionsDelimiter=%s, limitSplit=%s, aritySatisfiedByAttachedOptionParam=%s, " +
  4929. "toggleBooleanFlags=%s, unmatchedOptionsArePositionalParams=%s, collectErrors=%s," +
  4930. "caseInsensitiveEnumValuesAllowed=%s, trimQuotes=%s, splitQuotedStrings=%s",
  4931. posixClusteredShortOptionsAllowed, stopAtPositional, stopAtUnmatched,
  4932. separator, overwrittenOptionsAllowed, unmatchedArgumentsAllowed, expandAtFiles,
  4933. atFileCommentChar, useSimplifiedAtFiles, endOfOptionsDelimiter, limitSplit, aritySatisfiedByAttachedOptionParam,
  4934. toggleBooleanFlags, unmatchedOptionsArePositionalParams, collectErrors,
  4935. caseInsensitiveEnumValuesAllowed, trimQuotes, splitQuotedStrings);
  4936. }
  4937. void initFrom(ParserSpec settings) {
  4938. separator = settings.separator;
  4939. stopAtUnmatched = settings.stopAtUnmatched;
  4940. stopAtPositional = settings.stopAtPositional;
  4941. endOfOptionsDelimiter = settings.endOfOptionsDelimiter;
  4942. toggleBooleanFlags = settings.toggleBooleanFlags;
  4943. overwrittenOptionsAllowed = settings.overwrittenOptionsAllowed;
  4944. unmatchedArgumentsAllowed = settings.unmatchedArgumentsAllowed;
  4945. expandAtFiles = settings.expandAtFiles;
  4946. atFileCommentChar = settings.atFileCommentChar;
  4947. posixClusteredShortOptionsAllowed = settings.posixClusteredShortOptionsAllowed;
  4948. unmatchedOptionsArePositionalParams = settings.unmatchedOptionsArePositionalParams;
  4949. limitSplit = settings.limitSplit;
  4950. aritySatisfiedByAttachedOptionParam = settings.aritySatisfiedByAttachedOptionParam;
  4951. collectErrors = settings.collectErrors;
  4952. caseInsensitiveEnumValuesAllowed = settings.caseInsensitiveEnumValuesAllowed;
  4953. trimQuotes = settings.trimQuotes;
  4954. splitQuotedStrings = settings.splitQuotedStrings;
  4955. }
  4956. }
  4957. /** Models the shared attributes of {@link OptionSpec} and {@link PositionalParamSpec}.
  4958. * @since 3.0 */
  4959. public abstract static class ArgSpec {
  4960. static final String DESCRIPTION_VARIABLE_DEFAULT_VALUE = "${DEFAULT-VALUE}";
  4961. static final String DESCRIPTION_VARIABLE_COMPLETION_CANDIDATES = "${COMPLETION-CANDIDATES}";
  4962. private static final String NO_DEFAULT_VALUE = "__no_default_value__";
  4963. // help-related fields
  4964. private final boolean hidden;
  4965. private final String paramLabel;
  4966. private final boolean hideParamSyntax;
  4967. private final String[] description;
  4968. private final String descriptionKey;
  4969. private final Help.Visibility showDefaultValue;
  4970. private Messages messages;
  4971. CommandSpec commandSpec;
  4972. private ArgGroupSpec group;
  4973. private final Object userObject;
  4974. // parser fields
  4975. private final boolean interactive;
  4976. private final boolean required;
  4977. private final String splitRegex;
  4978. private final ITypeInfo typeInfo;
  4979. private final ITypeConverter<?>[] converters;
  4980. private final Iterable<String> completionCandidates;
  4981. private final String defaultValue;
  4982. private final Object initialValue;
  4983. private final boolean hasInitialValue;
  4984. private final IGetter getter;
  4985. private final ISetter setter;
  4986. private final IScope scope;
  4987. private final Range arity;
  4988. private List<String> stringValues = new ArrayList<String>();
  4989. private List<String> originalStringValues = new ArrayList<String>();
  4990. protected String toString;
  4991. private List<Object> typedValues = new ArrayList<Object>();
  4992. Map<Integer, Object> typedValueAtPosition = new TreeMap<Integer, Object>();
  4993. /** Constructs a new {@code ArgSpec}. */
  4994. private <T extends Builder<T>> ArgSpec(Builder<T> builder) {
  4995. userObject = builder.userObject;
  4996. description = builder.description == null ? new String[0] : builder.description;
  4997. descriptionKey = builder.descriptionKey;
  4998. splitRegex = builder.splitRegex == null ? "" : builder.splitRegex;
  4999. paramLabel = empty(builder.paramLabel) ? "PARAM" : builder.paramLabel;
  5000. hideParamSyntax = builder.hideParamSyntax;
  5001. converters = builder.converters == null ? new ITypeConverter<?>[0] : builder.converters;
  5002. showDefaultValue = builder.showDefaultValue == null ? Help.Visibility.ON_DEMAND : builder.showDefaultValue;
  5003. hidden = builder.hidden;
  5004. interactive = builder.interactive;
  5005. initialValue = builder.initialValue;
  5006. hasInitialValue = builder.hasInitialValue;
  5007. defaultValue = NO_DEFAULT_VALUE.equals(builder.defaultValue) ? null : builder.defaultValue;
  5008. required = builder.required && defaultValue == null; //#261 not required if it has a default
  5009. toString = builder.toString;
  5010. getter = builder.getter;
  5011. setter = builder.setter;
  5012. scope = builder.scope;
  5013. Range tempArity = builder.arity;
  5014. if (tempArity == null) {
  5015. if (isOption()) {
  5016. tempArity = (builder.type == null || isBoolean(builder.type)) ? Range.valueOf("0") : Range.valueOf("1");
  5017. } else {
  5018. tempArity = Range.valueOf("1");
  5019. }
  5020. tempArity = tempArity.unspecified(true);
  5021. }
  5022. arity = tempArity;
  5023. if (builder.typeInfo == null) {
  5024. this.typeInfo = RuntimeTypeInfo.create(builder.type, builder.auxiliaryTypes,
  5025. Collections.<String>emptyList(), arity, (isOption() ? boolean.class : String.class));
  5026. } else {
  5027. this.typeInfo = builder.typeInfo;
  5028. }
  5029. if (builder.completionCandidates == null && typeInfo.isEnum()) {
  5030. List<String> list = new ArrayList<String>();
  5031. for (Object c : typeInfo.getEnumConstantNames()) { list.add(c.toString()); }
  5032. completionCandidates = Collections.unmodifiableList(list);
  5033. } else {
  5034. completionCandidates = builder.completionCandidates;
  5035. }
  5036. if (interactive && (arity.min != 1 || arity.max != 1)) {
  5037. throw new InitializationException("Interactive options and positional parameters are only supported for arity=1, not for arity=" + arity);
  5038. }
  5039. }
  5040. void applyInitialValue(Tracer tracer) {
  5041. if (hasInitialValue()) {
  5042. try {
  5043. setter().set(initialValue());
  5044. tracer.debug("Set initial value for %s of type %s to %s.%n", this, type(), String.valueOf(initialValue()));
  5045. } catch (Exception ex) {
  5046. tracer.warn("Could not set initial value for %s of type %s to %s: %s%n", this, type(), String.valueOf(initialValue()), ex);
  5047. }
  5048. } else {
  5049. tracer.debug("Initial value not available for %s%n", this);
  5050. }
  5051. }
  5052. /** Returns whether this is a required option or positional parameter.
  5053. * If this argument is part of a {@linkplain ArgGroup group}, this method returns whether this argument is required <em>within the group</em> (so it is not necessarily a required argument for the command).
  5054. * @see Option#required() */
  5055. public boolean required() { return required; }
  5056. /** Returns whether this option will prompt the user to enter a value on the command line.
  5057. * @see Option#interactive() */
  5058. public boolean interactive() { return interactive; }
  5059. /** Returns the description template of this option, before variables are rendered.
  5060. * @see Option#description() */
  5061. public String[] description() { return description.clone(); }
  5062. /** Returns the description key of this arg spec, used to get the description from a resource bundle.
  5063. * @see Option#descriptionKey()
  5064. * @see Parameters#descriptionKey()
  5065. * @since 3.6 */
  5066. public String descriptionKey() { return descriptionKey; }
  5067. /** Returns the description of this option, after variables are rendered. Used when generating the usage documentation.
  5068. * @see Option#description()
  5069. * @since 3.2 */
  5070. public String[] renderedDescription() {
  5071. String[] desc = description();
  5072. if (desc.length == 0) { return desc; }
  5073. StringBuilder candidates = new StringBuilder();
  5074. if (completionCandidates() != null) {
  5075. for (String c : completionCandidates()) {
  5076. if (candidates.length() > 0) { candidates.append(", "); }
  5077. candidates.append(c);
  5078. }
  5079. }
  5080. String defaultValueString = defaultValueString();
  5081. String[] result = new String[desc.length];
  5082. for (int i = 0; i < desc.length; i++) {
  5083. result[i] = format(desc[i].replace(DESCRIPTION_VARIABLE_DEFAULT_VALUE, defaultValueString.replace("%", "%%"))
  5084. .replace(DESCRIPTION_VARIABLE_COMPLETION_CANDIDATES, candidates.toString()));
  5085. }
  5086. return result;
  5087. }
  5088. /** Returns how many arguments this option or positional parameter requires.
  5089. * @see Option#arity() */
  5090. public Range arity() { return arity; }
  5091. /** Returns the name of the option or positional parameter used in the usage help message.
  5092. * @see Option#paramLabel() {@link Parameters#paramLabel()} */
  5093. public String paramLabel() { return paramLabel; }
  5094. /** Returns whether usage syntax decorations around the {@linkplain #paramLabel() paramLabel} should be suppressed.
  5095. * The default is {@code false}: by default, the paramLabel is surrounded with {@code '['} and {@code ']'} characters
  5096. * if the value is optional and followed by ellipses ("...") when multiple values can be specified.
  5097. * @since 3.6.0 */
  5098. public boolean hideParamSyntax() { return hideParamSyntax; }
  5099. /** Returns auxiliary type information used when the {@link #type()} is a generic {@code Collection}, {@code Map} or an abstract class.
  5100. * @see Option#type() */
  5101. public Class<?>[] auxiliaryTypes() { return typeInfo.getAuxiliaryTypes(); }
  5102. /** Returns one or more {@link CommandLine.ITypeConverter type converters} to use to convert the command line
  5103. * argument into a strongly typed value (or key-value pair for map fields). This is useful when a particular
  5104. * option or positional parameter should use a custom conversion that is different from the normal conversion for the arg spec's type.
  5105. * @see Option#converter() */
  5106. public ITypeConverter<?>[] converters() { return converters.clone(); }
  5107. /** Returns a regular expression to split option parameter values or {@code ""} if the value should not be split.
  5108. * @see Option#split() */
  5109. public String splitRegex() { return splitRegex; }
  5110. /** Returns whether this option should be excluded from the usage message.
  5111. * @see Option#hidden() */
  5112. public boolean hidden() { return hidden; }
  5113. /** Returns the type to convert the option or positional parameter to before {@linkplain #setValue(Object) setting} the value. */
  5114. public Class<?> type() { return typeInfo.getType(); }
  5115. /** Returns the {@code ITypeInfo} that can be used both at compile time (by annotation processors) and at runtime.
  5116. * @since 4.0 */
  5117. public ITypeInfo typeInfo() { return typeInfo; }
  5118. /** Returns the user object associated with this option or positional parameters.
  5119. * @return may return the annotated program element, or some other useful object
  5120. * @since 4.0 */
  5121. public Object userObject() { return userObject; }
  5122. /** Returns the default value of this option or positional parameter, before splitting and type conversion.
  5123. * This method returns the programmatically set value; this may differ from the default value that is actually used:
  5124. * if this ArgSpec is part of a CommandSpec with a {@link IDefaultValueProvider}, picocli will first try to obtain
  5125. * the default value from the default value provider, and this method is only called if the default provider is
  5126. * {@code null} or returned a {@code null} value.
  5127. * @return the programmatically set default value of this option/positional parameter,
  5128. * returning {@code null} means this option or positional parameter does not have a default
  5129. * @see CommandSpec#defaultValueProvider()
  5130. */
  5131. public String defaultValue() { return defaultValue; }
  5132. /** Returns the initial value this option or positional parameter. If {@link #hasInitialValue()} is true,
  5133. * the option will be reset to the initial value before parsing (regardless of whether a default value exists),
  5134. * to clear values that would otherwise remain from parsing previous input. */
  5135. public Object initialValue() { return initialValue; }
  5136. /** Determines whether the option or positional parameter will be reset to the {@link #initialValue()}
  5137. * before parsing new input.*/
  5138. public boolean hasInitialValue() { return hasInitialValue; }
  5139. /** Returns whether this option or positional parameter's default value should be shown in the usage help. */
  5140. public Help.Visibility showDefaultValue() { return showDefaultValue; }
  5141. /** Returns the default value String displayed in the description. If this ArgSpec is part of a
  5142. * CommandSpec with a {@link IDefaultValueProvider}, this method will first try to obtain
  5143. * the default value from the default value provider; if the provider is {@code null} or if it
  5144. * returns a {@code null} value, then next any value set to {@link ArgSpec#defaultValue()}
  5145. * is returned, and if this is also {@code null}, finally the {@linkplain ArgSpec#initialValue() initial value} is returned.
  5146. * @see CommandSpec#defaultValueProvider()
  5147. * @see ArgSpec#defaultValue() */
  5148. public String defaultValueString() {
  5149. String fromProvider = defaultValueFromProvider();
  5150. String defaultVal = fromProvider == null ? this.defaultValue() : fromProvider;
  5151. Object value = defaultVal == null ? initialValue() : defaultVal;
  5152. if (value != null && value.getClass().isArray()) {
  5153. StringBuilder sb = new StringBuilder();
  5154. for (int i = 0; i < Array.getLength(value); i++) {
  5155. sb.append(i > 0 ? ", " : "").append(Array.get(value, i));
  5156. }
  5157. return sb.insert(0, "[").append("]").toString();
  5158. }
  5159. return String.valueOf(value);
  5160. }
  5161. private String defaultValueFromProvider() {
  5162. String fromProvider = null;
  5163. IDefaultValueProvider defaultValueProvider = null;
  5164. try {
  5165. defaultValueProvider = commandSpec.defaultValueProvider();
  5166. fromProvider = defaultValueProvider == null ? null : defaultValueProvider.defaultValue(this);
  5167. } catch (Exception ex) {
  5168. new Tracer().info("Error getting default value for %s from %s: %s", this, defaultValueProvider, ex);
  5169. }
  5170. return fromProvider;
  5171. }
  5172. /** Returns the explicitly set completion candidates for this option or positional parameter, valid enum
  5173. * constant names, or {@code null} if this option or positional parameter does not have any completion
  5174. * candidates and its type is not an enum.
  5175. * @return the completion candidates for this option or positional parameter, valid enum constant names,
  5176. * or {@code null}
  5177. * @since 3.2 */
  5178. public Iterable<String> completionCandidates() { return completionCandidates; }
  5179. /** Returns the {@link IGetter} that is responsible for supplying the value of this argument. */
  5180. public IGetter getter() { return getter; }
  5181. /** Returns the {@link ISetter} that is responsible for modifying the value of this argument. */
  5182. public ISetter setter() { return setter; }
  5183. /** Returns the {@link IScope} that determines on which object to set the value (or from which object to get the value) of this argument. */
  5184. public IScope scope() { return scope; }
  5185. /** Returns the current value of this argument. Delegates to the current {@link #getter()}. */
  5186. public <T> T getValue() throws PicocliException {
  5187. try {
  5188. return getter.get();
  5189. } catch (PicocliException ex) { throw ex;
  5190. } catch (Exception ex) { throw new PicocliException("Could not get value for " + this + ": " + ex, ex);
  5191. }
  5192. }
  5193. /** Sets the value of this argument to the specified value and returns the previous value. Delegates to the current {@link #setter()}. */
  5194. public <T> T setValue(T newValue) throws PicocliException {
  5195. try {
  5196. return setter.set(newValue);
  5197. } catch (PicocliException ex) { throw ex;
  5198. } catch (Exception ex) { throw new PicocliException("Could not set value (" + newValue + ") for " + this + ": " + ex, ex);
  5199. }
  5200. }
  5201. /** Sets the value of this argument to the specified value and returns the previous value. Delegates to the current {@link #setter()}.
  5202. * @deprecated use {@link #setValue(Object)} instead. This was a design mistake.
  5203. * @since 3.5 */
  5204. @Deprecated public <T> T setValue(T newValue, CommandLine commandLine) throws PicocliException {
  5205. return setValue(newValue);
  5206. }
  5207. /** Returns {@code true} if this argument's {@link #type()} is an array, a {@code Collection} or a {@code Map}, {@code false} otherwise. */
  5208. public boolean isMultiValue() { return typeInfo.isMultiValue(); }
  5209. /** Returns {@code true} if this argument is a named option, {@code false} otherwise. */
  5210. public abstract boolean isOption();
  5211. /** Returns {@code true} if this argument is a positional parameter, {@code false} otherwise. */
  5212. public abstract boolean isPositional();
  5213. /** Returns the groups this option or positional parameter belongs to, or {@code null} if this option is not part of a group.
  5214. * @since 4.0 */
  5215. public ArgGroupSpec group() { return group; }
  5216. /** Returns the untyped command line arguments matched by this option or positional parameter spec.
  5217. * @return the matched arguments after {@linkplain #splitRegex() splitting}, but before type conversion.
  5218. * For map properties, {@code "key=value"} values are split into the key and the value part. */
  5219. public List<String> stringValues() { return Collections.unmodifiableList(stringValues); }
  5220. /** Returns the typed command line arguments matched by this option or positional parameter spec.
  5221. * @return the matched arguments after {@linkplain #splitRegex() splitting} and type conversion.
  5222. * For map properties, {@code "key=value"} values are split into the key and the value part. */
  5223. public List<Object> typedValues() { return Collections.unmodifiableList(typedValues); }
  5224. /** Sets the {@code stringValues} to a new list instance. */
  5225. protected void resetStringValues() { stringValues = new ArrayList<String>(); }
  5226. /** Returns the original command line arguments matched by this option or positional parameter spec.
  5227. * @return the matched arguments as found on the command line: empty Strings for options without value, the
  5228. * values have not been {@linkplain #splitRegex() split}, and for map properties values may look like {@code "key=value"}*/
  5229. public List<String> originalStringValues() { return Collections.unmodifiableList(originalStringValues); }
  5230. /** Sets the {@code originalStringValues} to a new list instance. */
  5231. protected void resetOriginalStringValues() { originalStringValues = new ArrayList<String>(); }
  5232. /** Returns whether the default for this option or positional parameter should be shown, potentially overriding the specified global setting.
  5233. * @param usageHelpShowDefaults whether the command's UsageMessageSpec is configured to show default values. */
  5234. protected boolean internalShowDefaultValue(boolean usageHelpShowDefaults) {
  5235. if (showDefaultValue() == Help.Visibility.ALWAYS) { return true; } // override global usage help setting
  5236. if (showDefaultValue() == Help.Visibility.NEVER) { return false; } // override global usage help setting
  5237. if (initialValue == null && defaultValue() == null && defaultValueFromProvider() == null) { return false; } // no default value to show
  5238. return usageHelpShowDefaults && !isBoolean(type());
  5239. }
  5240. /** Returns the Messages for this arg specification, or {@code null}.
  5241. * @since 3.6 */
  5242. public Messages messages() { return messages; }
  5243. /** Sets the Messages for this ArgSpec, and returns this ArgSpec.
  5244. * @param msgs the new Messages value, may be {@code null}
  5245. * @see Command#resourceBundle()
  5246. * @see OptionSpec#description()
  5247. * @see PositionalParamSpec#description()
  5248. * @since 3.6 */
  5249. public ArgSpec messages(Messages msgs) { messages = msgs; return this; }
  5250. /** Returns a string respresentation of this option or positional parameter. */
  5251. public String toString() { return toString; }
  5252. String[] splitValue(String value, ParserSpec parser, Range arity, int consumed) {
  5253. if (splitRegex().length() == 0) { return new String[] {value}; }
  5254. int limit = parser.limitSplit() ? Math.max(arity.max - consumed, 0) : 0;
  5255. if (parser.splitQuotedStrings()) {
  5256. return debug(value.split(splitRegex(), limit), "Split (ignoring quotes)", value);
  5257. }
  5258. return debug(splitRespectingQuotedStrings(value, limit, parser, this, splitRegex()), "Split", value);
  5259. }
  5260. private String[] debug(String[] result, String msg, String value) {
  5261. Tracer t = new Tracer();
  5262. if (t.isDebug()) {t.debug("%s with regex '%s' resulted in %s parts: %s%n", msg, splitRegex(), result.length, Arrays.asList(result));}
  5263. return result;
  5264. }
  5265. // @since 3.7
  5266. private static String[] splitRespectingQuotedStrings(String value, int limit, ParserSpec parser, ArgSpec argSpec, String splitRegex) {
  5267. StringBuilder splittable = new StringBuilder();
  5268. StringBuilder temp = new StringBuilder();
  5269. StringBuilder current = splittable;
  5270. Queue<String> quotedValues = new LinkedList<String>();
  5271. boolean escaping = false, inQuote = false;
  5272. for (int ch = 0, i = 0; i < value.length(); i += Character.charCount(ch)) {
  5273. ch = value.codePointAt(i);
  5274. switch (ch) {
  5275. case '\\': escaping = !escaping; break;
  5276. case '\"':
  5277. if (!escaping) {
  5278. inQuote = !inQuote;
  5279. current = inQuote ? temp : splittable;
  5280. if (inQuote) {
  5281. splittable.appendCodePoint(ch);
  5282. continue;
  5283. } else {
  5284. quotedValues.add(temp.toString());
  5285. temp.setLength(0);
  5286. }
  5287. }
  5288. break;
  5289. default: escaping = false; break;
  5290. }
  5291. current.appendCodePoint(ch);
  5292. }
  5293. if (temp.length() > 0) {
  5294. new Tracer().warn("Unbalanced quotes in [%s] for %s (value=%s)%n", temp, argSpec, value);
  5295. quotedValues.add(temp.toString());
  5296. temp.setLength(0);
  5297. }
  5298. String[] result = splittable.toString().split(splitRegex, limit);
  5299. for (int i = 0; i < result.length; i++) {
  5300. result[i] = restoreQuotedValues(result[i], quotedValues, parser);
  5301. }
  5302. if (!quotedValues.isEmpty()) {
  5303. new Tracer().warn("Unable to respect quotes while splitting value %s for %s (unprocessed remainder: %s)%n", value, argSpec, quotedValues);
  5304. return value.split(splitRegex, limit);
  5305. }
  5306. return result;
  5307. }
  5308. private static String restoreQuotedValues(String part, Queue<String> quotedValues, ParserSpec parser) {
  5309. StringBuilder result = new StringBuilder();
  5310. boolean escaping = false, inQuote = false, skip = false;
  5311. for (int ch = 0, i = 0; i < part.length(); i += Character.charCount(ch)) {
  5312. ch = part.codePointAt(i);
  5313. switch (ch) {
  5314. case '\\': escaping = !escaping; break;
  5315. case '\"':
  5316. if (!escaping) {
  5317. inQuote = !inQuote;
  5318. if (!inQuote) { result.append(quotedValues.remove()); }
  5319. skip = parser.trimQuotes();
  5320. }
  5321. break;
  5322. default: escaping = false; break;
  5323. }
  5324. if (!skip) { result.appendCodePoint(ch); }
  5325. skip = false;
  5326. }
  5327. return result.toString();
  5328. }
  5329. protected boolean equalsImpl(ArgSpec other) {
  5330. boolean result = Assert.equals(this.defaultValue, other.defaultValue)
  5331. && Assert.equals(this.arity, other.arity)
  5332. && Assert.equals(this.hidden, other.hidden)
  5333. && Assert.equals(this.paramLabel, other.paramLabel)
  5334. && Assert.equals(this.hideParamSyntax, other.hideParamSyntax)
  5335. && Assert.equals(this.required, other.required)
  5336. && Assert.equals(this.splitRegex, other.splitRegex)
  5337. && Arrays.equals(this.description, other.description)
  5338. && Assert.equals(this.descriptionKey, other.descriptionKey)
  5339. && this.typeInfo.equals(other.typeInfo)
  5340. ;
  5341. return result;
  5342. }
  5343. protected int hashCodeImpl() {
  5344. return 17
  5345. + 37 * Assert.hashCode(defaultValue)
  5346. + 37 * Assert.hashCode(arity)
  5347. + 37 * Assert.hashCode(hidden)
  5348. + 37 * Assert.hashCode(paramLabel)
  5349. + 37 * Assert.hashCode(hideParamSyntax)
  5350. + 37 * Assert.hashCode(required)
  5351. + 37 * Assert.hashCode(splitRegex)
  5352. + 37 * Arrays.hashCode(description)
  5353. + 37 * Assert.hashCode(descriptionKey)
  5354. + 37 * typeInfo.hashCode()
  5355. ;
  5356. }
  5357. private static String describe(Collection<ArgSpec> args) {
  5358. StringBuilder sb = new StringBuilder();
  5359. for (ArgSpec arg : args) {
  5360. if (sb.length() > 0) { sb.append(", "); }
  5361. sb.append(describe(arg, "="));
  5362. }
  5363. return sb.toString();
  5364. }
  5365. /** Returns a description of the option or positional arg, e.g. {@code -a=<a>}
  5366. * @param separator separator between arg and arg parameter label, usually '=' */
  5367. private static String describe(ArgSpec argSpec, String separator) {
  5368. return describe(argSpec, separator, argSpec.paramLabel());
  5369. }
  5370. /** Returns a description of the option or positional arg
  5371. * @param separator separator between arg and arg parameter value, usually '='
  5372. * @param value the value to append after the separator*/
  5373. private static String describe(ArgSpec argSpec, String separator, String value) {
  5374. String prefix = (argSpec.isOption())
  5375. ? ((OptionSpec) argSpec).longestName()
  5376. : "params[" + ((PositionalParamSpec) argSpec).index() + "]";
  5377. return argSpec.arity().min > 0 ? prefix + separator + value : prefix;
  5378. }
  5379. abstract static class Builder<T extends Builder<T>> {
  5380. private Object userObject;
  5381. private Range arity;
  5382. private String[] description;
  5383. private String descriptionKey;
  5384. private boolean required;
  5385. private boolean interactive;
  5386. private String paramLabel;
  5387. private boolean hideParamSyntax;
  5388. private String splitRegex;
  5389. private boolean hidden;
  5390. private Class<?> type;
  5391. private Class<?>[] auxiliaryTypes;
  5392. private ITypeInfo typeInfo;
  5393. private ITypeConverter<?>[] converters;
  5394. private String defaultValue;
  5395. private Object initialValue;
  5396. private boolean hasInitialValue = true;
  5397. private Help.Visibility showDefaultValue;
  5398. private Iterable<String> completionCandidates;
  5399. private String toString;
  5400. private IGetter getter = new ObjectBinding();
  5401. private ISetter setter = (ISetter) getter;
  5402. private IScope scope = new ObjectScope(null);
  5403. Builder() {}
  5404. Builder(ArgSpec original) {
  5405. userObject = original.userObject;
  5406. arity = original.arity;
  5407. converters = original.converters;
  5408. defaultValue = original.defaultValue;
  5409. description = original.description;
  5410. getter = original.getter;
  5411. setter = original.setter;
  5412. hidden = original.hidden;
  5413. paramLabel = original.paramLabel;
  5414. hideParamSyntax = original.hideParamSyntax;
  5415. required = original.required;
  5416. interactive = original.interactive;
  5417. showDefaultValue = original.showDefaultValue;
  5418. completionCandidates = original.completionCandidates;
  5419. splitRegex = original.splitRegex;
  5420. toString = original.toString;
  5421. descriptionKey = original.descriptionKey;
  5422. setTypeInfo(original.typeInfo);
  5423. }
  5424. Builder(IAnnotatedElement source) {
  5425. userObject = source.userObject();
  5426. setTypeInfo(source.getTypeInfo());
  5427. toString = source.getToString();
  5428. getter = source.getter();
  5429. setter = source.setter();
  5430. scope = source.scope();
  5431. hasInitialValue = source.hasInitialValue();
  5432. try { initialValue = source.getter().get(); } catch (Exception ex) { initialValue = null; hasInitialValue = false; }
  5433. }
  5434. Builder(Option option, IAnnotatedElement source, IFactory factory) {
  5435. this(source);
  5436. arity = Range.optionArity(source);
  5437. required = option.required();
  5438. paramLabel = inferLabel(option.paramLabel(), source.getName(), source.getTypeInfo());
  5439. hideParamSyntax = option.hideParamSyntax();
  5440. interactive = option.interactive();
  5441. description = option.description();
  5442. descriptionKey = option.descriptionKey();
  5443. splitRegex = option.split();
  5444. hidden = option.hidden();
  5445. defaultValue = option.defaultValue();
  5446. showDefaultValue = option.showDefaultValue();
  5447. if (factory != null) {
  5448. converters = DefaultFactory.createConverter(factory, option.converter());
  5449. if (!NoCompletionCandidates.class.equals(option.completionCandidates())) {
  5450. completionCandidates = DefaultFactory.createCompletionCandidates(factory, option.completionCandidates());
  5451. }
  5452. }
  5453. }
  5454. Builder(Parameters parameters, IAnnotatedElement source, IFactory factory) {
  5455. this(source);
  5456. arity = Range.parameterArity(source);
  5457. required = arity.min > 0;
  5458. // method parameters may be positional parameters without @Parameters annotation
  5459. if (parameters == null) {
  5460. paramLabel = inferLabel(null, source.getName(), source.getTypeInfo());
  5461. } else {
  5462. paramLabel = inferLabel(parameters.paramLabel(), source.getName(), source.getTypeInfo());
  5463. hideParamSyntax = parameters.hideParamSyntax();
  5464. interactive = parameters.interactive();
  5465. description = parameters.description();
  5466. descriptionKey = parameters.descriptionKey();
  5467. splitRegex = parameters.split();
  5468. hidden = parameters.hidden();
  5469. defaultValue = parameters.defaultValue();
  5470. showDefaultValue = parameters.showDefaultValue();
  5471. if (factory != null) { // annotation processors will pass a null factory
  5472. converters = DefaultFactory.createConverter(factory, parameters.converter());
  5473. if (!NoCompletionCandidates.class.equals(parameters.completionCandidates())) {
  5474. completionCandidates = DefaultFactory.createCompletionCandidates(factory, parameters.completionCandidates());
  5475. }
  5476. }
  5477. }
  5478. }
  5479. private static String inferLabel(String label, String fieldName, ITypeInfo typeInfo) {
  5480. if (!empty(label)) { return label.trim(); }
  5481. String name = fieldName;
  5482. if (typeInfo.isMap()) { // #195 better param labels for map fields
  5483. List<ITypeInfo> aux = typeInfo.getAuxiliaryTypeInfos();
  5484. if (aux.size() < 2 || aux.get(0) == null || aux.get(1) == null) {
  5485. name = "String=String";
  5486. } else { name = aux.get(0).getClassSimpleName() + "=" + aux.get(1).getClassSimpleName(); }
  5487. }
  5488. return "<" + name + ">";
  5489. }
  5490. public abstract ArgSpec build();
  5491. protected abstract T self(); // subclasses must override to return "this"
  5492. /** Returns whether this is a required option or positional parameter.
  5493. * @see Option#required() */
  5494. public boolean required() { return required; }
  5495. /** Returns whether this option prompts the user to enter a value on the command line.
  5496. * @see Option#interactive() */
  5497. public boolean interactive() { return interactive; }
  5498. /** Returns the description of this option, used when generating the usage documentation.
  5499. * @see Option#description() */
  5500. public String[] description() { return description; }
  5501. /** Returns the description key of this arg spec, used to get the description from a resource bundle.
  5502. * @see Option#descriptionKey()
  5503. * @see Parameters#descriptionKey()
  5504. * @since 3.6 */
  5505. public String descriptionKey() { return descriptionKey; }
  5506. /** Returns how many arguments this option or positional parameter requires.
  5507. * @see Option#arity() */
  5508. public Range arity() { return arity; }
  5509. /** Returns the name of the option or positional parameter used in the usage help message.
  5510. * @see Option#paramLabel() {@link Parameters#paramLabel()} */
  5511. public String paramLabel() { return paramLabel; }
  5512. /** Returns whether usage syntax decorations around the {@linkplain #paramLabel() paramLabel} should be suppressed.
  5513. * The default is {@code false}: by default, the paramLabel is surrounded with {@code '['} and {@code ']'} characters
  5514. * if the value is optional and followed by ellipses ("...") when multiple values can be specified.
  5515. * @since 3.6.0 */
  5516. public boolean hideParamSyntax() { return hideParamSyntax; }
  5517. /** Returns auxiliary type information used when the {@link #type()} is a generic {@code Collection}, {@code Map} or an abstract class.
  5518. * @see Option#type() */
  5519. public Class<?>[] auxiliaryTypes() { return auxiliaryTypes; }
  5520. /** Returns one or more {@link CommandLine.ITypeConverter type converters} to use to convert the command line
  5521. * argument into a strongly typed value (or key-value pair for map fields). This is useful when a particular
  5522. * option or positional parameter should use a custom conversion that is different from the normal conversion for the arg spec's type.
  5523. * @see Option#converter() */
  5524. public ITypeConverter<?>[] converters() { return converters; }
  5525. /** Returns a regular expression to split option parameter values or {@code ""} if the value should not be split.
  5526. * @see Option#split() */
  5527. public String splitRegex() { return splitRegex; }
  5528. /** Returns whether this option should be excluded from the usage message.
  5529. * @see Option#hidden() */
  5530. public boolean hidden() { return hidden; }
  5531. /** Returns the type to convert the option or positional parameter to before {@linkplain #setValue(Object) setting} the value. */
  5532. public Class<?> type() { return type; }
  5533. /** Returns the type info for this option or positional parameter.
  5534. * @return type information that does not require {@code Class} objects and be constructed both at runtime and compile time
  5535. * @since 4.0
  5536. */
  5537. public ITypeInfo typeInfo() { return typeInfo; }
  5538. /** Returns the user object associated with this option or positional parameters.
  5539. * @return may return the annotated program element, or some other useful object
  5540. * @since 4.0 */
  5541. public Object userObject() { return userObject; }
  5542. /** Returns the default value of this option or positional parameter, before splitting and type conversion.
  5543. * A value of {@code null} means this option or positional parameter does not have a default. */
  5544. public String defaultValue() { return defaultValue; }
  5545. /** Returns the initial value this option or positional parameter. If {@link #hasInitialValue()} is true,
  5546. * the option will be reset to the initial value before parsing (regardless of whether a default value exists),
  5547. * to clear values that would otherwise remain from parsing previous input. */
  5548. public Object initialValue() { return initialValue; }
  5549. /** Determines whether the option or positional parameter will be reset to the {@link #initialValue()}
  5550. * before parsing new input.*/
  5551. public boolean hasInitialValue() { return hasInitialValue; }
  5552. /** Returns whether this option or positional parameter's default value should be shown in the usage help. */
  5553. public Help.Visibility showDefaultValue() { return showDefaultValue; }
  5554. /** Returns the completion candidates for this option or positional parameter, or {@code null}.
  5555. * @since 3.2 */
  5556. public Iterable<String> completionCandidates() { return completionCandidates; }
  5557. /** Returns the {@link IGetter} that is responsible for supplying the value of this argument. */
  5558. public IGetter getter() { return getter; }
  5559. /** Returns the {@link ISetter} that is responsible for modifying the value of this argument. */
  5560. public ISetter setter() { return setter; }
  5561. /** Returns the {@link IScope} that determines where the setter sets the value (or the getter gets the value) of this argument. */
  5562. public IScope scope() { return scope; }
  5563. public String toString() { return toString; }
  5564. /** Sets whether this is a required option or positional parameter, and returns this builder. */
  5565. public T required(boolean required) { this.required = required; return self(); }
  5566. /** Sets whether this option prompts the user to enter a value on the command line, and returns this builder. */
  5567. public T interactive(boolean interactive) { this.interactive = interactive; return self(); }
  5568. /** Sets the description of this option, used when generating the usage documentation, and returns this builder.
  5569. * @see Option#description() */
  5570. public T description(String... description) { this.description = Assert.notNull(description, "description").clone(); return self(); }
  5571. /** Sets the description key that is used to look up the description in a resource bundle, and returns this builder.
  5572. * @see Option#descriptionKey()
  5573. * @see Parameters#descriptionKey()
  5574. * @since 3.6 */
  5575. public T descriptionKey(String descriptionKey) { this.descriptionKey = descriptionKey; return self(); }
  5576. /** Sets how many arguments this option or positional parameter requires, and returns this builder. */
  5577. public T arity(String range) { return arity(Range.valueOf(range)); }
  5578. /** Sets how many arguments this option or positional parameter requires, and returns this builder. */
  5579. public T arity(Range arity) { this.arity = Assert.notNull(arity, "arity"); return self(); }
  5580. /** Sets the name of the option or positional parameter used in the usage help message, and returns this builder. */
  5581. public T paramLabel(String paramLabel) { this.paramLabel = Assert.notNull(paramLabel, "paramLabel"); return self(); }
  5582. /** Sets whether usage syntax decorations around the {@linkplain #paramLabel() paramLabel} should be suppressed.
  5583. * The default is {@code false}: by default, the paramLabel is surrounded with {@code '['} and {@code ']'} characters
  5584. * if the value is optional and followed by ellipses ("...") when multiple values can be specified.
  5585. * @since 3.6.0 */
  5586. public T hideParamSyntax(boolean hideParamSyntax) { this.hideParamSyntax = hideParamSyntax; return self(); }
  5587. /** Sets auxiliary type information, and returns this builder.
  5588. * @param types the element type(s) when the {@link #type()} is a generic {@code Collection} or a {@code Map};
  5589. * or the concrete type when the {@link #type()} is an abstract class. */
  5590. public T auxiliaryTypes(Class<?>... types) { this.auxiliaryTypes = Assert.notNull(types, "types").clone(); return self(); }
  5591. /** Sets option/positional param-specific converter (or converters for Maps), and returns this builder. */
  5592. public T converters(ITypeConverter<?>... cs) { this.converters = Assert.notNull(cs, "type converters").clone(); return self(); }
  5593. /** Sets a regular expression to split option parameter values or {@code ""} if the value should not be split, and returns this builder. */
  5594. public T splitRegex(String splitRegex) { this.splitRegex = Assert.notNull(splitRegex, "splitRegex"); return self(); }
  5595. /** Sets whether this option or positional parameter's default value should be shown in the usage help, and returns this builder. */
  5596. public T showDefaultValue(Help.Visibility visibility) { showDefaultValue = Assert.notNull(visibility, "visibility"); return self(); }
  5597. /** Sets the completion candidates for this option or positional parameter, and returns this builder.
  5598. * @since 3.2 */
  5599. public T completionCandidates(Iterable<String> completionCandidates) { this.completionCandidates = completionCandidates; return self(); }
  5600. /** Sets whether this option should be excluded from the usage message, and returns this builder. */
  5601. public T hidden(boolean hidden) { this.hidden = hidden; return self(); }
  5602. /** Sets the type to convert the option or positional parameter to before {@linkplain #setValue(Object) setting} the value, and returns this builder.
  5603. * @param propertyType the type of this option or parameter. For multi-value options and positional parameters this can be an array, or a (sub-type of) Collection or Map. */
  5604. public T type(Class<?> propertyType) { this.type = Assert.notNull(propertyType, "type"); return self(); }
  5605. /** Sets the type info for this option or positional parameter, and returns this builder.
  5606. * @param typeInfo type information that does not require {@code Class} objects and be constructed both at runtime and compile time
  5607. * @since 4.0 */
  5608. public T typeInfo(ITypeInfo typeInfo) {
  5609. setTypeInfo(Assert.notNull(typeInfo, "typeInfo"));
  5610. return self();
  5611. }
  5612. private void setTypeInfo(ITypeInfo newValue) {
  5613. this.typeInfo = newValue;
  5614. if (typeInfo != null) {
  5615. type = typeInfo.getType();
  5616. auxiliaryTypes = typeInfo.getAuxiliaryTypes();
  5617. }
  5618. }
  5619. /** Sets the user object associated with this option or positional parameters, and returns this builder.
  5620. * @param userObject may be the annotated program element, or some other useful object
  5621. * @since 4.0 */
  5622. public T userObject(Object userObject) { this.userObject = Assert.notNull(userObject, "userObject"); return self(); }
  5623. /** Sets the default value of this option or positional parameter to the specified value, and returns this builder.
  5624. * Before parsing the command line, the result of {@linkplain #splitRegex() splitting} and {@linkplain #converters() type converting}
  5625. * this default value is applied to the option or positional parameter. A value of {@code null} or {@code "__no_default_value__"} means no default. */
  5626. public T defaultValue(String defaultValue) { this.defaultValue = defaultValue; return self(); }
  5627. /** Sets the initial value of this option or positional parameter to the specified value, and returns this builder.
  5628. * If {@link #hasInitialValue()} is true, the option will be reset to the initial value before parsing (regardless
  5629. * of whether a default value exists), to clear values that would otherwise remain from parsing previous input. */
  5630. public T initialValue(Object initialValue) { this.initialValue = initialValue; return self(); }
  5631. /** Determines whether the option or positional parameter will be reset to the {@link #initialValue()}
  5632. * before parsing new input.*/
  5633. public T hasInitialValue(boolean hasInitialValue) { this.hasInitialValue = hasInitialValue; return self(); }
  5634. /** Sets the {@link IGetter} that is responsible for getting the value of this argument, and returns this builder. */
  5635. public T getter(IGetter getter) { this.getter = getter; return self(); }
  5636. /** Sets the {@link ISetter} that is responsible for modifying the value of this argument, and returns this builder. */
  5637. public T setter(ISetter setter) { this.setter = setter; return self(); }
  5638. /** Sets the {@link IScope} that targets where the setter sets the value, and returns this builder. */
  5639. public T scope(IScope scope) { this.scope = scope; return self(); }
  5640. /** Sets the string respresentation of this option or positional parameter to the specified value, and returns this builder. */
  5641. public T withToString(String toString) { this.toString = toString; return self(); }
  5642. }
  5643. }
  5644. /** The {@code OptionSpec} class models aspects of a <em>named option</em> of a {@linkplain CommandSpec command}, including whether
  5645. * it is required or optional, the option parameters supported (or required) by the option,
  5646. * and attributes for the usage help message describing the option.
  5647. * <p>
  5648. * An option has one or more names. The option is matched when the parser encounters one of the option names in the command line arguments.
  5649. * Depending on the option's {@link #arity() arity},
  5650. * the parser may expect it to have option parameters. The parser will call {@link #setValue(Object) setValue} on
  5651. * the matched option for each of the option parameters encountered.
  5652. * </p><p>
  5653. * For multi-value options, the {@code type} may be an array, a {@code Collection} or a {@code Map}. In this case
  5654. * the parser will get the data structure by calling {@link #getValue() getValue} and modify the contents of this data structure.
  5655. * (In the case of arrays, the array is replaced with a new instance with additional elements.)
  5656. * </p><p>
  5657. * Before calling the setter, picocli converts the option parameter value from a String to the option parameter's type.
  5658. * </p>
  5659. * <ul>
  5660. * <li>If a option-specific {@link #converters() converter} is configured, this will be used for type conversion.
  5661. * If the option's type is a {@code Map}, the map may have different types for its keys and its values, so
  5662. * {@link #converters() converters} should provide two converters: one for the map keys and one for the map values.</li>
  5663. * <li>Otherwise, the option's {@link #type() type} is used to look up a converter in the list of
  5664. * {@linkplain CommandLine#registerConverter(Class, ITypeConverter) registered converters}.
  5665. * For multi-value options,
  5666. * the {@code type} may be an array, or a {@code Collection} or a {@code Map}. In that case the elements are converted
  5667. * based on the option's {@link #auxiliaryTypes() auxiliaryTypes}. The auxiliaryType is used to look up
  5668. * the converter(s) to use to convert the individual parameter values.
  5669. * Maps may have different types for its keys and its values, so {@link #auxiliaryTypes() auxiliaryTypes}
  5670. * should provide two types: one for the map keys and one for the map values.</li>
  5671. * </ul>
  5672. * <p>
  5673. * {@code OptionSpec} objects are used by the picocli command line interpreter and help message generator.
  5674. * Picocli can construct an {@code OptionSpec} automatically from fields and methods with {@link Option @Option}
  5675. * annotations. Alternatively an {@code OptionSpec} can be constructed programmatically.
  5676. * </p><p>
  5677. * When an {@code OptionSpec} is created from an {@link Option @Option} -annotated field or method, it is "bound"
  5678. * to that field or method: this field is set (or the method is invoked) when the option is matched and
  5679. * {@link #setValue(Object) setValue} is called.
  5680. * Programmatically constructed {@code OptionSpec} instances will remember the value passed to the
  5681. * {@link #setValue(Object) setValue} method so it can be retrieved with the {@link #getValue() getValue} method.
  5682. * This behaviour can be customized by installing a custom {@link IGetter} and {@link ISetter} on the {@code OptionSpec}.
  5683. * </p>
  5684. * @since 3.0 */
  5685. public static class OptionSpec extends ArgSpec implements IOrdered {
  5686. static final int DEFAULT_ORDER = -1;
  5687. private String[] names;
  5688. private boolean help;
  5689. private boolean usageHelp;
  5690. private boolean versionHelp;
  5691. private int order;
  5692. public static OptionSpec.Builder builder(String name, String... names) {
  5693. String[] copy = new String[Assert.notNull(names, "names").length + 1];
  5694. copy[0] = Assert.notNull(name, "name");
  5695. System.arraycopy(names, 0, copy, 1, names.length);
  5696. return new Builder(copy);
  5697. }
  5698. public static OptionSpec.Builder builder(String[] names) { return new Builder(names); }
  5699. public static OptionSpec.Builder builder(IAnnotatedElement source, IFactory factory) { return new Builder(source, factory); }
  5700. /** Ensures all attributes of this {@code OptionSpec} have a valid value; throws an {@link InitializationException} if this cannot be achieved. */
  5701. private OptionSpec(Builder builder) {
  5702. super(builder);
  5703. if (builder.names == null) {
  5704. throw new InitializationException("OptionSpec names cannot be null. Specify at least one option name.");
  5705. }
  5706. names = builder.names.clone();
  5707. help = builder.help;
  5708. usageHelp = builder.usageHelp;
  5709. versionHelp = builder.versionHelp;
  5710. order = builder.order;
  5711. if (names.length == 0 || Arrays.asList(names).contains("")) {
  5712. throw new InitializationException("Invalid names: " + Arrays.toString(names));
  5713. }
  5714. if (toString() == null) { toString = "option " + longestName(); }
  5715. // if (arity().max == 0 && !(isBoolean(type()) || (isMultiValue() && isBoolean(auxiliaryTypes()[0])))) {
  5716. // throw new InitializationException("Option " + longestName() + " is not a boolean so should not be defined with arity=" + arity());
  5717. // }
  5718. }
  5719. /** Returns a new Builder initialized with the attributes from this {@code OptionSpec}. Calling {@code build} immediately will return a copy of this {@code OptionSpec}.
  5720. * @return a builder that can create a copy of this spec
  5721. */
  5722. public Builder toBuilder() { return new Builder(this); }
  5723. @Override public boolean isOption() { return true; }
  5724. @Override public boolean isPositional() { return false; }
  5725. protected boolean internalShowDefaultValue(boolean usageMessageShowDefaults) {
  5726. return super.internalShowDefaultValue(usageMessageShowDefaults) && !help() && !versionHelp() && !usageHelp();
  5727. }
  5728. /** Returns the description template of this option, before variables are {@linkplain Option#description() rendered}.
  5729. * If a resource bundle has been {@linkplain ArgSpec#messages(Messages) set}, this method will first try to find a value in the resource bundle:
  5730. * If the resource bundle has no entry for the {@code fully qualified commandName + "." + descriptionKey} or for the unqualified {@code descriptionKey},
  5731. * an attempt is made to find the option description using any of the option names (without leading hyphens) as key,
  5732. * first with the {@code fully qualified commandName + "."} prefix, then without.
  5733. * @see CommandSpec#qualifiedName(String)
  5734. * @see Option#description() */
  5735. @Override public String[] description() {
  5736. if (messages() == null) { return super.description(); }
  5737. String[] newValue = messages().getStringArray(descriptionKey(), null);
  5738. if (newValue != null) { return newValue; }
  5739. for (String name : names()) {
  5740. newValue = messages().getStringArray(CommandSpec.stripPrefix(name), null);
  5741. if (newValue != null) { return newValue; }
  5742. }
  5743. return super.description();
  5744. }
  5745. /** Returns one or more option names. The returned array will contain at least one option name.
  5746. * @see Option#names() */
  5747. public String[] names() { return names.clone(); }
  5748. /** Returns the longest {@linkplain #names() option name}. */
  5749. public String longestName() { return Help.ShortestFirst.longestFirst(names.clone())[0]; }
  5750. /** Returns the shortest {@linkplain #names() option name}.
  5751. * @since 3.8 */
  5752. public String shortestName() { return Help.ShortestFirst.sort(names.clone())[0]; }
  5753. /** Returns the position in the options list in the usage help message at which this option should be shown.
  5754. * Options with a lower number are shown before options with a higher number.
  5755. * This attribute is only honored if {@link UsageMessageSpec#sortOptions()} is {@code false} for this command.
  5756. * @see Option#order()
  5757. * @since 3.9 */
  5758. public int order() { return this.order; }
  5759. /** Returns whether this option disables validation of the other arguments.
  5760. * @see Option#help()
  5761. * @deprecated Use {@link #usageHelp()} and {@link #versionHelp()} instead. */
  5762. @Deprecated public boolean help() { return help; }
  5763. /** Returns whether this option allows the user to request usage help.
  5764. * @see Option#usageHelp() */
  5765. public boolean usageHelp() { return usageHelp; }
  5766. /** Returns whether this option allows the user to request version information.
  5767. * @see Option#versionHelp() */
  5768. public boolean versionHelp() { return versionHelp; }
  5769. public boolean equals(Object obj) {
  5770. if (obj == this) { return true; }
  5771. if (!(obj instanceof OptionSpec)) { return false; }
  5772. OptionSpec other = (OptionSpec) obj;
  5773. boolean result = super.equalsImpl(other)
  5774. && help == other.help
  5775. && usageHelp == other.usageHelp
  5776. && versionHelp == other.versionHelp
  5777. && order == other.order
  5778. && new HashSet<String>(Arrays.asList(names)).equals(new HashSet<String>(Arrays.asList(other.names)));
  5779. return result;
  5780. }
  5781. public int hashCode() {
  5782. return super.hashCodeImpl()
  5783. + 37 * Assert.hashCode(help)
  5784. + 37 * Assert.hashCode(usageHelp)
  5785. + 37 * Assert.hashCode(versionHelp)
  5786. + 37 * Arrays.hashCode(names)
  5787. + 37 * order;
  5788. }
  5789. /** Builder responsible for creating valid {@code OptionSpec} objects.
  5790. * @since 3.0
  5791. */
  5792. public static class Builder extends ArgSpec.Builder<Builder> {
  5793. private String[] names;
  5794. private boolean help;
  5795. private boolean usageHelp;
  5796. private boolean versionHelp;
  5797. private int order = DEFAULT_ORDER;
  5798. private Builder(String[] names) { this.names = names; }
  5799. private Builder(OptionSpec original) {
  5800. super(original);
  5801. names = original.names;
  5802. help = original.help;
  5803. usageHelp = original.usageHelp;
  5804. versionHelp = original.versionHelp;
  5805. order = original.order;
  5806. }
  5807. private Builder(IAnnotatedElement member, IFactory factory) {
  5808. super(member.getAnnotation(Option.class), member, factory);
  5809. Option option = member.getAnnotation(Option.class);
  5810. names = option.names();
  5811. help = option.help();
  5812. usageHelp = option.usageHelp();
  5813. versionHelp = option.versionHelp();
  5814. order = option.order();
  5815. }
  5816. /** Returns a valid {@code OptionSpec} instance. */
  5817. @Override public OptionSpec build() { return new OptionSpec(this); }
  5818. /** Returns this builder. */
  5819. @Override protected Builder self() { return this; }
  5820. /** Returns one or more option names. At least one option name is required.
  5821. * @see Option#names() */
  5822. public String[] names() { return names; }
  5823. /** Returns whether this option disables validation of the other arguments.
  5824. * @see Option#help()
  5825. * @deprecated Use {@link #usageHelp()} and {@link #versionHelp()} instead. */
  5826. @Deprecated public boolean help() { return help; }
  5827. /** Returns whether this option allows the user to request usage help.
  5828. * @see Option#usageHelp() */
  5829. public boolean usageHelp() { return usageHelp; }
  5830. /** Returns whether this option allows the user to request version information.
  5831. * @see Option#versionHelp() */
  5832. public boolean versionHelp() { return versionHelp; }
  5833. /** Returns the position in the options list in the usage help message at which this option should be shown.
  5834. * Options with a lower number are shown before options with a higher number.
  5835. * This attribute is only honored if {@link UsageMessageSpec#sortOptions()} is {@code false} for this command.
  5836. * @see Option#order()
  5837. * @since 3.9 */
  5838. public int order() { return order; }
  5839. /** Replaces the option names with the specified values. At least one option name is required, and returns this builder.
  5840. * @return this builder instance to provide a fluent interface */
  5841. public Builder names(String... names) { this.names = Assert.notNull(names, "names").clone(); return self(); }
  5842. /** Sets whether this option disables validation of the other arguments, and returns this builder. */
  5843. public Builder help(boolean help) { this.help = help; return self(); }
  5844. /** Sets whether this option allows the user to request usage help, and returns this builder. */
  5845. public Builder usageHelp(boolean usageHelp) { this.usageHelp = usageHelp; return self(); }
  5846. /** Sets whether this option allows the user to request version information, and returns this builder.*/
  5847. public Builder versionHelp(boolean versionHelp) { this.versionHelp = versionHelp; return self(); }
  5848. /** Sets the position in the options list in the usage help message at which this option should be shown, and returns this builder.
  5849. * @since 3.9 */
  5850. public Builder order(int order) { this.order = order; return self(); }
  5851. }
  5852. }
  5853. /** The {@code PositionalParamSpec} class models aspects of a <em>positional parameter</em> of a {@linkplain CommandSpec command}, including whether
  5854. * it is required or optional, and attributes for the usage help message describing the positional parameter.
  5855. * <p>
  5856. * Positional parameters have an {@link #index() index} (or a range of indices). A positional parameter is matched when the parser
  5857. * encounters a command line argument at that index. Named options and their parameters do not change the index counter,
  5858. * so the command line can contain a mixture of positional parameters and named options.
  5859. * </p><p>
  5860. * Depending on the positional parameter's {@link #arity() arity}, the parser may consume multiple command line
  5861. * arguments starting from the current index. The parser will call {@link #setValue(Object) setValue} on
  5862. * the {@code PositionalParamSpec} for each of the parameters encountered.
  5863. * For multi-value positional parameters, the {@code type} may be an array, a {@code Collection} or a {@code Map}. In this case
  5864. * the parser will get the data structure by calling {@link #getValue() getValue} and modify the contents of this data structure.
  5865. * (In the case of arrays, the array is replaced with a new instance with additional elements.)
  5866. * </p><p>
  5867. * Before calling the setter, picocli converts the positional parameter value from a String to the parameter's type.
  5868. * </p>
  5869. * <ul>
  5870. * <li>If a positional parameter-specific {@link #converters() converter} is configured, this will be used for type conversion.
  5871. * If the positional parameter's type is a {@code Map}, the map may have different types for its keys and its values, so
  5872. * {@link #converters() converters} should provide two converters: one for the map keys and one for the map values.</li>
  5873. * <li>Otherwise, the positional parameter's {@link #type() type} is used to look up a converter in the list of
  5874. * {@linkplain CommandLine#registerConverter(Class, ITypeConverter) registered converters}. For multi-value positional parameters,
  5875. * the {@code type} may be an array, or a {@code Collection} or a {@code Map}. In that case the elements are converted
  5876. * based on the positional parameter's {@link #auxiliaryTypes() auxiliaryTypes}. The auxiliaryType is used to look up
  5877. * the converter(s) to use to convert the individual parameter values.
  5878. * Maps may have different types for its keys and its values, so {@link #auxiliaryTypes() auxiliaryTypes}
  5879. * should provide two types: one for the map keys and one for the map values.</li>
  5880. * </ul>
  5881. * <p>
  5882. * {@code PositionalParamSpec} objects are used by the picocli command line interpreter and help message generator.
  5883. * Picocli can construct a {@code PositionalParamSpec} automatically from fields and methods with {@link Parameters @Parameters}
  5884. * annotations. Alternatively a {@code PositionalParamSpec} can be constructed programmatically.
  5885. * </p><p>
  5886. * When a {@code PositionalParamSpec} is created from a {@link Parameters @Parameters} -annotated field or method,
  5887. * it is "bound" to that field or method: this field is set (or the method is invoked) when the position is matched
  5888. * and {@link #setValue(Object) setValue} is called.
  5889. * Programmatically constructed {@code PositionalParamSpec} instances will remember the value passed to the
  5890. * {@link #setValue(Object) setValue} method so it can be retrieved with the {@link #getValue() getValue} method.
  5891. * This behaviour can be customized by installing a custom {@link IGetter} and {@link ISetter} on the {@code PositionalParamSpec}.
  5892. * </p>
  5893. * @since 3.0 */
  5894. public static class PositionalParamSpec extends ArgSpec {
  5895. private Range index;
  5896. private Range capacity;
  5897. /** Ensures all attributes of this {@code PositionalParamSpec} have a valid value; throws an {@link InitializationException} if this cannot be achieved. */
  5898. private PositionalParamSpec(Builder builder) {
  5899. super(builder);
  5900. index = builder.index == null ? Range.valueOf("*") : builder.index;
  5901. capacity = builder.capacity == null ? Range.parameterCapacity(arity(), index) : builder.capacity;
  5902. if (toString == null) { toString = "positional parameter[" + index() + "]"; }
  5903. }
  5904. public static Builder builder() { return new Builder(); }
  5905. public static Builder builder(IAnnotatedElement source, IFactory factory) { return new Builder(source, factory); }
  5906. /** Returns a new Builder initialized with the attributes from this {@code PositionalParamSpec}. Calling {@code build} immediately will return a copy of this {@code PositionalParamSpec}.
  5907. * @return a builder that can create a copy of this spec
  5908. */
  5909. public Builder toBuilder() { return new Builder(this); }
  5910. @Override public boolean isOption() { return false; }
  5911. @Override public boolean isPositional() { return true; }
  5912. /** Returns the description template of this positional parameter, before variables are {@linkplain Parameters#description() rendered}.
  5913. * If a resource bundle has been {@linkplain ArgSpec#messages(Messages) set}, this method will first try to find a value in the resource bundle:
  5914. * If the resource bundle has no entry for the {@code fully qualified commandName + "." + descriptionKey} or for the unqualified {@code descriptionKey},
  5915. * an attempt is made to find the positional parameter description using {@code paramLabel() + "[" + index() + "]"} as key,
  5916. * first with the {@code fully qualified commandName + "."} prefix, then without.
  5917. * @see Parameters#description()
  5918. * @see CommandSpec#qualifiedName(String)
  5919. * @since 3.6 */
  5920. @Override public String[] description() {
  5921. if (messages() == null) { return super.description(); }
  5922. String[] newValue = messages().getStringArray(descriptionKey(), null);
  5923. if (newValue != null) { return newValue; }
  5924. newValue = messages().getStringArray(paramLabel() + "[" + index() + "]", null);
  5925. if (newValue != null) { return newValue; }
  5926. return super.description();
  5927. }
  5928. /** Returns an index or range specifying which of the command line arguments should be assigned to this positional parameter.
  5929. * @see Parameters#index() */
  5930. public Range index() { return index; }
  5931. private Range capacity() { return capacity; }
  5932. public int hashCode() {
  5933. return super.hashCodeImpl()
  5934. + 37 * Assert.hashCode(capacity)
  5935. + 37 * Assert.hashCode(index);
  5936. }
  5937. public boolean equals(Object obj) {
  5938. if (obj == this) {
  5939. return true;
  5940. }
  5941. if (!(obj instanceof PositionalParamSpec)) {
  5942. return false;
  5943. }
  5944. PositionalParamSpec other = (PositionalParamSpec) obj;
  5945. return super.equalsImpl(other)
  5946. && Assert.equals(this.capacity, other.capacity)
  5947. && Assert.equals(this.index, other.index);
  5948. }
  5949. /** Builder responsible for creating valid {@code PositionalParamSpec} objects.
  5950. * @since 3.0
  5951. */
  5952. public static class Builder extends ArgSpec.Builder<Builder> {
  5953. private Range capacity;
  5954. private Range index;
  5955. private Builder() {}
  5956. private Builder(PositionalParamSpec original) {
  5957. super(original);
  5958. index = original.index;
  5959. capacity = original.capacity;
  5960. }
  5961. private Builder(IAnnotatedElement member, IFactory factory) {
  5962. super(member.getAnnotation(Parameters.class), member, factory);
  5963. index = Range.parameterIndex(member);
  5964. capacity = Range.parameterCapacity(member);
  5965. }
  5966. /** Returns a valid {@code PositionalParamSpec} instance. */
  5967. @Override public PositionalParamSpec build() { return new PositionalParamSpec(this); }
  5968. /** Returns this builder. */
  5969. @Override protected Builder self() { return this; }
  5970. /** Returns an index or range specifying which of the command line arguments should be assigned to this positional parameter.
  5971. * @see Parameters#index() */
  5972. public Range index() { return index; }
  5973. /** Sets the index or range specifying which of the command line arguments should be assigned to this positional parameter, and returns this builder. */
  5974. public Builder index(String range) { return index(Range.valueOf(range)); }
  5975. /** Sets the index or range specifying which of the command line arguments should be assigned to this positional parameter, and returns this builder. */
  5976. public Builder index(Range index) { this.index = index; return self(); }
  5977. Range capacity() { return capacity; }
  5978. Builder capacity(Range capacity) { this.capacity = capacity; return self(); }
  5979. }
  5980. }
  5981. /** Interface for sorting {@link OptionSpec options} and {@link ArgGroupSpec groups} together.
  5982. * @since 4.0 */
  5983. public interface IOrdered {
  5984. /** Returns the position in the options list in the usage help message at which this element should be shown.
  5985. * Elements with a lower number are shown before elements with a higher number.
  5986. * This attribute is only honored if {@link UsageMessageSpec#sortOptions()} is {@code false} for this command. */
  5987. int order();
  5988. }
  5989. /** The {@code ArgGroupSpec} class models a {@link ArgGroup group} of arguments (options, positional parameters or a mixture of the two).
  5990. * @see ArgGroup
  5991. * @since 4.0 */
  5992. public static class ArgGroupSpec implements IOrdered {
  5993. static final int DEFAULT_ORDER = -1;
  5994. private static final String NO_HEADING = "__no_heading__";
  5995. private static final String NO_HEADING_KEY = "__no_heading_key__";
  5996. private final String heading;
  5997. private final String headingKey;
  5998. private final boolean exclusive;
  5999. private final Range multiplicity;
  6000. private final boolean validate;
  6001. private final int order;
  6002. private final IGetter getter;
  6003. private final ISetter setter;
  6004. private final IScope scope;
  6005. private final ITypeInfo typeInfo;
  6006. private final List<ArgGroupSpec> subgroups;
  6007. private final Set<ArgSpec> args;
  6008. private ArgGroupSpec parentGroup;
  6009. private String id = "1";
  6010. ArgGroupSpec(ArgGroupSpec.Builder builder) {
  6011. heading = NO_HEADING .equals(builder.heading) ? null : builder.heading;
  6012. headingKey = NO_HEADING_KEY.equals(builder.headingKey) ? null : builder.headingKey;
  6013. exclusive = builder.exclusive;
  6014. multiplicity = builder.multiplicity;
  6015. validate = builder.validate;
  6016. order = builder.order;
  6017. typeInfo = builder.typeInfo;
  6018. getter = builder.getter;
  6019. setter = builder.setter;
  6020. scope = builder.scope;
  6021. args = Collections.unmodifiableSet(new LinkedHashSet<ArgSpec>(builder.args()));
  6022. subgroups = Collections.unmodifiableList(new ArrayList<ArgGroupSpec>(builder.subgroups()));
  6023. if (args.isEmpty() && subgroups.isEmpty()) { throw new InitializationException("ArgGroup has no options or positional parameters, and no subgroups"); }
  6024. int i = 1;
  6025. for (ArgGroupSpec sub : subgroups) { sub.parentGroup = this; sub.id = id + "." + i++; }
  6026. for (ArgSpec arg : args) { arg.group = this; }
  6027. }
  6028. /** Returns a new {@link Builder}.
  6029. * @return a new ArgGroupSpec.Builder instance */
  6030. public static Builder builder() { return new Builder(); }
  6031. /** Returns a new {@link Builder} associated with the specified annotated element.
  6032. * @param annotatedElement the annotated element containing {@code @Option} and {@code @Parameters}
  6033. * @return a new ArgGroupSpec.Builder instance */
  6034. public static Builder builder(IAnnotatedElement annotatedElement) { return new Builder(Assert.notNull(annotatedElement, "annotatedElement")); }
  6035. /** Returns whether this is a mutually exclusive group; {@code true} by default.
  6036. * If {@code false}, this is a co-occurring group. Ignored if {@link #validate()} is {@code false}.
  6037. * @see ArgGroup#exclusive() */
  6038. public boolean exclusive() { return exclusive; }
  6039. /** Returns the multiplicity of this group: how many occurrences it may have on the command line; {@code "0..1"} (optional) by default.
  6040. * A group can be made required by specifying a multiplicity of {@code "1"}. For a group of mutually exclusive arguments,
  6041. * being required means that one of the arguments in the group must appear on the command line, or a MissingParameterException is thrown.
  6042. * For a group of co-occurring arguments, being required means that all arguments in the group must appear on the command line.
  6043. * Ignored if {@link #validate()} is {@code false}.
  6044. * @see ArgGroup#multiplicity() */
  6045. public Range multiplicity() { return multiplicity; }
  6046. /** Returns whether picocli should validate the rules of this group:
  6047. * for a mutually exclusive group this means that no more than one arguments in the group is specified on the command line;
  6048. * for a co-ocurring group this means that all arguments in the group are specified on the command line.
  6049. * {@code true} by default.
  6050. * @see ArgGroup#validate() */
  6051. public boolean validate() { return validate; }
  6052. /** Returns the position in the options list in the usage help message at which this group should be shown.
  6053. * Options with a lower number are shown before options with a higher number.
  6054. * This attribute is only honored if {@link UsageMessageSpec#sortOptions()} is {@code false} for this command. */
  6055. public int order() { return this.order; }
  6056. /** Returns the heading of this group (may be {@code null}), used when generating the usage documentation.
  6057. * @see ArgGroup#heading() */
  6058. public String heading() { return heading; }
  6059. /** Returns the heading key of this group (may be {@code null}), used to get the heading from a resource bundle.
  6060. * @see ArgGroup#headingKey() */
  6061. public String headingKey() { return headingKey; }
  6062. /**
  6063. * Returns the parent group that this group is part of, or {@code null} if this group is not part of a composite.
  6064. */
  6065. public ArgGroupSpec parentGroup() { return parentGroup; }
  6066. /** Return the subgroups that this group is composed of; may be empty but not {@code null}.
  6067. * @return immutable list of subgroups that this group is composed of. */
  6068. public List<ArgGroupSpec> subgroups() { return subgroups; }
  6069. /**
  6070. * Returns {@code true} if this group is a subgroup (or a nested sub-subgroup, to any level of depth)
  6071. * of the specified group, {@code false} otherwise.
  6072. * @param group the group to check if it contains this group
  6073. * @return {@code true} if this group is a subgroup or a nested sub-subgroup of the specified group
  6074. */
  6075. public boolean isSubgroupOf(ArgGroupSpec group) {
  6076. for (ArgGroupSpec sub : group.subgroups) {
  6077. if (this == sub) { return true; }
  6078. if (isSubgroupOf(sub)) { return true; }
  6079. }
  6080. return false;
  6081. }
  6082. /** Returns the type info for the annotated program element associated with this group.
  6083. * @return type information that does not require {@code Class} objects and be constructed both at runtime and compile time
  6084. */
  6085. public ITypeInfo typeInfo() { return typeInfo; }
  6086. /** Returns the {@link IGetter} that is responsible for supplying the value of the annotated program element associated with this group. */
  6087. public IGetter getter() { return getter; }
  6088. /** Returns the {@link ISetter} that is responsible for modifying the value of the annotated program element associated with this group. */
  6089. public ISetter setter() { return setter; }
  6090. /** Returns the {@link IScope} that determines where the setter sets the value (or the getter gets the value) of the annotated program element associated with this group. */
  6091. public IScope scope() { return scope; }
  6092. Object userObject() { try { return getter.get(); } catch (Exception ex) { return ex.toString(); } }
  6093. String id() { return id; }
  6094. /** Returns the options and positional parameters in this group; may be empty but not {@code null}. */
  6095. public Set<ArgSpec> args() { return args; }
  6096. /** Returns the required options and positional parameters in this group; may be empty but not {@code null}. */
  6097. public Set<ArgSpec> requiredArgs() {
  6098. Set<ArgSpec> result = new LinkedHashSet<ArgSpec>(args);
  6099. for (Iterator<ArgSpec> iter = result.iterator(); iter.hasNext(); ) {
  6100. if (!iter.next().required()) { iter.remove(); }
  6101. }
  6102. return Collections.unmodifiableSet(result);
  6103. }
  6104. /** Returns the list of positional parameters configured for this group.
  6105. * @return an immutable list of positional parameters in this group. */
  6106. public List<PositionalParamSpec> positionalParameters() {
  6107. List<PositionalParamSpec> result = new ArrayList<PositionalParamSpec>();
  6108. for (ArgSpec arg : args()) { if (arg instanceof PositionalParamSpec) { result.add((PositionalParamSpec) arg); } }
  6109. return Collections.unmodifiableList(result);
  6110. }
  6111. /** Returns the list of options configured for this group.
  6112. * @return an immutable list of options in this group. */
  6113. public List<OptionSpec> options() {
  6114. List<OptionSpec> result = new ArrayList<OptionSpec>();
  6115. for (ArgSpec arg : args()) { if (arg instanceof OptionSpec) { result.add((OptionSpec) arg); } }
  6116. return Collections.unmodifiableList(result);
  6117. }
  6118. public String synopsis() {
  6119. return synopsisText(new Help.ColorScheme(Help.Ansi.OFF)).toString();
  6120. }
  6121. public Text synopsisText(Help.ColorScheme colorScheme) {
  6122. String infix = exclusive() ? " | " : " ";
  6123. Text synopsis = colorScheme.ansi().new Text(0);
  6124. for (ArgSpec arg : args()) {
  6125. if (synopsis.length > 0) { synopsis = synopsis.concat(infix); }
  6126. if (arg instanceof OptionSpec) {
  6127. synopsis = concatOptionText(synopsis, colorScheme, (OptionSpec) arg);
  6128. } else {
  6129. synopsis = concatPositionalText(synopsis, colorScheme, (PositionalParamSpec) arg);
  6130. }
  6131. }
  6132. for (ArgGroupSpec subgroup : subgroups()) {
  6133. if (synopsis.length > 0) { synopsis = synopsis.concat(infix); }
  6134. synopsis = synopsis.concat(subgroup.synopsisText(colorScheme));
  6135. }
  6136. String prefix = multiplicity().min > 0 ? "(" : "[";
  6137. String postfix = multiplicity().min > 0 ? ")" : "]";
  6138. Text result = colorScheme.ansi().text(prefix).concat(synopsis).concat(postfix);
  6139. if (multiplicity().isVariable) {
  6140. result = result.concat("...");
  6141. } else {
  6142. int i = 1;
  6143. for (; i < multiplicity.min; i++) {
  6144. result = result.concat(" (").concat(synopsis).concat(")");
  6145. }
  6146. for (; i < multiplicity.max; i++) {
  6147. result = result.concat(" [").concat(synopsis).concat("]");
  6148. }
  6149. }
  6150. return result;
  6151. }
  6152. private Text concatOptionText(Text text, Help.ColorScheme colorScheme, OptionSpec option) {
  6153. if (!option.hidden()) {
  6154. Text name = colorScheme.optionText(option.shortestName());
  6155. Text param = createLabelRenderer(option.commandSpec).renderParameterLabel(option, colorScheme.ansi(), colorScheme.optionParamStyles);
  6156. text = text.concat(open(option)).concat(name).concat(param).concat(close(option));
  6157. if (option.isMultiValue()) { // e.g., -x=VAL [-x=VAL]...
  6158. text = text.concat(" [").concat(name).concat(param).concat("]...");
  6159. }
  6160. }
  6161. return text;
  6162. }
  6163. private Text concatPositionalText(Text text, Help.ColorScheme colorScheme, PositionalParamSpec positionalParam) {
  6164. if (!positionalParam.hidden()) {
  6165. Text label = createLabelRenderer(positionalParam.commandSpec).renderParameterLabel(positionalParam, colorScheme.ansi(), colorScheme.parameterStyles);
  6166. text = text.concat(open(positionalParam)).concat(label).concat(close(positionalParam));
  6167. }
  6168. return text;
  6169. }
  6170. private String open(ArgSpec argSpec) { return argSpec.required() ? "" : "["; }
  6171. private String close(ArgSpec argSpec) { return argSpec.required() ? "" : "]"; }
  6172. public Help.IParamLabelRenderer createLabelRenderer(CommandSpec commandSpec) {
  6173. return new Help.DefaultParamLabelRenderer(commandSpec == null ? CommandSpec.create() : commandSpec);
  6174. }
  6175. @Override public boolean equals(Object obj) {
  6176. if (obj == this) { return true; }
  6177. if (!(obj instanceof ArgGroupSpec)) { return false; }
  6178. ArgGroupSpec other = (ArgGroupSpec) obj;
  6179. return exclusive == other.exclusive
  6180. && Assert.equals(multiplicity, other.multiplicity)
  6181. && validate == other.validate
  6182. && order == other.order
  6183. && Assert.equals(heading, other.heading)
  6184. && Assert.equals(headingKey, other.headingKey)
  6185. && Assert.equals(subgroups, other.subgroups)
  6186. && Assert.equals(args, other.args);
  6187. }
  6188. @Override public int hashCode() {
  6189. int result = 17;
  6190. result += 37 * result + Assert.hashCode(exclusive);
  6191. result += 37 * result + Assert.hashCode(multiplicity);
  6192. result += 37 * result + Assert.hashCode(validate);
  6193. result += 37 * result + order;
  6194. result += 37 * result + Assert.hashCode(heading);
  6195. result += 37 * result + Assert.hashCode(headingKey);
  6196. result += 37 * result + Assert.hashCode(subgroups);
  6197. result += 37 * result + Assert.hashCode(args);
  6198. return result;
  6199. }
  6200. @Override public String toString() {
  6201. List<String> argNames = new ArrayList<String>();
  6202. for (ArgSpec arg : args()) {
  6203. if (arg instanceof OptionSpec) {
  6204. argNames.add(((OptionSpec) arg).shortestName());
  6205. } else {
  6206. PositionalParamSpec p = (PositionalParamSpec) arg;
  6207. argNames.add(p.index() + " (" + p.paramLabel() + ")");
  6208. }
  6209. }
  6210. return "ArgGroup[exclusive=" + exclusive + ", multiplicity=" + multiplicity +
  6211. ", validate=" + validate + ", order=" + order + ", args=[" + ArgSpec.describe(args()) +
  6212. "], headingKey=" + quote(headingKey) + ", heading=" + quote(heading) +
  6213. ", subgroups=" + subgroups + "]";
  6214. }
  6215. private static String quote(String s) { return s == null ? "null" : "'" + s + "'"; }
  6216. void initUserObject(CommandLine commandLine) {
  6217. if (commandLine == null) { new Tracer().debug("Could not create user object for %s with null CommandLine%n.", this); }
  6218. try {
  6219. tryInitUserObject(commandLine);
  6220. } catch (PicocliException ex) {
  6221. throw ex;
  6222. } catch (Exception ex) {
  6223. throw new InitializationException("Could not create user object for " + this, ex);
  6224. }
  6225. }
  6226. void tryInitUserObject(CommandLine commandLine) throws Exception {
  6227. Tracer tracer = commandLine.tracer;
  6228. if (typeInfo() != null) {
  6229. tracer.debug("Creating new user object of type %s for group %s%n", typeInfo().getAuxiliaryTypes()[0], synopsis());
  6230. Object userObject = DefaultFactory.create(commandLine.factory, typeInfo().getAuxiliaryTypes()[0]);
  6231. tracer.debug("Created %s, invoking setter %s with scope %s%n", userObject, setter(), scope());
  6232. setUserObject(userObject, commandLine.factory);
  6233. for (ArgSpec arg : args()) {
  6234. tracer.debug("Initializing %s in group %s: setting scope to user object %s and initializing initial and default values%n", ArgSpec.describe(arg, "="), synopsis(), userObject);
  6235. arg.scope().set(userObject); // flip the actual user object for the arg (and all other args in this group; they share the same IScope instance)
  6236. commandLine.interpreter.parseResultBuilder.isInitializingDefaultValues = true;
  6237. arg.applyInitialValue(tracer);
  6238. commandLine.interpreter.applyDefault(commandLine.getCommandSpec().defaultValueProvider(), arg);
  6239. commandLine.interpreter.parseResultBuilder.isInitializingDefaultValues = false;
  6240. }
  6241. for (ArgGroupSpec subgroup : subgroups()) {
  6242. tracer.debug("Setting scope for subgroup %s with setter=%s in group %s to user object %s%n", subgroup.synopsis(), subgroup.setter(), synopsis(), userObject);
  6243. subgroup.scope().set(userObject); // flip the actual user object for the arg (and all other args in this group; they share the same IScope instance)
  6244. }
  6245. } else {
  6246. tracer.debug("No type information available for group %s: cannot create new user object. Scope for arg setters is not changed.%n", synopsis());
  6247. }
  6248. tracer.debug("Initialization complete for group %s%n", synopsis());
  6249. }
  6250. void setUserObject(Object userObject, IFactory factory) throws Exception {
  6251. if (typeInfo().isCollection()) {
  6252. @SuppressWarnings("unchecked") Collection<Object> c = (Collection<Object>) getter().get();
  6253. if (c == null) {
  6254. @SuppressWarnings("unchecked")
  6255. Collection<Object> c2 = (Collection<Object>) DefaultFactory.create(factory, typeInfo.getType());
  6256. setter().set(c = c2);
  6257. }
  6258. (c).add(userObject);
  6259. } else if (typeInfo().isArray()) {
  6260. Object old = getter().get();
  6261. int oldSize = old == null ? 0 : Array.getLength(old);
  6262. Object array = Array.newInstance(typeInfo().getAuxiliaryTypes()[0], oldSize + 1);
  6263. for (int i = 0; i < oldSize; i++) {
  6264. Array.set(array, i, Array.get(old, i));
  6265. }
  6266. Array.set(array, oldSize, userObject);
  6267. setter().set(array);
  6268. } else {
  6269. setter().set(userObject);
  6270. }
  6271. }
  6272. enum GroupValidationResult {
  6273. SUCCESS_PRESENT, SUCCESS_ABSENT,
  6274. FAILURE_PRESENT, FAILURE_ABSENT, FAILURE_PARTIAL;
  6275. static boolean containsBlockingFailure(EnumSet<GroupValidationResult> set) {
  6276. return set.contains(FAILURE_PRESENT) || set.contains(FAILURE_PARTIAL);
  6277. }
  6278. /** FAILURE_PRESENT or FAILURE_PARTIAL */
  6279. boolean blockingFailure() { return this == FAILURE_PRESENT || this == FAILURE_PARTIAL; }
  6280. boolean present() { return this == SUCCESS_PRESENT /*|| this == FAILURE_PRESENT*/; }
  6281. boolean success() { return this == SUCCESS_ABSENT || this == SUCCESS_PRESENT; }
  6282. }
  6283. private ParameterException validationException;
  6284. private GroupValidationResult validationResult;
  6285. /** Clears temporary validation state for this group and its subgroups. */
  6286. void clearValidationResult() {
  6287. validationException = null;
  6288. validationResult = null;
  6289. for (ArgGroupSpec sub : subgroups()) { sub.clearValidationResult(); }
  6290. }
  6291. /** Throws an exception if the constraints in this group are not met by the specified match. */
  6292. void validateConstraints(ParseResult parseResult) {
  6293. if (!validate()) { return; }
  6294. CommandLine commandLine = parseResult.commandSpec().commandLine();
  6295. // first validate args in this group
  6296. validationResult = validateArgs(commandLine, parseResult);
  6297. if (validationResult.blockingFailure()) {
  6298. commandLine.interpreter.maybeThrow(validationException); // composite parent validations cannot succeed anyway
  6299. }
  6300. // then validate sub groups
  6301. EnumSet<GroupValidationResult> validationResults = validateSubgroups(parseResult);
  6302. if (GroupValidationResult.containsBlockingFailure(validationResults)) {
  6303. commandLine.interpreter.maybeThrow(validationException); // composite parent validations cannot succeed anyway
  6304. }
  6305. List<MatchedGroup> matchedGroups = parseResult.findMatchedGroup(this);
  6306. if (matchedGroups.isEmpty()) {
  6307. // TODO can/should we verify minimum multiplicity here?
  6308. if (multiplicity().min > 0) {
  6309. if (validationResult.success()) {
  6310. validationResult = GroupValidationResult.FAILURE_ABSENT;
  6311. validationException = new MissingParameterException(commandLine, args(),
  6312. "Error: Group: " + synopsis() + " must be specified " + multiplicity().min + " times but was missing");
  6313. }
  6314. }
  6315. }
  6316. for (MatchedGroup matchedGroup : matchedGroups) {
  6317. int matchCount = matchedGroup.multiples().size();
  6318. // note: matchCount == 0 if only subgroup(s) are matched for a group without args (subgroups-only)
  6319. boolean checkMinimum = matchCount > 0 || !args().isEmpty();
  6320. if (checkMinimum && matchCount < multiplicity().min) {
  6321. if (validationResult.success()) {
  6322. validationResult = matchCount == 0 ? GroupValidationResult.FAILURE_ABSENT: GroupValidationResult.FAILURE_PARTIAL;
  6323. validationException = new MissingParameterException(commandLine, args(),
  6324. "Error: Group: " + synopsis() + " must be specified " + multiplicity().min + " times but was matched " + matchCount + " times");
  6325. }
  6326. } else if (matchCount > multiplicity().max) {
  6327. if (!validationResult.blockingFailure()) {
  6328. validationResult = GroupValidationResult.FAILURE_PRESENT;
  6329. validationException = new MaxValuesExceededException(commandLine,
  6330. "Error: Group: " + synopsis() + " can only be specified " + multiplicity().max + " times but was matched " + matchCount + " times.");
  6331. }
  6332. }
  6333. if (validationResult.blockingFailure()) {
  6334. commandLine.interpreter.maybeThrow(validationException);
  6335. }
  6336. }
  6337. if (validationException != null && parentGroup == null) {
  6338. commandLine.interpreter.maybeThrow(validationException);
  6339. }
  6340. }
  6341. private EnumSet<GroupValidationResult> validateSubgroups(ParseResult parseResult) {
  6342. EnumSet<GroupValidationResult> validationResults = EnumSet.of(validationResult);
  6343. if (subgroups().isEmpty()) { return validationResults; }
  6344. for (ArgGroupSpec subgroup : subgroups()) {
  6345. subgroup.validateConstraints(parseResult);
  6346. validationResults.add(Assert.notNull(subgroup.validationResult, "subgroup validation result"));
  6347. if (subgroup.validationResult.blockingFailure()) { this.validationException = subgroup.validationException; break; }
  6348. }
  6349. // now do some coarse-grained checking for exclusive subgroups
  6350. int elementCount = args().size() + subgroups().size();
  6351. int presentCount = validationResult.present() ? 1 : 0;
  6352. String exclusiveElements = "";
  6353. for (ArgGroupSpec subgroup : subgroups()) {
  6354. if (!parseResult.findMatchedGroup(subgroup).isEmpty()) { presentCount++; }
  6355. //presentCount += parseResult.findMatchedGroup(subgroup).size(); // this would give incorrect error message if A and B are exclusive and A is matched 2x and B is not matched
  6356. if (exclusiveElements.length() > 0) { exclusiveElements += " and "; }
  6357. exclusiveElements += subgroup.synopsis();
  6358. }
  6359. validationResult = validate(parseResult.commandSpec().commandLine(), presentCount, presentCount < elementCount,
  6360. presentCount > 0 && presentCount < elementCount, exclusiveElements, synopsis(), synopsis());
  6361. validationResults.add(validationResult);
  6362. return validationResults;
  6363. }
  6364. private GroupValidationResult validateArgs(CommandLine commandLine, ParseResult parseResult) {
  6365. if (args().isEmpty()) { return GroupValidationResult.SUCCESS_ABSENT; }
  6366. return validateArgs(commandLine, parseResult.findMatchedGroup(this));
  6367. }
  6368. private GroupValidationResult validateArgs(CommandLine commandLine, List<MatchedGroup> matchedGroups) {
  6369. if (matchedGroups.isEmpty()) {
  6370. int presentCount = 0;
  6371. boolean haveMissing = true;
  6372. boolean someButNotAllSpecified = false;
  6373. String exclusiveElements = "";
  6374. String missingElements = ArgSpec.describe(requiredArgs());
  6375. return validate(commandLine, presentCount, haveMissing, someButNotAllSpecified, exclusiveElements, missingElements, missingElements);
  6376. }
  6377. GroupValidationResult result = GroupValidationResult.SUCCESS_ABSENT;
  6378. Map<MatchedGroup, List<MatchedGroup>> byParent = groupByParent(matchedGroups);
  6379. for (Map.Entry<MatchedGroup, List<MatchedGroup>> entry : byParent.entrySet()) {
  6380. List<MatchedGroup> allForOneParent = entry.getValue();
  6381. for (MatchedGroup oneForOneParent : allForOneParent) {
  6382. result = validateMultiples(commandLine, oneForOneParent.multiples());
  6383. if (result.blockingFailure()) { return result; }
  6384. }
  6385. }
  6386. return result;
  6387. }
  6388. private Map<MatchedGroup, List<MatchedGroup>> groupByParent(List<MatchedGroup> matchedGroups) {
  6389. Map<MatchedGroup, List<MatchedGroup>> result = new HashMap<MatchedGroup, List<MatchedGroup>>();
  6390. for (MatchedGroup mg : matchedGroups) {
  6391. addValueToListInMap(result, mg.parentMatchedGroup(), mg);
  6392. }
  6393. return result;
  6394. }
  6395. private List<ParseResult.MatchedGroupMultiple> flatListMultiples(Collection<MatchedGroup> matchedGroups) {
  6396. List<ParseResult.MatchedGroupMultiple> all = new ArrayList<ParseResult.MatchedGroupMultiple>();
  6397. for (MatchedGroup matchedGroup : matchedGroups) {
  6398. all.addAll(matchedGroup.multiples());
  6399. }
  6400. return all;
  6401. }
  6402. private GroupValidationResult validateMultiples(CommandLine commandLine, List<ParseResult.MatchedGroupMultiple> multiples) {
  6403. Set<ArgSpec> intersection = new LinkedHashSet<ArgSpec>(this.args());
  6404. Set<ArgSpec> missing = new LinkedHashSet<ArgSpec>(this.requiredArgs());
  6405. Set<ArgSpec> found = new LinkedHashSet<ArgSpec>();
  6406. for (ParseResult.MatchedGroupMultiple multiple : multiples) {
  6407. found.addAll(multiple.matchedValues.keySet());
  6408. missing.removeAll(multiple.matchedValues.keySet());
  6409. }
  6410. intersection.retainAll(found);
  6411. int presentCount = intersection.size();
  6412. boolean haveMissing = !missing.isEmpty();
  6413. boolean someButNotAllSpecified = haveMissing && !intersection.isEmpty();
  6414. String exclusiveElements = ArgSpec.describe(intersection);
  6415. String requiredElements = ArgSpec.describe(requiredArgs());
  6416. String missingElements = ArgSpec.describe(missing);
  6417. return validate(commandLine, presentCount, haveMissing, someButNotAllSpecified, exclusiveElements, requiredElements, missingElements);
  6418. }
  6419. private GroupValidationResult validate(CommandLine commandLine, int presentCount, boolean haveMissing, boolean someButNotAllSpecified, String exclusiveElements, String requiredElements, String missingElements) {
  6420. if (exclusive()) {
  6421. if (presentCount > 1) {
  6422. validationException = new MutuallyExclusiveArgsException(commandLine,
  6423. "Error: " + exclusiveElements + " are mutually exclusive (specify only one)");
  6424. return GroupValidationResult.FAILURE_PRESENT;
  6425. }
  6426. // check that exactly one member was matched
  6427. if (multiplicity().min > 0 && presentCount < 1) {
  6428. validationException = new MissingParameterException(commandLine, args(),
  6429. "Error: Missing required argument (specify one of these): " + requiredElements);
  6430. return GroupValidationResult.FAILURE_ABSENT;
  6431. }
  6432. return GroupValidationResult.SUCCESS_PRESENT;
  6433. } else { // co-occurring group
  6434. if (someButNotAllSpecified) {
  6435. validationException = new MissingParameterException(commandLine, args(),
  6436. "Error: Missing required argument(s): " + missingElements);
  6437. return GroupValidationResult.FAILURE_PARTIAL;
  6438. }
  6439. if ((multiplicity().min > 0 && haveMissing)) {
  6440. validationException = new MissingParameterException(commandLine, args(),
  6441. "Error: Missing required argument(s): " + missingElements);
  6442. return GroupValidationResult.FAILURE_ABSENT;
  6443. }
  6444. return haveMissing ? GroupValidationResult.SUCCESS_ABSENT : GroupValidationResult.SUCCESS_PRESENT;
  6445. }
  6446. }
  6447. /** Builder responsible for creating valid {@code ArgGroupSpec} objects.
  6448. * @since 4.0 */
  6449. public static class Builder {
  6450. private IGetter getter;
  6451. private ISetter setter;
  6452. private IScope scope;
  6453. private ITypeInfo typeInfo;
  6454. private String heading;
  6455. private String headingKey;
  6456. private boolean exclusive = true;
  6457. private Range multiplicity = Range.valueOf("0..1");
  6458. private boolean validate = true;
  6459. private int order = DEFAULT_ORDER;
  6460. private List<ArgSpec> args = new ArrayList<ArgSpec>();
  6461. private List<ArgGroupSpec> subgroups = new ArrayList<ArgGroupSpec>();
  6462. // for topological sorting; private only
  6463. private Boolean topologicalSortDone;
  6464. private List<Builder> compositesReferencingMe = new ArrayList<Builder>();
  6465. Builder() { }
  6466. Builder(IAnnotatedElement source) {
  6467. typeInfo = source.getTypeInfo();
  6468. getter = source.getter();
  6469. setter = source.setter();
  6470. scope = source.scope();
  6471. }
  6472. /** Updates this builder from the specified annotation values.
  6473. * @param group annotation values
  6474. * @return this builder for method chaining */
  6475. public Builder updateArgGroupAttributes(ArgGroup group) {
  6476. return this
  6477. .heading(group.heading())
  6478. .headingKey(group.headingKey())
  6479. .exclusive(group.exclusive())
  6480. .multiplicity(group.multiplicity())
  6481. .validate(group.validate())
  6482. .order(group.order());
  6483. }
  6484. /** Returns a valid {@code ArgGroupSpec} instance. */
  6485. public ArgGroupSpec build() { return new ArgGroupSpec(this); }
  6486. /** Returns whether this is a mutually exclusive group; {@code true} by default.
  6487. * If {@code false}, this is a co-occurring group. Ignored if {@link #validate()} is {@code false}.
  6488. * @see ArgGroup#exclusive() */
  6489. public boolean exclusive() { return exclusive; }
  6490. /** Sets whether this is a mutually exclusive group; {@code true} by default.
  6491. * If {@code false}, this is a co-occurring group. Ignored if {@link #validate()} is {@code false}.
  6492. * @see ArgGroup#exclusive() */
  6493. public Builder exclusive(boolean newValue) { exclusive = newValue; return this; }
  6494. /** Returns the multiplicity of this group: how many occurrences it may have on the command line; {@code "0..1"} (optional) by default.
  6495. * A group can be made required by specifying a multiplicity of {@code "1"}. For a group of mutually exclusive arguments,
  6496. * being required means that one of the arguments in the group must appear on the command line, or a MissingParameterException is thrown.
  6497. * For a group of co-occurring arguments, being required means that all arguments in the group must appear on the command line.
  6498. * Ignored if {@link #validate()} is {@code false}.
  6499. * @see ArgGroup#multiplicity() */
  6500. public Range multiplicity() { return multiplicity; }
  6501. /** Sets the multiplicity of this group: how many occurrences it may have on the command line; {@code "0..1"} (optional) by default.
  6502. * A group can be made required by specifying a multiplicity of {@code "1"}. For a group of mutually exclusive arguments,
  6503. * being required means that one of the arguments in the group must appear on the command line, or a MissingParameterException is thrown.
  6504. * For a group of co-occurring arguments, being required means that all arguments in the group must appear on the command line.
  6505. * Ignored if {@link #validate()} is {@code false}.
  6506. * @see ArgGroup#multiplicity() */
  6507. public Builder multiplicity(String newValue) { return multiplicity(Range.valueOf(newValue)); }
  6508. /** Sets the multiplicity of this group: how many occurrences it may have on the command line; {@code "0..1"} (optional) by default.
  6509. * A group can be made required by specifying a multiplicity of {@code "1"}. For a group of mutually exclusive arguments,
  6510. * being required means that one of the arguments in the group must appear on the command line, or a MissingParameterException is thrown.
  6511. * For a group of co-occurring arguments, being required means that all arguments in the group must appear on the command line.
  6512. * Ignored if {@link #validate()} is {@code false}.
  6513. * @see ArgGroup#multiplicity() */
  6514. public Builder multiplicity(Range newValue) { multiplicity = newValue; return this; }
  6515. /** Returns whether picocli should validate the rules of this group:
  6516. * for a mutually exclusive group this means that no more than one arguments in the group is specified on the command line;
  6517. * for a co-ocurring group this means that all arguments in the group are specified on the command line.
  6518. * {@code true} by default.
  6519. * @see ArgGroup#validate() */
  6520. public boolean validate() { return validate; }
  6521. /** Sets whether picocli should validate the rules of this group:
  6522. * for a mutually exclusive group this means that no more than one arguments in the group is specified on the command line;
  6523. * for a co-ocurring group this means that all arguments in the group are specified on the command line.
  6524. * {@code true} by default.
  6525. * @see ArgGroup#validate() */
  6526. public Builder validate(boolean newValue) { validate = newValue; return this; }
  6527. /** Returns the position in the options list in the usage help message at which this group should be shown.
  6528. * Options with a lower number are shown before options with a higher number.
  6529. * This attribute is only honored if {@link UsageMessageSpec#sortOptions()} is {@code false} for this command.*/
  6530. public int order() { return order; }
  6531. /** Sets the position in the options list in the usage help message at which this group should be shown, and returns this builder. */
  6532. public Builder order(int order) { this.order = order; return this; }
  6533. /** Returns the heading of this group, used when generating the usage documentation.
  6534. * @see ArgGroup#heading() */
  6535. public String heading() { return heading; }
  6536. /** Sets the heading of this group (may be {@code null}), used when generating the usage documentation.
  6537. * @see ArgGroup#heading() */
  6538. public Builder heading(String newValue) { this.heading = newValue; return this; }
  6539. /** Returns the heading key of this group, used to get the heading from a resource bundle.
  6540. * @see ArgGroup#headingKey() */
  6541. public String headingKey() { return headingKey; }
  6542. /** Sets the heading key of this group, used to get the heading from a resource bundle.
  6543. * @see ArgGroup#headingKey() */
  6544. public Builder headingKey(String newValue) { this.headingKey = newValue; return this; }
  6545. /** Returns the type info for the annotated program element associated with this group.
  6546. * @return type information that does not require {@code Class} objects and be constructed both at runtime and compile time
  6547. */
  6548. public ITypeInfo typeInfo() { return typeInfo; }
  6549. /** Sets the type info for the annotated program element associated with this group, and returns this builder.
  6550. * @param newValue type information that does not require {@code Class} objects and be constructed both at runtime and compile time
  6551. */
  6552. public Builder typeInfo(ITypeInfo newValue) { this.typeInfo = newValue; return this; }
  6553. /** Returns the {@link IGetter} that is responsible for supplying the value of the annotated program element associated with this group. */
  6554. public IGetter getter() { return getter; }
  6555. /** Sets the {@link IGetter} that is responsible for getting the value of the annotated program element associated with this group, and returns this builder. */
  6556. public Builder getter(IGetter getter) { this.getter = getter; return this; }
  6557. /** Returns the {@link ISetter} that is responsible for modifying the value of the annotated program element associated with this group. */
  6558. public ISetter setter() { return setter; }
  6559. /** Sets the {@link ISetter} that is responsible for modifying the value of the annotated program element associated with this group, and returns this builder. */
  6560. public Builder setter(ISetter setter) { this.setter = setter; return this; }
  6561. /** Returns the {@link IScope} that determines where the setter sets the value (or the getter gets the value) of the annotated program element associated with this group. */
  6562. public IScope scope() { return scope; }
  6563. /** Sets the {@link IScope} that targets where the setter sets the value of the annotated program element associated with this group, and returns this builder. */
  6564. public Builder scope(IScope scope) { this.scope = scope; return this; }
  6565. /** Adds the specified argument to the list of options and positional parameters that depend on this group. */
  6566. public Builder addArg(ArgSpec arg) { args.add(arg); return this; }
  6567. /** Returns the list of options and positional parameters that depend on this group.*/
  6568. public List<ArgSpec> args() { return args; }
  6569. /** Adds the specified group to the list of subgroups that this group is composed of. */
  6570. public Builder addSubgroup(ArgGroupSpec group) { subgroups.add(group); return this; }
  6571. /** Returns the list of subgroups that this group is composed of.*/
  6572. public List<ArgGroupSpec> subgroups() { return subgroups; }
  6573. }
  6574. }
  6575. /** This class allows applications to specify a custom binding that will be invoked for unmatched arguments.
  6576. * A binding can be created with a {@code ISetter} that consumes the unmatched arguments {@code String[]}, or with a
  6577. * {@code IGetter} that produces a {@code Collection<String>} that the unmatched arguments can be added to.
  6578. * @since 3.0 */
  6579. public static class UnmatchedArgsBinding {
  6580. private final IGetter getter;
  6581. private final ISetter setter;
  6582. /** Creates a {@code UnmatchedArgsBinding} for a setter that consumes {@code String[]} objects.
  6583. * @param setter consumes the String[] array with unmatched arguments. */
  6584. public static UnmatchedArgsBinding forStringArrayConsumer(ISetter setter) { return new UnmatchedArgsBinding(null, setter); }
  6585. /** Creates a {@code UnmatchedArgsBinding} for a getter that produces a {@code Collection<String>} that the unmatched arguments can be added to.
  6586. * @param getter supplies a {@code Collection<String>} that the unmatched arguments can be added to. */
  6587. public static UnmatchedArgsBinding forStringCollectionSupplier(IGetter getter) { return new UnmatchedArgsBinding(getter, null); }
  6588. private UnmatchedArgsBinding(IGetter getter, ISetter setter) {
  6589. if (getter == null && setter == null) { throw new IllegalArgumentException("Getter and setter cannot both be null"); }
  6590. this.setter = setter;
  6591. this.getter = getter;
  6592. }
  6593. /** Returns the getter responsible for producing a {@code Collection} that the unmatched arguments can be added to. */
  6594. public IGetter getter() { return getter; }
  6595. /** Returns the setter responsible for consuming the unmatched arguments. */
  6596. public ISetter setter() { return setter; }
  6597. void addAll(String[] unmatched) {
  6598. if (setter != null) {
  6599. try {
  6600. setter.set(unmatched);
  6601. } catch (Exception ex) {
  6602. throw new PicocliException(String.format("Could not invoke setter (%s) with unmatched argument array '%s': %s", setter, Arrays.toString(unmatched), ex), ex);
  6603. }
  6604. }
  6605. if (getter != null) {
  6606. try {
  6607. Collection<String> collection = getter.get();
  6608. Assert.notNull(collection, "getter returned null Collection");
  6609. collection.addAll(Arrays.asList(unmatched));
  6610. } catch (Exception ex) {
  6611. throw new PicocliException(String.format("Could not add unmatched argument array '%s' to collection returned by getter (%s): %s",
  6612. Arrays.toString(unmatched), getter, ex), ex);
  6613. }
  6614. }
  6615. }
  6616. }
  6617. /** Command method parameter, similar to java.lang.reflect.Parameter (not available before Java 8).
  6618. * @since 4.0 */
  6619. public static class MethodParam extends AccessibleObject {
  6620. final Method method;
  6621. final int paramIndex;
  6622. final String name;
  6623. int position;
  6624. public MethodParam(Method method, int paramIndex) {
  6625. this.method = method;
  6626. this.paramIndex = paramIndex;
  6627. String tmp = "arg" + paramIndex;
  6628. try {
  6629. Method getParameters = Method.class.getMethod("getParameters");
  6630. Object parameters = getParameters.invoke(method);
  6631. Object parameter = Array.get(parameters, paramIndex);
  6632. tmp = (String) Class.forName("java.lang.reflect.Parameter").getDeclaredMethod("getName").invoke(parameter);
  6633. } catch (Exception ignored) {}
  6634. this.name = tmp;
  6635. }
  6636. public Type getParameterizedType() { return method.getGenericParameterTypes()[paramIndex]; }
  6637. public String getName() { return name; }
  6638. public Class<?> getType() { return method.getParameterTypes()[paramIndex]; }
  6639. public Method getDeclaringExecutable() { return method; }
  6640. @Override public <T extends Annotation> T getAnnotation(Class<T> annotationClass) {
  6641. for (Annotation annotation : getDeclaredAnnotations()) {
  6642. if (annotationClass.isAssignableFrom(annotation.getClass())) { return annotationClass.cast(annotation); }
  6643. }
  6644. return null;
  6645. }
  6646. @Override public Annotation[] getDeclaredAnnotations() { return method.getParameterAnnotations()[paramIndex]; }
  6647. @Override public void setAccessible(boolean flag) throws SecurityException { method.setAccessible(flag); }
  6648. @Override public String toString() { return method.toString() + ":" + getName(); }
  6649. }
  6650. /** Encapculates type information for an option or parameter to make this information available both at runtime
  6651. * and at compile time (when {@code Class} values are not available).
  6652. * Most of the methods in this interface (but not all!) are safe to use by annotation processors.
  6653. * @since 4.0
  6654. */
  6655. public interface ITypeInfo {
  6656. /** Returns {@code true} if {@link #getType()} is {@code boolean} or {@code java.lang.Boolean}. */
  6657. boolean isBoolean();
  6658. /** Returns {@code true} if {@link #getType()} is an array, map or collection. */
  6659. boolean isMultiValue();
  6660. boolean isArray();
  6661. boolean isCollection();
  6662. boolean isMap();
  6663. /** Returns {@code true} if {@link #getType()} is an enum. */
  6664. boolean isEnum();
  6665. List<String> getEnumConstantNames();
  6666. String getClassName();
  6667. String getClassSimpleName();
  6668. /** Returns type information of components or elements of a {@link #isMultiValue() multivalue} type. */
  6669. List<ITypeInfo> getAuxiliaryTypeInfos();
  6670. /** Returns the names of the type arguments if this is a generic type. For example, returns {@code ["java.lang.String"]} if this type is {@code List<String>}. */
  6671. List<String> getActualGenericTypeArguments();
  6672. /** Returns the class that the option or parameter value should be converted to when matched on the command
  6673. * line. This method is <em>not</em> safe for annotation processors to use.
  6674. * @return the class that the option or parameter value should be converted to
  6675. */
  6676. Class<?> getType();
  6677. /** Returns the component class of an array, or the parameter type of a generic Collection, or the parameter
  6678. * types of the key and the value of a generic Map.
  6679. * This method is <em>not</em> safe for annotation processors to use.
  6680. * @return the component type or types of an array, Collection or Map type
  6681. */
  6682. Class<?>[] getAuxiliaryTypes();
  6683. }
  6684. static class RuntimeTypeInfo implements ITypeInfo {
  6685. private final Class<?> type;
  6686. private final Class<?>[] auxiliaryTypes;
  6687. private final List<String> actualGenericTypeArguments;
  6688. RuntimeTypeInfo(Class<?> type, Class<?>[] auxiliaryTypes, List<String> actualGenericTypeArguments) {
  6689. this.type = Assert.notNull(type, "type");
  6690. this.auxiliaryTypes = Assert.notNull(auxiliaryTypes, "auxiliaryTypes").clone();
  6691. this.actualGenericTypeArguments = actualGenericTypeArguments == null ? Collections.<String>emptyList() : Collections.unmodifiableList(new ArrayList<String>(actualGenericTypeArguments));
  6692. }
  6693. static ITypeInfo createForAuxType(Class<?> type) {
  6694. return create(type, new Class[0], (Type) null, Range.valueOf("1"), String.class);
  6695. }
  6696. public static ITypeInfo create(Class<?> type,
  6697. Class<?>[] annotationTypes,
  6698. Type genericType,
  6699. Range arity,
  6700. Class<?> defaultType) {
  6701. Class<?>[] auxiliaryTypes = RuntimeTypeInfo.inferTypes(type, annotationTypes, genericType);
  6702. List<String> actualGenericTypeArguments = new ArrayList<String>();
  6703. if (genericType instanceof ParameterizedType) {
  6704. Class[] declaredTypeParameters = extractTypeParameters((ParameterizedType) genericType);
  6705. for (Class<?> c : declaredTypeParameters) { actualGenericTypeArguments.add(c.getName()); }
  6706. }
  6707. return create(type, auxiliaryTypes, actualGenericTypeArguments, arity, defaultType);
  6708. }
  6709. public static ITypeInfo create(Class<?> type, Class<?>[] auxiliaryTypes, List<String> actualGenericTypeArguments, Range arity, Class<?> defaultType) {
  6710. if (type == null) {
  6711. if (auxiliaryTypes == null || auxiliaryTypes.length == 0) {
  6712. if (arity.isVariable || arity.max > 1) {
  6713. type = String[].class;
  6714. } else if (arity.max == 1) {
  6715. type = String.class;
  6716. } else {
  6717. type = defaultType;
  6718. }
  6719. } else {
  6720. type = auxiliaryTypes[0];
  6721. }
  6722. }
  6723. if (auxiliaryTypes == null || auxiliaryTypes.length == 0) {
  6724. if (type.isArray()) {
  6725. auxiliaryTypes = new Class<?>[] {type.getComponentType()};
  6726. } else if (Collection.class.isAssignableFrom(type)) { // type is a collection but element type is unspecified
  6727. auxiliaryTypes = new Class<?>[] {String.class}; // use String elements
  6728. } else if (Map.class.isAssignableFrom(type)) { // type is a map but element type is unspecified
  6729. auxiliaryTypes = new Class<?>[] {String.class, String.class}; // use String keys and String values
  6730. } else {
  6731. auxiliaryTypes = new Class<?>[] {type};
  6732. }
  6733. }
  6734. return new RuntimeTypeInfo(type, auxiliaryTypes, actualGenericTypeArguments);
  6735. }
  6736. static Class<?>[] inferTypes(Class<?> propertyType, Class<?>[] annotationTypes, Type genericType) {
  6737. if (annotationTypes != null && annotationTypes.length > 0) { return annotationTypes; }
  6738. if (propertyType.isArray()) { return new Class<?>[] { propertyType.getComponentType() }; }
  6739. if (CommandLine.isMultiValue(propertyType)) {
  6740. if (genericType instanceof ParameterizedType) {// e.g. Map<Long, ? extends Number>
  6741. return extractTypeParameters((ParameterizedType) genericType);
  6742. }
  6743. return new Class<?>[] {String.class, String.class}; // field is multi-value but not ParameterizedType
  6744. }
  6745. return new Class<?>[] {propertyType}; // not a multi-value field
  6746. }
  6747. static Class<?>[] extractTypeParameters(ParameterizedType genericType) {
  6748. ParameterizedType parameterizedType = genericType;
  6749. Type[] paramTypes = parameterizedType.getActualTypeArguments(); // e.g. ? extends Number
  6750. Class<?>[] result = new Class<?>[paramTypes.length];
  6751. for (int i = 0; i < paramTypes.length; i++) {
  6752. if (paramTypes[i] instanceof Class) { result[i] = (Class<?>) paramTypes[i]; continue; } // e.g. Long
  6753. if (paramTypes[i] instanceof WildcardType) { // e.g. ? extends Number
  6754. WildcardType wildcardType = (WildcardType) paramTypes[i];
  6755. Type[] lower = wildcardType.getLowerBounds(); // e.g. []
  6756. if (lower.length > 0 && lower[0] instanceof Class) { result[i] = (Class<?>) lower[0]; continue; }
  6757. Type[] upper = wildcardType.getUpperBounds(); // e.g. Number
  6758. if (upper.length > 0 && upper[0] instanceof Class) { result[i] = (Class<?>) upper[0]; continue; }
  6759. }
  6760. Arrays.fill(result, String.class); return result; // too convoluted generic type, giving up
  6761. }
  6762. return result; // we inferred all types from ParameterizedType
  6763. }
  6764. public boolean isBoolean() { return auxiliaryTypes[0] == boolean.class || auxiliaryTypes[0] == Boolean.class; }
  6765. public boolean isMultiValue() { return CommandLine.isMultiValue(type); }
  6766. public boolean isArray() { return type.isArray(); }
  6767. public boolean isCollection() { return Collection.class.isAssignableFrom(type); }
  6768. public boolean isMap() { return Map.class.isAssignableFrom(type); }
  6769. public boolean isEnum() { return auxiliaryTypes[0].isEnum(); }
  6770. public String getClassName() { return type.getName(); }
  6771. public String getClassSimpleName() { return type.getSimpleName(); }
  6772. public Class<?> getType() { return type; }
  6773. public Class<?>[] getAuxiliaryTypes() { return auxiliaryTypes; }
  6774. public List<String> getActualGenericTypeArguments() { return actualGenericTypeArguments; }
  6775. public List<ITypeInfo> getAuxiliaryTypeInfos() {
  6776. List<ITypeInfo> result = new ArrayList<ITypeInfo>();
  6777. for (Class<?> c : auxiliaryTypes) { result.add(createForAuxType(c)); }
  6778. return result;
  6779. }
  6780. public List<String> getEnumConstantNames() {
  6781. if (!isEnum()) { return Collections.emptyList(); }
  6782. List<String> result = new ArrayList<String>();
  6783. for (Object c : auxiliaryTypes[0].getEnumConstants()) { result.add(c.toString()); }
  6784. return result;
  6785. }
  6786. public boolean equals(Object obj) {
  6787. if (obj == this) { return true; }
  6788. if (!(obj instanceof RuntimeTypeInfo)) { return false; }
  6789. RuntimeTypeInfo other = (RuntimeTypeInfo) obj;
  6790. return Arrays.equals(other.auxiliaryTypes, auxiliaryTypes) && type.equals(other.type);
  6791. }
  6792. public int hashCode() {
  6793. return Arrays.hashCode(auxiliaryTypes) + 37 * Assert.hashCode(type);
  6794. }
  6795. public String toString() {
  6796. return String.format("RuntimeTypeInfo(%s, aux=%s, collection=%s, map=%s)",
  6797. type.getCanonicalName(), Arrays.toString(auxiliaryTypes), isCollection(), isMap());
  6798. }
  6799. }
  6800. /** Internal interface to allow annotation processors to construct a command model at compile time.
  6801. * @since 4.0 */
  6802. public interface IAnnotatedElement {
  6803. Object userObject();
  6804. boolean isAnnotationPresent(Class<? extends Annotation> annotationClass);
  6805. <T extends Annotation> T getAnnotation(Class<T> annotationClass);
  6806. String getName();
  6807. String getMixinName();
  6808. boolean isArgSpec();
  6809. boolean isOption();
  6810. boolean isParameter();
  6811. boolean isArgGroup();
  6812. boolean isMixin();
  6813. boolean isUnmatched();
  6814. boolean isInjectSpec();
  6815. boolean isMultiValue();
  6816. boolean hasInitialValue();
  6817. boolean isMethodParameter();
  6818. int getMethodParamPosition();
  6819. CommandLine.Model.IScope scope();
  6820. CommandLine.Model.IGetter getter();
  6821. CommandLine.Model.ISetter setter();
  6822. ITypeInfo getTypeInfo();
  6823. String getToString();
  6824. }
  6825. static class TypedMember implements IAnnotatedElement {
  6826. final AccessibleObject accessible;
  6827. final String name;
  6828. final ITypeInfo typeInfo;
  6829. boolean hasInitialValue;
  6830. private IScope scope;
  6831. private IGetter getter;
  6832. private ISetter setter;
  6833. static TypedMember createIfAnnotated(Field field, IScope scope) {
  6834. return isAnnotated(field) ? new TypedMember(field, scope) : null;
  6835. }
  6836. static boolean isAnnotated(AnnotatedElement e) {
  6837. return false
  6838. || e.isAnnotationPresent(Option.class)
  6839. || e.isAnnotationPresent(Parameters.class)
  6840. || e.isAnnotationPresent(ArgGroup.class)
  6841. || e.isAnnotationPresent(Unmatched.class)
  6842. || e.isAnnotationPresent(Mixin.class)
  6843. || e.isAnnotationPresent(Spec.class)
  6844. || e.isAnnotationPresent(ParentCommand.class);
  6845. }
  6846. TypedMember(Field field) {
  6847. accessible = Assert.notNull(field, "field");
  6848. accessible.setAccessible(true);
  6849. name = field.getName();
  6850. typeInfo = createTypeInfo(field.getType(), field.getGenericType());
  6851. hasInitialValue = true;
  6852. }
  6853. private TypedMember(Field field, IScope scope) {
  6854. this(field);
  6855. Object obj = ObjectScope.tryGet(scope);
  6856. if (obj != null && Proxy.isProxyClass(obj.getClass())) {
  6857. throw new InitializationException("Invalid picocli annotation on interface field");
  6858. }
  6859. FieldBinding binding = new FieldBinding(scope, field);
  6860. getter = binding; setter = binding;
  6861. this.scope = scope;
  6862. hasInitialValue &= obj != null ;
  6863. }
  6864. static TypedMember createIfAnnotated(Method method, IScope scope, CommandSpec spec) {
  6865. return isAnnotated(method) ? new TypedMember(method, scope, spec) : null;
  6866. }
  6867. private TypedMember(Method method, IScope scope, CommandSpec spec) {
  6868. accessible = Assert.notNull(method, "method");
  6869. accessible.setAccessible(true);
  6870. name = propertyName(method.getName());
  6871. Class<?>[] parameterTypes = method.getParameterTypes();
  6872. boolean isGetter = parameterTypes.length == 0 && method.getReturnType() != Void.TYPE && method.getReturnType() != Void.class;
  6873. boolean isSetter = parameterTypes.length > 0;
  6874. if (isSetter == isGetter) { throw new InitializationException("Invalid method, must be either getter or setter: " + method); }
  6875. if (isGetter) {
  6876. hasInitialValue = true;
  6877. typeInfo = createTypeInfo(method.getReturnType(), method.getGenericReturnType());
  6878. Object proxy = ObjectScope.tryGet(scope);
  6879. if (Proxy.isProxyClass(proxy.getClass())) {
  6880. PicocliInvocationHandler handler = (PicocliInvocationHandler) Proxy.getInvocationHandler(proxy);
  6881. PicocliInvocationHandler.ProxyBinding binding = handler.new ProxyBinding(method);
  6882. getter = binding; setter = binding;
  6883. initializeInitialValue(method);
  6884. } else {
  6885. //throw new IllegalArgumentException("Getter method but not a proxy: " + scope + ": " + method);
  6886. MethodBinding binding = new MethodBinding(scope, method, spec);
  6887. getter = binding; setter = binding;
  6888. }
  6889. } else {
  6890. hasInitialValue = false;
  6891. typeInfo = createTypeInfo(parameterTypes[0], method.getGenericParameterTypes()[0]);
  6892. MethodBinding binding = new MethodBinding(scope, method, spec);
  6893. getter = binding; setter = binding;
  6894. }
  6895. }
  6896. TypedMember(MethodParam param, IScope scope) {
  6897. accessible = Assert.notNull(param, "command method parameter");
  6898. accessible.setAccessible(true);
  6899. name = param.getName();
  6900. typeInfo = createTypeInfo(param.getType(), param.getParameterizedType());
  6901. // bind parameter
  6902. ObjectBinding binding = new ObjectBinding();
  6903. getter = binding; setter = binding;
  6904. initializeInitialValue(param);
  6905. hasInitialValue = true;
  6906. }
  6907. private ITypeInfo createTypeInfo(Class<?> type, Type genericType) {
  6908. Range arity = null;
  6909. if (isOption()) { arity = Range.valueOf(getAnnotation(Option.class).arity()); }
  6910. if (isParameter()) { arity = Range.valueOf(getAnnotation(Parameters.class).arity()); }
  6911. if (arity == null || arity.isUnspecified) {
  6912. if (isOption()) {
  6913. arity = (type == null || isBoolean(type)) ? Range.valueOf("0") : Range.valueOf("1");
  6914. } else {
  6915. arity = Range.valueOf("1");
  6916. }
  6917. arity = arity.unspecified(true);
  6918. }
  6919. return RuntimeTypeInfo.create(type, annotationTypes(), genericType, arity, (isOption() ? boolean.class : String.class));
  6920. }
  6921. private void initializeInitialValue(Object arg) {
  6922. Class<?> type = typeInfo.getType();
  6923. try {
  6924. if (type == Boolean.TYPE ) { setter.set(false); }
  6925. else if (type == Byte.TYPE ) { setter.set(Byte.valueOf((byte) 0)); }
  6926. else if (type == Character.TYPE) { setter.set(Character.valueOf((char) 0)); }
  6927. else if (type == Short.TYPE ) { setter.set(Short.valueOf((short) 0)); }
  6928. else if (type == Integer.TYPE ) { setter.set(Integer.valueOf(0)); }
  6929. else if (type == Long.TYPE ) { setter.set(Long.valueOf(0L)); }
  6930. else if (type == Float.TYPE ) { setter.set(Float.valueOf(0f)); }
  6931. else if (type == Double.TYPE ) { setter.set(Double.valueOf(0d)); }
  6932. else { setter.set(null); }
  6933. } catch (Exception ex) {
  6934. throw new InitializationException("Could not set initial value for " + arg + ": " + ex.toString(), ex);
  6935. }
  6936. }
  6937. public Object userObject() { return accessible; }
  6938. public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) { return accessible.isAnnotationPresent(annotationClass); }
  6939. public <T extends Annotation> T getAnnotation(Class<T> annotationClass) { return accessible.getAnnotation(annotationClass); }
  6940. public String getName() { return name; }
  6941. public boolean isArgSpec() { return isOption() || isParameter() || (isMethodParameter() && !isMixin()); }
  6942. public boolean isOption() { return isAnnotationPresent(Option.class); }
  6943. public boolean isParameter() { return isAnnotationPresent(Parameters.class); }
  6944. public boolean isArgGroup() { return isAnnotationPresent(ArgGroup.class); }
  6945. public boolean isMixin() { return isAnnotationPresent(Mixin.class); }
  6946. public boolean isUnmatched() { return isAnnotationPresent(Unmatched.class); }
  6947. public boolean isInjectSpec() { return isAnnotationPresent(Spec.class); }
  6948. public boolean isMultiValue() { return CommandLine.isMultiValue(getType()); }
  6949. public IScope scope() { return scope; }
  6950. public IGetter getter() { return getter; }
  6951. public ISetter setter() { return setter; }
  6952. public ITypeInfo getTypeInfo() { return typeInfo; }
  6953. public Class<?> getType() { return typeInfo.getType(); }
  6954. public Class<?>[] getAuxiliaryTypes() { return typeInfo.getAuxiliaryTypes(); }
  6955. private Class<?>[] annotationTypes() {
  6956. if (isOption()) { return getAnnotation(Option.class).type(); }
  6957. if (isParameter()) { return getAnnotation(Parameters.class).type(); }
  6958. return new Class[0];
  6959. }
  6960. public String toString() { return accessible.toString(); }
  6961. public String getToString() {
  6962. if (isMixin()) { return abbreviate("mixin from member " + toGenericString()); }
  6963. return (accessible instanceof Field ? "field " : accessible instanceof Method ? "method " : accessible.getClass().getSimpleName() + " ") + abbreviate(toGenericString());
  6964. }
  6965. public String toGenericString() { return accessible instanceof Field ? ((Field) accessible).toGenericString() : accessible instanceof Method ? ((Method) accessible).toGenericString() : ((MethodParam)accessible).toString(); }
  6966. public boolean hasInitialValue() { return hasInitialValue; }
  6967. public boolean isMethodParameter() { return accessible instanceof MethodParam; }
  6968. public int getMethodParamPosition() { return isMethodParameter() ? ((MethodParam) accessible).position : -1; }
  6969. public String getMixinName() {
  6970. String annotationName = getAnnotation(Mixin.class).name();
  6971. return empty(annotationName) ? getName() : annotationName;
  6972. }
  6973. static String propertyName(String methodName) {
  6974. if (methodName.length() > 3 && (methodName.startsWith("get") || methodName.startsWith("set"))) { return decapitalize(methodName.substring(3)); }
  6975. return decapitalize(methodName);
  6976. }
  6977. private static String decapitalize(String name) {
  6978. if (name == null || name.length() == 0) { return name; }
  6979. char[] chars = name.toCharArray();
  6980. chars[0] = Character.toLowerCase(chars[0]);
  6981. return new String(chars);
  6982. }
  6983. static String abbreviate(String text) {
  6984. return text.replace("private ", "")
  6985. .replace("protected ", "")
  6986. .replace("public ", "")
  6987. .replace("java.lang.", "");
  6988. }
  6989. }
  6990. /** Utility class for getting resource bundle strings.
  6991. * Enhances the standard <a href="https://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html">ResourceBundle</a>
  6992. * with support for String arrays and qualified keys: keys that may or may not be prefixed with the fully qualified command name.
  6993. * <p>Example properties resource bundle:</p><pre>
  6994. * # Usage Help Message Sections
  6995. * # ---------------------------
  6996. * # Numbered resource keys can be used to create multi-line sections.
  6997. * usage.headerHeading = This is my app. There are other apps like it but this one is mine.%n
  6998. * usage.header = header first line
  6999. * usage.header.0 = header second line
  7000. * usage.descriptionHeading = Description:%n
  7001. * usage.description.0 = first line
  7002. * usage.description.1 = second line
  7003. * usage.description.2 = third line
  7004. * usage.synopsisHeading = Usage:&#92;u0020
  7005. * # Leading whitespace is removed by default. Start with &#92;u0020 to keep the leading whitespace.
  7006. * usage.customSynopsis.0 = Usage: ln [OPTION]... [-T] TARGET LINK_NAME (1st form)
  7007. * usage.customSynopsis.1 = &#92;u0020 or: ln [OPTION]... TARGET (2nd form)
  7008. * usage.customSynopsis.2 = &#92;u0020 or: ln [OPTION]... TARGET... DIRECTORY (3rd form)
  7009. * # Headings can contain the %n character to create multi-line values.
  7010. * usage.parameterListHeading = %nPositional parameters:%n
  7011. * usage.optionListHeading = %nOptions:%n
  7012. * usage.commandListHeading = %nCommands:%n
  7013. * usage.footerHeading = Powered by picocli%n
  7014. * usage.footer = footer
  7015. *
  7016. * # Option Descriptions
  7017. * # -------------------
  7018. * # Use numbered keys to create multi-line descriptions.
  7019. * help = Show this help message and exit.
  7020. * version = Print version information and exit.
  7021. * </pre>
  7022. * <p>Resources for multiple commands can be specified in a single ResourceBundle. Keys and their value can be
  7023. * shared by multiple commands (so you don't need to repeat them for every command), but keys can be prefixed with
  7024. * {@code fully qualified command name + "."} to specify different values for different commands.
  7025. * The most specific key wins. For example: </p>
  7026. * <pre>
  7027. * jfrog.rt.usage.header = Artifactory commands
  7028. * jfrog.rt.config.usage.header = Configure Artifactory details.
  7029. * jfrog.rt.upload.usage.header = Upload files.
  7030. *
  7031. * jfrog.bt.usage.header = Bintray commands
  7032. * jfrog.bt.config.usage.header = Configure Bintray details.
  7033. * jfrog.bt.upload.usage.header = Upload files.
  7034. *
  7035. * # shared between all commands
  7036. * usage.footerHeading = Environment Variables:
  7037. * usage.footer.0 = footer line 0
  7038. * usage.footer.1 = footer line 1
  7039. * </pre>
  7040. * @see Command#resourceBundle()
  7041. * @see Option#descriptionKey()
  7042. * @see OptionSpec#description()
  7043. * @see PositionalParamSpec#description()
  7044. * @see CommandSpec#qualifiedName(String)
  7045. * @since 3.6 */
  7046. public static class Messages {
  7047. private final CommandSpec spec;
  7048. private final String bundleBaseName;
  7049. private final ResourceBundle rb;
  7050. private final Set<String> keys;
  7051. public Messages(CommandSpec spec, String baseName) {
  7052. this(spec, baseName, createBundle(baseName));
  7053. }
  7054. public Messages(CommandSpec spec, ResourceBundle rb) {
  7055. this(spec, extractName(rb), rb);
  7056. }
  7057. public Messages(CommandSpec spec, String baseName, ResourceBundle rb) {
  7058. this.spec = Assert.notNull(spec, "CommandSpec");
  7059. this.bundleBaseName = baseName;
  7060. this.rb = rb;
  7061. this.keys = keys(rb);
  7062. }
  7063. private static ResourceBundle createBundle(String baseName) {
  7064. return ResourceBundle.getBundle(baseName);
  7065. }
  7066. private static String extractName(ResourceBundle rb) {
  7067. try { // ResourceBundle.getBaseBundleName was introduced in Java 8
  7068. return (String) ResourceBundle.class.getDeclaredMethod("getBaseBundleName").invoke(rb);
  7069. } catch (Exception ignored) { return ""; }
  7070. }
  7071. private static Set<String> keys(ResourceBundle rb) {
  7072. if (rb == null) { return Collections.emptySet(); }
  7073. Set<String> keys = new LinkedHashSet<String>();
  7074. for (Enumeration<String> k = rb.getKeys(); k.hasMoreElements(); keys.add(k.nextElement()));
  7075. return keys;
  7076. }
  7077. /** Returns a copy of the specified Messages object with the CommandSpec replaced by the specified one.
  7078. * @param spec the CommandSpec of the returned Messages
  7079. * @param original the Messages object whose ResourceBundle to reference
  7080. * @return a Messages object with the specified CommandSpec and the ResourceBundle of the specified Messages object
  7081. */
  7082. public static Messages copy(CommandSpec spec, Messages original) {
  7083. return original == null ? null : new Messages(spec, original.bundleBaseName, original.rb);
  7084. }
  7085. /** Returns {@code true} if the specified {@code Messages} is {@code null} or has a {@code null ResourceBundle}. */
  7086. public static boolean empty(Messages messages) { return messages == null || messages.rb == null; }
  7087. /** Returns the String value found in the resource bundle for the specified key, or the specified default value if not found.
  7088. * @param key unqualified resource bundle key. This method will first try to find a value by qualifying the key with the command's fully qualified name,
  7089. * and if not found, it will try with the unqualified key.
  7090. * @param defaultValue value to return if the resource bundle is null or empty, or if no value was found by the qualified or unqualified key
  7091. * @return the String value found in the resource bundle for the specified key, or the specified default value
  7092. */
  7093. public String getString(String key, String defaultValue) {
  7094. if (isEmpty()) { return defaultValue; }
  7095. String cmd = spec.qualifiedName(".");
  7096. if (keys.contains(cmd + "." + key)) { return rb.getString(cmd + "." + key); }
  7097. if (keys.contains(key)) { return rb.getString(key); }
  7098. return defaultValue;
  7099. }
  7100. boolean isEmpty() { return rb == null || keys.isEmpty(); }
  7101. /** Returns the String array value found in the resource bundle for the specified key, or the specified default value if not found.
  7102. * Multi-line strings can be specified in the resource bundle with {@code key.0}, {@code key.1}, {@code key.2}, etc.
  7103. * @param key unqualified resource bundle key. This method will first try to find a value by qualifying the key with the command's fully qualified name,
  7104. * and if not found, it will try with the unqualified key.
  7105. * @param defaultValues value to return if the resource bundle is null or empty, or if no value was found by the qualified or unqualified key
  7106. * @return the String array value found in the resource bundle for the specified key, or the specified default value
  7107. */
  7108. public String[] getStringArray(String key, String[] defaultValues) {
  7109. if (isEmpty()) { return defaultValues; }
  7110. String cmd = spec.qualifiedName(".");
  7111. List<String> result = addAllWithPrefix(rb, cmd + "." + key, keys, new ArrayList<String>());
  7112. if (!result.isEmpty()) { return result.toArray(new String[0]); }
  7113. addAllWithPrefix(rb, key, keys, result);
  7114. return result.isEmpty() ? defaultValues : result.toArray(new String[0]);
  7115. }
  7116. private static List<String> addAllWithPrefix(ResourceBundle rb, String key, Set<String> keys, List<String> result) {
  7117. if (keys.contains(key)) { result.add(rb.getString(key)); }
  7118. for (int i = 0; true; i++) {
  7119. String elementKey = key + "." + i;
  7120. if (keys.contains(elementKey)) {
  7121. result.add(rb.getString(elementKey));
  7122. } else {
  7123. return result;
  7124. }
  7125. }
  7126. }
  7127. /** Returns the ResourceBundle of the specified Messages object or {@code null} if the specified Messages object is {@code null}.
  7128. * @since 4.0 */
  7129. public static String resourceBundleBaseName(Messages messages) { return messages == null ? null : messages.resourceBundleBaseName(); }
  7130. /** Returns the ResourceBundle of the specified Messages object or {@code null} if the specified Messages object is {@code null}. */
  7131. public static ResourceBundle resourceBundle(Messages messages) { return messages == null ? null : messages.resourceBundle(); }
  7132. /** Returns the base name of the ResourceBundle of this object or {@code null}.
  7133. * @since 4.0 */
  7134. public String resourceBundleBaseName() { return bundleBaseName; }
  7135. /** Returns the ResourceBundle of this object or {@code null}. */
  7136. public ResourceBundle resourceBundle() { return rb; }
  7137. /** Returns the CommandSpec of this object, never {@code null}. */
  7138. public CommandSpec commandSpec() { return spec; }
  7139. }
  7140. private static class CommandReflection {
  7141. static ArgGroupSpec extractArgGroupSpec(IAnnotatedElement member, IFactory factory, CommandSpec commandSpec, boolean annotationsAreMandatory) throws Exception {
  7142. Object instance = null;
  7143. try { instance = member.getter().get(); } catch (Exception ignored) {}
  7144. Class<?> cls = instance == null ? member.getTypeInfo().getType() : instance.getClass();
  7145. Tracer t = new Tracer();
  7146. if (member.isMultiValue()) {
  7147. cls = member.getTypeInfo().getAuxiliaryTypes()[0];
  7148. }
  7149. IScope scope = new ObjectScope(instance);
  7150. ArgGroupSpec.Builder builder = ArgGroupSpec.builder(member);
  7151. builder.updateArgGroupAttributes(member.getAnnotation(ArgGroup.class));
  7152. if (member.isOption() || member.isParameter()) {
  7153. if (member instanceof TypedMember) { validateArgSpecMember((TypedMember) member); }
  7154. builder.addArg(buildArgForMember(member, factory));
  7155. }
  7156. Stack<Class<?>> hierarchy = new Stack<Class<?>>();
  7157. while (cls != null) { hierarchy.add(cls); cls = cls.getSuperclass(); }
  7158. boolean hasArgAnnotation = false;
  7159. while (!hierarchy.isEmpty()) {
  7160. cls = hierarchy.pop();
  7161. hasArgAnnotation |= initFromAnnotatedFields(scope, cls, commandSpec, builder, factory);
  7162. }
  7163. ArgGroupSpec result = builder.build();
  7164. if (annotationsAreMandatory) {validateArgGroupSpec(result, hasArgAnnotation, cls.getName()); }
  7165. return result;
  7166. }
  7167. static CommandSpec extractCommandSpec(Object command, IFactory factory, boolean annotationsAreMandatory) {
  7168. Class<?> cls = command.getClass();
  7169. Tracer t = new Tracer();
  7170. t.debug("Creating CommandSpec for object of class %s with factory %s%n", cls.getName(), factory.getClass().getName());
  7171. if (command instanceof CommandSpec) { return (CommandSpec) command; }
  7172. Object[] tmp = getOrCreateInstance(cls, command, factory, t);
  7173. cls = (Class<?>) tmp[0];
  7174. Object instance = tmp[1];
  7175. String commandClassName = (String) tmp[2];
  7176. CommandSpec result = CommandSpec.wrapWithoutInspection(Assert.notNull(instance, "command"));
  7177. ObjectScope scope = new ObjectScope(instance);
  7178. Stack<Class<?>> hierarchy = new Stack<Class<?>>();
  7179. while (cls != null) { hierarchy.add(cls); cls = cls.getSuperclass(); }
  7180. boolean hasCommandAnnotation = false;
  7181. boolean mixinStandardHelpOptions = false;
  7182. while (!hierarchy.isEmpty()) {
  7183. cls = hierarchy.pop();
  7184. Command cmd = cls.getAnnotation(Command.class);
  7185. if (cmd != null) {
  7186. result.updateCommandAttributes(cmd, factory);
  7187. initSubcommands(cmd, cls, result, factory);
  7188. // addGroups(cmd, groupBuilders); // TODO delete
  7189. hasCommandAnnotation = true;
  7190. }
  7191. hasCommandAnnotation |= initFromAnnotatedFields(scope, cls, result, null, factory);
  7192. if (cls.isAnnotationPresent(Command.class)) {
  7193. mixinStandardHelpOptions |= cls.getAnnotation(Command.class).mixinStandardHelpOptions();
  7194. }
  7195. }
  7196. result.mixinStandardHelpOptions(mixinStandardHelpOptions); //#377 Standard help options should be added last
  7197. if (command instanceof Method) {
  7198. Method method = (Method) command;
  7199. t.debug("Using method %s as command %n", method);
  7200. commandClassName = method.toString();
  7201. Command cmd = method.getAnnotation(Command.class);
  7202. result.updateCommandAttributes(cmd, factory);
  7203. result.setAddMethodSubcommands(false); // method commands don't have method subcommands
  7204. initSubcommands(cmd, null, result, factory);
  7205. hasCommandAnnotation = true;
  7206. result.mixinStandardHelpOptions(method.getAnnotation(Command.class).mixinStandardHelpOptions());
  7207. initFromMethodParameters(scope, method, result, null, factory);
  7208. // set command name to method name, unless @Command#name is set
  7209. result.initName(((Method)command).getName());
  7210. }
  7211. result.updateArgSpecMessages();
  7212. if (annotationsAreMandatory) {validateCommandSpec(result, hasCommandAnnotation, commandClassName); }
  7213. result.withToString(commandClassName).validate();
  7214. return result;
  7215. }
  7216. private static Object[] getOrCreateInstance(Class<?> cls, Object command, IFactory factory, Tracer t) {
  7217. Object instance = command;
  7218. String commandClassName = cls.getName();
  7219. if (command instanceof Class) {
  7220. cls = (Class) command;
  7221. commandClassName = cls.getName();
  7222. try {
  7223. t.debug("Getting a %s instance from the factory%n", cls.getName());
  7224. instance = DefaultFactory.create(factory, cls);
  7225. cls = instance.getClass();
  7226. commandClassName = cls.getName();
  7227. t.debug("Factory returned a %s instance%n", commandClassName);
  7228. } catch (InitializationException ex) {
  7229. if (cls.isInterface()) {
  7230. t.debug("%s. Creating Proxy for interface %s%n", ex.getCause(), cls.getName());
  7231. instance = Proxy.newProxyInstance(cls.getClassLoader(), new Class<?>[]{cls}, new PicocliInvocationHandler());
  7232. } else {
  7233. throw ex;
  7234. }
  7235. }
  7236. } else if (command instanceof Method) {
  7237. cls = null; // don't mix in options/positional params from outer class @Command
  7238. } else if (instance == null) {
  7239. t.debug("Getting a %s instance from the factory%n", cls.getName());
  7240. instance = DefaultFactory.create(factory, cls);
  7241. t.debug("Factory returned a %s instance%n", instance.getClass().getName());
  7242. }
  7243. return new Object[] { cls, instance, commandClassName };
  7244. }
  7245. private static void initSubcommands(Command cmd, Class<?> cls, CommandSpec parent, IFactory factory) {
  7246. for (Class<?> sub : cmd.subcommands()) {
  7247. try {
  7248. if (Help.class == sub) { throw new InitializationException(Help.class.getName() + " is not a valid subcommand. Did you mean " + HelpCommand.class.getName() + "?"); }
  7249. CommandLine subcommandLine = toCommandLine(factory.create(sub), factory);
  7250. parent.addSubcommand(subcommandName(sub), subcommandLine);
  7251. initParentCommand(subcommandLine.getCommandSpec().userObject(), parent.userObject());
  7252. }
  7253. catch (InitializationException ex) { throw ex; }
  7254. catch (NoSuchMethodException ex) { throw new InitializationException("Cannot instantiate subcommand " +
  7255. sub.getName() + ": the class has no constructor", ex); }
  7256. catch (Exception ex) {
  7257. throw new InitializationException("Could not instantiate and add subcommand " +
  7258. sub.getName() + ": " + ex, ex);
  7259. }
  7260. }
  7261. if (cmd.addMethodSubcommands() && cls != null) {
  7262. for (CommandLine sub : CommandSpec.createMethodSubcommands(cls, factory)) {
  7263. parent.addSubcommand(sub.getCommandName(), sub);
  7264. }
  7265. }
  7266. }
  7267. static void initParentCommand(Object subcommand, Object parent) {
  7268. if (subcommand == null) { return; }
  7269. try {
  7270. Class<?> cls = subcommand.getClass();
  7271. while (cls != null) {
  7272. for (Field f : cls.getDeclaredFields()) {
  7273. if (f.isAnnotationPresent(ParentCommand.class)) {
  7274. f.setAccessible(true);
  7275. f.set(subcommand, parent);
  7276. }
  7277. }
  7278. cls = cls.getSuperclass();
  7279. }
  7280. } catch (Exception ex) {
  7281. throw new InitializationException("Unable to initialize @ParentCommand field: " + ex, ex);
  7282. }
  7283. }
  7284. private static String subcommandName(Class<?> sub) {
  7285. Command subCommand = sub.getAnnotation(Command.class);
  7286. if (subCommand == null || Help.DEFAULT_COMMAND_NAME.equals(subCommand.name())) {
  7287. throw new InitializationException("Subcommand " + sub.getName() +
  7288. " is missing the mandatory @Command annotation with a 'name' attribute");
  7289. }
  7290. return subCommand.name();
  7291. }
  7292. private static boolean initFromAnnotatedFields(IScope scope, Class<?> cls, CommandSpec receiver, ArgGroupSpec.Builder groupBuilder, IFactory factory) {
  7293. boolean result = false;
  7294. for (Field field : cls.getDeclaredFields()) {
  7295. result |= initFromAnnotatedTypedMembers(TypedMember.createIfAnnotated(field, scope), receiver, groupBuilder, factory);
  7296. }
  7297. for (Method method : cls.getDeclaredMethods()) {
  7298. result |= initFromAnnotatedTypedMembers(TypedMember.createIfAnnotated(method, scope, receiver), receiver, groupBuilder, factory);
  7299. }
  7300. return result;
  7301. }
  7302. @SuppressWarnings("unchecked")
  7303. private static boolean initFromAnnotatedTypedMembers(TypedMember member,
  7304. CommandSpec commandSpec,
  7305. ArgGroupSpec.Builder groupBuilder,
  7306. IFactory factory) {
  7307. boolean result = false;
  7308. if (member == null) { return result; }
  7309. if (member.isMixin()) {
  7310. assertNoDuplicateAnnotations(member, Mixin.class, Option.class, Parameters.class, Unmatched.class, Spec.class, ArgGroup.class);
  7311. if (groupBuilder != null) {
  7312. throw new InitializationException("@Mixins are not supported on @ArgGroups");
  7313. // TODO groupBuilder.addMixin(member.getMixinName(), buildMixinForMember(member, factory));
  7314. } else {
  7315. commandSpec.addMixin(member.getMixinName(), buildMixinForMember(member, factory));
  7316. }
  7317. result = true;
  7318. }
  7319. if (member.isArgGroup()) {
  7320. assertNoDuplicateAnnotations(member, ArgGroup.class, Spec.class, Parameters.class, Option.class, Unmatched.class, Mixin.class);
  7321. if (groupBuilder != null) {
  7322. groupBuilder.addSubgroup(buildArgGroupForMember(member, factory, commandSpec));
  7323. } else {
  7324. commandSpec.addArgGroup(buildArgGroupForMember(member, factory, commandSpec));
  7325. }
  7326. return true;
  7327. }
  7328. if (member.isUnmatched()) {
  7329. assertNoDuplicateAnnotations(member, Unmatched.class, Mixin.class, Option.class, Parameters.class, Spec.class, ArgGroup.class);
  7330. if (groupBuilder != null) {
  7331. // we don't support @Unmatched on @ArgGroup class members...
  7332. throw new InitializationException("@Unmatched are not supported on @ArgGroups");
  7333. } else {
  7334. commandSpec.addUnmatchedArgsBinding(buildUnmatchedForMember(member));
  7335. }
  7336. }
  7337. if (member.isArgSpec()) {
  7338. validateArgSpecMember(member);
  7339. if (groupBuilder != null) {
  7340. groupBuilder.addArg(buildArgForMember(member, factory));
  7341. } else {
  7342. commandSpec.add(buildArgForMember(member, factory));
  7343. }
  7344. result = true;
  7345. }
  7346. if (member.isInjectSpec()) {
  7347. validateInjectSpec(member);
  7348. try { member.setter().set(commandSpec); } catch (Exception ex) { throw new InitializationException("Could not inject spec", ex); }
  7349. }
  7350. return result;
  7351. }
  7352. private static boolean initFromMethodParameters(IScope scope, Method method, CommandSpec receiver, ArgGroupSpec.Builder groupBuilder, IFactory factory) {
  7353. boolean result = false;
  7354. int optionCount = 0;
  7355. for (int i = 0, count = method.getParameterTypes().length; i < count; i++) {
  7356. MethodParam param = new MethodParam(method, i);
  7357. if (param.isAnnotationPresent(Option.class) || param.isAnnotationPresent(Mixin.class)) {
  7358. optionCount++;
  7359. } else {
  7360. param.position = i - optionCount;
  7361. }
  7362. result |= initFromAnnotatedTypedMembers(new TypedMember(param, scope), receiver, groupBuilder, factory);
  7363. }
  7364. return result;
  7365. }
  7366. @SuppressWarnings("unchecked")
  7367. private static void validateArgSpecMember(TypedMember member) {
  7368. if (!member.isArgSpec()) { throw new IllegalStateException("Bug: validateArgSpecMember() should only be called with an @Option or @Parameters member"); }
  7369. if (member.isOption()) {
  7370. assertNoDuplicateAnnotations(member, Option.class, Unmatched.class, Mixin.class, Parameters.class, Spec.class, ArgGroup.class);
  7371. } else {
  7372. assertNoDuplicateAnnotations(member, Parameters.class, Option.class, Unmatched.class, Mixin.class, Spec.class, ArgGroup.class);
  7373. }
  7374. if (!(member.accessible instanceof Field)) { return; }
  7375. Field field = (Field) member.accessible;
  7376. if (Modifier.isFinal(field.getModifiers()) && (field.getType().isPrimitive() || String.class.isAssignableFrom(field.getType()))) {
  7377. throw new InitializationException("Constant (final) primitive and String fields like " + field + " cannot be used as " +
  7378. (member.isOption() ? "an @Option" : "a @Parameter") + ": compile-time constant inlining may hide new values written to it.");
  7379. }
  7380. }
  7381. private static void validateCommandSpec(CommandSpec result, boolean hasCommandAnnotation, String commandClassName) {
  7382. if (!hasCommandAnnotation && result.positionalParameters.isEmpty() && result.optionsByNameMap.isEmpty() && result.unmatchedArgs.isEmpty()) {
  7383. throw new InitializationException(commandClassName + " is not a command: it has no @Command, @Option, @Parameters or @Unmatched annotations");
  7384. }
  7385. }
  7386. private static void validateArgGroupSpec(ArgGroupSpec result, boolean hasArgAnnotation, String className) {
  7387. if (!hasArgAnnotation && result.args().isEmpty()) {
  7388. throw new InitializationException(className + " is not a group: it has no @Option or @Parameters annotations");
  7389. }
  7390. }
  7391. @SuppressWarnings("unchecked")
  7392. private static void validateInjectSpec(TypedMember member) {
  7393. if (!member.isInjectSpec()) { throw new IllegalStateException("Bug: validateInjectSpec() should only be called with @Spec members"); }
  7394. assertNoDuplicateAnnotations(member, Spec.class, Parameters.class, Option.class, Unmatched.class, Mixin.class, ArgGroup.class);
  7395. if (!CommandSpec.class.getName().equals(member.getTypeInfo().getClassName())) {
  7396. throw new InitializationException("@picocli.CommandLine.Spec annotation is only supported on fields of type " + CommandSpec.class.getName());
  7397. }
  7398. }
  7399. private static void assertNoDuplicateAnnotations(TypedMember member, Class<? extends Annotation> myAnnotation, Class<? extends Annotation>... forbidden) {
  7400. for (Class<? extends Annotation> annotation : forbidden) {
  7401. if (member.isAnnotationPresent(annotation)) {
  7402. throw new DuplicateOptionAnnotationsException("A member cannot have both @" + myAnnotation.getSimpleName() + " and @" + annotation.getSimpleName() + " annotations, but '" + member + "' has both.");
  7403. }
  7404. }
  7405. }
  7406. private static CommandSpec buildMixinForMember(IAnnotatedElement member, IFactory factory) {
  7407. try {
  7408. Object userObject = member.getter().get();
  7409. if (userObject == null) {
  7410. userObject = factory.create(member.getTypeInfo().getType());
  7411. member.setter().set(userObject);
  7412. }
  7413. CommandSpec result = CommandSpec.forAnnotatedObject(userObject, factory);
  7414. return result.withToString(member.getToString());
  7415. } catch (InitializationException ex) {
  7416. throw ex;
  7417. } catch (Exception ex) {
  7418. throw new InitializationException("Could not access or modify mixin member " + member + ": " + ex, ex);
  7419. }
  7420. }
  7421. private static ArgSpec buildArgForMember(IAnnotatedElement member, IFactory factory) {
  7422. if (member.isOption()) { return OptionSpec.builder(member, factory).build(); }
  7423. else if (member.isParameter()) { return PositionalParamSpec.builder(member, factory).build(); }
  7424. else { return PositionalParamSpec.builder(member, factory).build(); }
  7425. }
  7426. private static ArgGroupSpec buildArgGroupForMember(IAnnotatedElement member, IFactory factory, CommandSpec commandSpec) {
  7427. try {
  7428. return extractArgGroupSpec(member, factory, commandSpec, true);
  7429. } catch (InitializationException ex) {
  7430. throw ex;
  7431. } catch (Exception ex) {
  7432. throw new InitializationException("Could not access or modify ArgGroup member " + member + ": " + ex, ex);
  7433. }
  7434. }
  7435. private static UnmatchedArgsBinding buildUnmatchedForMember(final IAnnotatedElement member) {
  7436. ITypeInfo info = member.getTypeInfo();
  7437. if (!(info.getClassName().equals(String[].class.getName()) ||
  7438. (info.isCollection() && info.getActualGenericTypeArguments().equals(Arrays.asList(String.class.getName()))))) {
  7439. throw new InitializationException("Invalid type for " + member + ": must be either String[] or List<String>");
  7440. }
  7441. if (info.getClassName().equals(String[].class.getName())) {
  7442. return UnmatchedArgsBinding.forStringArrayConsumer(member.setter());
  7443. } else {
  7444. return UnmatchedArgsBinding.forStringCollectionSupplier(new IGetter() {
  7445. @SuppressWarnings("unchecked") public <T> T get() throws Exception {
  7446. List<String> result = (List<String>) member.getter().get();
  7447. if (result == null) {
  7448. result = new ArrayList<String>();
  7449. member.setter().set(result);
  7450. }
  7451. return (T) result;
  7452. }
  7453. });
  7454. }
  7455. }
  7456. }
  7457. static class FieldBinding implements IGetter, ISetter {
  7458. private final IScope scope;
  7459. private final Field field;
  7460. private static IScope asScope(Object scope) { return scope instanceof IScope ? ((IScope) scope) : new ObjectScope(scope); }
  7461. FieldBinding(Object scope, Field field) { this(asScope(scope), field); }
  7462. FieldBinding(IScope scope, Field field) { this.scope = scope; this.field = field; }
  7463. public <T> T get() throws PicocliException {
  7464. Object obj = null;
  7465. try { obj = scope.get(); }
  7466. catch (Exception ex) { throw new PicocliException("Could not get scope for field " + field, ex); }
  7467. try {
  7468. @SuppressWarnings("unchecked") T result = (T) field.get(obj);
  7469. return result;
  7470. } catch (Exception ex) {
  7471. throw new PicocliException("Could not get value for field " + field, ex);
  7472. }
  7473. }
  7474. public <T> T set(T value) throws PicocliException {
  7475. Object obj = null;
  7476. try { obj = scope.get(); }
  7477. catch (Exception ex) { throw new PicocliException("Could not get scope for field " + field, ex); }
  7478. try {
  7479. @SuppressWarnings("unchecked") T result = (T) field.get(obj);
  7480. field.set(obj, value);
  7481. return result;
  7482. } catch (Exception ex) {
  7483. throw new PicocliException("Could not set value for field " + field + " to " + value, ex);
  7484. }
  7485. }
  7486. public String toString() {
  7487. return String.format("%s(%s %s.%s)", getClass().getSimpleName(), field.getType().getName(),
  7488. field.getDeclaringClass().getName(), field.getName());
  7489. }
  7490. }
  7491. static class MethodBinding implements IGetter, ISetter {
  7492. private final IScope scope;
  7493. private final Method method;
  7494. private final CommandSpec spec;
  7495. private Object currentValue;
  7496. MethodBinding(IScope scope, Method method, CommandSpec spec) {
  7497. this.scope = scope;
  7498. this.method = method;
  7499. this.spec = spec;
  7500. }
  7501. @SuppressWarnings("unchecked") public <T> T get() { return (T) currentValue; }
  7502. public <T> T set(T value) throws PicocliException {
  7503. Object obj = null;
  7504. try { obj = scope.get(); }
  7505. catch (Exception ex) { throw new PicocliException("Could not get scope for method " + method, ex); }
  7506. try {
  7507. @SuppressWarnings("unchecked") T result = (T) currentValue;
  7508. method.invoke(obj, value);
  7509. currentValue = value;
  7510. return result;
  7511. } catch (InvocationTargetException ex) {
  7512. if (ex.getCause() instanceof PicocliException) { throw (PicocliException) ex.getCause(); }
  7513. throw createParameterException(value, ex.getCause());
  7514. } catch (Exception ex) {
  7515. throw createParameterException(value, ex);
  7516. }
  7517. }
  7518. private ParameterException createParameterException(Object value, Throwable t) {
  7519. CommandLine cmd = spec.commandLine() == null ? new CommandLine(spec) : spec.commandLine();
  7520. return new ParameterException(cmd, "Could not invoke " + method + " with " + value, t);
  7521. }
  7522. public String toString() {
  7523. return String.format("%s(%s)", getClass().getSimpleName(), method);
  7524. }
  7525. }
  7526. private static class PicocliInvocationHandler implements InvocationHandler {
  7527. final Map<String, Object> map = new HashMap<String, Object>();
  7528. public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
  7529. return map.get(method.getName());
  7530. }
  7531. class ProxyBinding implements IGetter, ISetter {
  7532. private final Method method;
  7533. ProxyBinding(Method method) { this.method = Assert.notNull(method, "method"); }
  7534. @SuppressWarnings("unchecked") public <T> T get() { return (T) map.get(method.getName()); }
  7535. public <T> T set(T value) {
  7536. T result = get();
  7537. map.put(method.getName(), value);
  7538. return result;
  7539. }
  7540. }
  7541. }
  7542. private static class ObjectBinding implements IGetter, ISetter {
  7543. private Object value;
  7544. @SuppressWarnings("unchecked") public <T> T get() { return (T) value; }
  7545. public <T> T set(T value) {
  7546. @SuppressWarnings("unchecked") T result = value;
  7547. this.value = value;
  7548. return result;
  7549. }
  7550. public String toString() {
  7551. return String.format("%s(value=%s)", getClass().getSimpleName(), value);
  7552. }
  7553. }
  7554. static class ObjectScope implements IScope {
  7555. private Object value;
  7556. public ObjectScope(Object value) { this.value = value; }
  7557. @SuppressWarnings("unchecked") public <T> T get() { return (T) value; }
  7558. @SuppressWarnings("unchecked") public <T> T set(T value) { T old = (T) this.value; this.value = value; return old; }
  7559. public static Object tryGet(IScope scope) {
  7560. try {
  7561. return scope.get();
  7562. } catch (Exception e) {
  7563. throw new InitializationException("Could not get scope value", e);
  7564. }
  7565. }
  7566. public String toString() { return String.format("Scope(value=%s)", value); }
  7567. }
  7568. }
  7569. /** Encapsulates the result of parsing an array of command line arguments.
  7570. * @since 3.0 */
  7571. public static class ParseResult {
  7572. private final CommandSpec commandSpec;
  7573. private final List<OptionSpec> matchedOptions;
  7574. private final List<PositionalParamSpec> matchedUniquePositionals;
  7575. private final List<String> originalArgs;
  7576. private final List<String> unmatched;
  7577. private final List<List<PositionalParamSpec>> matchedPositionalParams;
  7578. private final List<Exception> errors;
  7579. private final MatchedGroup matchedGroup;
  7580. final List<Object> tentativeMatch;
  7581. private final ParseResult subcommand;
  7582. private final boolean usageHelpRequested;
  7583. private final boolean versionHelpRequested;
  7584. private ParseResult(ParseResult.Builder builder) {
  7585. commandSpec = builder.commandSpec;
  7586. subcommand = builder.subcommand;
  7587. matchedOptions = new ArrayList<OptionSpec>(builder.options);
  7588. unmatched = new ArrayList<String>(builder.unmatched);
  7589. originalArgs = new ArrayList<String>(builder.originalArgList);
  7590. matchedUniquePositionals = new ArrayList<PositionalParamSpec>(builder.positionals);
  7591. matchedPositionalParams = new ArrayList<List<PositionalParamSpec>>(builder.positionalParams);
  7592. errors = new ArrayList<Exception>(builder.errors);
  7593. usageHelpRequested = builder.usageHelpRequested;
  7594. versionHelpRequested = builder.versionHelpRequested;
  7595. tentativeMatch = builder.nowProcessing;
  7596. matchedGroup = builder.matchedGroup.trim();
  7597. }
  7598. /** Creates and returns a new {@code ParseResult.Builder} for the specified command spec. */
  7599. public static Builder builder(CommandSpec commandSpec) { return new Builder(commandSpec); }
  7600. /**
  7601. * Returns the matches for the specified argument group.
  7602. * @since 4.0 */
  7603. public List<MatchedGroup> findMatchedGroup(ArgGroupSpec group) {
  7604. return matchedGroup.findMatchedGroup(group, new ArrayList<MatchedGroup>());
  7605. }
  7606. /**
  7607. * Returns the top-level container for the {@link ArgGroupSpec ArgGroupSpec} match or matches found.
  7608. * <p>
  7609. * If the user input was a valid combination of group arguments, the returned list should contain a single
  7610. * {@linkplain MatchedGroupMultiple multiple}. Details of the {@linkplain MatchedGroup matched groups} encountered
  7611. * on the command line can be obtained via its {@link MatchedGroupMultiple#matchedSubgroups() matchedSubgroups()} method.
  7612. * The top-level multiple returned by this method contains no {@linkplain MatchedGroupMultiple#matchedValues(ArgSpec) matched arguments}.
  7613. * </p><p>
  7614. * If the returned list contains more than one {@linkplain MatchedGroupMultiple multiple}, the user input was invalid:
  7615. * the maximum {@linkplain ArgGroup#multiplicity() multiplicity} of a group was exceeded, and the parser created an extra
  7616. * {@code multiple} to capture the values. Usually this results in a {@link ParameterException ParameterException}
  7617. * being thrown by the {@code parse} method, unless the parser is configured to {@linkplain ParserSpec#collectErrors() collect errors}.
  7618. * </p>
  7619. * @since 4.0 */
  7620. public List<MatchedGroupMultiple> getMatchedGroupMultiples() {
  7621. return matchedGroup.multiples();
  7622. }
  7623. /** Returns the option with the specified short name, or {@code null} if no option with that name was matched
  7624. * on the command line.
  7625. * <p>Use {@link OptionSpec#getValue() getValue} on the returned {@code OptionSpec} to get the matched value (or values),
  7626. * converted to the type of the option. Alternatively, use {@link OptionSpec#stringValues() stringValues}
  7627. * to get the matched String values after they were {@linkplain OptionSpec#splitRegex() split} into parts, or
  7628. * {@link OptionSpec#originalStringValues() originalStringValues} to get the original String values that were
  7629. * matched on the command line, before any processing.
  7630. * </p><p>To get the {@linkplain OptionSpec#defaultValue() default value} of an option that was
  7631. * {@linkplain #hasMatchedOption(char) <em>not</em> matched} on the command line, use
  7632. * {@code parseResult.commandSpec().findOption(shortName).getValue()}. </p>
  7633. * @see CommandSpec#findOption(char) */
  7634. public OptionSpec matchedOption(char shortName) { return CommandSpec.findOption(shortName, matchedOptions); }
  7635. /** Returns the option with the specified name, or {@code null} if no option with that name was matched on the command line.
  7636. * <p>Use {@link OptionSpec#getValue() getValue} on the returned {@code OptionSpec} to get the matched value (or values),
  7637. * converted to the type of the option. Alternatively, use {@link OptionSpec#stringValues() stringValues}
  7638. * to get the matched String values after they were {@linkplain OptionSpec#splitRegex() split} into parts, or
  7639. * {@link OptionSpec#originalStringValues() originalStringValues} to get the original String values that were
  7640. * matched on the command line, before any processing.
  7641. * </p><p>To get the {@linkplain OptionSpec#defaultValue() default value} of an option that was
  7642. * {@linkplain #hasMatchedOption(String) <em>not</em> matched} on the command line, use
  7643. * {@code parseResult.commandSpec().findOption(String).getValue()}. </p>
  7644. * @see CommandSpec#findOption(String)
  7645. * @param name used to search the matched options. May be an alias of the option name that was actually specified on the command line.
  7646. * The specified name may include option name prefix characters or not. */
  7647. public OptionSpec matchedOption(String name) { return CommandSpec.findOption(name, matchedOptions); }
  7648. /** Returns the first {@code PositionalParamSpec} that matched an argument at the specified position, or {@code null} if no positional parameters were matched at that position. */
  7649. public PositionalParamSpec matchedPositional(int position) {
  7650. if (matchedPositionalParams.size() <= position || matchedPositionalParams.get(position).isEmpty()) { return null; }
  7651. return matchedPositionalParams.get(position).get(0);
  7652. }
  7653. /** Returns all {@code PositionalParamSpec} objects that matched an argument at the specified position, or an empty list if no positional parameters were matched at that position. */
  7654. public List<PositionalParamSpec> matchedPositionals(int position) {
  7655. if (matchedPositionalParams.size() <= position) { return Collections.emptyList(); }
  7656. return matchedPositionalParams.get(position) == null ? Collections.<PositionalParamSpec>emptyList() : matchedPositionalParams.get(position);
  7657. }
  7658. /** Returns the {@code CommandSpec} for the matched command. */
  7659. public CommandSpec commandSpec() { return commandSpec; }
  7660. /** Returns whether an option whose aliases include the specified short name was matched on the command line.
  7661. * @param shortName used to search the matched options. May be an alias of the option name that was actually specified on the command line. */
  7662. public boolean hasMatchedOption(char shortName) { return matchedOption(shortName) != null; }
  7663. /** Returns whether an option whose aliases include the specified name was matched on the command line.
  7664. * @param name used to search the matched options. May be an alias of the option name that was actually specified on the command line.
  7665. * The specified name may include option name prefix characters or not. */
  7666. public boolean hasMatchedOption(String name) { return matchedOption(name) != null; }
  7667. /** Returns whether the specified option was matched on the command line. */
  7668. public boolean hasMatchedOption(OptionSpec option) { return matchedOptions.contains(option); }
  7669. /** Returns whether a positional parameter was matched at the specified position. */
  7670. public boolean hasMatchedPositional(int position) { return matchedPositional(position) != null; }
  7671. /** Returns whether the specified positional parameter was matched on the command line. */
  7672. public boolean hasMatchedPositional(PositionalParamSpec positional) { return matchedUniquePositionals.contains(positional); }
  7673. /** Returns a list of matched options, in the order they were found on the command line. */
  7674. public List<OptionSpec> matchedOptions() { return Collections.unmodifiableList(matchedOptions); }
  7675. /** Returns a list of matched positional parameters. */
  7676. public List<PositionalParamSpec> matchedPositionals() { return Collections.unmodifiableList(matchedUniquePositionals); }
  7677. /** Returns a list of command line arguments that did not match any options or positional parameters. */
  7678. public List<String> unmatched() { return Collections.unmodifiableList(unmatched); }
  7679. /** Returns the command line arguments that were parsed. */
  7680. public List<String> originalArgs() { return Collections.unmodifiableList(originalArgs); }
  7681. /** If {@link ParserSpec#collectErrors} is {@code true}, returns the list of exceptions that were encountered during parsing, otherwise, returns an empty list.
  7682. * @since 3.2 */
  7683. public List<Exception> errors() { return Collections.unmodifiableList(errors); }
  7684. /** Returns the command line argument value of the option with the specified name, converted to the {@linkplain OptionSpec#type() type} of the option, or the specified default value if no option with the specified name was matched. */
  7685. public <T> T matchedOptionValue(char shortName, T defaultValue) { return matchedOptionValue(matchedOption(shortName), defaultValue); }
  7686. /** Returns the command line argument value of the option with the specified name, converted to the {@linkplain OptionSpec#type() type} of the option, or the specified default value if no option with the specified name was matched. */
  7687. public <T> T matchedOptionValue(String name, T defaultValue) { return matchedOptionValue(matchedOption(name), defaultValue); }
  7688. /** Returns the command line argument value of the specified option, converted to the {@linkplain OptionSpec#type() type} of the option, or the specified default value if the specified option is {@code null}. */
  7689. @SuppressWarnings("unchecked")
  7690. private <T> T matchedOptionValue(OptionSpec option, T defaultValue) { return option == null ? defaultValue : (T) option.getValue(); }
  7691. /** Returns the command line argument value of the positional parameter at the specified position, converted to the {@linkplain PositionalParamSpec#type() type} of the positional parameter, or the specified default value if no positional parameter was matched at that position. */
  7692. public <T> T matchedPositionalValue(int position, T defaultValue) { return matchedPositionalValue(matchedPositional(position), defaultValue); }
  7693. /** Returns the command line argument value of the specified positional parameter, converted to the {@linkplain PositionalParamSpec#type() type} of the positional parameter, or the specified default value if the specified positional parameter is {@code null}. */
  7694. @SuppressWarnings("unchecked")
  7695. private <T> T matchedPositionalValue(PositionalParamSpec positional, T defaultValue) { return positional == null ? defaultValue : (T) positional.getValue(); }
  7696. /** Returns {@code true} if a subcommand was matched on the command line, {@code false} otherwise. */
  7697. public boolean hasSubcommand() { return subcommand != null; }
  7698. /** Returns the {@code ParseResult} for the subcommand of this command that was matched on the command line, or {@code null} if no subcommand was matched. */
  7699. public ParseResult subcommand() { return subcommand; }
  7700. /** Returns {@code true} if one of the options that was matched on the command line is a {@link OptionSpec#usageHelp() usageHelp} option. */
  7701. public boolean isUsageHelpRequested() { return usageHelpRequested; }
  7702. /** Returns {@code true} if one of the options that was matched on the command line is a {@link OptionSpec#versionHelp() versionHelp} option. */
  7703. public boolean isVersionHelpRequested() { return versionHelpRequested; }
  7704. /** Returns this {@code ParseResult} as a list of {@code CommandLine} objects, one for each matched command/subcommand.
  7705. * For backwards compatibility with pre-3.0 methods. */
  7706. public List<CommandLine> asCommandLineList() {
  7707. List<CommandLine> result = new ArrayList<CommandLine>();
  7708. ParseResult pr = this;
  7709. while (pr != null) { result.add(pr.commandSpec().commandLine()); pr = pr.hasSubcommand() ? pr.subcommand() : null; }
  7710. return result;
  7711. }
  7712. /** Builds immutable {@code ParseResult} instances. */
  7713. public static class Builder {
  7714. private final CommandSpec commandSpec;
  7715. private final Set<OptionSpec> options = new LinkedHashSet<OptionSpec>();
  7716. private final Set<PositionalParamSpec> positionals = new LinkedHashSet<PositionalParamSpec>();
  7717. private final List<String> unmatched = new ArrayList<String>();
  7718. private final List<String> originalArgList = new ArrayList<String>();
  7719. private final List<List<PositionalParamSpec>> positionalParams = new ArrayList<List<PositionalParamSpec>>();
  7720. private ParseResult subcommand;
  7721. private boolean usageHelpRequested;
  7722. private boolean versionHelpRequested;
  7723. boolean isInitializingDefaultValues;
  7724. private List<Exception> errors = new ArrayList<Exception>(1);
  7725. private List<Object> nowProcessing;
  7726. private MatchedGroup matchedGroup = new MatchedGroup(null, null);
  7727. private Builder(CommandSpec spec) { commandSpec = Assert.notNull(spec, "commandSpec"); }
  7728. /** Creates and returns a new {@code ParseResult} instance for this builder's configuration. */
  7729. public ParseResult build() {
  7730. return new ParseResult(this);
  7731. }
  7732. private void nowProcessing(ArgSpec spec, Object value) {
  7733. if (nowProcessing != null && !isInitializingDefaultValues) {
  7734. nowProcessing.add(spec.isPositional() ? spec : value);
  7735. }
  7736. }
  7737. /** Adds the specified {@code OptionSpec} or {@code PositionalParamSpec} to the list of options and parameters
  7738. * that were matched on the command line.
  7739. * @param arg the matched {@code OptionSpec} or {@code PositionalParamSpec}
  7740. * @param position the command line position at which the {@code PositionalParamSpec} was matched. Ignored for {@code OptionSpec}s.
  7741. * @return this builder for method chaining */
  7742. public Builder add(ArgSpec arg, int position) {
  7743. if (arg.isOption()) {
  7744. addOption((OptionSpec) arg);
  7745. } else {
  7746. addPositionalParam((PositionalParamSpec) arg, position);
  7747. }
  7748. afterMatchingGroupElement(arg, position);
  7749. return this;
  7750. }
  7751. /** Adds the specified {@code OptionSpec} to the list of options that were matched on the command line. */
  7752. public Builder addOption(OptionSpec option) { if (!isInitializingDefaultValues) {options.add(option);} return this; }
  7753. /** Adds the specified {@code PositionalParamSpec} to the list of parameters that were matched on the command line.
  7754. * @param positionalParam the matched {@code PositionalParamSpec}
  7755. * @param position the command line position at which the {@code PositionalParamSpec} was matched.
  7756. * @return this builder for method chaining */
  7757. public Builder addPositionalParam(PositionalParamSpec positionalParam, int position) {
  7758. if (isInitializingDefaultValues) { return this; }
  7759. positionals.add(positionalParam);
  7760. while (positionalParams.size() <= position) { positionalParams.add(new ArrayList<PositionalParamSpec>()); }
  7761. positionalParams.get(position).add(positionalParam);
  7762. return this;
  7763. }
  7764. /** Adds the specified command line argument to the list of unmatched command line arguments. */
  7765. public Builder addUnmatched(String arg) { unmatched.add(arg); return this; }
  7766. /** Adds all elements of the specified command line arguments stack to the list of unmatched command line arguments. */
  7767. public Builder addUnmatched(Stack<String> args) { while (!args.isEmpty()) { addUnmatched(args.pop()); } return this; }
  7768. /** Sets the specified {@code ParseResult} for a subcommand that was matched on the command line. */
  7769. public Builder subcommand(ParseResult subcommand) { this.subcommand = subcommand; return this; }
  7770. /** Sets the specified command line arguments that were parsed. */
  7771. public Builder originalArgs(String[] originalArgs) { originalArgList.addAll(Arrays.asList(originalArgs)); return this;}
  7772. void addStringValue (ArgSpec argSpec, String value) { if (!isInitializingDefaultValues) { argSpec.stringValues.add(value);} }
  7773. void addOriginalStringValue(ArgSpec argSpec, String value) {
  7774. if (!isInitializingDefaultValues) {
  7775. argSpec.originalStringValues.add(value);
  7776. if (argSpec.group() != null) {
  7777. MatchedGroup matchedGroup = this.matchedGroup.findOrCreateMatchingGroup(argSpec, commandSpec.commandLine);
  7778. matchedGroup.multiple().addOriginalStringValue(argSpec, value);
  7779. }
  7780. }
  7781. }
  7782. void addTypedValues(ArgSpec argSpec, int position, Object typedValue) {
  7783. if (!isInitializingDefaultValues) {
  7784. argSpec.typedValues.add(typedValue);
  7785. if (argSpec.group() == null) {
  7786. argSpec.typedValueAtPosition.put(position, typedValue);
  7787. } else {
  7788. MatchedGroup matchedGroup = this.matchedGroup.findOrCreateMatchingGroup(argSpec, commandSpec.commandLine);
  7789. matchedGroup.multiple().addMatchedValue(argSpec, position, typedValue, commandSpec.commandLine.tracer);
  7790. }
  7791. }
  7792. }
  7793. public void addError(PicocliException ex) {
  7794. errors.add(Assert.notNull(ex, "exception"));
  7795. }
  7796. void beforeMatchingGroupElement(ArgSpec argSpec) throws Exception {
  7797. ArgGroupSpec group = argSpec.group();
  7798. if (group == null || isInitializingDefaultValues) { return; }
  7799. MatchedGroup foundMatchedGroup = this.matchedGroup.findOrCreateMatchingGroup(argSpec, commandSpec.commandLine);
  7800. if (foundMatchedGroup.multiple().matchedMinElements() && argSpec.required()) {
  7801. // we need to create a new multiple; if maxMultiplicity has been reached, we need to add a new MatchedGroup.
  7802. String elementDescription = ArgSpec.describe(argSpec, "=");
  7803. Tracer tracer = commandSpec.commandLine.tracer;
  7804. tracer.info("MatchedGroupMultiple %s is complete: its mandatory elements are all matched. (User object: %s.) %s is required in the group, so it starts a new MatchedGroupMultiple.%n", foundMatchedGroup.multiple(), foundMatchedGroup.group.userObject(), elementDescription);
  7805. foundMatchedGroup.addMultiple(commandSpec.commandLine);
  7806. }
  7807. }
  7808. private void afterMatchingGroupElement(ArgSpec argSpec, int position) {
  7809. // ArgGroupSpec group = argSpec.group();
  7810. // if (group == null || isInitializingDefaultValues) { return; }
  7811. // MatchedGroup matchedGroup = this.matchedGroup.findOrCreateMatchingGroup(argSpec, commandSpec.commandLine);
  7812. // promotePartiallyMatchedGroupToMatched(group, matchedGroup, true);
  7813. }
  7814. private void promotePartiallyMatchedGroupToMatched(ArgGroupSpec group, MatchedGroup matchedGroup, boolean allRequired) {
  7815. if (!matchedGroup.matchedFully(allRequired)) { return; }
  7816. // FIXME: before promoting the child group, check to see if the parent is matched, given the child group
  7817. Tracer tracer = commandSpec.commandLine.tracer;
  7818. if (matchedGroup.matchedMaxElements()) {
  7819. tracer.info("Marking matched group %s as complete: max elements reached. User object: %s%n", matchedGroup, matchedGroup.group.userObject());
  7820. matchedGroup.complete(commandSpec.commandLine());
  7821. }
  7822. }
  7823. }
  7824. /** Provides information about an {@link ArgGroup} that was matched on the command line.
  7825. * <p>
  7826. * The {@code ParseResult} may have more than one {@code MatchedGroup} for an {@code ArgGroupSpec}, when the
  7827. * group was matched more often than its maximum {@linkplain ArgGroup#multiplicity() multiplicity}.
  7828. * This is not necessarily a problem: the parser will add a multiple to the {@linkplain MatchedGroup#parentMatchedGroup() parent matched group}
  7829. * until the maximum multiplicity of the parent group is exceeded, in which case parser will add a multiple to the parent's parent group, etc.
  7830. * </p><p>
  7831. * Ultimately, as long as the {@link ParseResult#getMatchedGroupMultiples()} method does not return more than one multiple, the maximum number of elements is not exceeded.
  7832. * </p>
  7833. * @since 4.0 */
  7834. public static class MatchedGroup {
  7835. private final ArgGroupSpec group;
  7836. private MatchedGroup parentMatchedGroup;
  7837. private List<MatchedGroupMultiple> multiples = new ArrayList<MatchedGroupMultiple>();
  7838. MatchedGroup(ArgGroupSpec group, CommandLine cmd) { this.group = group; addMultiple(cmd);}
  7839. /** Returns the {@code ArgGroupSpec} whose matches are captured in this {@code MatchedGroup}. */
  7840. public ArgGroupSpec group() { return group; }
  7841. /** Returns the {@code MatchedGroup} of the parent {@code ArgGroupSpec}, or {@code null} if this group has no parent. */
  7842. public MatchedGroup parentMatchedGroup() { return parentMatchedGroup; }
  7843. /** Returns the list of {@code MatchedGroupMultiple} instances: {@code ArgGroupSpec}s with a multiplicity greater than one may be matched multiple times. */
  7844. public List<MatchedGroupMultiple> multiples() { return Collections.unmodifiableList(multiples); }
  7845. void addMultiple(CommandLine commandLine) {
  7846. Tracer tracer = commandLine == null ? new Tracer() : commandLine.tracer;
  7847. if (group != null && isMaxMultiplicityReached()) {
  7848. tracer.info("Completing MatchedGroup %s: max multiplicity is reached.%n", this);
  7849. complete(commandLine);
  7850. } else {
  7851. if (group != null) {
  7852. tracer.info("Adding multiple to MatchedGroup %s (group=%s %s).%n", this, group == null ? "?" : group.id(), group == null ? "ROOT" : group.synopsis());
  7853. }
  7854. multiples.add(new MatchedGroupMultiple(this));
  7855. if (group == null) { return; }
  7856. }
  7857. group.initUserObject(commandLine);
  7858. }
  7859. void complete(CommandLine commandLine) {
  7860. if (parentMatchedGroup == null) {
  7861. addMultiple(commandLine); // we have no choice but to potentially exceed the max multiplicity of this group...
  7862. } else {
  7863. parentMatchedGroup.addMultiple(commandLine);
  7864. }
  7865. }
  7866. /** Returns the "active" multiple of this MatchedGroup. */
  7867. MatchedGroupMultiple multiple() { return multiples.get(multiples.size() - 1); }
  7868. /** Returns {@code true} if no more {@code MatchedGroupMultiples} can be added to this {@code MatchedGroup}. Each multiple may be a complete or an incomplete match.*/
  7869. boolean isMaxMultiplicityReached() { return multiples.size() >= group.multiplicity.max; }
  7870. /** Returns {@code true} if this {@code MatchedGroup} has at least the minimum number of {@code MatchedGroupMultiples}. Each multiple may be a complete or an incomplete match. */
  7871. boolean isMinMultiplicityReached() { return multiples.size() >= group.multiplicity.min; }
  7872. /** Returns {@code true} if the minimum number of multiples has been matched for the multiplicity of this group,
  7873. * and each multiple has matched at least the {@linkplain MatchedGroupMultiple#matchedMinElements() minimum number of elements}.*/
  7874. boolean matchedMinElements() { return matchedFully(false); }
  7875. /** Returns {@code true} if the maximum number of multiples has been matched for the multiplicity of this group,
  7876. * and the last multiple has {@linkplain MatchedGroupMultiple#matchedMaxElements() matched the maximum number of elements},
  7877. * while all other multiples have matched at least the {@linkplain MatchedGroupMultiple#matchedMinElements() minimum number of elements}.*/
  7878. boolean matchedMaxElements() { return matchedFully(true); }
  7879. private boolean matchedFully(boolean allRequired) {
  7880. for (MatchedGroupMultiple multiple : multiples) {
  7881. boolean actuallyAllRequired = allRequired && multiple == multiple();
  7882. if (!multiple.matchedFully(actuallyAllRequired)) { return false; }
  7883. }
  7884. return allRequired ? isMaxMultiplicityReached() : isMinMultiplicityReached();
  7885. }
  7886. private MatchedGroup findOrCreateMatchingGroup(ArgSpec argSpec, CommandLine commandLine) {
  7887. ArgGroupSpec searchGroup = Assert.notNull(argSpec.group(), "group for " + argSpec);
  7888. MatchedGroup match = this;
  7889. if (searchGroup == match.group()) { return match; }
  7890. List<ArgGroupSpec> keys = new ArrayList<ArgGroupSpec>();
  7891. while (searchGroup != null) {
  7892. keys.add(searchGroup);
  7893. searchGroup = searchGroup.parentGroup();
  7894. }
  7895. Collections.reverse(keys);
  7896. for (ArgGroupSpec key : keys) {
  7897. MatchedGroup sub = match.multiple().matchedSubgroups().get(key);
  7898. if (sub == null) {
  7899. sub = createMatchedGroup(key, match, commandLine);
  7900. }
  7901. match = sub;
  7902. }
  7903. return match;
  7904. }
  7905. private MatchedGroup createMatchedGroup(ArgGroupSpec group, MatchedGroup parent, CommandLine commandLine) {
  7906. MatchedGroup result = new MatchedGroup(group, commandLine);
  7907. result.parentMatchedGroup = parent;
  7908. parent.multiple().matchedSubgroups.put(group, result);
  7909. return result;
  7910. }
  7911. MatchedGroup trim() {
  7912. for (Iterator<MatchedGroupMultiple> iter = multiples.iterator(); iter.hasNext(); ) {
  7913. MatchedGroupMultiple multiple = iter.next();
  7914. if (multiple.isEmpty()) { iter.remove(); }
  7915. for (MatchedGroup sub : multiple.matchedSubgroups.values()) { sub.trim(); }
  7916. }
  7917. return this;
  7918. }
  7919. List<MatchedGroup> findMatchedGroup(ArgGroupSpec group, List<MatchedGroup> result) {
  7920. if (this.group == group) { result.add(this); return result; }
  7921. for (MatchedGroupMultiple multiple : multiples()) {
  7922. for (MatchedGroup mg : multiple.matchedSubgroups.values()) {
  7923. mg.findMatchedGroup(group, result);
  7924. }
  7925. }
  7926. return result;
  7927. }
  7928. @Override public String toString() {
  7929. return toString(new StringBuilder()).toString();
  7930. }
  7931. private StringBuilder toString(StringBuilder result) {
  7932. String prefix = result.length() == 0 ? "={" : "";
  7933. String suffix = result.length() == 0 ? "}" : "";
  7934. if (group != null && result.length() == 0) {
  7935. result.append(group.synopsis());
  7936. }
  7937. result.append(prefix);
  7938. String infix = "";
  7939. for (MatchedGroupMultiple occurrence : multiples) {
  7940. result.append(infix);
  7941. occurrence.toString(result);
  7942. infix = " ";
  7943. }
  7944. return result.append(suffix);
  7945. }
  7946. }
  7947. /** A group's {@linkplain ArgGroup#multiplicity() multiplicity} specifies how many multiples of a group can/must
  7948. * appear on the command line before a group is fully matched. This class models a single "multiple".
  7949. * For example, this group: {@code (-a -b) (-a -b)} requires two multiples of its arguments to fully match.
  7950. * @since 4.0
  7951. */
  7952. public static class MatchedGroupMultiple {
  7953. int position;
  7954. final MatchedGroup container;
  7955. Map<ArgGroupSpec, MatchedGroup> matchedSubgroups = new LinkedHashMap<ArgGroupSpec, MatchedGroup>(2); // preserve order: used in toString()
  7956. Map<ArgSpec, List<Object>> matchedValues = new IdentityHashMap<ArgSpec, List<Object>>(); // identity map for performance
  7957. Map<ArgSpec, List<String>> originalStringValues = new LinkedHashMap<ArgSpec, List<String>>(); // preserve order: used in toString()
  7958. Map<ArgSpec, Map<Integer, List<Object>>> matchedValuesAtPosition = new IdentityHashMap<ArgSpec, Map<Integer, List<Object>>>();
  7959. MatchedGroupMultiple(MatchedGroup container) { this.container = container; }
  7960. /** Returns {@code true} if this multiple has no matched arguments and no matched subgroups. */
  7961. public boolean isEmpty() { return originalStringValues.isEmpty() && matchedSubgroups.isEmpty(); }
  7962. /** Returns the {@code ArgGroupSpec} of the container {@code MatchedGroup} of this multiple. */
  7963. public ArgGroupSpec group() { return container.group; }
  7964. /** Returns the container {@code MatchedGroup} of this multiple. */
  7965. public MatchedGroup container() { return container; }
  7966. /** Returns matches for the subgroups, if any. */
  7967. public Map<ArgGroupSpec, MatchedGroup> matchedSubgroups() { return Collections.unmodifiableMap(matchedSubgroups); }
  7968. int matchCount(ArgSpec argSpec) { return matchedValues.get(argSpec) == null ? 0 : matchedValues.get(argSpec).size(); }
  7969. /** Returns the values matched for the specified argument, converted to the type of the argument. */
  7970. public List<Object> matchedValues(ArgSpec argSpec) { return matchedValues.get(argSpec) == null ? Collections.emptyList() : Collections.unmodifiableList(matchedValues.get(argSpec)); }
  7971. void addOriginalStringValue(ArgSpec argSpec, String value) {
  7972. addValueToListInMap(originalStringValues, argSpec, value);
  7973. }
  7974. void addMatchedValue(ArgSpec argSpec, int matchPosition, Object stronglyTypedValue, Tracer tracer) {
  7975. addValueToListInMap(matchedValues, argSpec, stronglyTypedValue);
  7976. Map<Integer, List<Object>> positionalValues = matchedValuesAtPosition.get(argSpec);
  7977. if (positionalValues == null) {
  7978. positionalValues = new TreeMap<Integer, List<Object>>();
  7979. matchedValuesAtPosition.put(argSpec, positionalValues);
  7980. }
  7981. addValueToListInMap(positionalValues, matchPosition, stronglyTypedValue);
  7982. }
  7983. boolean hasMatchedValueAtPosition(ArgSpec arg, int position) { Map<Integer, List<Object>> atPos = matchedValuesAtPosition.get(arg); return atPos != null && atPos.containsKey(position); }
  7984. /** Returns {@code true} if the minimum number of elements have been matched for this multiple:
  7985. * all required arguments have been matched, and for each subgroup,
  7986. * the {@linkplain MatchedGroup#matchedMinElements() minimum number of elements have been matched}.*/
  7987. boolean matchedMinElements() { return matchedFully(false); }
  7988. /** Returns {@code true} if the maximum number of multiples has been matched for this multiple:
  7989. * all arguments (required or not) have been matched, and for each subgroup,
  7990. * the {@linkplain MatchedGroup#matchedMaxElements() maximum number of elements have been matched}.*/
  7991. boolean matchedMaxElements() { return matchedFully(true); }
  7992. private boolean matchedFully(boolean allRequired) {
  7993. if (group().exclusive()) { return !matchedValues.isEmpty() || hasFullyMatchedSubgroup(allRequired); }
  7994. for (ArgSpec arg : group().args()) {
  7995. if (matchedValues.get(arg) == null && (arg.required() || allRequired)) { return false; }
  7996. }
  7997. for (ArgGroupSpec subgroup : group().subgroups()) {
  7998. MatchedGroup matchedGroup = matchedSubgroups.get(subgroup);
  7999. if (matchedGroup != null) {
  8000. if (!matchedGroup.matchedFully(allRequired)) { return false; }
  8001. } else {
  8002. if (allRequired || subgroup.multiplicity().min > 0) { return false; }
  8003. }
  8004. }
  8005. return true;
  8006. }
  8007. private boolean hasFullyMatchedSubgroup(boolean allRequired) {
  8008. for (MatchedGroup sub : matchedSubgroups.values()) { if (sub.matchedFully(allRequired)) { return true; } }
  8009. return false;
  8010. }
  8011. @Override public String toString() {
  8012. return toString(new StringBuilder()).toString();
  8013. }
  8014. private StringBuilder toString(StringBuilder result) {
  8015. int originalLength = result.length();
  8016. for (ArgSpec arg : originalStringValues.keySet()) {
  8017. List<String> values = originalStringValues.get(arg);
  8018. for (String value : values) {
  8019. if (result.length() != originalLength) { result.append(" "); }
  8020. result.append(ArgSpec.describe(arg, "=", value));
  8021. }
  8022. }
  8023. for (MatchedGroup sub : matchedSubgroups.values()) {
  8024. if (result.length() != originalLength) { result.append(" "); }
  8025. if (originalLength == 0) {
  8026. result.append(sub.toString()); // include synopsis
  8027. } else {
  8028. sub.toString(result); // without synopsis
  8029. }
  8030. }
  8031. return result;
  8032. }
  8033. }
  8034. }
  8035. static <K, T> void addValueToListInMap(Map<K, List<T>> map, K key, T value) {
  8036. List<T> values = map.get(key);
  8037. if (values == null) { values = new ArrayList<T>(); map.put(key, values); }
  8038. values.add(value);
  8039. }
  8040. static <T> List<T> flatList(Collection<? extends Collection<T>> collection) {
  8041. List<T> result = new ArrayList<T>();
  8042. for (Collection<T> sub : collection) { result.addAll(sub); }
  8043. return result;
  8044. }
  8045. private enum LookBehind { SEPARATE, ATTACHED, ATTACHED_WITH_SEPARATOR;
  8046. public boolean isAttached() { return this != LookBehind.SEPARATE; }
  8047. }
  8048. /**
  8049. * Helper class responsible for processing command line arguments.
  8050. */
  8051. private class Interpreter {
  8052. private final Map<Class<?>, ITypeConverter<?>> converterRegistry = new HashMap<Class<?>, ITypeConverter<?>>();
  8053. private boolean isHelpRequested;
  8054. private int position;
  8055. private boolean endOfOptions;
  8056. private ParseResult.Builder parseResultBuilder;
  8057. Interpreter() { registerBuiltInConverters(); }
  8058. private void registerBuiltInConverters() {
  8059. converterRegistry.put(Object.class, new BuiltIn.StringConverter());
  8060. converterRegistry.put(String.class, new BuiltIn.StringConverter());
  8061. converterRegistry.put(StringBuilder.class, new BuiltIn.StringBuilderConverter());
  8062. converterRegistry.put(CharSequence.class, new BuiltIn.CharSequenceConverter());
  8063. converterRegistry.put(Byte.class, new BuiltIn.ByteConverter());
  8064. converterRegistry.put(Byte.TYPE, new BuiltIn.ByteConverter());
  8065. converterRegistry.put(Boolean.class, new BuiltIn.BooleanConverter());
  8066. converterRegistry.put(Boolean.TYPE, new BuiltIn.BooleanConverter());
  8067. converterRegistry.put(Character.class, new BuiltIn.CharacterConverter());
  8068. converterRegistry.put(Character.TYPE, new BuiltIn.CharacterConverter());
  8069. converterRegistry.put(Short.class, new BuiltIn.ShortConverter());
  8070. converterRegistry.put(Short.TYPE, new BuiltIn.ShortConverter());
  8071. converterRegistry.put(Integer.class, new BuiltIn.IntegerConverter());
  8072. converterRegistry.put(Integer.TYPE, new BuiltIn.IntegerConverter());
  8073. converterRegistry.put(Long.class, new BuiltIn.LongConverter());
  8074. converterRegistry.put(Long.TYPE, new BuiltIn.LongConverter());
  8075. converterRegistry.put(Float.class, new BuiltIn.FloatConverter());
  8076. converterRegistry.put(Float.TYPE, new BuiltIn.FloatConverter());
  8077. converterRegistry.put(Double.class, new BuiltIn.DoubleConverter());
  8078. converterRegistry.put(Double.TYPE, new BuiltIn.DoubleConverter());
  8079. converterRegistry.put(File.class, new BuiltIn.FileConverter());
  8080. converterRegistry.put(URI.class, new BuiltIn.URIConverter());
  8081. converterRegistry.put(URL.class, new BuiltIn.URLConverter());
  8082. converterRegistry.put(Date.class, new BuiltIn.ISO8601DateConverter());
  8083. converterRegistry.put(BigDecimal.class, new BuiltIn.BigDecimalConverter());
  8084. converterRegistry.put(BigInteger.class, new BuiltIn.BigIntegerConverter());
  8085. converterRegistry.put(Charset.class, new BuiltIn.CharsetConverter());
  8086. converterRegistry.put(InetAddress.class, new BuiltIn.InetAddressConverter());
  8087. converterRegistry.put(Pattern.class, new BuiltIn.PatternConverter());
  8088. converterRegistry.put(UUID.class, new BuiltIn.UUIDConverter());
  8089. converterRegistry.put(Currency.class, new BuiltIn.CurrencyConverter());
  8090. converterRegistry.put(TimeZone.class, new BuiltIn.TimeZoneConverter());
  8091. converterRegistry.put(ByteOrder.class, new BuiltIn.ByteOrderConverter());
  8092. converterRegistry.put(Class.class, new BuiltIn.ClassConverter());
  8093. converterRegistry.put(NetworkInterface.class, new BuiltIn.NetworkInterfaceConverter());
  8094. BuiltIn.ISO8601TimeConverter.registerIfAvailable(converterRegistry, tracer);
  8095. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.sql.Connection", "java.sql.DriverManager","getConnection", String.class);
  8096. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.sql.Driver", "java.sql.DriverManager","getDriver", String.class);
  8097. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.sql.Timestamp", "java.sql.Timestamp","valueOf", String.class);
  8098. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.Duration", "parse", CharSequence.class);
  8099. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.Instant", "parse", CharSequence.class);
  8100. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.LocalDate", "parse", CharSequence.class);
  8101. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.LocalDateTime", "parse", CharSequence.class);
  8102. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.LocalTime", "parse", CharSequence.class);
  8103. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.MonthDay", "parse", CharSequence.class);
  8104. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.OffsetDateTime", "parse", CharSequence.class);
  8105. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.OffsetTime", "parse", CharSequence.class);
  8106. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.Period", "parse", CharSequence.class);
  8107. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.Year", "parse", CharSequence.class);
  8108. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.YearMonth", "parse", CharSequence.class);
  8109. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.ZonedDateTime", "parse", CharSequence.class);
  8110. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.ZoneId", "of", String.class);
  8111. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.time.ZoneOffset", "of", String.class);
  8112. BuiltIn.registerIfAvailable(converterRegistry, tracer, "java.nio.file.Path", "java.nio.file.Paths", "get", String.class, String[].class);
  8113. }
  8114. private ParserSpec config() { return commandSpec.parser(); }
  8115. /**
  8116. * Entry point into parsing command line arguments.
  8117. * @param args the command line arguments
  8118. * @return a list with all commands and subcommands initialized by this method
  8119. * @throws ParameterException if the specified command line arguments are invalid
  8120. */
  8121. List<CommandLine> parse(String... args) {
  8122. Assert.notNull(args, "argument array");
  8123. if (tracer.isInfo()) {tracer.info("Picocli version: %s%n", versionString());}
  8124. if (tracer.isInfo()) {tracer.info("Parsing %d command line args %s%n", args.length, Arrays.toString(args));}
  8125. if (tracer.isDebug()){tracer.debug("Parser configuration: %s%n", config());}
  8126. if (tracer.isDebug()){tracer.debug("(ANSI is %s by default: isatty=%s, XTERM=%s, OSTYPE=%s, isWindows=%s, JansiConsoleInstalled=%s, ANSICON=%s, ConEmuANSI=%s, NO_COLOR=%s, CLICOLOR=%s, CLICOLOR_FORCE=%s)%n",
  8127. Help.Ansi.ansiPossible() ? "enabled" : "disabled", Help.Ansi.isTTY(), System.getenv("XTERM"), System.getenv("OSTYPE"), Help.Ansi.isWindows(), Help.Ansi.isJansiConsoleInstalled(), System.getenv("ANSICON"), System.getenv("ConEmuANSI"), System.getenv("NO_COLOR"), System.getenv("CLICOLOR"), System.getenv("CLICOLOR_FORCE"));}
  8128. List<String> expanded = new ArrayList<String>();
  8129. for (String arg : args) { addOrExpand(arg, expanded, new LinkedHashSet<String>()); }
  8130. Stack<String> arguments = new Stack<String>();
  8131. arguments.addAll(reverseList(expanded));
  8132. List<CommandLine> result = new ArrayList<CommandLine>();
  8133. parse(result, arguments, args, new ArrayList<Object>());
  8134. return result;
  8135. }
  8136. private void addOrExpand(String arg, List<String> arguments, Set<String> visited) {
  8137. if (config().expandAtFiles() && !arg.equals("@") && arg.startsWith("@")) {
  8138. arg = arg.substring(1);
  8139. if (arg.startsWith("@")) {
  8140. if (tracer.isInfo()) { tracer.info("Not expanding @-escaped argument %s (trimmed leading '@' char)%n", arg); }
  8141. } else {
  8142. if (tracer.isInfo()) { tracer.info("Expanding argument file @%s%n", arg); }
  8143. expandArgumentFile(arg, arguments, visited);
  8144. return;
  8145. }
  8146. }
  8147. arguments.add(arg);
  8148. }
  8149. private void expandArgumentFile(String fileName, List<String> arguments, Set<String> visited) {
  8150. File file = new File(fileName);
  8151. if (!file.canRead()) {
  8152. if (tracer.isInfo()) {tracer.info("File %s does not exist or cannot be read; treating argument literally%n", fileName);}
  8153. arguments.add("@" + fileName);
  8154. } else if (visited.contains(file.getAbsolutePath())) {
  8155. if (tracer.isInfo()) {tracer.info("Already visited file %s; ignoring...%n", file.getAbsolutePath());}
  8156. } else {
  8157. expandValidArgumentFile(fileName, file, arguments, visited);
  8158. }
  8159. }
  8160. private void expandValidArgumentFile(String fileName, File file, List<String> arguments, Set<String> visited) {
  8161. List<String> result = new ArrayList<String>();
  8162. LineNumberReader reader = null;
  8163. try {
  8164. visited.add(file.getAbsolutePath());
  8165. reader = new LineNumberReader(new FileReader(file));
  8166. if (commandSpec.parser().useSimplifiedAtFiles()) {
  8167. String token;
  8168. while ((token = reader.readLine()) != null) {
  8169. if (token.length() > 0 && !token.trim().startsWith(String.valueOf(commandSpec.parser().atFileCommentChar()))) {
  8170. addOrExpand(token, result, visited);
  8171. }
  8172. }
  8173. } else {
  8174. StreamTokenizer tok = new StreamTokenizer(reader);
  8175. tok.resetSyntax();
  8176. tok.wordChars(' ', 255);
  8177. tok.whitespaceChars(0, ' ');
  8178. tok.quoteChar('"');
  8179. tok.quoteChar('\'');
  8180. if (commandSpec.parser().atFileCommentChar() != null) {
  8181. tok.commentChar(commandSpec.parser().atFileCommentChar());
  8182. }
  8183. while (tok.nextToken() != StreamTokenizer.TT_EOF) {
  8184. addOrExpand(tok.sval, result, visited);
  8185. }
  8186. }
  8187. } catch (Exception ex) {
  8188. throw new InitializationException("Could not read argument file @" + fileName, ex);
  8189. } finally {
  8190. if (reader != null) { try {reader.close();} catch (Exception ignored) {} }
  8191. }
  8192. if (tracer.isInfo()) {tracer.info("Expanded file @%s to arguments %s%n", fileName, result);}
  8193. arguments.addAll(result);
  8194. }
  8195. private void clear() {
  8196. position = 0;
  8197. endOfOptions = false;
  8198. isHelpRequested = false;
  8199. parseResultBuilder = ParseResult.builder(getCommandSpec());
  8200. for (OptionSpec option : getCommandSpec().options()) { clear(option); }
  8201. for (PositionalParamSpec positional : getCommandSpec().positionalParameters()) { clear(positional); }
  8202. }
  8203. private void clear(ArgSpec argSpec) {
  8204. argSpec.resetStringValues();
  8205. argSpec.resetOriginalStringValues();
  8206. argSpec.typedValues.clear();
  8207. argSpec.typedValueAtPosition.clear();
  8208. if (argSpec.group() == null) { argSpec.applyInitialValue(tracer); } // groups do their own initialization
  8209. }
  8210. private void maybeThrow(PicocliException ex) throws PicocliException {
  8211. if (commandSpec.parser().collectErrors) {
  8212. parseResultBuilder.addError(ex);
  8213. } else {
  8214. throw ex;
  8215. }
  8216. }
  8217. private void parse(List<CommandLine> parsedCommands, Stack<String> argumentStack, String[] originalArgs, List<Object> nowProcessing) {
  8218. clear(); // first reset any state in case this CommandLine instance is being reused
  8219. if (tracer.isDebug()) {
  8220. tracer.debug("Initializing %s: %d options, %d positional parameters, %d required, %d groups, %d subcommands.%n",
  8221. commandSpec.toString(), new HashSet<ArgSpec>(commandSpec.optionsMap().values()).size(),
  8222. commandSpec.positionalParameters().size(), commandSpec.requiredArgs().size(),
  8223. commandSpec.argGroups().size(), commandSpec.subcommands().size());
  8224. }
  8225. parsedCommands.add(CommandLine.this);
  8226. List<ArgSpec> required = new ArrayList<ArgSpec>(commandSpec.requiredArgs());
  8227. Set<ArgSpec> initialized = new LinkedHashSet<ArgSpec>();
  8228. Collections.sort(required, new PositionalParametersSorter());
  8229. boolean continueOnError = commandSpec.parser().collectErrors();
  8230. do {
  8231. int stackSize = argumentStack.size();
  8232. try {
  8233. applyDefaultValues(required);
  8234. processArguments(parsedCommands, argumentStack, required, initialized, originalArgs, nowProcessing);
  8235. } catch (ParameterException ex) {
  8236. maybeThrow(ex);
  8237. } catch (Exception ex) {
  8238. int offendingArgIndex = originalArgs.length - argumentStack.size() - 1;
  8239. String arg = offendingArgIndex >= 0 && offendingArgIndex < originalArgs.length ? originalArgs[offendingArgIndex] : "?";
  8240. maybeThrow(ParameterException.create(CommandLine.this, ex, arg, offendingArgIndex, originalArgs));
  8241. }
  8242. if (continueOnError && stackSize == argumentStack.size() && stackSize > 0) {
  8243. parseResultBuilder.unmatched.add(argumentStack.pop());
  8244. }
  8245. } while (!argumentStack.isEmpty() && continueOnError);
  8246. validateConstraints(argumentStack, required, initialized);
  8247. }
  8248. private void validateConstraints(Stack<String> argumentStack, List<ArgSpec> required, Set<ArgSpec> matched) {
  8249. if (!isAnyHelpRequested() && !required.isEmpty()) {
  8250. for (ArgSpec missing : required) {
  8251. Assert.assertTrue(missing.group() == null, "Arguments in a group are not necessarily required for the command");
  8252. if (missing.isOption()) {
  8253. maybeThrow(MissingParameterException.create(CommandLine.this, required, config().separator()));
  8254. } else {
  8255. assertNoMissingParameters(missing, missing.arity(), argumentStack);
  8256. }
  8257. }
  8258. }
  8259. if (!parseResultBuilder.unmatched.isEmpty()) {
  8260. String[] unmatched = parseResultBuilder.unmatched.toArray(new String[0]);
  8261. for (UnmatchedArgsBinding unmatchedArgsBinding : getCommandSpec().unmatchedArgsBindings()) {
  8262. unmatchedArgsBinding.addAll(unmatched.clone());
  8263. }
  8264. if (!isUnmatchedArgumentsAllowed()) { maybeThrow(new UnmatchedArgumentException(CommandLine.this, Collections.unmodifiableList(parseResultBuilder.unmatched))); }
  8265. if (tracer.isInfo()) { tracer.info("Unmatched arguments: %s%n", parseResultBuilder.unmatched); }
  8266. }
  8267. for (ArgGroupSpec group : commandSpec.argGroups()) {
  8268. group.clearValidationResult();
  8269. }
  8270. ParseResult pr = parseResultBuilder.build();
  8271. for (ArgGroupSpec group : commandSpec.argGroups()) {
  8272. group.validateConstraints(pr);
  8273. }
  8274. List<ParseResult.MatchedGroupMultiple> matchedGroupMultiples = pr.getMatchedGroupMultiples();
  8275. if (matchedGroupMultiples.size() > 1) {
  8276. failGroupMultiplicityExceeded(matchedGroupMultiples);
  8277. }
  8278. }
  8279. private void failGroupMultiplicityExceeded(List<ParseResult.MatchedGroupMultiple> matchedGroupMultiples) {
  8280. Map<ArgGroupSpec, List<List<ParseResult.MatchedGroupMultiple>>> multiplesPerGroup = new IdentityHashMap<ArgGroupSpec, List<List<ParseResult.MatchedGroupMultiple>>>();
  8281. String msg = "";
  8282. for (ParseResult.MatchedGroupMultiple multiple : matchedGroupMultiples) {
  8283. if (msg.length() > 0) { msg += " and "; }
  8284. msg += multiple.toString();
  8285. Map<ArgGroupSpec, MatchedGroup> subgroups = multiple.matchedSubgroups();
  8286. for (ArgGroupSpec group : subgroups.keySet()) {
  8287. addValueToListInMap(multiplesPerGroup, group, subgroups.get(group).multiples());
  8288. }
  8289. }
  8290. if (!simplifyErrorMessageForSingleGroup(multiplesPerGroup)) {
  8291. maybeThrow(new MaxValuesExceededException(CommandLine.this, "Error: expected only one match but got " + msg));
  8292. }
  8293. }
  8294. private boolean simplifyErrorMessageForSingleGroup(Map<ArgGroupSpec, List<List<ParseResult.MatchedGroupMultiple>>> multiplesPerGroup) {
  8295. if (multiplesPerGroup.size() == 1) { // all multiples were matches for a single group
  8296. ArgGroupSpec group = multiplesPerGroup.keySet().iterator().next();
  8297. List<ParseResult.MatchedGroupMultiple> flat = flatList(multiplesPerGroup.get(group));
  8298. for (ParseResult.MatchedGroupMultiple multiple : flat) {
  8299. if (!multiple.matchedSubgroups().isEmpty()) { return false; }
  8300. }
  8301. group.validationException = null;
  8302. group.validateMultiples(CommandLine.this, flat);
  8303. if (group.validationException != null) {
  8304. maybeThrow(group.validationException);
  8305. return true;
  8306. }
  8307. }
  8308. return false;
  8309. }
  8310. private void applyDefaultValues(List<ArgSpec> required) throws Exception {
  8311. parseResultBuilder.isInitializingDefaultValues = true;
  8312. for (ArgSpec arg : commandSpec.args()) {
  8313. if (arg.group() == null) {
  8314. if (applyDefault(commandSpec.defaultValueProvider(), arg)) { required.remove(arg); }
  8315. }
  8316. }
  8317. parseResultBuilder.isInitializingDefaultValues = false;
  8318. }
  8319. private boolean applyDefault(IDefaultValueProvider defaultValueProvider, ArgSpec arg) throws Exception {
  8320. // Default value provider return value is only used if provider exists and if value
  8321. // is not null otherwise the original default or initial value are used
  8322. String fromProvider = defaultValueProvider == null ? null : defaultValueProvider.defaultValue(arg);
  8323. String defaultValue = fromProvider == null ? arg.defaultValue() : fromProvider;
  8324. if (defaultValue != null) {
  8325. if (tracer.isDebug()) {tracer.debug("Applying defaultValue (%s) to %s%n", defaultValue, arg);}
  8326. Range arity = arg.arity().min(Math.max(1, arg.arity().min));
  8327. applyOption(arg, LookBehind.SEPARATE, arity, stack(defaultValue), new HashSet<ArgSpec>(), arg.toString);
  8328. }
  8329. return defaultValue != null;
  8330. }
  8331. private Stack<String> stack(String value) {Stack<String> result = new Stack<String>(); result.push(value); return result;}
  8332. private void processArguments(List<CommandLine> parsedCommands,
  8333. Stack<String> args,
  8334. Collection<ArgSpec> required,
  8335. Set<ArgSpec> initialized,
  8336. String[] originalArgs,
  8337. List<Object> nowProcessing) throws Exception {
  8338. // arg must be one of:
  8339. // 1. the "--" double dash separating options from positional arguments
  8340. // 1. a stand-alone flag, like "-v" or "--verbose": no value required, must map to boolean or Boolean field
  8341. // 2. a short option followed by an argument, like "-f file" or "-ffile": may map to any type of field
  8342. // 3. a long option followed by an argument, like "-file out.txt" or "-file=out.txt"
  8343. // 3. one or more remaining arguments without any associated options. Must be the last in the list.
  8344. // 4. a combination of stand-alone options, like "-vxr". Equivalent to "-v -x -r", "-v true -x true -r true"
  8345. // 5. a combination of stand-alone options and one option with an argument, like "-vxrffile"
  8346. parseResultBuilder.originalArgs(originalArgs);
  8347. parseResultBuilder.nowProcessing = nowProcessing;
  8348. String separator = config().separator();
  8349. while (!args.isEmpty()) {
  8350. if (endOfOptions) {
  8351. processRemainderAsPositionalParameters(required, initialized, args);
  8352. return;
  8353. }
  8354. String arg = args.pop();
  8355. if (tracer.isDebug()) {tracer.debug("Processing argument '%s'. Remainder=%s%n", arg, reverse(copy(args)));}
  8356. // Double-dash separates options from positional arguments.
  8357. // If found, then interpret the remaining args as positional parameters.
  8358. if (commandSpec.parser.endOfOptionsDelimiter().equals(arg)) {
  8359. tracer.info("Found end-of-options delimiter '--'. Treating remainder as positional parameters.%n");
  8360. endOfOptions = true;
  8361. processRemainderAsPositionalParameters(required, initialized, args);
  8362. return; // we are done
  8363. }
  8364. // if we find another command, we are done with the current command
  8365. if (commandSpec.subcommands().containsKey(arg)) {
  8366. CommandLine subcommand = commandSpec.subcommands().get(arg);
  8367. nowProcessing.add(subcommand.commandSpec);
  8368. updateHelpRequested(subcommand.commandSpec);
  8369. if (!isAnyHelpRequested() && !required.isEmpty()) { // ensure current command portion is valid
  8370. throw MissingParameterException.create(CommandLine.this, required, separator);
  8371. }
  8372. if (tracer.isDebug()) {tracer.debug("Found subcommand '%s' (%s)%n", arg, subcommand.commandSpec.toString());}
  8373. subcommand.interpreter.parse(parsedCommands, args, originalArgs, nowProcessing);
  8374. parseResultBuilder.subcommand(subcommand.interpreter.parseResultBuilder.build());
  8375. return; // remainder done by the command
  8376. }
  8377. // First try to interpret the argument as a single option (as opposed to a compact group of options).
  8378. // A single option may be without option parameters, like "-v" or "--verbose" (a boolean value),
  8379. // or an option may have one or more option parameters.
  8380. // A parameter may be attached to the option.
  8381. boolean paramAttachedToOption = false;
  8382. int separatorIndex = arg.indexOf(separator);
  8383. if (separatorIndex > 0) {
  8384. String key = arg.substring(0, separatorIndex);
  8385. // be greedy. Consume the whole arg as an option if possible.
  8386. if (commandSpec.optionsMap().containsKey(key) && commandSpec.optionsMap().containsKey(arg)) {
  8387. tracer.warn("Both '%s' and '%s' are valid option names in %s. Using '%s'...%n", arg, key, getCommandName(), arg);
  8388. } else if (commandSpec.optionsMap().containsKey(key)) {
  8389. paramAttachedToOption = true;
  8390. String optionParam = arg.substring(separatorIndex + separator.length());
  8391. args.push(optionParam);
  8392. arg = key;
  8393. if (tracer.isDebug()) {tracer.debug("Separated '%s' option from '%s' option parameter%n", key, optionParam);}
  8394. } else {
  8395. if (tracer.isDebug()) {tracer.debug("'%s' contains separator '%s' but '%s' is not a known option%n", arg, separator, key);}
  8396. }
  8397. } else {
  8398. if (tracer.isDebug()) {tracer.debug("'%s' cannot be separated into <option>%s<option-parameter>%n", arg, separator);}
  8399. }
  8400. if (isStandaloneOption(arg)) {
  8401. processStandaloneOption(required, initialized, arg, args, paramAttachedToOption);
  8402. }
  8403. // Compact (single-letter) options can be grouped with other options or with an argument.
  8404. // only single-letter options can be combined with other options or with an argument
  8405. else if (config().posixClusteredShortOptionsAllowed() && arg.length() > 2 && arg.startsWith("-")) {
  8406. if (tracer.isDebug()) {tracer.debug("Trying to process '%s' as clustered short options%n", arg, args);}
  8407. processClusteredShortOptions(required, initialized, arg, args);
  8408. }
  8409. // The argument could not be interpreted as an option: process it as a positional argument
  8410. else {
  8411. args.push(arg);
  8412. if (tracer.isDebug()) {tracer.debug("Could not find option '%s', deciding whether to treat as unmatched option or positional parameter...%n", arg);}
  8413. if (commandSpec.resemblesOption(arg, tracer)) { handleUnmatchedArgument(args); continue; } // #149
  8414. if (tracer.isDebug()) {tracer.debug("No option named '%s' found. Processing as positional parameter%n", arg);}
  8415. processPositionalParameter(required, initialized, args);
  8416. }
  8417. }
  8418. }
  8419. private boolean isStandaloneOption(String arg) {
  8420. return commandSpec.optionsMap().containsKey(arg);
  8421. }
  8422. private void handleUnmatchedArgument(Stack<String> args) throws Exception {
  8423. if (!args.isEmpty()) { handleUnmatchedArgument(args.pop()); }
  8424. if (config().stopAtUnmatched()) {
  8425. // addAll would give args in reverse order
  8426. while (!args.isEmpty()) { handleUnmatchedArgument(args.pop()); }
  8427. }
  8428. }
  8429. private void handleUnmatchedArgument(String arg) {
  8430. parseResultBuilder.unmatched.add(arg);
  8431. }
  8432. private void processRemainderAsPositionalParameters(Collection<ArgSpec> required, Set<ArgSpec> initialized, Stack<String> args) throws Exception {
  8433. while (!args.empty()) {
  8434. processPositionalParameter(required, initialized, args);
  8435. }
  8436. }
  8437. private void processPositionalParameter(Collection<ArgSpec> required, Set<ArgSpec> initialized, Stack<String> args) throws Exception {
  8438. if (tracer.isDebug()) {tracer.debug("Processing next arg as a positional parameter. Command-local position=%d. Remainder=%s%n", position, reverse(copy(args)));}
  8439. if (config().stopAtPositional()) {
  8440. if (!endOfOptions && tracer.isDebug()) {tracer.debug("Parser was configured with stopAtPositional=true, treating remaining arguments as positional parameters.%n");}
  8441. endOfOptions = true;
  8442. }
  8443. int consumedByGroup = 0;
  8444. int argsConsumed = 0;
  8445. int interactiveConsumed = 0;
  8446. int originalNowProcessingSize = parseResultBuilder.nowProcessing.size();
  8447. Map<PositionalParamSpec, Integer> newPositions = new IdentityHashMap<PositionalParamSpec, Integer>();
  8448. for (PositionalParamSpec positionalParam : commandSpec.positionalParameters()) {
  8449. Range indexRange = positionalParam.index();
  8450. int localPosition = getPosition(positionalParam);
  8451. if (positionalParam.group() != null) { // does the positionalParam's index range contain the current position in the currently matching group
  8452. MatchedGroup matchedGroup = parseResultBuilder.matchedGroup.findOrCreateMatchingGroup(positionalParam, commandSpec.commandLine());
  8453. if (!indexRange.contains(localPosition) || (matchedGroup != null && matchedGroup.multiple().hasMatchedValueAtPosition(positionalParam, localPosition))) {
  8454. continue;
  8455. }
  8456. } else {
  8457. if (!indexRange.contains(localPosition) || positionalParam.typedValueAtPosition.get(localPosition) != null) {
  8458. continue;
  8459. }
  8460. }
  8461. Stack<String> argsCopy = copy(args);
  8462. Range arity = positionalParam.arity();
  8463. if (tracer.isDebug()) {tracer.debug("Position %s is in index range %s. Trying to assign args to %s, arity=%s%n", positionDesc(positionalParam), indexRange, positionalParam, arity);}
  8464. if (!assertNoMissingParameters(positionalParam, arity, argsCopy)) { break; } // #389 collectErrors parsing
  8465. int originalSize = argsCopy.size();
  8466. int actuallyConsumed = applyOption(positionalParam, LookBehind.SEPARATE, arity, argsCopy, initialized, "args[" + indexRange + "] at position " + localPosition);
  8467. int count = originalSize - argsCopy.size();
  8468. if (count > 0 || actuallyConsumed > 0) {
  8469. required.remove(positionalParam);
  8470. if (positionalParam.interactive()) { interactiveConsumed++; }
  8471. }
  8472. if (positionalParam.group() == null) { // don't update the command-level position for group args
  8473. argsConsumed = Math.max(argsConsumed, count);
  8474. } else {
  8475. newPositions.put(positionalParam, localPosition + count);
  8476. consumedByGroup = Math.max(consumedByGroup, count);
  8477. }
  8478. while (parseResultBuilder.nowProcessing.size() > originalNowProcessingSize + count) {
  8479. parseResultBuilder.nowProcessing.remove(parseResultBuilder.nowProcessing.size() - 1);
  8480. }
  8481. }
  8482. // remove processed args from the stack
  8483. int maxConsumed = Math.max(consumedByGroup, argsConsumed);
  8484. for (int i = 0; i < maxConsumed; i++) { args.pop(); }
  8485. position += argsConsumed + interactiveConsumed;
  8486. if (tracer.isDebug()) {tracer.debug("Consumed %d arguments and %d interactive values, moving command-local position to index %d.%n", argsConsumed, interactiveConsumed, position);}
  8487. for (PositionalParamSpec positional : newPositions.keySet()) {
  8488. MatchedGroup inProgress = parseResultBuilder.matchedGroup.findOrCreateMatchingGroup(positional, commandSpec.commandLine());
  8489. if (inProgress != null) {
  8490. inProgress.multiple().position = newPositions.get(positional);
  8491. if (tracer.isDebug()) {tracer.debug("Updated group position to %s for group %s.%n", inProgress.multiple().position, inProgress);}
  8492. }
  8493. }
  8494. if (consumedByGroup == 0 && argsConsumed == 0 && interactiveConsumed == 0 && !args.isEmpty()) {
  8495. handleUnmatchedArgument(args);
  8496. }
  8497. }
  8498. private void processStandaloneOption(Collection<ArgSpec> required,
  8499. Set<ArgSpec> initialized,
  8500. String arg,
  8501. Stack<String> args,
  8502. boolean paramAttachedToKey) throws Exception {
  8503. ArgSpec argSpec = commandSpec.optionsMap().get(arg);
  8504. required.remove(argSpec);
  8505. Range arity = argSpec.arity();
  8506. if (paramAttachedToKey) {
  8507. arity = arity.min(Math.max(1, arity.min)); // if key=value, minimum arity is at least 1
  8508. }
  8509. LookBehind lookBehind = paramAttachedToKey ? LookBehind.ATTACHED_WITH_SEPARATOR : LookBehind.SEPARATE;
  8510. if (tracer.isDebug()) {tracer.debug("Found option named '%s': %s, arity=%s%n", arg, argSpec, arity);}
  8511. parseResultBuilder.nowProcessing.add(argSpec);
  8512. applyOption(argSpec, lookBehind, arity, args, initialized, "option " + arg);
  8513. }
  8514. private void processClusteredShortOptions(Collection<ArgSpec> required,
  8515. Set<ArgSpec> initialized,
  8516. String arg,
  8517. Stack<String> args) throws Exception {
  8518. String prefix = arg.substring(0, 1);
  8519. String cluster = arg.substring(1);
  8520. boolean paramAttachedToOption = true;
  8521. boolean first = true;
  8522. do {
  8523. if (cluster.length() > 0 && commandSpec.posixOptionsMap().containsKey(cluster.charAt(0))) {
  8524. ArgSpec argSpec = commandSpec.posixOptionsMap().get(cluster.charAt(0));
  8525. Range arity = argSpec.arity();
  8526. String argDescription = "option " + prefix + cluster.charAt(0);
  8527. if (tracer.isDebug()) {tracer.debug("Found option '%s%s' in %s: %s, arity=%s%n", prefix, cluster.charAt(0), arg,
  8528. argSpec, arity);}
  8529. required.remove(argSpec);
  8530. cluster = cluster.substring(1);
  8531. paramAttachedToOption = cluster.length() > 0;
  8532. LookBehind lookBehind = paramAttachedToOption ? LookBehind.ATTACHED : LookBehind.SEPARATE;
  8533. if (cluster.startsWith(config().separator())) {// attached with separator, like -f=FILE or -v=true
  8534. lookBehind = LookBehind.ATTACHED_WITH_SEPARATOR;
  8535. cluster = cluster.substring(config().separator().length());
  8536. arity = arity.min(Math.max(1, arity.min)); // if key=value, minimum arity is at least 1
  8537. }
  8538. if (arity.min > 0 && !empty(cluster)) {
  8539. if (tracer.isDebug()) {tracer.debug("Trying to process '%s' as option parameter%n", cluster);}
  8540. }
  8541. // arity may be >= 1, or
  8542. // arity <= 0 && !cluster.startsWith(separator)
  8543. // e.g., boolean @Option("-v", arity=0, varargs=true); arg "-rvTRUE", remainder cluster="TRUE"
  8544. if (!empty(cluster)) {
  8545. args.push(cluster); // interpret remainder as option parameter (CAUTION: may be empty string!)
  8546. }
  8547. if (first) {
  8548. parseResultBuilder.nowProcessing.add(argSpec);
  8549. first = false;
  8550. } else {
  8551. parseResultBuilder.nowProcessing.set(parseResultBuilder.nowProcessing.size() - 1, argSpec); // replace
  8552. }
  8553. int argCount = args.size();
  8554. int consumed = applyOption(argSpec, lookBehind, arity, args, initialized, argDescription);
  8555. // if cluster was consumed as a parameter or if this field was the last in the cluster we're done; otherwise continue do-while loop
  8556. if (empty(cluster) || args.isEmpty() || args.size() < argCount) {
  8557. return;
  8558. }
  8559. cluster = args.pop();
  8560. } else { // cluster is empty || cluster.charAt(0) is not a short option key
  8561. if (cluster.length() == 0) { // we finished parsing a group of short options like -rxv
  8562. return; // return normally and parse the next arg
  8563. }
  8564. // We get here when the remainder of the cluster group is neither an option,
  8565. // nor a parameter that the last option could consume.
  8566. if (arg.endsWith(cluster)) {
  8567. args.push(paramAttachedToOption ? prefix + cluster : cluster);
  8568. if (args.peek().equals(arg)) { // #149 be consistent between unmatched short and long options
  8569. if (tracer.isDebug()) {tracer.debug("Could not match any short options in %s, deciding whether to treat as unmatched option or positional parameter...%n", arg);}
  8570. if (commandSpec.resemblesOption(arg, tracer)) { handleUnmatchedArgument(args); return; } // #149
  8571. processPositionalParameter(required, initialized, args);
  8572. return;
  8573. }
  8574. // remainder was part of a clustered group that could not be completely parsed
  8575. if (tracer.isDebug()) {tracer.debug("No option found for %s in %s%n", cluster, arg);}
  8576. String tmp = args.pop();
  8577. tmp = tmp + " (while processing option: '" + arg + "')";
  8578. args.push(tmp);
  8579. handleUnmatchedArgument(args);
  8580. } else {
  8581. args.push(cluster);
  8582. if (tracer.isDebug()) {tracer.debug("%s is not an option parameter for %s%n", cluster, arg);}
  8583. processPositionalParameter(required, initialized, args);
  8584. }
  8585. return;
  8586. }
  8587. } while (true);
  8588. }
  8589. private int applyOption(ArgSpec argSpec,
  8590. LookBehind lookBehind,
  8591. Range arity,
  8592. Stack<String> args,
  8593. Set<ArgSpec> initialized,
  8594. String argDescription) throws Exception {
  8595. updateHelpRequested(argSpec);
  8596. boolean consumeOnlyOne = commandSpec.parser().aritySatisfiedByAttachedOptionParam() && lookBehind.isAttached();
  8597. Stack<String> workingStack = args;
  8598. if (consumeOnlyOne) {
  8599. workingStack = args.isEmpty() ? args : stack(args.pop());
  8600. } else {
  8601. if (!assertNoMissingParameters(argSpec, arity, args)) { return 0; } // #389 collectErrors parsing
  8602. }
  8603. if (argSpec.interactive()) {
  8604. String name = argSpec.isOption() ? ((OptionSpec) argSpec).longestName() : "position " + position;
  8605. String prompt = String.format("Enter value for %s (%s): ", name, str(argSpec.renderedDescription(), 0));
  8606. if (tracer.isDebug()) {tracer.debug("Reading value for %s from console...%n", name);}
  8607. char[] value = readPassword(prompt);
  8608. if (tracer.isDebug()) {tracer.debug("User entered '%s' for %s.%n", value, name);}
  8609. workingStack.push(new String(value));
  8610. }
  8611. parseResultBuilder.beforeMatchingGroupElement(argSpec);
  8612. int result;
  8613. if (argSpec.type().isArray()) {
  8614. result = applyValuesToArrayField(argSpec, lookBehind, arity, workingStack, initialized, argDescription);
  8615. } else if (Collection.class.isAssignableFrom(argSpec.type())) {
  8616. result = applyValuesToCollectionField(argSpec, lookBehind, arity, workingStack, initialized, argDescription);
  8617. } else if (Map.class.isAssignableFrom(argSpec.type())) {
  8618. result = applyValuesToMapField(argSpec, lookBehind, arity, workingStack, initialized, argDescription);
  8619. } else {
  8620. result = applyValueToSingleValuedField(argSpec, lookBehind, arity, workingStack, initialized, argDescription);
  8621. }
  8622. if (workingStack != args && !workingStack.isEmpty()) {
  8623. args.push(workingStack.pop());
  8624. Assert.assertTrue(workingStack.isEmpty(), "Working stack should be empty but was " + new ArrayList<String>(workingStack));
  8625. }
  8626. return result;
  8627. }
  8628. private int applyValueToSingleValuedField(ArgSpec argSpec,
  8629. LookBehind lookBehind,
  8630. Range derivedArity,
  8631. Stack<String> args,
  8632. Set<ArgSpec> initialized,
  8633. String argDescription) throws Exception {
  8634. boolean noMoreValues = args.isEmpty();
  8635. String value = args.isEmpty() ? null : trim(args.pop()); // unquote the value
  8636. Range arity = argSpec.arity().isUnspecified ? derivedArity : argSpec.arity(); // #509
  8637. if (arity.max == 0 && !arity.isUnspecified && lookBehind == LookBehind.ATTACHED_WITH_SEPARATOR) { // #509
  8638. throw new MaxValuesExceededException(CommandLine.this, optionDescription("", argSpec, 0) +
  8639. " should be specified without '" + value + "' parameter");
  8640. }
  8641. int result = arity.min; // the number or args we need to consume
  8642. Class<?> cls = argSpec.auxiliaryTypes()[0]; // field may be interface/abstract type, use annotation to get concrete type
  8643. if (arity.min <= 0) { // value may be optional
  8644. // special logic for booleans: BooleanConverter accepts only "true" or "false".
  8645. if (cls == Boolean.class || cls == Boolean.TYPE) {
  8646. // boolean option with arity = 0..1 or 0..*: value MAY be a param
  8647. if (arity.max > 0 && ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value))) {
  8648. result = 1; // if it is a varargs we only consume 1 argument if it is a boolean value
  8649. if (!lookBehind.isAttached()) { parseResultBuilder.nowProcessing(argSpec, value); }
  8650. } else if (lookBehind != LookBehind.ATTACHED_WITH_SEPARATOR) { // if attached, try converting the value to boolean (and fail if invalid value)
  8651. // it's okay to ignore value if not attached to option
  8652. if (value != null) {
  8653. args.push(value); // we don't consume the value
  8654. }
  8655. if (commandSpec.parser().toggleBooleanFlags()) {
  8656. Boolean currentValue = (Boolean) argSpec.getValue();
  8657. value = String.valueOf(currentValue == null || !currentValue); // #147 toggle existing boolean value
  8658. } else {
  8659. value = "true";
  8660. }
  8661. }
  8662. } else { // non-boolean option with optional value #325, #279
  8663. if (isOption(value)) {
  8664. args.push(value); // we don't consume the value
  8665. value = "";
  8666. } else if (value == null) {
  8667. value = "";
  8668. } else {
  8669. if (!lookBehind.isAttached()) { parseResultBuilder.nowProcessing(argSpec, value); }
  8670. }
  8671. }
  8672. } else {
  8673. if (!lookBehind.isAttached()) { parseResultBuilder.nowProcessing(argSpec, value); }
  8674. }
  8675. if (noMoreValues && value == null) {
  8676. return 0;
  8677. }
  8678. ITypeConverter<?> converter = getTypeConverter(cls, argSpec, 0);
  8679. Object newValue = tryConvert(argSpec, -1, converter, value, cls);
  8680. Object oldValue = argSpec.getValue();
  8681. String traceMessage = "Setting %s to '%3$s' (was '%2$s') for %4$s%n";
  8682. if (argSpec.group() == null && initialized.contains(argSpec)) {
  8683. if (!isOverwrittenOptionsAllowed()) {
  8684. throw new OverwrittenOptionException(CommandLine.this, argSpec, optionDescription("", argSpec, 0) + " should be specified only once");
  8685. }
  8686. traceMessage = "Overwriting %s value '%s' with '%s' for %s%n";
  8687. }
  8688. initialized.add(argSpec);
  8689. if (tracer.isInfo()) { tracer.info(traceMessage, argSpec.toString(), String.valueOf(oldValue), String.valueOf(newValue), argDescription); }
  8690. int pos = getPosition(argSpec);
  8691. argSpec.setValue(newValue);
  8692. parseResultBuilder.addOriginalStringValue(argSpec, value);// #279 track empty string value if no command line argument was consumed
  8693. parseResultBuilder.addStringValue(argSpec, value);
  8694. parseResultBuilder.addTypedValues(argSpec, pos, newValue);
  8695. parseResultBuilder.add(argSpec, pos);
  8696. return result;
  8697. }
  8698. private int applyValuesToMapField(ArgSpec argSpec,
  8699. LookBehind lookBehind,
  8700. Range arity,
  8701. Stack<String> args,
  8702. Set<ArgSpec> initialized,
  8703. String argDescription) throws Exception {
  8704. Class<?>[] classes = argSpec.auxiliaryTypes();
  8705. if (classes.length < 2) { throw new ParameterException(CommandLine.this, argSpec.toString() + " needs two types (one for the map key, one for the value) but only has " + classes.length + " types configured.",argSpec, null); }
  8706. ITypeConverter<?> keyConverter = getTypeConverter(classes[0], argSpec, 0);
  8707. ITypeConverter<?> valueConverter = getTypeConverter(classes[1], argSpec, 1);
  8708. @SuppressWarnings("unchecked") Map<Object, Object> map = (Map<Object, Object>) argSpec.getValue();
  8709. if (map == null || (!map.isEmpty() && !initialized.contains(argSpec))) {
  8710. tracer.debug("Initializing binding for %s with empty %s%n", optionDescription("", argSpec, 0), argSpec.type().getSimpleName());
  8711. map = createMap(argSpec.type()); // map class
  8712. argSpec.setValue(map);
  8713. }
  8714. initialized.add(argSpec);
  8715. int originalSize = map.size();
  8716. int pos = getPosition(argSpec);
  8717. consumeMapArguments(argSpec, lookBehind, arity, args, classes, keyConverter, valueConverter, map, argDescription);
  8718. parseResultBuilder.add(argSpec, pos);
  8719. argSpec.setValue(map);
  8720. return map.size() - originalSize;
  8721. }
  8722. private void consumeMapArguments(ArgSpec argSpec,
  8723. LookBehind lookBehind,
  8724. Range arity,
  8725. Stack<String> args,
  8726. Class<?>[] classes,
  8727. ITypeConverter<?> keyConverter,
  8728. ITypeConverter<?> valueConverter,
  8729. Map<Object, Object> result,
  8730. String argDescription) throws Exception {
  8731. // don't modify Interpreter.position: same position may be consumed by multiple ArgSpec objects
  8732. int currentPosition = getPosition(argSpec);
  8733. // first do the arity.min mandatory parameters
  8734. int initialSize = argSpec.stringValues().size();
  8735. int consumed = consumedCountMap(0, initialSize, argSpec);
  8736. for (int i = 0; consumed < arity.min && !args.isEmpty(); i++) {
  8737. Map<Object, Object> typedValuesAtPosition = new LinkedHashMap<Object, Object>();
  8738. parseResultBuilder.addTypedValues(argSpec, currentPosition++, typedValuesAtPosition);
  8739. assertNoMissingMandatoryParameter(argSpec, args, i, arity);
  8740. consumeOneMapArgument(argSpec, lookBehind, arity, consumed, args.pop(), classes, keyConverter, valueConverter, typedValuesAtPosition, i, argDescription);
  8741. result.putAll(typedValuesAtPosition);
  8742. consumed = consumedCountMap(i + 1, initialSize, argSpec);
  8743. lookBehind = LookBehind.SEPARATE;
  8744. }
  8745. // now process the varargs if any
  8746. for (int i = consumed; consumed < arity.max && !args.isEmpty(); i++) {
  8747. if (!varargCanConsumeNextValue(argSpec, args.peek())) { break; }
  8748. Map<Object, Object> typedValuesAtPosition = new LinkedHashMap<Object, Object>();
  8749. parseResultBuilder.addTypedValues(argSpec, currentPosition++, typedValuesAtPosition);
  8750. if (!canConsumeOneMapArgument(argSpec, arity, consumed, args.peek(), classes, keyConverter, valueConverter, argDescription)) {
  8751. break; // leave empty map at argSpec.typedValueAtPosition[currentPosition] so we won't try to consume that position again
  8752. }
  8753. consumeOneMapArgument(argSpec, lookBehind, arity, consumed, args.pop(), classes, keyConverter, valueConverter, typedValuesAtPosition, i, argDescription);
  8754. result.putAll(typedValuesAtPosition);
  8755. consumed = consumedCountMap(i + 1, initialSize, argSpec);
  8756. lookBehind = LookBehind.SEPARATE;
  8757. }
  8758. }
  8759. private void consumeOneMapArgument(ArgSpec argSpec,
  8760. LookBehind lookBehind,
  8761. Range arity, int consumed,
  8762. String arg,
  8763. Class<?>[] classes,
  8764. ITypeConverter<?> keyConverter, ITypeConverter<?> valueConverter,
  8765. Map<Object, Object> result,
  8766. int index,
  8767. String argDescription) throws Exception {
  8768. if (!lookBehind.isAttached()) { parseResultBuilder.nowProcessing(argSpec, arg); }
  8769. String raw = trim(arg);
  8770. String[] values = argSpec.splitValue(raw, commandSpec.parser(), arity, consumed);
  8771. for (String value : values) {
  8772. String[] keyValue = splitKeyValue(argSpec, value);
  8773. Object mapKey = tryConvert(argSpec, index, keyConverter, keyValue[0], classes[0]);
  8774. Object mapValue = tryConvert(argSpec, index, valueConverter, keyValue[1], classes[1]);
  8775. result.put(mapKey, mapValue);
  8776. if (tracer.isInfo()) { tracer.info("Putting [%s : %s] in %s<%s, %s> %s for %s%n", String.valueOf(mapKey), String.valueOf(mapValue),
  8777. result.getClass().getSimpleName(), classes[0].getSimpleName(), classes[1].getSimpleName(), argSpec.toString(), argDescription); }
  8778. parseResultBuilder.addStringValue(argSpec, keyValue[0]);
  8779. parseResultBuilder.addStringValue(argSpec, keyValue[1]);
  8780. }
  8781. parseResultBuilder.addOriginalStringValue(argSpec, raw);
  8782. }
  8783. private boolean canConsumeOneMapArgument(ArgSpec argSpec, Range arity, int consumed,
  8784. String raw, Class<?>[] classes,
  8785. ITypeConverter<?> keyConverter, ITypeConverter<?> valueConverter,
  8786. String argDescription) {
  8787. String[] values = argSpec.splitValue(raw, commandSpec.parser(), arity, consumed);
  8788. try {
  8789. for (String value : values) {
  8790. String[] keyValue = splitKeyValue(argSpec, value);
  8791. tryConvert(argSpec, -1, keyConverter, keyValue[0], classes[0]);
  8792. tryConvert(argSpec, -1, valueConverter, keyValue[1], classes[1]);
  8793. }
  8794. return true;
  8795. } catch (PicocliException ex) {
  8796. tracer.debug("$s cannot be assigned to %s: type conversion fails: %s.%n", raw, argDescription, ex.getMessage());
  8797. return false;
  8798. }
  8799. }
  8800. private String[] splitKeyValue(ArgSpec argSpec, String value) {
  8801. String[] keyValue = ArgSpec.splitRespectingQuotedStrings(value, 2, config(), argSpec, "=");
  8802. if (keyValue.length < 2) {
  8803. String splitRegex = argSpec.splitRegex();
  8804. if (splitRegex.length() == 0) {
  8805. throw new ParameterException(CommandLine.this, "Value for option " + optionDescription("",
  8806. argSpec, 0) + " should be in KEY=VALUE format but was " + value, argSpec, value);
  8807. } else {
  8808. throw new ParameterException(CommandLine.this, "Value for option " + optionDescription("",
  8809. argSpec, 0) + " should be in KEY=VALUE[" + splitRegex + "KEY=VALUE]... format but was " + value, argSpec, value);
  8810. }
  8811. }
  8812. return keyValue;
  8813. }
  8814. private void assertNoMissingMandatoryParameter(ArgSpec argSpec, Stack<String> args, int i, Range arity) {
  8815. if (!varargCanConsumeNextValue(argSpec, args.peek())) {
  8816. String desc = arity.min > 1 ? (i + 1) + " (of " + arity.min + " mandatory parameters) " : "";
  8817. throw new MissingParameterException(CommandLine.this, argSpec, "Expected parameter " + desc + "for " + optionDescription("", argSpec, -1) + " but found '" + args.peek() + "'");
  8818. }
  8819. }
  8820. private int applyValuesToArrayField(ArgSpec argSpec,
  8821. LookBehind lookBehind,
  8822. Range arity,
  8823. Stack<String> args,
  8824. Set<ArgSpec> initialized,
  8825. String argDescription) throws Exception {
  8826. Object existing = argSpec.getValue();
  8827. int length = existing == null ? 0 : Array.getLength(existing);
  8828. Class<?> type = argSpec.auxiliaryTypes()[0];
  8829. int pos = getPosition(argSpec);
  8830. List<Object> converted = consumeArguments(argSpec, lookBehind, arity, args, type, argDescription);
  8831. List<Object> newValues = new ArrayList<Object>();
  8832. if (initialized.contains(argSpec)) { // existing values are default values if initialized does NOT contain argsSpec
  8833. for (int i = 0; i < length; i++) {
  8834. newValues.add(Array.get(existing, i)); // keep non-default values
  8835. }
  8836. }
  8837. initialized.add(argSpec);
  8838. for (Object obj : converted) {
  8839. if (obj instanceof Collection<?>) {
  8840. newValues.addAll((Collection<?>) obj);
  8841. } else {
  8842. newValues.add(obj);
  8843. }
  8844. }
  8845. Object array = Array.newInstance(type, newValues.size());
  8846. for (int i = 0; i < newValues.size(); i++) {
  8847. Array.set(array, i, newValues.get(i));
  8848. }
  8849. argSpec.setValue(array);
  8850. parseResultBuilder.add(argSpec, pos);
  8851. return converted.size(); // return how many args were consumed
  8852. }
  8853. @SuppressWarnings("unchecked")
  8854. private int applyValuesToCollectionField(ArgSpec argSpec,
  8855. LookBehind lookBehind,
  8856. Range arity,
  8857. Stack<String> args,
  8858. Set<ArgSpec> initialized,
  8859. String argDescription) throws Exception {
  8860. Collection<Object> collection = (Collection<Object>) argSpec.getValue();
  8861. Class<?> type = argSpec.auxiliaryTypes()[0];
  8862. int pos = getPosition(argSpec);
  8863. List<Object> converted = consumeArguments(argSpec, lookBehind, arity, args, type, argDescription);
  8864. if (collection == null || (!collection.isEmpty() && !initialized.contains(argSpec))) {
  8865. tracer.debug("Initializing binding for %s with empty %s%n", optionDescription("", argSpec, 0), argSpec.type().getSimpleName());
  8866. collection = createCollection(argSpec.type(), type); // collection type, element type
  8867. argSpec.setValue(collection);
  8868. }
  8869. initialized.add(argSpec);
  8870. for (Object element : converted) {
  8871. if (element instanceof Collection<?>) {
  8872. collection.addAll((Collection<?>) element);
  8873. } else {
  8874. collection.add(element);
  8875. }
  8876. }
  8877. parseResultBuilder.add(argSpec, pos);
  8878. argSpec.setValue(collection);
  8879. return converted.size();
  8880. }
  8881. private List<Object> consumeArguments(ArgSpec argSpec,
  8882. LookBehind lookBehind,
  8883. Range arity,
  8884. Stack<String> args,
  8885. Class<?> type,
  8886. String argDescription) throws Exception {
  8887. List<Object> result = new ArrayList<Object>();
  8888. // don't modify Interpreter.position: same position may be consumed by multiple ArgSpec objects
  8889. int currentPosition = getPosition(argSpec);
  8890. // first do the arity.min mandatory parameters
  8891. int initialSize = argSpec.stringValues().size();
  8892. int consumed = consumedCount(0, initialSize, argSpec);
  8893. for (int i = 0; consumed < arity.min && !args.isEmpty(); i++) {
  8894. List<Object> typedValuesAtPosition = new ArrayList<Object>();
  8895. parseResultBuilder.addTypedValues(argSpec, currentPosition++, typedValuesAtPosition);
  8896. assertNoMissingMandatoryParameter(argSpec, args, i, arity);
  8897. consumeOneArgument(argSpec, lookBehind, arity, consumed, args.pop(), type, typedValuesAtPosition, i, argDescription);
  8898. result.addAll(typedValuesAtPosition);
  8899. consumed = consumedCount(i + 1, initialSize, argSpec);
  8900. lookBehind = LookBehind.SEPARATE;
  8901. }
  8902. // now process the varargs if any
  8903. for (int i = consumed; consumed < arity.max && !args.isEmpty(); i++) {
  8904. if (!varargCanConsumeNextValue(argSpec, args.peek())) { break; }
  8905. List<Object> typedValuesAtPosition = new ArrayList<Object>();
  8906. parseResultBuilder.addTypedValues(argSpec, currentPosition++, typedValuesAtPosition);
  8907. if (!canConsumeOneArgument(argSpec, arity, consumed, args.peek(), type, argDescription)) {
  8908. break; // leave empty list at argSpec.typedValueAtPosition[currentPosition] so we won't try to consume that position again
  8909. }
  8910. consumeOneArgument(argSpec, lookBehind, arity, consumed, args.pop(), type, typedValuesAtPosition, i, argDescription);
  8911. result.addAll(typedValuesAtPosition);
  8912. consumed = consumedCount(i + 1, initialSize, argSpec);
  8913. lookBehind = LookBehind.SEPARATE;
  8914. }
  8915. if (result.isEmpty() && arity.min == 0 && arity.max <= 1 && isBoolean(type)) {
  8916. return Arrays.asList((Object) Boolean.TRUE);
  8917. }
  8918. return result;
  8919. }
  8920. private int consumedCount(int i, int initialSize, ArgSpec arg) {
  8921. return commandSpec.parser().splitFirst() ? arg.stringValues().size() - initialSize : i;
  8922. }
  8923. private int consumedCountMap(int i, int initialSize, ArgSpec arg) {
  8924. return commandSpec.parser().splitFirst() ? (arg.stringValues().size() - initialSize) / 2 : i;
  8925. }
  8926. private int consumeOneArgument(ArgSpec argSpec,
  8927. LookBehind lookBehind,
  8928. Range arity,
  8929. int consumed,
  8930. String arg,
  8931. Class<?> type,
  8932. List<Object> result,
  8933. int index,
  8934. String argDescription) {
  8935. if (!lookBehind.isAttached()) { parseResultBuilder.nowProcessing(argSpec, arg); }
  8936. String raw = trim(arg);
  8937. String[] values = argSpec.splitValue(raw, commandSpec.parser(), arity, consumed);
  8938. ITypeConverter<?> converter = getTypeConverter(type, argSpec, 0);
  8939. for (int j = 0; j < values.length; j++) {
  8940. Object stronglyTypedValue = tryConvert(argSpec, index, converter, values[j], type);
  8941. result.add(stronglyTypedValue);
  8942. if (tracer.isInfo()) {
  8943. tracer.info("Adding [%s] to %s for %s%n", String.valueOf(result.get(result.size() - 1)), argSpec.toString(), argDescription);
  8944. }
  8945. parseResultBuilder.addStringValue(argSpec, values[j]);
  8946. }
  8947. parseResultBuilder.addOriginalStringValue(argSpec, raw);
  8948. return ++index;
  8949. }
  8950. private boolean canConsumeOneArgument(ArgSpec argSpec, Range arity, int consumed, String arg, Class<?> type, String argDescription) {
  8951. ITypeConverter<?> converter = getTypeConverter(type, argSpec, 0);
  8952. try {
  8953. String[] values = argSpec.splitValue(trim(arg), commandSpec.parser(), arity, consumed);
  8954. // if (!argSpec.acceptsValues(values.length, commandSpec.parser())) {
  8955. // tracer.debug("$s would split into %s values but %s cannot accept that many values.%n", arg, values.length, argDescription);
  8956. // return false;
  8957. // }
  8958. for (String value : values) {
  8959. tryConvert(argSpec, -1, converter, value, type);
  8960. }
  8961. return true;
  8962. } catch (PicocliException ex) {
  8963. tracer.debug("$s cannot be assigned to %s: type conversion fails: %s.%n", arg, argDescription, ex.getMessage());
  8964. return false;
  8965. }
  8966. }
  8967. /** Returns whether the next argument can be assigned to a vararg option/positional parameter.
  8968. * <p>
  8969. * Usually, we stop if we encounter '--', a command, or another option.
  8970. * However, if end-of-options has been reached, positional parameters may consume all remaining arguments. </p>*/
  8971. private boolean varargCanConsumeNextValue(ArgSpec argSpec, String nextValue) {
  8972. if (endOfOptions && argSpec.isPositional()) { return true; }
  8973. boolean isCommand = commandSpec.subcommands().containsKey(nextValue);
  8974. return !isCommand && !isOption(nextValue);
  8975. }
  8976. /**
  8977. * Called when parsing varargs parameters for a multi-value option.
  8978. * When an option is encountered, the remainder should not be interpreted as vararg elements.
  8979. * @param arg the string to determine whether it is an option or not
  8980. * @return true if it is an option, false otherwise
  8981. */
  8982. private boolean isOption(String arg) {
  8983. if (arg == null) { return false; }
  8984. if ("--".equals(arg)) { return true; }
  8985. // not just arg prefix: we may be in the middle of parsing -xrvfFILE
  8986. if (commandSpec.optionsMap().containsKey(arg)) { // -v or -f or --file (not attached to param or other option)
  8987. return true;
  8988. }
  8989. int separatorIndex = arg.indexOf(config().separator());
  8990. if (separatorIndex > 0) { // -f=FILE or --file==FILE (attached to param via separator)
  8991. if (commandSpec.optionsMap().containsKey(arg.substring(0, separatorIndex))) {
  8992. return true;
  8993. }
  8994. }
  8995. return (arg.length() > 2 && arg.startsWith("-") && commandSpec.posixOptionsMap().containsKey(arg.charAt(1)));
  8996. }
  8997. private Object tryConvert(ArgSpec argSpec, int index, ITypeConverter<?> converter, String value, Class<?> type)
  8998. throws ParameterException {
  8999. try {
  9000. return converter.convert(value);
  9001. } catch (TypeConversionException ex) {
  9002. String msg = String.format("Invalid value for %s: %s", optionDescription("", argSpec, index), ex.getMessage());
  9003. throw new ParameterException(CommandLine.this, msg, argSpec, value);
  9004. } catch (Exception other) {
  9005. String desc = optionDescription("", argSpec, index);
  9006. String msg = String.format("Invalid value for %s: cannot convert '%s' to %s (%s)", desc, value, type.getSimpleName(), other);
  9007. throw new ParameterException(CommandLine.this, msg, other, argSpec, value);
  9008. }
  9009. }
  9010. private String optionDescription(String prefix, ArgSpec argSpec, int index) {
  9011. String desc = "";
  9012. if (argSpec.isOption()) {
  9013. desc = prefix + "option '" + ((OptionSpec) argSpec).longestName() + "'";
  9014. if (index >= 0) {
  9015. if (argSpec.arity().max > 1) {
  9016. desc += " at index " + index;
  9017. }
  9018. desc += " (" + argSpec.paramLabel() + ")";
  9019. }
  9020. } else {
  9021. desc = prefix + "positional parameter at index " + ((PositionalParamSpec) argSpec).index() + " (" + argSpec.paramLabel() + ")";
  9022. }
  9023. return desc;
  9024. }
  9025. private boolean isAnyHelpRequested() { return isHelpRequested || parseResultBuilder.versionHelpRequested || parseResultBuilder.usageHelpRequested; }
  9026. private void updateHelpRequested(CommandSpec command) {
  9027. isHelpRequested |= command.helpCommand();
  9028. }
  9029. private void updateHelpRequested(ArgSpec argSpec) {
  9030. if (!parseResultBuilder.isInitializingDefaultValues && argSpec.isOption()) {
  9031. OptionSpec option = (OptionSpec) argSpec;
  9032. isHelpRequested |= is(argSpec, "help", option.help());
  9033. parseResultBuilder.versionHelpRequested |= is(argSpec, "versionHelp", option.versionHelp());
  9034. parseResultBuilder.usageHelpRequested |= is(argSpec, "usageHelp", option.usageHelp());
  9035. }
  9036. }
  9037. private boolean is(ArgSpec p, String attribute, boolean value) {
  9038. if (value) { if (tracer.isInfo()) {tracer.info("%s has '%s' annotation: not validating required fields%n", p.toString(), attribute); }}
  9039. return value;
  9040. }
  9041. @SuppressWarnings("unchecked")
  9042. private Collection<Object> createCollection(Class<?> collectionClass, Class<?> elementType) throws Exception {
  9043. if (EnumSet.class.isAssignableFrom(collectionClass) && Enum.class.isAssignableFrom(elementType)) {
  9044. Object enumSet = EnumSet.noneOf((Class<Enum>) elementType);
  9045. return (Collection<Object>) enumSet;
  9046. }
  9047. // custom Collection implementation class must have default constructor
  9048. return (Collection<Object>) factory.create(collectionClass);
  9049. }
  9050. @SuppressWarnings("unchecked") private Map<Object, Object> createMap(Class<?> mapClass) throws Exception {
  9051. return (Map<Object, Object>) factory.create(mapClass);
  9052. }
  9053. private ITypeConverter<?> getTypeConverter(final Class<?> type, ArgSpec argSpec, int index) {
  9054. if (argSpec.converters().length > index) { return argSpec.converters()[index]; }
  9055. if (converterRegistry.containsKey(type)) { return converterRegistry.get(type); }
  9056. if (type.isEnum()) {
  9057. return new ITypeConverter<Object>() {
  9058. @SuppressWarnings("unchecked")
  9059. public Object convert(String value) throws Exception {
  9060. String sensitivity = "case-sensitive";
  9061. if (commandSpec.parser().caseInsensitiveEnumValuesAllowed()) {
  9062. String upper = value.toUpperCase();
  9063. for (Object enumConstant : type.getEnumConstants()) {
  9064. if (upper.equals(String.valueOf(enumConstant).toUpperCase())) { return enumConstant; }
  9065. }
  9066. sensitivity = "case-insensitive";
  9067. }
  9068. try { return Enum.valueOf((Class<Enum>) type, value); }
  9069. catch (Exception ex) {
  9070. Enum<?>[] constants = ((Class<Enum<?>>) type).getEnumConstants();
  9071. String[] names = new String[constants.length];
  9072. for (int i = 0; i < names.length; i++) { names[i] = constants[i].name(); }
  9073. throw new TypeConversionException(
  9074. String.format("expected one of %s (%s) but was '%s'", Arrays.asList(names), sensitivity, value)); }
  9075. }
  9076. };
  9077. }
  9078. throw new MissingTypeConverterException(CommandLine.this, "No TypeConverter registered for " + type.getName() + " of " + argSpec);
  9079. }
  9080. private boolean assertNoMissingParameters(ArgSpec argSpec, Range arity, Stack<String> args) {
  9081. if (argSpec.interactive()) { return true; }
  9082. int available = args.size();
  9083. if (available > 0 && commandSpec.parser().splitFirst() && argSpec.splitRegex().length() > 0) {
  9084. available += argSpec.splitValue(args.peek(), commandSpec.parser(), arity, 0).length - 1;
  9085. }
  9086. if (arity.min > available) {
  9087. if (arity.min == 1) {
  9088. if (argSpec.isOption()) {
  9089. maybeThrow(new MissingParameterException(CommandLine.this, argSpec, "Missing required parameter for " +
  9090. optionDescription("", argSpec, 0)));
  9091. return false;
  9092. }
  9093. Range indexRange = ((PositionalParamSpec) argSpec).index();
  9094. String sep = "";
  9095. String names = ": ";
  9096. int count = 0;
  9097. List<PositionalParamSpec> positionalParameters = commandSpec.positionalParameters();
  9098. for (int i = indexRange.min; i < positionalParameters.size(); i++) {
  9099. if (positionalParameters.get(i).arity().min > 0) {
  9100. names += sep + positionalParameters.get(i).paramLabel();
  9101. sep = ", ";
  9102. count++;
  9103. }
  9104. }
  9105. String msg = "Missing required parameter";
  9106. Range paramArity = argSpec.arity();
  9107. if (count > 1 || arity.min - available > 1) {
  9108. msg += "s";
  9109. }
  9110. maybeThrow(new MissingParameterException(CommandLine.this, argSpec, msg + names));
  9111. } else if (args.isEmpty()) {
  9112. maybeThrow(new MissingParameterException(CommandLine.this, argSpec, optionDescription("", argSpec, 0) +
  9113. " requires at least " + arity.min + " values, but none were specified."));
  9114. } else {
  9115. maybeThrow(new MissingParameterException(CommandLine.this, argSpec, optionDescription("", argSpec, 0) +
  9116. " requires at least " + arity.min + " values, but only " + available + " were specified: " + reverse(args)));
  9117. }
  9118. return false;
  9119. }
  9120. return true;
  9121. }
  9122. private String trim(String value) {
  9123. return unquote(value);
  9124. }
  9125. private String unquote(String value) {
  9126. if (!commandSpec.parser().trimQuotes()) { return value; }
  9127. return value == null
  9128. ? null
  9129. : (value.length() > 1 && value.startsWith("\"") && value.endsWith("\""))
  9130. ? value.substring(1, value.length() - 1)
  9131. : value;
  9132. }
  9133. char[] readPassword(String prompt) {
  9134. try {
  9135. Object console = System.class.getDeclaredMethod("console").invoke(null);
  9136. Method method = Class.forName("java.io.Console").getDeclaredMethod("readPassword", String.class, Object[].class);
  9137. return (char[]) method.invoke(console, prompt, new Object[0]);
  9138. } catch (Exception e) {
  9139. System.out.print(prompt);
  9140. InputStreamReader isr = new InputStreamReader(System.in);
  9141. BufferedReader in = new BufferedReader(isr);
  9142. try {
  9143. return in.readLine().toCharArray();
  9144. } catch (IOException ex2) {
  9145. throw new IllegalStateException(ex2);
  9146. }
  9147. }
  9148. }
  9149. int getPosition(ArgSpec arg) {
  9150. if (arg.group() == null) { return position; }
  9151. MatchedGroup matchedGroup = parseResultBuilder.matchedGroup.findOrCreateMatchingGroup(arg, commandSpec.commandLine());
  9152. return matchedGroup == null ? 0 : matchedGroup.multiple().position;
  9153. }
  9154. String positionDesc(ArgSpec arg) {
  9155. int pos = getPosition(arg);
  9156. return (arg.group() == null) ? pos + " (command-local)" : pos + " (in group " + arg.group().synopsis() + ")";
  9157. }
  9158. }
  9159. private static class PositionalParametersSorter implements Comparator<ArgSpec> {
  9160. private static final Range OPTION_INDEX = new Range(0, 0, false, true, "0");
  9161. public int compare(ArgSpec p1, ArgSpec p2) {
  9162. int result = index(p1).compareTo(index(p2));
  9163. return (result == 0) ? p1.arity().compareTo(p2.arity()) : result;
  9164. }
  9165. private Range index(ArgSpec arg) { return arg.isOption() ? OPTION_INDEX : ((PositionalParamSpec) arg).index(); }
  9166. }
  9167. /**
  9168. * Inner class to group the built-in {@link ITypeConverter} implementations.
  9169. */
  9170. private static class BuiltIn {
  9171. static class StringConverter implements ITypeConverter<String> {
  9172. public String convert(String value) { return value; }
  9173. }
  9174. static class StringBuilderConverter implements ITypeConverter<StringBuilder> {
  9175. public StringBuilder convert(String value) { return new StringBuilder(value); }
  9176. }
  9177. static class CharSequenceConverter implements ITypeConverter<CharSequence> {
  9178. public String convert(String value) { return value; }
  9179. }
  9180. /** Converts {@code "true"} or {@code "false"} to a {@code Boolean}. Other values result in a ParameterException.*/
  9181. static class BooleanConverter implements ITypeConverter<Boolean> {
  9182. public Boolean convert(String value) {
  9183. if ("true".equalsIgnoreCase(value) || "false".equalsIgnoreCase(value)) {
  9184. return Boolean.parseBoolean(value);
  9185. } else {
  9186. throw new TypeConversionException("'" + value + "' is not a boolean");
  9187. }
  9188. }
  9189. }
  9190. static class CharacterConverter implements ITypeConverter<Character> {
  9191. public Character convert(String value) {
  9192. if (value.length() > 1) {
  9193. throw new TypeConversionException("'" + value + "' is not a single character");
  9194. }
  9195. return value.charAt(0);
  9196. }
  9197. }
  9198. private static TypeConversionException fail(String value, Class<?> c) { return fail(value, c, "'%s' is not a %s"); }
  9199. private static TypeConversionException fail(String value, Class<?> c, String template) {
  9200. return new TypeConversionException(String.format(template, value, c.getSimpleName()));
  9201. }
  9202. /** Converts text to a {@code Byte} by delegating to {@link Byte#valueOf(String)}.*/
  9203. static class ByteConverter implements ITypeConverter<Byte> {
  9204. public Byte convert(String value) { try {return Byte.valueOf(value);} catch (Exception ex) {throw fail(value, Byte.TYPE);} }
  9205. }
  9206. /** Converts text to a {@code Short} by delegating to {@link Short#valueOf(String)}.*/
  9207. static class ShortConverter implements ITypeConverter<Short> {
  9208. public Short convert(String value) { try {return Short.valueOf(value);} catch (Exception ex) {throw fail(value, Short.TYPE);} }
  9209. }
  9210. /** Converts text to an {@code Integer} by delegating to {@link Integer#valueOf(String)}.*/
  9211. static class IntegerConverter implements ITypeConverter<Integer> {
  9212. public Integer convert(String value) { try {return Integer.valueOf(value);} catch (Exception ex) {throw fail(value, Integer.TYPE, "'%s' is not an %s");} }
  9213. }
  9214. /** Converts text to a {@code Long} by delegating to {@link Long#valueOf(String)}.*/
  9215. static class LongConverter implements ITypeConverter<Long> {
  9216. public Long convert(String value) { try {return Long.valueOf(value);} catch (Exception ex) {throw fail(value, Long.TYPE);} }
  9217. }
  9218. static class FloatConverter implements ITypeConverter<Float> {
  9219. public Float convert(String value) { try {return Float.valueOf(value);} catch (Exception ex) {throw fail(value, Float.TYPE);} }
  9220. }
  9221. static class DoubleConverter implements ITypeConverter<Double> {
  9222. public Double convert(String value) { try {return Double.valueOf(value);} catch (Exception ex) {throw fail(value, Double.TYPE);} }
  9223. }
  9224. static class FileConverter implements ITypeConverter<File> {
  9225. public File convert(String value) { return new File(value); }
  9226. }
  9227. static class URLConverter implements ITypeConverter<URL> {
  9228. public URL convert(String value) throws MalformedURLException { return new URL(value); }
  9229. }
  9230. static class URIConverter implements ITypeConverter<URI> {
  9231. public URI convert(String value) throws URISyntaxException { return new URI(value); }
  9232. }
  9233. /** Converts text in {@code yyyy-mm-dd} format to a {@code java.util.Date}. ParameterException on failure. */
  9234. static class ISO8601DateConverter implements ITypeConverter<Date> {
  9235. public Date convert(String value) {
  9236. try {
  9237. return new SimpleDateFormat("yyyy-MM-dd").parse(value);
  9238. } catch (ParseException e) {
  9239. throw new TypeConversionException("'" + value + "' is not a yyyy-MM-dd date");
  9240. }
  9241. }
  9242. }
  9243. /** Converts text in any of the following formats to a {@code java.sql.Time}: {@code HH:mm}, {@code HH:mm:ss},
  9244. * {@code HH:mm:ss.SSS}, {@code HH:mm:ss,SSS}. Other formats result in a ParameterException. */
  9245. static class ISO8601TimeConverter implements ITypeConverter<Object> {
  9246. // Implementation note: use reflection so that picocli only requires the java.base module in Java 9.
  9247. private static /*final*/ String FQCN = "java.sql.Time"; // non-final for testing
  9248. public Object convert(String value) {
  9249. try {
  9250. if (value.length() <= 5) {
  9251. return createTime(new SimpleDateFormat("HH:mm").parse(value).getTime());
  9252. } else if (value.length() <= 8) {
  9253. return createTime(new SimpleDateFormat("HH:mm:ss").parse(value).getTime());
  9254. } else if (value.length() <= 12) {
  9255. try {
  9256. return createTime(new SimpleDateFormat("HH:mm:ss.SSS").parse(value).getTime());
  9257. } catch (ParseException e2) {
  9258. return createTime(new SimpleDateFormat("HH:mm:ss,SSS").parse(value).getTime());
  9259. }
  9260. }
  9261. } catch (ParseException ignored) {
  9262. // ignored because we throw a ParameterException below
  9263. }
  9264. throw new TypeConversionException("'" + value + "' is not a HH:mm[:ss[.SSS]] time");
  9265. }
  9266. private Object createTime(long epochMillis) {
  9267. try {
  9268. Class<?> timeClass = Class.forName(FQCN);
  9269. Constructor<?> constructor = timeClass.getDeclaredConstructor(long.class);
  9270. return constructor.newInstance(epochMillis);
  9271. } catch (Exception e) {
  9272. throw new TypeConversionException("Unable to create new java.sql.Time with long value " + epochMillis + ": " + e.getMessage());
  9273. }
  9274. }
  9275. public static void registerIfAvailable(Map<Class<?>, ITypeConverter<?>> registry, Tracer tracer) {
  9276. if (excluded(FQCN, tracer)) { return; }
  9277. try {
  9278. registry.put(Class.forName(FQCN), new ISO8601TimeConverter());
  9279. } catch (Exception e) {
  9280. if (!traced.contains(FQCN)) {
  9281. tracer.debug("Could not register converter for %s: %s%n", FQCN, e.toString());
  9282. }
  9283. traced.add(FQCN);
  9284. }
  9285. }
  9286. }
  9287. static class BigDecimalConverter implements ITypeConverter<BigDecimal> {
  9288. public BigDecimal convert(String value) { return new BigDecimal(value); }
  9289. }
  9290. static class BigIntegerConverter implements ITypeConverter<BigInteger> {
  9291. public BigInteger convert(String value) { return new BigInteger(value); }
  9292. }
  9293. static class CharsetConverter implements ITypeConverter<Charset> {
  9294. public Charset convert(String s) { return Charset.forName(s); }
  9295. }
  9296. /** Converts text to a {@code InetAddress} by delegating to {@link InetAddress#getByName(String)}. */
  9297. static class InetAddressConverter implements ITypeConverter<InetAddress> {
  9298. public InetAddress convert(String s) throws Exception { return InetAddress.getByName(s); }
  9299. }
  9300. static class PatternConverter implements ITypeConverter<Pattern> {
  9301. public Pattern convert(String s) { return Pattern.compile(s); }
  9302. }
  9303. static class UUIDConverter implements ITypeConverter<UUID> {
  9304. public UUID convert(String s) throws Exception { return UUID.fromString(s); }
  9305. }
  9306. static class CurrencyConverter implements ITypeConverter<Currency> {
  9307. public Currency convert(String s) throws Exception { return Currency.getInstance(s); }
  9308. }
  9309. static class TimeZoneConverter implements ITypeConverter<TimeZone> {
  9310. public TimeZone convert(String s) throws Exception { return TimeZone.getTimeZone(s); }
  9311. }
  9312. static class ByteOrderConverter implements ITypeConverter<ByteOrder> {
  9313. public ByteOrder convert(String s) throws Exception {
  9314. if (s.equalsIgnoreCase(ByteOrder.BIG_ENDIAN.toString())) { return ByteOrder.BIG_ENDIAN; }
  9315. if (s.equalsIgnoreCase(ByteOrder.LITTLE_ENDIAN.toString())) { return ByteOrder.LITTLE_ENDIAN; }
  9316. throw new TypeConversionException("'" + s + "' is not a valid ByteOrder");
  9317. }
  9318. }
  9319. static class ClassConverter implements ITypeConverter<Class<?>> {
  9320. public Class<?> convert(String s) throws Exception { return Class.forName(s); }
  9321. }
  9322. static class NetworkInterfaceConverter implements ITypeConverter<NetworkInterface> {
  9323. public NetworkInterface convert(String s) throws Exception {
  9324. try {
  9325. InetAddress addr = new InetAddressConverter().convert(s);
  9326. return NetworkInterface.getByInetAddress(addr);
  9327. } catch (Exception ex) {
  9328. try { return NetworkInterface.getByName(s);
  9329. } catch (Exception ex2) {
  9330. throw new TypeConversionException("'" + s + "' is not an InetAddress or NetworkInterface name");
  9331. }
  9332. }
  9333. }
  9334. }
  9335. static void registerIfAvailable(Map<Class<?>, ITypeConverter<?>> registry, Tracer tracer, String fqcn, String factoryMethodName, Class<?>... paramTypes) {
  9336. registerIfAvailable(registry, tracer, fqcn, fqcn, factoryMethodName, paramTypes);
  9337. }
  9338. static void registerIfAvailable(Map<Class<?>, ITypeConverter<?>> registry, Tracer tracer, String fqcn, String factoryClass, String factoryMethodName, Class<?>... paramTypes) {
  9339. if (excluded(fqcn, tracer)) { return; }
  9340. try {
  9341. Class<?> cls = Class.forName(fqcn);
  9342. Class<?> factory = Class.forName(factoryClass);
  9343. Method method = factory.getDeclaredMethod(factoryMethodName, paramTypes);
  9344. registry.put(cls, new ReflectionConverter(method, paramTypes));
  9345. } catch (Exception e) {
  9346. if (!traced.contains(fqcn)) {
  9347. tracer.debug("Could not register converter for %s: %s%n", fqcn, e.toString());
  9348. }
  9349. traced.add(fqcn);
  9350. }
  9351. }
  9352. static boolean excluded(String fqcn, Tracer tracer) {
  9353. String[] excludes = System.getProperty("picocli.converters.excludes", "").split(",");
  9354. for (String regex : excludes) {
  9355. if (fqcn.matches(regex)) {
  9356. tracer.debug("BuiltIn type converter for %s is not loaded: (picocli.converters.excludes=%s)%n", fqcn, System.getProperty("picocli.converters.excludes"));
  9357. return true;
  9358. }
  9359. }
  9360. return false;
  9361. }
  9362. static Set<String> traced = new HashSet<String>();
  9363. static class ReflectionConverter implements ITypeConverter<Object> {
  9364. private final Method method;
  9365. private Class<?>[] paramTypes;
  9366. public ReflectionConverter(Method method, Class<?>... paramTypes) {
  9367. this.method = Assert.notNull(method, "method");
  9368. this.paramTypes = Assert.notNull(paramTypes, "paramTypes");
  9369. }
  9370. public Object convert(String s) {
  9371. try {
  9372. if (paramTypes.length > 1) {
  9373. return method.invoke(null, s, new String[0]);
  9374. } else {
  9375. return method.invoke(null, s);
  9376. }
  9377. } catch (InvocationTargetException e) {
  9378. throw new TypeConversionException(String.format("cannot convert '%s' to %s (%s)", s, method.getReturnType(), e.getTargetException()));
  9379. } catch (Exception e) {
  9380. throw new TypeConversionException(String.format("Internal error converting '%s' to %s (%s)", s, method.getReturnType(), e));
  9381. }
  9382. }
  9383. }
  9384. private BuiltIn() {} // private constructor: never instantiate
  9385. }
  9386. static class AutoHelpMixin {
  9387. private static final String KEY = "mixinStandardHelpOptions";
  9388. @Option(names = {"-h", "--help"}, usageHelp = true, descriptionKey = "mixinStandardHelpOptions.help",
  9389. description = "Show this help message and exit.")
  9390. private boolean helpRequested;
  9391. @Option(names = {"-V", "--version"}, versionHelp = true, descriptionKey = "mixinStandardHelpOptions.version",
  9392. description = "Print version information and exit.")
  9393. private boolean versionRequested;
  9394. }
  9395. /** Help command that can be installed as a subcommand on all application commands. When invoked with a subcommand
  9396. * argument, it prints usage help for the specified subcommand. For example:<pre>
  9397. *
  9398. * // print help for subcommand
  9399. * command help subcommand
  9400. * </pre><p>
  9401. * When invoked without additional parameters, it prints usage help for the parent command. For example:
  9402. * </p><pre>
  9403. *
  9404. * // print help for command
  9405. * command help
  9406. * </pre>
  9407. * For {@linkplain Messages internationalization}: this command has a {@code --help} option with {@code descriptionKey = "helpCommand.help"},
  9408. * and a {@code COMMAND} positional parameter with {@code descriptionKey = "helpCommand.command"}.
  9409. * @since 3.0
  9410. */
  9411. @Command(name = "help", header = "Displays help information about the specified command",
  9412. synopsisHeading = "%nUsage: ", helpCommand = true,
  9413. description = {"%nWhen no COMMAND is given, the usage help for the main command is displayed.",
  9414. "If a COMMAND is specified, the help for that command is shown.%n"})
  9415. public static final class HelpCommand implements IHelpCommandInitializable, Runnable {
  9416. @Option(names = {"-h", "--help"}, usageHelp = true, descriptionKey = "helpCommand.help",
  9417. description = "Show usage help for the help command and exit.")
  9418. private boolean helpRequested;
  9419. @Parameters(paramLabel = "COMMAND", descriptionKey = "helpCommand.command",
  9420. description = "The COMMAND to display the usage help message for.")
  9421. private String[] commands = new String[0];
  9422. private CommandLine self;
  9423. private PrintStream out;
  9424. private PrintStream err;
  9425. private Help.Ansi ansi;
  9426. /** Invokes {@link #usage(PrintStream, Help.Ansi) usage} for the specified command, or for the parent command. */
  9427. public void run() {
  9428. CommandLine parent = self == null ? null : self.getParent();
  9429. if (parent == null) { return; }
  9430. if (commands.length > 0) {
  9431. CommandLine subcommand = parent.getSubcommands().get(commands[0]);
  9432. if (subcommand != null) {
  9433. subcommand.usage(out, ansi);
  9434. } else {
  9435. throw new ParameterException(parent, "Unknown subcommand '" + commands[0] + "'.", null, commands[0]);
  9436. }
  9437. } else {
  9438. parent.usage(out, ansi);
  9439. }
  9440. }
  9441. /** {@inheritDoc} */
  9442. public void init(CommandLine helpCommandLine, Help.Ansi ansi, PrintStream out, PrintStream err) {
  9443. this.self = Assert.notNull(helpCommandLine, "helpCommandLine");
  9444. this.ansi = Assert.notNull(ansi, "ansi");
  9445. this.out = Assert.notNull(out, "out");
  9446. this.err = Assert.notNull(err, "err");
  9447. }
  9448. }
  9449. /** Help commands that provide usage help for other commands can implement this interface to be initialized with the information they need.
  9450. * <p>The {@link #printHelpIfRequested(List, PrintStream, PrintStream, Help.Ansi) CommandLine::printHelpIfRequested} method calls the
  9451. * {@link #init(CommandLine, picocli.CommandLine.Help.Ansi, PrintStream, PrintStream) init} method on commands marked as {@link Command#helpCommand() helpCommand}
  9452. * before the help command's {@code run} or {@code call} method is called.</p>
  9453. * <p><b>Implementation note:</b></p><p>
  9454. * If an error occurs in the {@code run} or {@code call} method while processing the help request, it is recommended custom Help
  9455. * commands throw a {@link ParameterException ParameterException} with a reference to the parent command. The {@link DefaultExceptionHandler DefaultExceptionHandler} will print
  9456. * the error message and the usage for the parent command, and will terminate with the exit code of the exception handler if one was set.
  9457. * </p>
  9458. * @since 3.0 */
  9459. public static interface IHelpCommandInitializable {
  9460. /** Initializes this object with the information needed to implement a help command that provides usage help for other commands.
  9461. * @param helpCommandLine the {@code CommandLine} object associated with this help command. Implementors can use
  9462. * this to walk the command hierarchy and get access to the help command's parent and sibling commands.
  9463. * @param ansi whether to use Ansi colors or not
  9464. * @param out the stream to print the usage help message to
  9465. * @param err the error stream to print any diagnostic messages to, in addition to the output from the exception handler
  9466. */
  9467. void init(CommandLine helpCommandLine, Help.Ansi ansi, PrintStream out, PrintStream err);
  9468. }
  9469. /**
  9470. * Renders a section of the usage help message. The usage help message can be customized:
  9471. * use the {@link #setHelpSectionKeys(List)} and {@link #setHelpSectionMap(Map)} to change the order of sections,
  9472. * delete standard sections, add custom sections or replace the renderer of a standard sections with a custom one.
  9473. * <p>
  9474. * This gives complete freedom on how a usage help message section is rendered, but it also means that the section renderer
  9475. * is responsible for all aspects of rendering the section, including layout and emitting ANSI escape codes.
  9476. * The {@link Help.TextTable} and {@link Help.Ansi.Text} classes, and the {@link CommandLine.Help.Ansi#string(String)} and {@link CommandLine.Help.Ansi#text(String)} methods may be useful.
  9477. * </p>
  9478. * @see UsageMessageSpec
  9479. * @since 3.9
  9480. */
  9481. public interface IHelpSectionRenderer {
  9482. /**
  9483. * Renders a section of the usage help, like header heading, header, synopsis heading,
  9484. * synopsis, description heading, description, etc.
  9485. * @param help the {@code Help} instance for which to render a section
  9486. * @return the text for this section; may contain {@linkplain Help.Ansi ANSI} escape codes
  9487. * @since 3.9
  9488. */
  9489. String render(Help help);
  9490. }
  9491. /**
  9492. * A collection of methods and inner classes that provide fine-grained control over the contents and layout of
  9493. * the usage help message to display to end users when help is requested or invalid input values were specified.
  9494. * <h2>Class Diagram of the CommandLine.Help API</h2>
  9495. * <p>
  9496. * <img src="doc-files/class-diagram-help-api.png" alt="Class Diagram of the CommandLine.Help API">
  9497. * </p>
  9498. * <h2>Layered API</h2>
  9499. * <p>The {@link Command} annotation and the {@link UsageMessageSpec} programmatic API equivalent
  9500. * provide the easiest way to configure the usage help message. See
  9501. * the <a href="https://remkop.github.io/picocli/index.html#_usage_help">Manual</a> for details.</p>
  9502. * <p>This Help class provides high-level functions to create sections of the usage help message and headings
  9503. * for these sections. Instead of calling the {@link CommandLine#usage(PrintStream, CommandLine.Help.ColorScheme)}
  9504. * method, application authors may want to create a custom usage help message by reorganizing sections in a
  9505. * different order and/or adding custom sections.</p>
  9506. * <p>Finally, the Help class contains inner classes and interfaces that can be used to create custom help messages.</p>
  9507. * <h3>IOptionRenderer and IParameterRenderer</h3>
  9508. * <p>Renders a field annotated with {@link Option} or {@link Parameters} to an array of {@link Text} values.
  9509. * By default, these values are</p><ul>
  9510. * <li>mandatory marker character (if the option/parameter is {@link Option#required() required})</li>
  9511. * <li>short option name (empty for parameters)</li>
  9512. * <li>comma or empty (empty for parameters)</li>
  9513. * <li>long option names (the parameter {@link IParamLabelRenderer label} for parameters)</li>
  9514. * <li>description</li>
  9515. * </ul>
  9516. * <p>Other components rely on this ordering.</p>
  9517. * <h3>Layout</h3>
  9518. * <p>Delegates to the renderers to create {@link Text} values for the annotated fields, and uses a
  9519. * {@link TextTable} to display these values in tabular format. Layout is responsible for deciding which values
  9520. * to display where in the table. By default, Layout shows one option or parameter per table row.</p>
  9521. * <h3>TextTable</h3>
  9522. * <p>Responsible for spacing out {@link Text} values according to the {@link Column} definitions the table was
  9523. * created with. Columns have a width, indentation, and an overflow policy that decides what to do if a value is
  9524. * longer than the column's width.</p>
  9525. * <h3>Text</h3>
  9526. * <p>Encapsulates rich text with styles and colors in a way that other components like {@link TextTable} are
  9527. * unaware of the embedded ANSI escape codes.</p>
  9528. */
  9529. public static class Help {
  9530. /** Constant String holding the default program name, value defined in {@link CommandSpec#DEFAULT_COMMAND_NAME}. */
  9531. protected static final String DEFAULT_COMMAND_NAME = CommandSpec.DEFAULT_COMMAND_NAME;
  9532. /** Constant String holding the default string that separates options from option parameters, value defined in {@link ParserSpec#DEFAULT_SEPARATOR}. */
  9533. protected static final String DEFAULT_SEPARATOR = ParserSpec.DEFAULT_SEPARATOR;
  9534. private final static int defaultOptionsColumnWidth = 24;
  9535. private final CommandSpec commandSpec;
  9536. private final ColorScheme colorScheme;
  9537. private final Map<String, Help> commands = new LinkedHashMap<String, Help>();
  9538. private List<String> aliases = Collections.emptyList();
  9539. private IParamLabelRenderer parameterLabelRenderer;
  9540. /** Constructs a new {@code Help} instance with a default color scheme, initialized from annotatations
  9541. * on the specified class and superclasses.
  9542. * @param command the annotated object to create usage help for */
  9543. public Help(Object command) {
  9544. this(command, Ansi.AUTO);
  9545. }
  9546. /** Constructs a new {@code Help} instance with a default color scheme, initialized from annotatations
  9547. * on the specified class and superclasses.
  9548. * @param command the annotated object to create usage help for
  9549. * @param ansi whether to emit ANSI escape codes or not */
  9550. public Help(Object command, Ansi ansi) {
  9551. this(command, defaultColorScheme(ansi));
  9552. }
  9553. /** Constructs a new {@code Help} instance with the specified color scheme, initialized from annotatations
  9554. * on the specified class and superclasses.
  9555. * @param command the annotated object to create usage help for
  9556. * @param colorScheme the color scheme to use
  9557. * @deprecated use {@link picocli.CommandLine.Help#Help(picocli.CommandLine.Model.CommandSpec, picocli.CommandLine.Help.ColorScheme)} */
  9558. @Deprecated public Help(Object command, ColorScheme colorScheme) {
  9559. this(CommandSpec.forAnnotatedObject(command, new DefaultFactory()), colorScheme);
  9560. }
  9561. /** Constructs a new {@code Help} instance with the specified color scheme, initialized from annotatations
  9562. * on the specified class and superclasses.
  9563. * @param commandSpec the command model to create usage help for
  9564. * @param colorScheme the color scheme to use */
  9565. public Help(CommandSpec commandSpec, ColorScheme colorScheme) {
  9566. this.commandSpec = Assert.notNull(commandSpec, "commandSpec");
  9567. this.aliases = new ArrayList<String>(Arrays.asList(commandSpec.aliases()));
  9568. this.aliases.add(0, commandSpec.name());
  9569. this.colorScheme = Assert.notNull(colorScheme, "colorScheme").applySystemProperties();
  9570. parameterLabelRenderer = createDefaultParamLabelRenderer(); // uses help separator
  9571. this.addAllSubcommands(commandSpec.subcommands());
  9572. }
  9573. Help withCommandNames(List<String> aliases) { this.aliases = aliases; return this; }
  9574. /** Returns the {@code CommandSpec} model that this Help was constructed with.
  9575. * @since 3.9 */
  9576. public CommandSpec commandSpec() { return commandSpec; }
  9577. /** Returns the {@code ColorScheme} model that this Help was constructed with.
  9578. * @since 3.0 */
  9579. public ColorScheme colorScheme() { return colorScheme; }
  9580. /** Returns the {@code IHelpFactory} that this Help was constructed with.
  9581. * @since 3.9 */
  9582. private IHelpFactory getHelpFactory() { return commandSpec.usageMessage().helpFactory(); }
  9583. /** Returns the map of subcommand {@code Help} instances for this command Help.
  9584. * @since 3.9 */
  9585. protected Map<String, Help> subcommands() { return Collections.unmodifiableMap(commands); }
  9586. /** Returns the list of aliases for the command in this Help.
  9587. * @since 3.9 */
  9588. protected List<String> aliases() { return Collections.unmodifiableList(aliases); }
  9589. /** Option and positional parameter value label renderer used for the synopsis line(s) and the option list.
  9590. * By default initialized to the result of {@link #createDefaultParamLabelRenderer()}, which takes a snapshot
  9591. * of the {@link ParserSpec#separator()} at construction time. If the separator is modified after Help construction, you
  9592. * may need to re-initialize this field by calling {@link #createDefaultParamLabelRenderer()} again. */
  9593. public IParamLabelRenderer parameterLabelRenderer() {return parameterLabelRenderer;}
  9594. /** Registers all specified subcommands with this Help.
  9595. * @param commands maps the command names to the associated CommandLine object
  9596. * @return this Help instance (for method chaining)
  9597. * @see CommandLine#getSubcommands()
  9598. */
  9599. public Help addAllSubcommands(Map<String, CommandLine> commands) {
  9600. if (commands != null) {
  9601. // first collect aliases
  9602. Map<CommandLine, List<String>> done = new IdentityHashMap<CommandLine, List<String>>();
  9603. for (CommandLine cmd : commands.values()) {
  9604. if (!done.containsKey(cmd)) {
  9605. done.put(cmd, new ArrayList<String>(Arrays.asList(cmd.commandSpec.aliases())));
  9606. }
  9607. }
  9608. // then loop over all names that the command was registered with and add this name to the front of the list (if it isn't already in the list)
  9609. for (Map.Entry<String, CommandLine> entry : commands.entrySet()) {
  9610. List<String> aliases = done.get(entry.getValue());
  9611. if (!aliases.contains(entry.getKey())) { aliases.add(0, entry.getKey()); }
  9612. }
  9613. // The aliases list for each command now has at least one entry, with the main name at the front.
  9614. // Now we loop over the commands in the order that they were registered on their parent command.
  9615. for (Map.Entry<String, CommandLine> entry : commands.entrySet()) {
  9616. // not registering hidden commands is easier than suppressing display in Help.commandList():
  9617. // if all subcommands are hidden, help should not show command list header
  9618. if (!entry.getValue().getCommandSpec().usageMessage().hidden()) {
  9619. List<String> aliases = done.remove(entry.getValue());
  9620. if (aliases != null) { // otherwise we already processed this command by another alias
  9621. addSubcommand(aliases, entry.getValue());
  9622. }
  9623. }
  9624. }
  9625. }
  9626. return this;
  9627. }
  9628. /** Registers the specified subcommand with this Help.
  9629. * @param commandNames the name and aliases of the subcommand to display in the usage message
  9630. * @param commandLine the {@code CommandLine} object to get more information from
  9631. * @return this Help instance (for method chaining) */
  9632. Help addSubcommand(List<String> commandNames, CommandLine commandLine) {
  9633. String all = commandNames.toString();
  9634. commands.put(all.substring(1, all.length() - 1), getHelpFactory().create(commandLine.commandSpec, colorScheme).withCommandNames(commandNames));
  9635. return this;
  9636. }
  9637. /** Registers the specified subcommand with this Help.
  9638. * @param commandName the name of the subcommand to display in the usage message
  9639. * @param command the {@code CommandSpec} or {@code @Command} annotated object to get more information from
  9640. * @return this Help instance (for method chaining)
  9641. * @deprecated
  9642. */
  9643. @Deprecated public Help addSubcommand(String commandName, Object command) {
  9644. commands.put(commandName,
  9645. getHelpFactory().create(CommandSpec.forAnnotatedObject(command, commandSpec.commandLine().factory), defaultColorScheme(Ansi.AUTO)));
  9646. return this;
  9647. }
  9648. List<OptionSpec> options() { return commandSpec.options(); }
  9649. List<PositionalParamSpec> positionalParameters() { return commandSpec.positionalParameters(); }
  9650. String commandName() { return commandSpec.name(); }
  9651. /** Returns a synopsis for the command without reserving space for the synopsis heading.
  9652. * @return a synopsis
  9653. * @see #abbreviatedSynopsis()
  9654. * @see #detailedSynopsis(Comparator, boolean)
  9655. * @deprecated use {@link #synopsis(int)} instead
  9656. */
  9657. @Deprecated public String synopsis() { return synopsis(0); }
  9658. /**
  9659. * Returns a synopsis for the command, reserving the specified space for the synopsis heading.
  9660. * @param synopsisHeadingLength the length of the synopsis heading that will be displayed on the same line
  9661. * @return a synopsis
  9662. * @see #abbreviatedSynopsis()
  9663. * @see #detailedSynopsis(Comparator, boolean)
  9664. * @see #synopsisHeading
  9665. */
  9666. public String synopsis(int synopsisHeadingLength) {
  9667. if (!empty(commandSpec.usageMessage().customSynopsis())) { return customSynopsis(); }
  9668. return commandSpec.usageMessage().abbreviateSynopsis() ? abbreviatedSynopsis()
  9669. : detailedSynopsis(synopsisHeadingLength, createShortOptionArityAndNameComparator(), true);
  9670. }
  9671. /** Generates a generic synopsis like {@code <command name> [OPTIONS] [PARAM1 [PARAM2]...]}, omitting parts
  9672. * that don't apply to the command (e.g., does not show [OPTIONS] if the command has no options).
  9673. * @return a generic synopsis */
  9674. public String abbreviatedSynopsis() {
  9675. StringBuilder sb = new StringBuilder();
  9676. if (!commandSpec.optionsMap().isEmpty()) { // only show if annotated object actually has options
  9677. sb.append(" [OPTIONS]");
  9678. }
  9679. // sb.append(" [--] "); // implied
  9680. for (PositionalParamSpec positionalParam : commandSpec.positionalParameters()) {
  9681. if (!positionalParam.hidden()) {
  9682. sb.append(' ').append(parameterLabelRenderer().renderParameterLabel(positionalParam, ansi(), colorScheme.parameterStyles));
  9683. }
  9684. }
  9685. // only show if object has subcommands
  9686. if (!commandSpec.subcommands().isEmpty()) {
  9687. sb.append(" [COMMAND]");
  9688. }
  9689. return colorScheme.commandText(commandSpec.qualifiedName()).toString()
  9690. + (sb.toString()) + System.getProperty("line.separator");
  9691. }
  9692. /** Generates a detailed synopsis message showing all options and parameters. Follows the unix convention of
  9693. * showing optional options and parameters in square brackets ({@code [ ]}).
  9694. * @param optionSort comparator to sort options or {@code null} if options should not be sorted
  9695. * @param clusterBooleanOptions {@code true} if boolean short options should be clustered into a single string
  9696. * @return a detailed synopsis
  9697. * @deprecated use {@link #detailedSynopsis(int, Comparator, boolean)} instead. */
  9698. @Deprecated public String detailedSynopsis(Comparator<OptionSpec> optionSort, boolean clusterBooleanOptions) {
  9699. return detailedSynopsis(0, optionSort, clusterBooleanOptions);
  9700. }
  9701. /** Generates a detailed synopsis message showing all options and parameters. Follows the unix convention of
  9702. * showing optional options and parameters in square brackets ({@code [ ]}).
  9703. * @param synopsisHeadingLength the length of the synopsis heading that will be displayed on the same line
  9704. * @param optionSort comparator to sort options or {@code null} if options should not be sorted
  9705. * @param clusterBooleanOptions {@code true} if boolean short options should be clustered into a single string
  9706. * @return a detailed synopsis
  9707. * @since 3.0 */
  9708. public String detailedSynopsis(int synopsisHeadingLength, Comparator<OptionSpec> optionSort, boolean clusterBooleanOptions) {
  9709. Set<ArgSpec> argsInGroups = new HashSet<ArgSpec>();
  9710. Text groupsText = createDetailedSynopsisGroupsText(argsInGroups);
  9711. Text optionText = createDetailedSynopsisOptionsText(argsInGroups, optionSort, clusterBooleanOptions);
  9712. Text positionalParamText = createDetailedSynopsisPositionalsText(argsInGroups);
  9713. Text commandText = createDetailedSynopsisCommandText();
  9714. Text text = groupsText.concat(optionText).concat(positionalParamText).concat(commandText);
  9715. return insertSynopsisCommandName(synopsisHeadingLength, text);
  9716. }
  9717. /** Returns a Text object containing a partial detailed synopsis showing only the options and positional parameters in
  9718. * the specified {@linkplain ArgGroup#validate() validating} {@linkplain ArgGroup groups}, starting with a {@code " "} space.
  9719. * @param outparam_groupArgs all options and positional parameters in the groups this method generates a synopsis for;
  9720. * these options and positional parameters should be excluded from appearing elsewhere in the synopsis
  9721. * @return the formatted groups synopsis elements, starting with a {@code " "} space, or an empty Text if this command has no validating groups
  9722. * @since 4.0 */
  9723. protected Text createDetailedSynopsisGroupsText(Set<ArgSpec> outparam_groupArgs) {
  9724. Set<ArgGroupSpec> remove = new HashSet<ArgGroupSpec>();
  9725. List<ArgGroupSpec> groups = new ArrayList<ArgGroupSpec>(commandSpec().argGroups());
  9726. for (ArgGroupSpec group : groups) {
  9727. if (group.validate()) {
  9728. // remove subgroups
  9729. remove.addAll(group.subgroups());
  9730. // exclude options and positional parameters in this group
  9731. outparam_groupArgs.addAll(group.args());
  9732. // exclude options and positional parameters in the subgroups
  9733. for (ArgGroupSpec subgroup : group.subgroups()) {
  9734. outparam_groupArgs.addAll(subgroup.args());
  9735. }
  9736. } else {
  9737. remove.add(group); // non-validating groups should not impact synopsis
  9738. }
  9739. }
  9740. groups.removeAll(remove);
  9741. Text groupText = ansi().new Text(0);
  9742. for (ArgGroupSpec group : groups) {
  9743. groupText = groupText.concat(" ").concat(group.synopsisText(colorScheme()));
  9744. }
  9745. return groupText;
  9746. }
  9747. /** Returns a Text object containing a partial detailed synopsis showing only the options, starting with a {@code " "} space.
  9748. * Follows the unix convention of showing optional options and parameters in square brackets ({@code [ ]}).
  9749. * @param done the list of options and positional parameters for which a synopsis was already generated. Options in this set should be excluded.
  9750. * @param optionSort comparator to sort options or {@code null} if options should not be sorted
  9751. * @param clusterBooleanOptions {@code true} if boolean short options should be clustered into a single string
  9752. * @return the formatted options, starting with a {@code " "} space, or an empty Text if this command has no named options
  9753. * @since 3.9 */
  9754. protected Text createDetailedSynopsisOptionsText(Collection<ArgSpec> done, Comparator<OptionSpec> optionSort, boolean clusterBooleanOptions) {
  9755. Text optionText = ansi().new Text(0);
  9756. List<OptionSpec> options = new ArrayList<OptionSpec>(commandSpec.options()); // iterate in declaration order
  9757. if (optionSort != null) {
  9758. Collections.sort(options, optionSort);// iterate in specified sort order
  9759. }
  9760. options.removeAll(done);
  9761. if (clusterBooleanOptions) { // cluster all short boolean options into a single string
  9762. List<OptionSpec> booleanOptions = new ArrayList<OptionSpec>();
  9763. StringBuilder clusteredRequired = new StringBuilder("-");
  9764. StringBuilder clusteredOptional = new StringBuilder("-");
  9765. for (OptionSpec option : options) {
  9766. if (option.hidden()) { continue; }
  9767. boolean isFlagOption = option.typeInfo().isBoolean();
  9768. if (isFlagOption && option.arity().max <= 0) { // #612 consider arity: boolean options may require a parameter
  9769. String shortestName = option.shortestName();
  9770. if (shortestName.length() == 2 && shortestName.startsWith("-")) {
  9771. booleanOptions.add(option);
  9772. if (option.required()) {
  9773. clusteredRequired.append(shortestName.substring(1));
  9774. } else {
  9775. clusteredOptional.append(shortestName.substring(1));
  9776. }
  9777. }
  9778. }
  9779. }
  9780. options.removeAll(booleanOptions);
  9781. if (clusteredRequired.length() > 1) { // initial length was 1
  9782. optionText = optionText.concat(" ").concat(colorScheme.optionText(clusteredRequired.toString()));
  9783. }
  9784. if (clusteredOptional.length() > 1) { // initial length was 1
  9785. optionText = optionText.concat(" [").concat(colorScheme.optionText(clusteredOptional.toString())).concat("]");
  9786. }
  9787. }
  9788. for (OptionSpec option : options) {
  9789. if (!option.hidden()) {
  9790. Text name = colorScheme.optionText(option.shortestName());
  9791. Text param = parameterLabelRenderer().renderParameterLabel(option, colorScheme.ansi(), colorScheme.optionParamStyles);
  9792. if (option.required()) { // e.g., -x=VAL
  9793. optionText = optionText.concat(" ").concat(name).concat(param).concat("");
  9794. if (option.isMultiValue()) { // e.g., -x=VAL [-x=VAL]...
  9795. optionText = optionText.concat(" [").concat(name).concat(param).concat("]...");
  9796. }
  9797. } else {
  9798. optionText = optionText.concat(" [").concat(name).concat(param).concat("]");
  9799. if (option.isMultiValue()) { // add ellipsis to show option is repeatable
  9800. optionText = optionText.concat("...");
  9801. }
  9802. }
  9803. }
  9804. }
  9805. return optionText;
  9806. }
  9807. /** Returns a Text object containing a partial detailed synopsis showing only the positional parameters, starting with a {@code " "} space.
  9808. * Follows the unix convention of showing optional options and parameters in square brackets ({@code [ ]}).
  9809. * @param done the list of options and positional parameters for which a synopsis was already generated. Positional parameters in this set should be excluded.
  9810. * @return the formatted positional parameters, starting with a {@code " "} space, or an empty Text if this command has no positional parameters
  9811. * @since 3.9 */
  9812. protected Text createDetailedSynopsisPositionalsText(Collection<ArgSpec> done) {
  9813. Text positionalParamText = ansi().new Text(0);
  9814. List<PositionalParamSpec> positionals = new ArrayList<PositionalParamSpec>(commandSpec.positionalParameters()); // iterate in declaration order
  9815. positionals.removeAll(done);
  9816. for (PositionalParamSpec positionalParam : positionals) {
  9817. if (!positionalParam.hidden()) {
  9818. positionalParamText = positionalParamText.concat(" ");
  9819. Text label = parameterLabelRenderer().renderParameterLabel(positionalParam, colorScheme.ansi(), colorScheme.parameterStyles);
  9820. positionalParamText = positionalParamText.concat(label);
  9821. }
  9822. }
  9823. return positionalParamText;
  9824. }
  9825. /** Returns a Text object containing a partial detailed synopsis showing only the subcommands, starting with a {@code " "} space.
  9826. * Follows the unix convention of showing optional elements in square brackets ({@code [ ]}).
  9827. * @return this implementation returns a hard-coded string {@code " [COMMAND]"} if this command has subcommands, an empty Text otherwise
  9828. * @since 3.9 */
  9829. protected Text createDetailedSynopsisCommandText() {
  9830. Text commandText = ansi().new Text(0);
  9831. if (!commandSpec.subcommands().isEmpty()){
  9832. commandText = commandText.concat(" [")
  9833. .concat("COMMAND")
  9834. .concat("]");
  9835. }
  9836. return commandText;
  9837. }
  9838. /**
  9839. * Returns the detailed synopsis text by inserting the command name before the specified text with options and positional parameters details.
  9840. * @param synopsisHeadingLength length of the synopsis heading string to be displayed on the same line as the first synopsis line.
  9841. * For example, if the synopsis heading is {@code "Usage: "}, this value is 7.
  9842. * @param optionsAndPositionalsAndCommandsDetails formatted string with options, positional parameters and subcommands.
  9843. * Follows the unix convention of showing optional options and parameters in square brackets ({@code [ ]}).
  9844. * @return the detailed synopsis text, in multiple lines if the length exceeds the usage width
  9845. */
  9846. protected String insertSynopsisCommandName(int synopsisHeadingLength, Text optionsAndPositionalsAndCommandsDetails) {
  9847. // Fix for #142: first line of synopsis overshoots max. characters
  9848. String commandName = commandSpec.qualifiedName();
  9849. int firstColumnLength = commandName.length() + synopsisHeadingLength;
  9850. // synopsis heading ("Usage: ") may be on the same line, so adjust column width
  9851. TextTable textTable = TextTable.forColumnWidths(ansi(), firstColumnLength, width() - firstColumnLength);
  9852. textTable.indentWrappedLines = 1; // don't worry about first line: options (2nd column) always start with a space
  9853. // right-adjust the command name by length of synopsis heading
  9854. Text PADDING = Ansi.OFF.new Text(stringOf('X', synopsisHeadingLength));
  9855. textTable.addRowValues(PADDING.concat(colorScheme.commandText(commandName)), optionsAndPositionalsAndCommandsDetails);
  9856. return textTable.toString().substring(synopsisHeadingLength); // cut off leading synopsis heading spaces
  9857. }
  9858. /** Returns the number of characters the synopsis heading will take on the same line as the synopsis.
  9859. * @return the number of characters the synopsis heading will take on the same line as the synopsis.
  9860. * @see #detailedSynopsis(int, Comparator, boolean)
  9861. */
  9862. public int synopsisHeadingLength() {
  9863. String[] lines = Ansi.OFF.new Text(commandSpec.usageMessage().synopsisHeading()).toString().split("\\r?\\n|\\r|%n", -1);
  9864. return lines[lines.length - 1].length();
  9865. }
  9866. /**
  9867. * <p>Returns a description of the {@linkplain Option options} supported by the application.
  9868. * This implementation {@linkplain #createShortOptionNameComparator() sorts options alphabetically}, and shows
  9869. * only the {@linkplain Option#hidden() non-hidden} options in a {@linkplain TextTable tabular format}
  9870. * using the {@linkplain #createDefaultOptionRenderer() default renderer} and {@linkplain Layout default layout}.</p>
  9871. * @return the fully formatted option list
  9872. * @see #optionList(Layout, Comparator, IParamLabelRenderer)
  9873. */
  9874. public String optionList() {
  9875. Comparator<OptionSpec> sortOrder = commandSpec.usageMessage().sortOptions()
  9876. ? createShortOptionNameComparator()
  9877. : createOrderComparatorIfNecessary(commandSpec.options());
  9878. return optionList(createLayout(calcLongOptionColumnWidth()), sortOrder, parameterLabelRenderer());
  9879. }
  9880. private static Comparator<OptionSpec> createOrderComparatorIfNecessary(List<OptionSpec> options) {
  9881. for (OptionSpec option : options) { if (option.order() != OptionSpec.DEFAULT_ORDER) { return createOrderComparator(); } }
  9882. return null;
  9883. }
  9884. private int calcLongOptionColumnWidth() {
  9885. int max = 0;
  9886. IOptionRenderer optionRenderer = new DefaultOptionRenderer(false, " ");
  9887. for (OptionSpec option : commandSpec.options()) {
  9888. Text[][] values = optionRenderer.render(option, parameterLabelRenderer(), colorScheme);
  9889. int len = values[0][3].length;
  9890. if (len < Help.defaultOptionsColumnWidth - 3) { max = Math.max(max, len); }
  9891. }
  9892. IParameterRenderer paramRenderer = new DefaultParameterRenderer(false, " ");
  9893. for (PositionalParamSpec positional : commandSpec.positionalParameters()) {
  9894. Text[][] values = paramRenderer.render(positional, parameterLabelRenderer(), colorScheme);
  9895. int len = values[0][3].length;
  9896. if (len < Help.defaultOptionsColumnWidth - 3) { max = Math.max(max, len); }
  9897. }
  9898. return max + 3;
  9899. }
  9900. /** Sorts all {@code Options} with the specified {@code comparator} (if the comparator is non-{@code null}),
  9901. * then {@linkplain Layout#addOption(CommandLine.Model.OptionSpec, CommandLine.Help.IParamLabelRenderer) adds} all non-hidden options to the
  9902. * specified TextTable and returns the result of TextTable.toString().
  9903. * @param layout responsible for rendering the option list
  9904. * @param valueLabelRenderer used for options with a parameter
  9905. * @return the fully formatted option list
  9906. * @since 3.0 */
  9907. public String optionList(Layout layout, Comparator<OptionSpec> optionSort, IParamLabelRenderer valueLabelRenderer) {
  9908. List<OptionSpec> options = new ArrayList<OptionSpec>(commandSpec.options()); // options are stored in order of declaration
  9909. if (optionSort != null) {
  9910. Collections.sort(options, optionSort); // default: sort options ABC
  9911. }
  9912. List<ArgGroupSpec> groups = optionListGroups();
  9913. for (ArgGroupSpec group : groups) { options.removeAll(group.options()); }
  9914. StringBuilder sb = new StringBuilder();
  9915. layout.addOptions(options, valueLabelRenderer);
  9916. sb.append(layout.toString());
  9917. int longOptionColumnWidth = calcLongOptionColumnWidth();
  9918. Collections.sort(groups, new SortByOrder<ArgGroupSpec>());
  9919. for (ArgGroupSpec group : groups) {
  9920. sb.append(heading(ansi(), width(), group.heading()));
  9921. Layout groupLayout = createLayout(longOptionColumnWidth);
  9922. groupLayout.addPositionalParameters(group.positionalParameters(), valueLabelRenderer);
  9923. List<OptionSpec> groupOptions = new ArrayList<OptionSpec>(group.options());
  9924. if (optionSort != null) {
  9925. Collections.sort(groupOptions, optionSort);
  9926. }
  9927. groupLayout.addOptions(groupOptions, valueLabelRenderer);
  9928. sb.append(groupLayout);
  9929. }
  9930. return sb.toString();
  9931. }
  9932. /** Returns the list of {@code ArgGroupSpec}s with a non-{@code null} heading. */
  9933. private List<ArgGroupSpec> optionListGroups() {
  9934. List<ArgGroupSpec> result = new ArrayList<ArgGroupSpec>();
  9935. optionListGroups(commandSpec.argGroups(), result);
  9936. return result;
  9937. }
  9938. private static void optionListGroups(List<ArgGroupSpec> groups, List<ArgGroupSpec> result) {
  9939. for (ArgGroupSpec group : groups) {
  9940. optionListGroups(group.subgroups(), result);
  9941. if (group.heading() != null) { result.add(group); }
  9942. }
  9943. }
  9944. /**
  9945. * Returns the section of the usage help message that lists the parameters with their descriptions.
  9946. * @return the section of the usage help message that lists the parameters
  9947. */
  9948. public String parameterList() {
  9949. return parameterList(createLayout(calcLongOptionColumnWidth()), parameterLabelRenderer());
  9950. }
  9951. /**
  9952. * Returns the section of the usage help message that lists the parameters with their descriptions.
  9953. * @param layout the layout to use
  9954. * @param paramLabelRenderer for rendering parameter names
  9955. * @return the section of the usage help message that lists the parameters
  9956. */
  9957. public String parameterList(Layout layout, IParamLabelRenderer paramLabelRenderer) {
  9958. List<PositionalParamSpec> positionals = new ArrayList<PositionalParamSpec>(commandSpec.positionalParameters());
  9959. List<ArgGroupSpec> groups = optionListGroups();
  9960. for (ArgGroupSpec group : groups) { positionals.removeAll(group.positionalParameters()); }
  9961. layout.addPositionalParameters(positionals, paramLabelRenderer);
  9962. return layout.toString();
  9963. }
  9964. private static String heading(Ansi ansi, int usageWidth, String values, Object... params) {
  9965. StringBuilder sb = join(ansi, usageWidth, new String[] {values}, new StringBuilder(), params);
  9966. return trimLineSeparator(sb.toString()) + new String(spaces(countTrailingSpaces(values)));
  9967. }
  9968. static String trimLineSeparator(String result) {
  9969. return result.endsWith(System.getProperty("line.separator"))
  9970. ? result.substring(0, result.length() - System.getProperty("line.separator").length()) : result;
  9971. }
  9972. private static char[] spaces(int length) { char[] result = new char[length]; Arrays.fill(result, ' '); return result; }
  9973. private static int countTrailingSpaces(String str) {
  9974. if (str == null) {return 0;}
  9975. int trailingSpaces = 0;
  9976. for (int i = str.length() - 1; i >= 0 && str.charAt(i) == ' '; i--) { trailingSpaces++; }
  9977. return trailingSpaces;
  9978. }
  9979. /** Formats each of the specified values and appends it to the specified StringBuilder.
  9980. * @param ansi whether the result should contain ANSI escape codes or not
  9981. * @param usageHelpWidth the width of the usage help message
  9982. * @param values the values to format and append to the StringBuilder
  9983. * @param sb the StringBuilder to collect the formatted strings
  9984. * @param params the parameters to pass to the format method when formatting each value
  9985. * @return the specified StringBuilder */
  9986. public static StringBuilder join(Ansi ansi, int usageHelpWidth, String[] values, StringBuilder sb, Object... params) {
  9987. if (values != null) {
  9988. TextTable table = TextTable.forColumnWidths(ansi, usageHelpWidth);
  9989. table.indentWrappedLines = 0;
  9990. for (String summaryLine : values) {
  9991. Text[] lines = ansi.new Text(format(summaryLine, params)).splitLines();
  9992. for (Text line : lines) { table.addRowValues(line); }
  9993. }
  9994. table.toString(sb);
  9995. }
  9996. return sb;
  9997. }
  9998. private int width() { return commandSpec.usageMessage().width(); }
  9999. /** Returns command custom synopsis as a string. A custom synopsis can be zero or more lines, and can be
  10000. * specified declaratively with the {@link Command#customSynopsis()} annotation attribute or programmatically
  10001. * by setting the Help instance's {@link Help#customSynopsis} field.
  10002. * @param params Arguments referenced by the format specifiers in the synopsis strings
  10003. * @return the custom synopsis lines combined into a single String (which may be empty)
  10004. */
  10005. public String customSynopsis(Object... params) {
  10006. return join(ansi(), width(), commandSpec.usageMessage().customSynopsis(), new StringBuilder(), params).toString();
  10007. }
  10008. /** Returns command description text as a string. Description text can be zero or more lines, and can be specified
  10009. * declaratively with the {@link Command#description()} annotation attribute or programmatically by
  10010. * setting the Help instance's {@link Help#description} field.
  10011. * @param params Arguments referenced by the format specifiers in the description strings
  10012. * @return the description lines combined into a single String (which may be empty)
  10013. */
  10014. public String description(Object... params) {
  10015. return join(ansi(), width(), commandSpec.usageMessage().description(), new StringBuilder(), params).toString();
  10016. }
  10017. /** Returns the command header text as a string. Header text can be zero or more lines, and can be specified
  10018. * declaratively with the {@link Command#header()} annotation attribute or programmatically by
  10019. * setting the Help instance's {@link Help#header} field.
  10020. * @param params Arguments referenced by the format specifiers in the header strings
  10021. * @return the header lines combined into a single String (which may be empty)
  10022. */
  10023. public String header(Object... params) {
  10024. return join(ansi(), width(), commandSpec.usageMessage().header(), new StringBuilder(), params).toString();
  10025. }
  10026. /** Returns command footer text as a string. Footer text can be zero or more lines, and can be specified
  10027. * declaratively with the {@link Command#footer()} annotation attribute or programmatically by
  10028. * setting the Help instance's {@link Help#footer} field.
  10029. * @param params Arguments referenced by the format specifiers in the footer strings
  10030. * @return the footer lines combined into a single String (which may be empty)
  10031. */
  10032. public String footer(Object... params) {
  10033. return join(ansi(), width(), commandSpec.usageMessage().footer(), new StringBuilder(), params).toString();
  10034. }
  10035. /** Returns the text displayed before the header text; the result of {@code String.format(headerHeading, params)}.
  10036. * @param params the parameters to use to format the header heading
  10037. * @return the formatted header heading */
  10038. public String headerHeading(Object... params) {
  10039. return heading(ansi(), width(), commandSpec.usageMessage().headerHeading(), params);
  10040. }
  10041. /** Returns the text displayed before the synopsis text; the result of {@code String.format(synopsisHeading, params)}.
  10042. * @param params the parameters to use to format the synopsis heading
  10043. * @return the formatted synopsis heading */
  10044. public String synopsisHeading(Object... params) {
  10045. return heading(ansi(), width(), commandSpec.usageMessage().synopsisHeading(), params);
  10046. }
  10047. /** Returns the text displayed before the description text; an empty string if there is no description,
  10048. * otherwise the result of {@code String.format(descriptionHeading, params)}.
  10049. * @param params the parameters to use to format the description heading
  10050. * @return the formatted description heading */
  10051. public String descriptionHeading(Object... params) {
  10052. return empty(commandSpec.usageMessage().descriptionHeading()) ? "" : heading(ansi(), width(), commandSpec.usageMessage().descriptionHeading(), params);
  10053. }
  10054. /** Returns the text displayed before the positional parameter list; an empty string if there are no positional
  10055. * parameters, otherwise the result of {@code String.format(parameterListHeading, params)}.
  10056. * @param params the parameters to use to format the parameter list heading
  10057. * @return the formatted parameter list heading */
  10058. public String parameterListHeading(Object... params) {
  10059. return commandSpec.positionalParameters().isEmpty() ? "" : heading(ansi(), width(), commandSpec.usageMessage().parameterListHeading(), params);
  10060. }
  10061. /** Returns the text displayed before the option list; an empty string if there are no options,
  10062. * otherwise the result of {@code String.format(optionListHeading, params)}.
  10063. * @param params the parameters to use to format the option list heading
  10064. * @return the formatted option list heading */
  10065. public String optionListHeading(Object... params) {
  10066. return commandSpec.optionsMap().isEmpty() ? "" : heading(ansi(), width(), commandSpec.usageMessage().optionListHeading(), params);
  10067. }
  10068. /** Returns the text displayed before the command list; an empty string if there are no commands,
  10069. * otherwise the result of {@code String.format(commandListHeading, params)}.
  10070. * @param params the parameters to use to format the command list heading
  10071. * @return the formatted command list heading */
  10072. public String commandListHeading(Object... params) {
  10073. return commands.isEmpty() ? "" : heading(ansi(), width(), commandSpec.usageMessage().commandListHeading(), params);
  10074. }
  10075. /** Returns the text displayed before the footer text; the result of {@code String.format(footerHeading, params)}.
  10076. * @param params the parameters to use to format the footer heading
  10077. * @return the formatted footer heading */
  10078. public String footerHeading(Object... params) {
  10079. return heading(ansi(), width(), commandSpec.usageMessage().footerHeading(), params);
  10080. }
  10081. /** Returns a 2-column list with command names and the first line of their header or (if absent) description.
  10082. * @return a usage help section describing the added commands */
  10083. public String commandList() {
  10084. if (subcommands().isEmpty()) { return ""; }
  10085. int commandLength = maxLength(subcommands().keySet());
  10086. Help.TextTable textTable = Help.TextTable.forColumns(ansi(),
  10087. new Help.Column(commandLength + 2, 2, Help.Column.Overflow.SPAN),
  10088. new Help.Column(width() - (commandLength + 2), 2, Help.Column.Overflow.WRAP));
  10089. for (Map.Entry<String, Help> entry : subcommands().entrySet()) {
  10090. Help help = entry.getValue();
  10091. UsageMessageSpec usage = help.commandSpec().usageMessage();
  10092. String header = !empty(usage.header())
  10093. ? usage.header()[0]
  10094. : (!empty(usage.description()) ? usage.description()[0] : "");
  10095. Text[] lines = ansi().text(format(header)).splitLines();
  10096. for (int i = 0; i < lines.length; i++) {
  10097. textTable.addRowValues(i == 0 ? help.commandNamesText(", ") : Ansi.EMPTY_TEXT, lines[i]);
  10098. }
  10099. }
  10100. return textTable.toString();
  10101. }
  10102. private static int maxLength(Collection<String> any) {
  10103. List<String> strings = new ArrayList<String>(any);
  10104. Collections.sort(strings, Collections.reverseOrder(Help.shortestFirst()));
  10105. return strings.get(0).length();
  10106. }
  10107. /** Returns a {@code Text} object containing the command name and all aliases, separated with the specified separator.
  10108. * Command names will use the {@link ColorScheme#commandText(String) command style} for the color scheme of this Help.
  10109. * @since 3.9 */
  10110. public Text commandNamesText(String separator) {
  10111. Text result = colorScheme().commandText(aliases().get(0));
  10112. for (int i = 1; i < aliases().size(); i++) {
  10113. result = result.concat(separator).concat(colorScheme().commandText(aliases().get(i)));
  10114. }
  10115. return result;
  10116. }
  10117. private static String join(String[] names, int offset, int length, String separator) {
  10118. if (names == null) { return ""; }
  10119. StringBuilder result = new StringBuilder();
  10120. for (int i = offset; i < offset + length; i++) {
  10121. result.append((i > offset) ? separator : "").append(names[i]);
  10122. }
  10123. return result.toString();
  10124. }
  10125. private static String stringOf(char chr, int length) {
  10126. char[] buff = new char[length];
  10127. Arrays.fill(buff, chr);
  10128. return new String(buff);
  10129. }
  10130. /** Returns a {@code Layout} instance configured with the user preferences captured in this Help instance.
  10131. * @return a Layout */
  10132. public Layout createDefaultLayout() {
  10133. return createLayout(Help.defaultOptionsColumnWidth);
  10134. }
  10135. private Layout createLayout(int longOptionsColumnWidth) {
  10136. return new Layout(colorScheme, TextTable.forDefaultColumns(colorScheme.ansi(), longOptionsColumnWidth, width()), createDefaultOptionRenderer(), createDefaultParameterRenderer());
  10137. }
  10138. /** Returns a new default OptionRenderer which converts {@link OptionSpec Options} to five columns of text to match
  10139. * the default {@linkplain TextTable TextTable} column layout. The first row of values looks like this:
  10140. * <ol>
  10141. * <li>the required option marker</li>
  10142. * <li>2-character short option name (or empty string if no short option exists)</li>
  10143. * <li>comma separator (only if both short option and long option exist, empty string otherwise)</li>
  10144. * <li>comma-separated string with long option name(s)</li>
  10145. * <li>first element of the {@link OptionSpec#description()} array</li>
  10146. * </ol>
  10147. * <p>Following this, there will be one row for each of the remaining elements of the {@link
  10148. * OptionSpec#description()} array, and these rows look like {@code {"", "", "", "", option.description()[i]}}.</p>
  10149. * <p>If configured, this option renderer adds an additional row to display the default field value.</p>
  10150. * @return a new default OptionRenderer
  10151. */
  10152. public IOptionRenderer createDefaultOptionRenderer() {
  10153. return new DefaultOptionRenderer(commandSpec.usageMessage.showDefaultValues(), "" +commandSpec.usageMessage().requiredOptionMarker());
  10154. }
  10155. /** Returns a new minimal OptionRenderer which converts {@link OptionSpec Options} to a single row with two columns
  10156. * of text: an option name and a description. If multiple names or descriptions exist, the first value is used.
  10157. * @return a new minimal OptionRenderer */
  10158. public static IOptionRenderer createMinimalOptionRenderer() {
  10159. return new MinimalOptionRenderer();
  10160. }
  10161. /** Returns a new default ParameterRenderer which converts {@linkplain PositionalParamSpec positional parameters} to four columns of
  10162. * text to match the default {@linkplain TextTable TextTable} column layout. The first row of values looks like this:
  10163. * <ol>
  10164. * <li>empty string </li>
  10165. * <li>empty string </li>
  10166. * <li>parameter(s) label as rendered by the {@link IParamLabelRenderer}</li>
  10167. * <li>first element of the {@link PositionalParamSpec#description()} array</li>
  10168. * </ol>
  10169. * <p>Following this, there will be one row for each of the remaining elements of the {@link
  10170. * PositionalParamSpec#description()} array, and these rows look like {@code {"", "", "", param.description()[i]}}.</p>
  10171. * <p>If configured, this parameter renderer adds an additional row to display the default field value.</p>
  10172. * @return a new default ParameterRenderer
  10173. */
  10174. public IParameterRenderer createDefaultParameterRenderer() {
  10175. return new DefaultParameterRenderer(commandSpec.usageMessage.showDefaultValues(), "" + commandSpec.usageMessage().requiredOptionMarker());
  10176. }
  10177. /** Returns a new minimal ParameterRenderer which converts {@linkplain PositionalParamSpec positional parameters}
  10178. * to a single row with two columns of text: an option name and a description. If multiple descriptions exist, the first value is used.
  10179. * @return a new minimal ParameterRenderer */
  10180. public static IParameterRenderer createMinimalParameterRenderer() {
  10181. return new MinimalParameterRenderer();
  10182. }
  10183. /** Returns a value renderer that returns the {@code paramLabel} if defined or the field name otherwise.
  10184. * @return a new minimal ParamLabelRenderer */
  10185. public static IParamLabelRenderer createMinimalParamLabelRenderer() {
  10186. return new IParamLabelRenderer() {
  10187. public Text renderParameterLabel(ArgSpec argSpec, Ansi ansi, List<IStyle> styles) {
  10188. return ansi.apply(argSpec.paramLabel(), styles);
  10189. }
  10190. public String separator() { return ""; }
  10191. };
  10192. }
  10193. /** Returns a new default param label renderer that separates option parameters from their option name
  10194. * with the specified separator string, and, unless {@link ArgSpec#hideParamSyntax()} is true,
  10195. * surrounds optional parameters with {@code '['} and {@code ']'}
  10196. * characters and uses ellipses ("...") to indicate that any number of a parameter are allowed.
  10197. * @return a new default ParamLabelRenderer
  10198. */
  10199. public IParamLabelRenderer createDefaultParamLabelRenderer() {
  10200. return new DefaultParamLabelRenderer(commandSpec);
  10201. }
  10202. /** Sorts {@link OptionSpec OptionSpecs} by their option name in case-insensitive alphabetic order. If an
  10203. * option has multiple names, the shortest name is used for the sorting. Help options follow non-help options.
  10204. * @return a comparator that sorts OptionSpecs by their option name in case-insensitive alphabetic order */
  10205. public static Comparator<OptionSpec> createShortOptionNameComparator() {
  10206. return new SortByShortestOptionNameAlphabetically();
  10207. }
  10208. /** Sorts {@link OptionSpec OptionSpecs} by their option {@linkplain Range#max max arity} first, by
  10209. * {@linkplain Range#min min arity} next, and by {@linkplain #createShortOptionNameComparator() option name} last.
  10210. * @return a comparator that sorts OptionSpecs by arity first, then their option name */
  10211. public static Comparator<OptionSpec> createShortOptionArityAndNameComparator() {
  10212. return new SortByOptionArityAndNameAlphabetically();
  10213. }
  10214. /** Sorts short strings before longer strings.
  10215. * @return a comparators that sorts short strings before longer strings */
  10216. public static Comparator<String> shortestFirst() { return new ShortestFirst(); }
  10217. /** Sorts {@link OptionSpec options} by their option {@linkplain IOrdered#order() order}, lowest first, highest last.
  10218. * @return a comparator that sorts OptionSpecs by their order
  10219. * @since 3.9*/
  10220. static Comparator<OptionSpec> createOrderComparator() {
  10221. return new SortByOrder<OptionSpec>();
  10222. }
  10223. /** Returns whether ANSI escape codes are enabled or not.
  10224. * @return whether ANSI escape codes are enabled or not
  10225. */
  10226. public Ansi ansi() { return colorScheme.ansi; }
  10227. /** Controls the visibility of certain aspects of the usage help message. */
  10228. public enum Visibility { ALWAYS, NEVER, ON_DEMAND }
  10229. /** When customizing online help for {@link OptionSpec Option} details, a custom {@code IOptionRenderer} can be
  10230. * used to create textual representation of an Option in a tabular format: one or more rows, each containing
  10231. * one or more columns. The {@link Layout Layout} is responsible for placing these text values in the
  10232. * {@link TextTable TextTable}. */
  10233. public interface IOptionRenderer {
  10234. /**
  10235. * Returns a text representation of the specified option and its parameter(s) if any.
  10236. * @param option the command line option to show online usage help for
  10237. * @param parameterLabelRenderer responsible for rendering option parameters to text
  10238. * @param scheme color scheme for applying ansi color styles to options and option parameters
  10239. * @return a 2-dimensional array of text values: one or more rows, each containing one or more columns
  10240. * @since 3.0
  10241. */
  10242. Text[][] render(OptionSpec option, IParamLabelRenderer parameterLabelRenderer, ColorScheme scheme);
  10243. }
  10244. /** The DefaultOptionRenderer converts {@link OptionSpec Options} to five columns of text to match the default
  10245. * {@linkplain TextTable TextTable} column layout. The first row of values looks like this:
  10246. * <ol>
  10247. * <li>the required option marker (if the option is required)</li>
  10248. * <li>2-character short option name (or empty string if no short option exists)</li>
  10249. * <li>comma separator (only if both short option and long option exist, empty string otherwise)</li>
  10250. * <li>comma-separated string with long option name(s)</li>
  10251. * <li>first element of the {@link OptionSpec#description()} array</li>
  10252. * </ol>
  10253. * <p>Following this, there will be one row for each of the remaining elements of the {@link
  10254. * OptionSpec#description()} array, and these rows look like {@code {"", "", "", option.description()[i]}}.</p>
  10255. */
  10256. static class DefaultOptionRenderer implements IOptionRenderer {
  10257. private String requiredMarker = " ";
  10258. private boolean showDefaultValues;
  10259. private String sep;
  10260. public DefaultOptionRenderer(boolean showDefaultValues, String requiredMarker) {
  10261. this.showDefaultValues = showDefaultValues;
  10262. this.requiredMarker = Assert.notNull(requiredMarker, "requiredMarker");
  10263. }
  10264. public Text[][] render(OptionSpec option, IParamLabelRenderer paramLabelRenderer, ColorScheme scheme) {
  10265. String[] names = ShortestFirst.sort(option.names());
  10266. int shortOptionCount = names[0].length() == 2 ? 1 : 0;
  10267. String shortOption = shortOptionCount > 0 ? names[0] : "";
  10268. sep = shortOptionCount > 0 && names.length > 1 ? "," : "";
  10269. String longOption = join(names, shortOptionCount, names.length - shortOptionCount, ", ");
  10270. Text longOptionText = createLongOptionText(option, paramLabelRenderer, scheme, longOption);
  10271. String requiredOption = option.required() ? requiredMarker : "";
  10272. return renderDescriptionLines(option, scheme, requiredOption, shortOption, longOptionText);
  10273. }
  10274. private Text createLongOptionText(OptionSpec option, IParamLabelRenderer renderer, ColorScheme scheme, String longOption) {
  10275. Text paramLabelText = renderer.renderParameterLabel(option, scheme.ansi(), scheme.optionParamStyles);
  10276. // if no long option, fill in the space between the short option name and the param label value
  10277. if (paramLabelText.length > 0 && longOption.length() == 0) {
  10278. sep = renderer.separator();
  10279. // #181 paramLabelText may be =LABEL or [=LABEL...]
  10280. int sepStart = paramLabelText.plainString().indexOf(sep);
  10281. Text prefix = paramLabelText.substring(0, sepStart);
  10282. paramLabelText = prefix.concat(paramLabelText.substring(sepStart + sep.length()));
  10283. }
  10284. Text longOptionText = scheme.optionText(longOption);
  10285. longOptionText = longOptionText.concat(paramLabelText);
  10286. return longOptionText;
  10287. }
  10288. private Text[][] renderDescriptionLines(OptionSpec option,
  10289. ColorScheme scheme,
  10290. String requiredOption,
  10291. String shortOption,
  10292. Text longOptionText) {
  10293. Text EMPTY = Ansi.EMPTY_TEXT;
  10294. boolean[] showDefault = {option.internalShowDefaultValue(showDefaultValues)};
  10295. List<Text[]> result = new ArrayList<Text[]>();
  10296. String[] description = option.renderedDescription();
  10297. Text[] descriptionFirstLines = createDescriptionFirstLines(scheme, option, description, showDefault);
  10298. result.add(new Text[] { scheme.optionText(requiredOption), scheme.optionText(shortOption),
  10299. scheme.ansi().new Text(sep), longOptionText, descriptionFirstLines[0] });
  10300. for (int i = 1; i < descriptionFirstLines.length; i++) {
  10301. result.add(new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, descriptionFirstLines[i] });
  10302. }
  10303. for (int i = 1; i < description.length; i++) {
  10304. Text[] descriptionNextLines = scheme.ansi().new Text(description[i]).splitLines();
  10305. for (Text line : descriptionNextLines) {
  10306. result.add(new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, line });
  10307. }
  10308. }
  10309. if (showDefault[0]) { addTrailingDefaultLine(result, option, scheme); }
  10310. return result.toArray(new Text[result.size()][]);
  10311. }
  10312. }
  10313. /** The MinimalOptionRenderer converts {@link OptionSpec Options} to a single row with two columns of text: an
  10314. * option name and a description. If multiple names or description lines exist, the first value is used. */
  10315. static class MinimalOptionRenderer implements IOptionRenderer {
  10316. public Text[][] render(OptionSpec option, IParamLabelRenderer parameterLabelRenderer, ColorScheme scheme) {
  10317. Text optionText = scheme.optionText(option.names()[0]);
  10318. Text paramLabelText = parameterLabelRenderer.renderParameterLabel(option, scheme.ansi(), scheme.optionParamStyles);
  10319. optionText = optionText.concat(paramLabelText);
  10320. return new Text[][] {{ optionText,
  10321. scheme.ansi().new Text(option.description().length == 0 ? "" : option.description()[0]) }};
  10322. }
  10323. }
  10324. /** The MinimalParameterRenderer converts {@linkplain PositionalParamSpec positional parameters} to a single row with two columns of
  10325. * text: the parameters label and a description. If multiple description lines exist, the first value is used. */
  10326. static class MinimalParameterRenderer implements IParameterRenderer {
  10327. public Text[][] render(PositionalParamSpec param, IParamLabelRenderer parameterLabelRenderer, ColorScheme scheme) {
  10328. return new Text[][] {{ parameterLabelRenderer.renderParameterLabel(param, scheme.ansi(), scheme.parameterStyles),
  10329. scheme.ansi().new Text(param.description().length == 0 ? "" : param.description()[0]) }};
  10330. }
  10331. }
  10332. /** When customizing online help for {@linkplain PositionalParamSpec positional parameters} details, a custom {@code IParameterRenderer}
  10333. * can be used to create textual representation of a Parameters field in a tabular format: one or more rows,
  10334. * each containing one or more columns. The {@link Layout Layout} is responsible for placing these text
  10335. * values in the {@link TextTable TextTable}. */
  10336. public interface IParameterRenderer {
  10337. /**
  10338. * Returns a text representation of the specified positional parameter.
  10339. * @param param the positional parameter to show online usage help for
  10340. * @param parameterLabelRenderer responsible for rendering parameter labels to text
  10341. * @param scheme color scheme for applying ansi color styles to positional parameters
  10342. * @return a 2-dimensional array of text values: one or more rows, each containing one or more columns
  10343. * @since 3.0
  10344. */
  10345. Text[][] render(PositionalParamSpec param, IParamLabelRenderer parameterLabelRenderer, ColorScheme scheme);
  10346. }
  10347. /** The DefaultParameterRenderer converts {@linkplain PositionalParamSpec positional parameters} to five columns of text to match the
  10348. * default {@linkplain TextTable TextTable} column layout. The first row of values looks like this:
  10349. * <ol>
  10350. * <li>the required option marker (if the parameter's arity is to have at least one value)</li>
  10351. * <li>empty string </li>
  10352. * <li>empty string </li>
  10353. * <li>parameter(s) label as rendered by the {@link IParamLabelRenderer}</li>
  10354. * <li>first element of the {@link PositionalParamSpec#description()} array</li>
  10355. * </ol>
  10356. * <p>Following this, there will be one row for each of the remaining elements of the {@link
  10357. * PositionalParamSpec#description()} array, and these rows look like {@code {"", "", "", param.description()[i]}}.</p>
  10358. */
  10359. static class DefaultParameterRenderer implements IParameterRenderer {
  10360. private String requiredMarker = " ";
  10361. private boolean showDefaultValues;
  10362. public DefaultParameterRenderer(boolean showDefaultValues, String requiredMarker) {
  10363. this.showDefaultValues = showDefaultValues;
  10364. this.requiredMarker = Assert.notNull(requiredMarker, "requiredMarker");
  10365. }
  10366. public Text[][] render(PositionalParamSpec param, IParamLabelRenderer paramLabelRenderer, ColorScheme scheme) {
  10367. Text label = paramLabelRenderer.renderParameterLabel(param, scheme.ansi(), scheme.parameterStyles);
  10368. Text requiredParameter = scheme.parameterText(param.arity().min > 0 ? requiredMarker : "");
  10369. Text EMPTY = Ansi.EMPTY_TEXT;
  10370. boolean[] showDefault = {param.internalShowDefaultValue(showDefaultValues)};
  10371. List<Text[]> result = new ArrayList<Text[]>();
  10372. String[] description = param.renderedDescription();
  10373. Text[] descriptionFirstLines = createDescriptionFirstLines(scheme, param, description, showDefault);
  10374. result.add(new Text[] { requiredParameter, EMPTY, EMPTY, label, descriptionFirstLines[0] });
  10375. for (int i = 1; i < descriptionFirstLines.length; i++) {
  10376. result.add(new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, descriptionFirstLines[i] });
  10377. }
  10378. for (int i = 1; i < description.length; i++) {
  10379. Text[] descriptionNextLines = scheme.ansi().new Text(description[i]).splitLines();
  10380. for (Text line : descriptionNextLines) {
  10381. result.add(new Text[] { EMPTY, EMPTY, EMPTY, EMPTY, line });
  10382. }
  10383. }
  10384. if (showDefault[0]) { addTrailingDefaultLine(result, param, scheme); }
  10385. return result.toArray(new Text[result.size()][]);
  10386. }
  10387. }
  10388. private static void addTrailingDefaultLine(List<Text[]> result, ArgSpec arg, ColorScheme scheme) {
  10389. Text EMPTY = Ansi.EMPTY_TEXT;
  10390. result.add(new Text[]{EMPTY, EMPTY, EMPTY, EMPTY, scheme.ansi().new Text(" Default: " + arg.defaultValueString())});
  10391. }
  10392. private static Text[] createDescriptionFirstLines(ColorScheme scheme, ArgSpec arg, String[] description, boolean[] showDefault) {
  10393. Text[] result = scheme.ansi().new Text(str(description, 0)).splitLines();
  10394. if (result.length == 0 || (result.length == 1 && result[0].plain.length() == 0)) {
  10395. if (showDefault[0]) {
  10396. result = new Text[]{scheme.ansi().new Text(" Default: " + arg.defaultValueString())};
  10397. showDefault[0] = false; // don't show the default value twice
  10398. } else {
  10399. result = new Text[]{ Ansi.EMPTY_TEXT };
  10400. }
  10401. }
  10402. return result;
  10403. }
  10404. /** When customizing online usage help for an option parameter or a positional parameter, a custom
  10405. * {@code IParamLabelRenderer} can be used to render the parameter name or label to a String. */
  10406. public interface IParamLabelRenderer {
  10407. /** Returns a text rendering of the option parameter or positional parameter; returns an empty string
  10408. * {@code ""} if the option is a boolean and does not take a parameter.
  10409. * @param argSpec the named or positional parameter with a parameter label
  10410. * @param ansi determines whether ANSI escape codes should be emitted or not
  10411. * @param styles the styles to apply to the parameter label
  10412. * @return a text rendering of the Option parameter or positional parameter
  10413. * @since 3.0 */
  10414. Text renderParameterLabel(ArgSpec argSpec, Ansi ansi, List<IStyle> styles);
  10415. /** Returns the separator between option name and param label.
  10416. * @return the separator between option name and param label */
  10417. String separator();
  10418. }
  10419. /**
  10420. * DefaultParamLabelRenderer separates option parameters from their {@linkplain OptionSpec option names} with a
  10421. * {@linkplain CommandLine.Model.ParserSpec#separator() separator} string, and, unless
  10422. * {@link ArgSpec#hideParamSyntax()} is true, surrounds optional values with {@code '['} and {@code ']'} characters
  10423. * and uses ellipses ("...") to indicate that any number of values is allowed for options or parameters with variable arity.
  10424. */
  10425. static class DefaultParamLabelRenderer implements IParamLabelRenderer {
  10426. private final CommandSpec commandSpec;
  10427. /** Constructs a new DefaultParamLabelRenderer with the specified separator string. */
  10428. public DefaultParamLabelRenderer(CommandSpec commandSpec) {
  10429. this.commandSpec = Assert.notNull(commandSpec, "commandSpec");
  10430. }
  10431. public String separator() { return commandSpec.parser().separator(); }
  10432. public Text renderParameterLabel(ArgSpec argSpec, Ansi ansi, List<IStyle> styles) {
  10433. Range capacity = argSpec.isOption() ? argSpec.arity() : ((PositionalParamSpec)argSpec).capacity();
  10434. if (capacity.max == 0) { return ansi.new Text(""); }
  10435. if (argSpec.hideParamSyntax()) { return ansi.apply((argSpec.isOption() ? separator() : "") + argSpec.paramLabel(), styles); }
  10436. Text paramName = ansi.apply(argSpec.paramLabel(), styles);
  10437. String split = argSpec.splitRegex();
  10438. String mandatorySep = empty(split) ? " " : split;
  10439. String optionalSep = empty(split) ? " [" : "[" + split;
  10440. boolean unlimitedSplit = !empty(split) && !commandSpec.parser().limitSplit();
  10441. boolean limitedSplit = !empty(split) && commandSpec.parser().limitSplit();
  10442. Text repeating = paramName;
  10443. int paramCount = 1;
  10444. if (unlimitedSplit) {
  10445. repeating = paramName.concat("[" + split).concat(paramName).concat("...]");
  10446. paramCount++;
  10447. mandatorySep = " ";
  10448. optionalSep = " [";
  10449. }
  10450. Text result = repeating;
  10451. int done = 1;
  10452. for (; done < capacity.min; done++) {
  10453. result = result.concat(mandatorySep).concat(repeating); // " PARAM" or ",PARAM"
  10454. paramCount += paramCount;
  10455. }
  10456. if (!capacity.isVariable) {
  10457. for (int i = done; i < capacity.max; i++) {
  10458. result = result.concat(optionalSep).concat(paramName); // " [PARAM" or "[,PARAM"
  10459. paramCount++;
  10460. }
  10461. for (int i = done; i < capacity.max; i++) {
  10462. result = result.concat("]");
  10463. }
  10464. }
  10465. // show an extra trailing "[,PARAM]" if split and either max=* or splitting is not restricted to max
  10466. boolean effectivelyVariable = capacity.isVariable || (limitedSplit && paramCount == 1);
  10467. if (limitedSplit && effectivelyVariable && paramCount == 1) {
  10468. result = result.concat(optionalSep).concat(repeating).concat("]"); // PARAM[,PARAM]...
  10469. }
  10470. if (effectivelyVariable) {
  10471. if (!argSpec.arity().isVariable && argSpec.arity().min > 1) {
  10472. result = ansi.new Text("(").concat(result).concat(")"); // repeating group
  10473. }
  10474. result = result.concat("..."); // PARAM...
  10475. }
  10476. String optionSeparator = argSpec.isOption() ? separator() : "";
  10477. if (capacity.min == 0) { // optional
  10478. String sep2 = empty(optionSeparator.trim()) ? optionSeparator + "[" : "[" + optionSeparator;
  10479. result = ansi.new Text(sep2).concat(result).concat("]");
  10480. } else {
  10481. result = ansi.new Text(optionSeparator).concat(result);
  10482. }
  10483. return result;
  10484. }
  10485. }
  10486. /** Use a Layout to format usage help text for options and parameters in tabular format.
  10487. * <p>Delegates to the renderers to create {@link Text} values for the annotated fields, and uses a
  10488. * {@link TextTable} to display these values in tabular format. Layout is responsible for deciding which values
  10489. * to display where in the table. By default, Layout shows one option or parameter per table row.</p>
  10490. * <p>Customize by overriding the {@link #layout(CommandLine.Model.ArgSpec, CommandLine.Help.Ansi.Text[][])} method.</p>
  10491. * @see IOptionRenderer rendering options to text
  10492. * @see IParameterRenderer rendering parameters to text
  10493. * @see TextTable showing values in a tabular format
  10494. */
  10495. public static class Layout {
  10496. protected final ColorScheme colorScheme;
  10497. protected final TextTable table;
  10498. protected IOptionRenderer optionRenderer;
  10499. protected IParameterRenderer parameterRenderer;
  10500. /** Constructs a Layout with the specified color scheme, a new default TextTable, the
  10501. * {@linkplain Help#createDefaultOptionRenderer() default option renderer}, and the
  10502. * {@linkplain Help#createDefaultParameterRenderer() default parameter renderer}.
  10503. * @param colorScheme the color scheme to use for common, auto-generated parts of the usage help message */
  10504. public Layout(ColorScheme colorScheme, int tableWidth) { this(colorScheme, TextTable.forDefaultColumns(colorScheme.ansi(), tableWidth)); }
  10505. /** Constructs a Layout with the specified color scheme, the specified TextTable, the
  10506. * {@linkplain Help#createDefaultOptionRenderer() default option renderer}, and the
  10507. * {@linkplain Help#createDefaultParameterRenderer() default parameter renderer}.
  10508. * @param colorScheme the color scheme to use for common, auto-generated parts of the usage help message
  10509. * @param textTable the TextTable to lay out parts of the usage help message in tabular format */
  10510. public Layout(ColorScheme colorScheme, TextTable textTable) {
  10511. this(colorScheme, textTable, new DefaultOptionRenderer(false, " "), new DefaultParameterRenderer(false, " "));
  10512. }
  10513. /** Constructs a Layout with the specified color scheme, the specified TextTable, the
  10514. * specified option renderer and the specified parameter renderer.
  10515. * @param colorScheme the color scheme to use for common, auto-generated parts of the usage help message
  10516. * @param optionRenderer the object responsible for rendering Options to Text
  10517. * @param parameterRenderer the object responsible for rendering Parameters to Text
  10518. * @param textTable the TextTable to lay out parts of the usage help message in tabular format */
  10519. public Layout(ColorScheme colorScheme, TextTable textTable, IOptionRenderer optionRenderer, IParameterRenderer parameterRenderer) {
  10520. this.colorScheme = Assert.notNull(colorScheme, "colorScheme");
  10521. this.table = Assert.notNull(textTable, "textTable");
  10522. this.optionRenderer = Assert.notNull(optionRenderer, "optionRenderer");
  10523. this.parameterRenderer = Assert.notNull(parameterRenderer, "parameterRenderer");
  10524. }
  10525. /**
  10526. * Copies the specified text values into the correct cells in the {@link TextTable}. This implementation
  10527. * delegates to {@link TextTable#addRowValues(CommandLine.Help.Ansi.Text...)} for each row of values.
  10528. * <p>Subclasses may override.</p>
  10529. * @param argSpec the Option or Parameters
  10530. * @param cellValues the text values representing the Option/Parameters, to be displayed in tabular form
  10531. * @since 3.0 */
  10532. public void layout(ArgSpec argSpec, Text[][] cellValues) {
  10533. for (Text[] oneRow : cellValues) {
  10534. table.addRowValues(oneRow);
  10535. }
  10536. }
  10537. /** Calls {@link #addOption(CommandLine.Model.OptionSpec, CommandLine.Help.IParamLabelRenderer)} for all non-hidden Options in the list.
  10538. * @param options options to add usage descriptions for
  10539. * @param paramLabelRenderer object that knows how to render option parameters
  10540. * @since 3.0 */
  10541. public void addOptions(List<OptionSpec> options, IParamLabelRenderer paramLabelRenderer) {
  10542. for (OptionSpec option : options) {
  10543. if (!option.hidden()) {
  10544. addOption(option, paramLabelRenderer);
  10545. }
  10546. }
  10547. }
  10548. /**
  10549. * Delegates to the {@link #optionRenderer option renderer} of this layout to obtain
  10550. * text values for the specified {@link OptionSpec}, and then calls the {@link #layout(CommandLine.Model.ArgSpec, CommandLine.Help.Ansi.Text[][])}
  10551. * method to write these text values into the correct cells in the TextTable.
  10552. * @param option the option argument
  10553. * @param paramLabelRenderer knows how to render option parameters
  10554. * @since 3.0 */
  10555. public void addOption(OptionSpec option, IParamLabelRenderer paramLabelRenderer) {
  10556. Text[][] values = optionRenderer.render(option, paramLabelRenderer, colorScheme);
  10557. layout(option, values);
  10558. }
  10559. /** Calls {@link #addPositionalParameter(CommandLine.Model.PositionalParamSpec, CommandLine.Help.IParamLabelRenderer)} for all non-hidden Parameters in the list.
  10560. * @param params positional parameters to add usage descriptions for
  10561. * @param paramLabelRenderer knows how to render option parameters
  10562. * @since 3.0 */
  10563. public void addPositionalParameters(List<PositionalParamSpec> params, IParamLabelRenderer paramLabelRenderer) {
  10564. for (PositionalParamSpec param : params) {
  10565. if (!param.hidden()) {
  10566. addPositionalParameter(param, paramLabelRenderer);
  10567. }
  10568. }
  10569. }
  10570. /**
  10571. * Delegates to the {@link #parameterRenderer parameter renderer} of this layout
  10572. * to obtain text values for the specified {@linkplain PositionalParamSpec positional parameter}, and then calls
  10573. * {@link #layout(CommandLine.Model.ArgSpec, CommandLine.Help.Ansi.Text[][])} to write these text values into the correct cells in the TextTable.
  10574. * @param param the positional parameter
  10575. * @param paramLabelRenderer knows how to render option parameters
  10576. * @since 3.0 */
  10577. public void addPositionalParameter(PositionalParamSpec param, IParamLabelRenderer paramLabelRenderer) {
  10578. Text[][] values = parameterRenderer.render(param, paramLabelRenderer, colorScheme);
  10579. layout(param, values);
  10580. }
  10581. /** Returns the section of the usage help message accumulated in the TextTable owned by this layout. */
  10582. @Override public String toString() { return table.toString(); }
  10583. }
  10584. /** Sorts short strings before longer strings. */
  10585. static class ShortestFirst implements Comparator<String> {
  10586. public int compare(String o1, String o2) {
  10587. return o1.length() - o2.length();
  10588. }
  10589. /** Sorts the specified array of Strings shortest-first and returns it. */
  10590. public static String[] sort(String[] names) {
  10591. Arrays.sort(names, new ShortestFirst());
  10592. return names;
  10593. }
  10594. /** Sorts the specified array of Strings longest-first and returns it. */
  10595. public static String[] longestFirst(String[] names) {
  10596. Arrays.sort(names, Collections.reverseOrder(new ShortestFirst()));
  10597. return names;
  10598. }
  10599. }
  10600. /** Sorts {@code OptionSpec} instances by their name in case-insensitive alphabetic order. If an option has
  10601. * multiple names, the shortest name is used for the sorting. Help options follow non-help options. */
  10602. static class SortByShortestOptionNameAlphabetically implements Comparator<OptionSpec> {
  10603. public int compare(OptionSpec o1, OptionSpec o2) {
  10604. if (o1 == null) { return 1; } else if (o2 == null) { return -1; } // options before params
  10605. String[] names1 = ShortestFirst.sort(o1.names());
  10606. String[] names2 = ShortestFirst.sort(o2.names());
  10607. int result = names1[0].toUpperCase().compareTo(names2[0].toUpperCase()); // case insensitive sort
  10608. result = result == 0 ? -names1[0].compareTo(names2[0]) : result; // lower case before upper case
  10609. return o1.help() == o2.help() ? result : o2.help() ? -1 : 1; // help options come last
  10610. }
  10611. }
  10612. /** Sorts {@code OptionSpec} instances by their max arity first, then their min arity, then delegates to super class. */
  10613. static class SortByOptionArityAndNameAlphabetically extends SortByShortestOptionNameAlphabetically {
  10614. public int compare(OptionSpec o1, OptionSpec o2) {
  10615. Range arity1 = o1.arity();
  10616. Range arity2 = o2.arity();
  10617. int result = arity1.max - arity2.max;
  10618. if (result == 0) {
  10619. result = arity1.min - arity2.min;
  10620. }
  10621. if (result == 0) { // arity is same
  10622. if (o1.isMultiValue() && !o2.isMultiValue()) { result = 1; } // f1 > f2
  10623. if (!o1.isMultiValue() && o2.isMultiValue()) { result = -1; } // f1 < f2
  10624. }
  10625. return result == 0 ? super.compare(o1, o2) : result;
  10626. }
  10627. }
  10628. static class SortByOrder<T extends IOrdered> implements Comparator<T> {
  10629. public int compare(T o1, T o2) {
  10630. return Integer.signum(o1.order() - o2.order());
  10631. }
  10632. }
  10633. /**
  10634. * <p>Responsible for spacing out {@link Text} values according to the {@link Column} definitions the table was
  10635. * created with. Columns have a width, indentation, and an overflow policy that decides what to do if a value is
  10636. * longer than the column's width.</p>
  10637. */
  10638. public static class TextTable {
  10639. /**
  10640. * Helper class to index positions in a {@code Help.TextTable}.
  10641. * @since 2.0
  10642. */
  10643. public static class Cell {
  10644. /** Table column index (zero based). */
  10645. public final int column;
  10646. /** Table row index (zero based). */
  10647. public final int row;
  10648. /** Constructs a new Cell with the specified coordinates in the table.
  10649. * @param column the zero-based table column
  10650. * @param row the zero-based table row */
  10651. public Cell(int column, int row) { this.column = column; this.row = row; }
  10652. }
  10653. private static final int OPTION_SEPARATOR_COLUMN = 2;
  10654. private static final int LONG_OPTION_COLUMN = 3;
  10655. /** The column definitions of this table. */
  10656. private final Column[] columns;
  10657. /** The {@code char[]} slots of the {@code TextTable} to copy text values into. */
  10658. protected final List<Text> columnValues = new ArrayList<Text>();
  10659. /** By default, indent wrapped lines by 2 spaces. */
  10660. public int indentWrappedLines = 2;
  10661. private final Ansi ansi;
  10662. private final int tableWidth;
  10663. /** Constructs a TextTable with five columns as follows:
  10664. * <ol>
  10665. * <li>required option/parameter marker (width: 2, indent: 0, TRUNCATE on overflow)</li>
  10666. * <li>short option name (width: 2, indent: 0, TRUNCATE on overflow)</li>
  10667. * <li>comma separator (width: 1, indent: 0, TRUNCATE on overflow)</li>
  10668. * <li>long option name(s) (width: 24, indent: 1, SPAN multiple columns on overflow)</li>
  10669. * <li>description line(s) (width: 51, indent: 1, WRAP to next row on overflow)</li>
  10670. * </ol>
  10671. * @param ansi whether to emit ANSI escape codes or not
  10672. * @param usageHelpWidth the total width of the columns combined
  10673. */
  10674. public static TextTable forDefaultColumns(Ansi ansi, int usageHelpWidth) {
  10675. return forDefaultColumns(ansi, defaultOptionsColumnWidth, usageHelpWidth);
  10676. }
  10677. /** Constructs a TextTable with five columns as follows:
  10678. * <ol>
  10679. * <li>required option/parameter marker (width: 2, indent: 0, TRUNCATE on overflow)</li>
  10680. * <li>short option name (width: 2, indent: 0, TRUNCATE on overflow)</li>
  10681. * <li>comma separator (width: 1, indent: 0, TRUNCATE on overflow)</li>
  10682. * <li>long option name(s) (width: 24, indent: 1, SPAN multiple columns on overflow)</li>
  10683. * <li>description line(s) (width: 51, indent: 1, WRAP to next row on overflow)</li>
  10684. * </ol>
  10685. * @param ansi whether to emit ANSI escape codes or not
  10686. * @param longOptionsColumnWidth the width of the long options column
  10687. * @param usageHelpWidth the total width of the columns combined
  10688. */
  10689. public static TextTable forDefaultColumns(Ansi ansi, int longOptionsColumnWidth, int usageHelpWidth) {
  10690. // "* -c, --create Creates a ...."
  10691. return forColumns(ansi,
  10692. new Column(2, 0, TRUNCATE), // "*"
  10693. new Column(2, 0, TRUNCATE), // "-c"
  10694. new Column(1, 0, TRUNCATE), // ","
  10695. new Column(longOptionsColumnWidth, 1, SPAN), // " --create"
  10696. new Column(usageHelpWidth - longOptionsColumnWidth, 1, WRAP)); // " Creates a ..."
  10697. }
  10698. /** Constructs a new TextTable with columns with the specified width, all SPANning multiple columns on
  10699. * overflow except the last column which WRAPS to the next row.
  10700. * @param ansi whether to emit ANSI escape codes or not
  10701. * @param columnWidths the width of each table column (all columns have zero indent)
  10702. */
  10703. public static TextTable forColumnWidths(Ansi ansi, int... columnWidths) {
  10704. Column[] columns = new Column[columnWidths.length];
  10705. for (int i = 0; i < columnWidths.length; i++) {
  10706. columns[i] = new Column(columnWidths[i], 0, i == columnWidths.length - 1 ? WRAP : SPAN);
  10707. }
  10708. return new TextTable(ansi, columns);
  10709. }
  10710. /** Constructs a {@code TextTable} with the specified columns.
  10711. * @param ansi whether to emit ANSI escape codes or not
  10712. * @param columns columns to construct this TextTable with */
  10713. public static TextTable forColumns(Ansi ansi, Column... columns) { return new TextTable(ansi, columns); }
  10714. protected TextTable(Ansi ansi, Column[] columns) {
  10715. this.ansi = Assert.notNull(ansi, "ansi");
  10716. this.columns = Assert.notNull(columns, "columns").clone();
  10717. if (columns.length == 0) { throw new IllegalArgumentException("At least one column is required"); }
  10718. int totalWidth = 0;
  10719. for (Column col : columns) { totalWidth += col.width; }
  10720. tableWidth = totalWidth;
  10721. }
  10722. /** The column definitions of this table. */
  10723. public Column[] columns() { return columns.clone(); }
  10724. /** Returns the {@code Text} slot at the specified row and column to write a text value into.
  10725. * @param row the row of the cell whose Text to return
  10726. * @param col the column of the cell whose Text to return
  10727. * @return the Text object at the specified row and column
  10728. * @since 2.0 */
  10729. public Text textAt(int row, int col) { return columnValues.get(col + (row * columns.length)); }
  10730. /** Returns the {@code Text} slot at the specified row and column to write a text value into.
  10731. * @param row the row of the cell whose Text to return
  10732. * @param col the column of the cell whose Text to return
  10733. * @return the Text object at the specified row and column
  10734. * @deprecated use {@link #textAt(int, int)} instead */
  10735. @Deprecated public Text cellAt(int row, int col) { return textAt(row, col); }
  10736. /** Returns the current number of rows of this {@code TextTable}.
  10737. * @return the current number of rows in this TextTable */
  10738. public int rowCount() { return columnValues.size() / columns.length; }
  10739. /** Adds the required {@code char[]} slots for a new row to the {@link #columnValues} field. */
  10740. public void addEmptyRow() {
  10741. for (int i = 0; i < columns.length; i++) {
  10742. columnValues.add(ansi.new Text(columns[i].width));
  10743. }
  10744. }
  10745. /** Delegates to {@link #addRowValues(CommandLine.Help.Ansi.Text...)}.
  10746. * @param values the text values to display in each column of the current row */
  10747. public void addRowValues(String... values) {
  10748. Text[] array = new Text[values.length];
  10749. for (int i = 0; i < array.length; i++) {
  10750. array[i] = values[i] == null ? Ansi.EMPTY_TEXT : ansi.new Text(values[i]);
  10751. }
  10752. addRowValues(array);
  10753. }
  10754. /**
  10755. * Adds a new {@linkplain TextTable#addEmptyRow() empty row}, then calls {@link
  10756. * TextTable#putValue(int, int, CommandLine.Help.Ansi.Text) putValue} for each of the specified values, adding more empty rows
  10757. * if the return value indicates that the value spanned multiple columns or was wrapped to multiple rows.
  10758. * @param values the values to write into a new row in this TextTable
  10759. * @throws IllegalArgumentException if the number of values exceeds the number of Columns in this table
  10760. */
  10761. public void addRowValues(Text... values) {
  10762. if (values.length > columns.length) {
  10763. throw new IllegalArgumentException(values.length + " values don't fit in " +
  10764. columns.length + " columns");
  10765. }
  10766. addEmptyRow();
  10767. int oldIndent = unindent(values);
  10768. for (int col = 0; col < values.length; col++) {
  10769. int row = rowCount() - 1;// write to last row: previous value may have wrapped to next row
  10770. Cell cell = putValue(row, col, values[col]);
  10771. // add row if a value spanned/wrapped and there are still remaining values
  10772. if ((cell.row != row || cell.column != col) && col != values.length - 1) {
  10773. addEmptyRow();
  10774. }
  10775. }
  10776. reindent(oldIndent);
  10777. }
  10778. private int unindent(Text[] values) {
  10779. if (columns.length <= LONG_OPTION_COLUMN) { return 0; }
  10780. int oldIndent = columns[LONG_OPTION_COLUMN].indent;
  10781. if ("=".equals(values[OPTION_SEPARATOR_COLUMN].toString())) {
  10782. columns[LONG_OPTION_COLUMN].indent = 0;
  10783. }
  10784. return oldIndent;
  10785. }
  10786. private void reindent(int oldIndent) {
  10787. if (columns.length <= LONG_OPTION_COLUMN) { return; }
  10788. columns[LONG_OPTION_COLUMN].indent = oldIndent;
  10789. }
  10790. /**
  10791. * Writes the specified value into the cell at the specified row and column and returns the last row and
  10792. * column written to. Depending on the Column's {@link Column#overflow Overflow} policy, the value may span
  10793. * multiple columns or wrap to multiple rows when larger than the column width.
  10794. * @param row the target row in the table
  10795. * @param col the target column in the table to write to
  10796. * @param value the value to write
  10797. * @return a Cell indicating the position in the table that was last written to (since 2.0)
  10798. * @throws IllegalArgumentException if the specified row exceeds the table's {@linkplain
  10799. * TextTable#rowCount() row count}
  10800. * @since 2.0 (previous versions returned a {@code java.awt.Point} object)
  10801. */
  10802. public Cell putValue(int row, int col, Text value) {
  10803. if (row > rowCount() - 1) {
  10804. throw new IllegalArgumentException("Cannot write to row " + row + ": rowCount=" + rowCount());
  10805. }
  10806. if (value == null || value.plain.length() == 0) { return new Cell(col, row); }
  10807. Column column = columns[col];
  10808. int indent = column.indent;
  10809. switch (column.overflow) {
  10810. case TRUNCATE:
  10811. copy(value, textAt(row, col), indent);
  10812. return new Cell(col, row);
  10813. case SPAN:
  10814. int startColumn = col;
  10815. do {
  10816. boolean lastColumn = col == columns.length - 1;
  10817. int charsWritten = lastColumn
  10818. ? copy(BreakIterator.getLineInstance(), value, textAt(row, col), indent)
  10819. : copy(value, textAt(row, col), indent);
  10820. value = value.substring(charsWritten);
  10821. indent = 0;
  10822. if (value.length > 0) { // value did not fit in column
  10823. ++col; // write remainder of value in next column
  10824. }
  10825. if (value.length > 0 && col >= columns.length) { // we filled up all columns on this row
  10826. addEmptyRow();
  10827. row++;
  10828. col = startColumn;
  10829. indent = column.indent + indentWrappedLines;
  10830. }
  10831. } while (value.length > 0);
  10832. return new Cell(col, row);
  10833. case WRAP:
  10834. BreakIterator lineBreakIterator = BreakIterator.getLineInstance();
  10835. do {
  10836. int charsWritten = copy(lineBreakIterator, value, textAt(row, col), indent);
  10837. value = value.substring(charsWritten);
  10838. indent = column.indent + indentWrappedLines;
  10839. if (value.length > 0) { // value did not fit in column
  10840. ++row; // write remainder of value in next row
  10841. addEmptyRow();
  10842. }
  10843. } while (value.length > 0);
  10844. return new Cell(col, row);
  10845. }
  10846. throw new IllegalStateException(column.overflow.toString());
  10847. }
  10848. private static int length(Text str) {
  10849. return str.length; // TODO count some characters as double length
  10850. }
  10851. private int copy(BreakIterator line, Text text, Text columnValue, int offset) {
  10852. // Deceive the BreakIterator to ensure no line breaks after '-' character
  10853. line.setText(text.plainString().replace("-", "\u00ff"));
  10854. int done = 0;
  10855. for (int start = line.first(), end = line.next(); end != BreakIterator.DONE; start = end, end = line.next()) {
  10856. Text word = text.substring(start, end); //.replace("\u00ff", "-"); // not needed
  10857. if (columnValue.maxLength >= offset + done + length(word)) {
  10858. done += copy(word, columnValue, offset + done); // TODO messages length
  10859. } else {
  10860. break;
  10861. }
  10862. }
  10863. if (done == 0 && length(text) + offset > columnValue.maxLength) {
  10864. // The value is a single word that is too big to be written to the column. Write as much as we can.
  10865. done = copy(text, columnValue, offset);
  10866. }
  10867. return done;
  10868. }
  10869. private static int copy(Text value, Text destination, int offset) {
  10870. int length = Math.min(value.length, destination.maxLength - offset);
  10871. value.getStyledChars(value.from, length, destination, offset);
  10872. return length;
  10873. }
  10874. /** Copies the text representation that we built up from the options into the specified StringBuilder.
  10875. * @param text the StringBuilder to write into
  10876. * @return the specified StringBuilder object (to allow method chaining and a more fluid API) */
  10877. public StringBuilder toString(StringBuilder text) {
  10878. int columnCount = this.columns.length;
  10879. StringBuilder row = new StringBuilder(tableWidth);
  10880. for (int i = 0; i < columnValues.size(); i++) {
  10881. Text column = columnValues.get(i);
  10882. row.append(column.toString());
  10883. row.append(new String(spaces(columns[i % columnCount].width - column.length)));
  10884. if (i % columnCount == columnCount - 1) {
  10885. int lastChar = row.length() - 1;
  10886. while (lastChar >= 0 && row.charAt(lastChar) == ' ') {lastChar--;} // rtrim
  10887. row.setLength(lastChar + 1);
  10888. text.append(row.toString()).append(System.getProperty("line.separator"));
  10889. row.setLength(0);
  10890. }
  10891. }
  10892. return text;
  10893. }
  10894. public String toString() { return toString(new StringBuilder()).toString(); }
  10895. }
  10896. /** Columns define the width, indent (leading number of spaces in a column before the value) and
  10897. * {@linkplain Overflow Overflow} policy of a column in a {@linkplain TextTable TextTable}. */
  10898. public static class Column {
  10899. /** Policy for handling text that is longer than the column width:
  10900. * span multiple columns, wrap to the next row, or simply truncate the portion that doesn't fit. */
  10901. public enum Overflow { TRUNCATE, SPAN, WRAP }
  10902. /** Column width in characters */
  10903. public final int width;
  10904. /** Indent (number of empty spaces at the start of the column preceding the text value) */
  10905. public int indent;
  10906. /** Policy that determines how to handle values larger than the column width. */
  10907. public final Overflow overflow;
  10908. public Column(int width, int indent, Overflow overflow) {
  10909. this.width = width;
  10910. this.indent = indent;
  10911. this.overflow = Assert.notNull(overflow, "overflow");
  10912. }
  10913. }
  10914. /** All usage help message are generated with a color scheme that assigns certain styles and colors to common
  10915. * parts of a usage message: the command name, options, positional parameters and option parameters.
  10916. * Users may customize these styles by creating Help with a custom color scheme.
  10917. * <p>Note that these options and styles may not be rendered if ANSI escape codes are not
  10918. * {@linkplain Ansi#enabled() enabled}.</p>
  10919. * @see Help#defaultColorScheme(Ansi)
  10920. */
  10921. public static class ColorScheme {
  10922. public final List<IStyle> commandStyles = new ArrayList<IStyle>();
  10923. public final List<IStyle> optionStyles = new ArrayList<IStyle>();
  10924. public final List<IStyle> parameterStyles = new ArrayList<IStyle>();
  10925. public final List<IStyle> optionParamStyles = new ArrayList<IStyle>();
  10926. private final Ansi ansi;
  10927. /** Constructs a new empty ColorScheme with {@link Help.Ansi#AUTO}. */
  10928. public ColorScheme() { this(Ansi.AUTO); }
  10929. /** Constructs a new empty ColorScheme with the specified Ansi enabled mode.
  10930. * @see Help#defaultColorScheme(Ansi)
  10931. * @param ansi whether to emit ANSI escape codes or not
  10932. */
  10933. public ColorScheme(Ansi ansi) {this.ansi = Assert.notNull(ansi, "ansi"); }
  10934. /** Adds the specified styles to the registered styles for commands in this color scheme and returns this color scheme.
  10935. * @param styles the styles to add to the registered styles for commands in this color scheme
  10936. * @return this color scheme to enable method chaining for a more fluent API */
  10937. public ColorScheme commands(IStyle... styles) { return addAll(commandStyles, styles); }
  10938. /** Adds the specified styles to the registered styles for options in this color scheme and returns this color scheme.
  10939. * @param styles the styles to add to registered the styles for options in this color scheme
  10940. * @return this color scheme to enable method chaining for a more fluent API */
  10941. public ColorScheme options(IStyle... styles) { return addAll(optionStyles, styles);}
  10942. /** Adds the specified styles to the registered styles for positional parameters in this color scheme and returns this color scheme.
  10943. * @param styles the styles to add to registered the styles for parameters in this color scheme
  10944. * @return this color scheme to enable method chaining for a more fluent API */
  10945. public ColorScheme parameters(IStyle... styles) { return addAll(parameterStyles, styles);}
  10946. /** Adds the specified styles to the registered styles for option parameters in this color scheme and returns this color scheme.
  10947. * @param styles the styles to add to the registered styles for option parameters in this color scheme
  10948. * @return this color scheme to enable method chaining for a more fluent API */
  10949. public ColorScheme optionParams(IStyle... styles) { return addAll(optionParamStyles, styles);}
  10950. /** Returns a Text with all command styles applied to the specified command string.
  10951. * @param command the command string to apply the registered command styles to
  10952. * @return a Text with all command styles applied to the specified command string */
  10953. public Ansi.Text commandText(String command) { return ansi().apply(command, commandStyles); }
  10954. /** Returns a Text with all option styles applied to the specified option string.
  10955. * @param option the option string to apply the registered option styles to
  10956. * @return a Text with all option styles applied to the specified option string */
  10957. public Ansi.Text optionText(String option) { return ansi().apply(option, optionStyles); }
  10958. /** Returns a Text with all parameter styles applied to the specified parameter string.
  10959. * @param parameter the parameter string to apply the registered parameter styles to
  10960. * @return a Text with all parameter styles applied to the specified parameter string */
  10961. public Ansi.Text parameterText(String parameter) { return ansi().apply(parameter, parameterStyles); }
  10962. /** Returns a Text with all optionParam styles applied to the specified optionParam string.
  10963. * @param optionParam the option parameter string to apply the registered option parameter styles to
  10964. * @return a Text with all option parameter styles applied to the specified option parameter string */
  10965. public Ansi.Text optionParamText(String optionParam) { return ansi().apply(optionParam, optionParamStyles); }
  10966. /** Replaces colors and styles in this scheme with ones specified in system properties, and returns this scheme.
  10967. * Supported property names:<ul>
  10968. * <li>{@code picocli.color.commands}</li>
  10969. * <li>{@code picocli.color.options}</li>
  10970. * <li>{@code picocli.color.parameters}</li>
  10971. * <li>{@code picocli.color.optionParams}</li>
  10972. * </ul><p>Property values can be anything that {@link Help.Ansi.Style#parse(String)} can handle.</p>
  10973. * @return this ColorScheme
  10974. */
  10975. public ColorScheme applySystemProperties() {
  10976. replace(commandStyles, System.getProperty("picocli.color.commands"));
  10977. replace(optionStyles, System.getProperty("picocli.color.options"));
  10978. replace(parameterStyles, System.getProperty("picocli.color.parameters"));
  10979. replace(optionParamStyles, System.getProperty("picocli.color.optionParams"));
  10980. return this;
  10981. }
  10982. private void replace(List<IStyle> styles, String property) {
  10983. if (property != null) {
  10984. styles.clear();
  10985. addAll(styles, Style.parse(property));
  10986. }
  10987. }
  10988. private ColorScheme addAll(List<IStyle> styles, IStyle... add) {
  10989. styles.addAll(Arrays.asList(add));
  10990. return this;
  10991. }
  10992. public Ansi ansi() { return ansi; }
  10993. }
  10994. /** Creates and returns a new {@link ColorScheme} initialized with picocli default values: commands are bold,
  10995. * options and parameters use a yellow foreground, and option parameters use italic.
  10996. * @param ansi whether the usage help message should contain ANSI escape codes or not
  10997. * @return a new default color scheme
  10998. */
  10999. public static ColorScheme defaultColorScheme(Ansi ansi) {
  11000. return new ColorScheme(ansi)
  11001. .commands(Style.bold)
  11002. .options(Style.fg_yellow)
  11003. .parameters(Style.fg_yellow)
  11004. .optionParams(Style.italic);
  11005. }
  11006. /** Provides methods and inner classes to support using ANSI escape codes in usage help messages. */
  11007. public enum Ansi {
  11008. /** Only emit ANSI escape codes if the platform supports it and system property {@code "picocli.ansi"}
  11009. * is not set to any value other than {@code "true"} (case insensitive). */
  11010. AUTO,
  11011. /** Forced ON: always emit ANSI escape code regardless of the platform. */
  11012. ON,
  11013. /** Forced OFF: never emit ANSI escape code regardless of the platform. */
  11014. OFF;
  11015. static Text EMPTY_TEXT = OFF.new Text(0);
  11016. static Boolean tty;
  11017. static boolean isTTY() {
  11018. if (tty == null) { tty = calcTTY(); }
  11019. return tty;
  11020. }
  11021. static final boolean isWindows() { return System.getProperty("os.name").startsWith("Windows"); }
  11022. static final boolean isXterm() { return System.getenv("TERM") != null && System.getenv("TERM").startsWith("xterm"); }
  11023. // null on Windows unless on Cygwin or MSYS
  11024. static final boolean hasOsType() { return System.getenv("OSTYPE") != null; }
  11025. // see Jan Niklas Hasse's https://bixense.com/clicolors/ proposal
  11026. // https://conemu.github.io/en/AnsiEscapeCodes.html#Environment_variable
  11027. static final boolean hintDisabled() { return "0".equals(System.getenv("CLICOLOR"))
  11028. || "OFF".equals(System.getenv("ConEmuANSI")); }
  11029. /** https://github.com/adoxa/ansicon/blob/master/readme.txt,
  11030. * Jan Niklas Hasse's https://bixense.com/clicolors/ proposal,
  11031. * https://conemu.github.io/en/AnsiEscapeCodes.html#Environment_variable */
  11032. static final boolean hintEnabled() { return System.getenv("ANSICON") != null
  11033. || "1".equals(System.getenv("CLICOLOR"))
  11034. || "ON".equals(System.getenv("ConEmuANSI")); }
  11035. /** https://no-color.org/ */
  11036. static final boolean forceDisabled() { return System.getenv("NO_COLOR") != null; }
  11037. /** Jan Niklas Hasse's https://bixense.com/clicolors/ proposal */
  11038. static final boolean forceEnabled() { return System.getenv("CLICOLOR_FORCE") != null
  11039. && !"0".equals(System.getenv("CLICOLOR_FORCE"));}
  11040. /** http://stackoverflow.com/questions/1403772/how-can-i-check-if-a-java-programs-input-output-streams-are-connected-to-a-term */
  11041. static boolean calcTTY() {
  11042. try { return System.class.getDeclaredMethod("console").invoke(null) != null; }
  11043. catch (Throwable reflectionFailed) { return true; }
  11044. }
  11045. /** Cygwin and MSYS use pseudo-tty and console is always null... */
  11046. static boolean isPseudoTTY() { return isWindows() && (isXterm() || hasOsType()); }
  11047. static boolean ansiPossible() {
  11048. if (forceDisabled()) { return false; }
  11049. if (forceEnabled()) { return true; }
  11050. if (isWindows() && isJansiConsoleInstalled()) { return true; } // #630 JVM crash loading jansi.AnsiConsole on Linux
  11051. if (hintDisabled()) { return false; }
  11052. if (!isTTY() && !isPseudoTTY()) { return false; }
  11053. return hintEnabled() || !isWindows() || isXterm() || hasOsType();
  11054. }
  11055. static boolean isJansiConsoleInstalled() {
  11056. try {
  11057. Class<?> ansiConsole = Class.forName("org.fusesource.jansi.AnsiConsole");
  11058. Field out = ansiConsole.getField("out");
  11059. return out.get(null) == System.out;
  11060. } catch (Exception reflectionFailed) {
  11061. return false;
  11062. }
  11063. }
  11064. /** Returns {@code true} if ANSI escape codes should be emitted, {@code false} otherwise.
  11065. * @return ON: {@code true}, OFF: {@code false}, AUTO: if system property {@code "picocli.ansi"} is
  11066. * defined then return its boolean value, otherwise return whether the platform supports ANSI escape codes */
  11067. public boolean enabled() {
  11068. if (this == ON) { return true; }
  11069. if (this == OFF) { return false; }
  11070. String ansi = System.getProperty("picocli.ansi");
  11071. boolean auto = ansi == null || "AUTO".equalsIgnoreCase(ansi);
  11072. return auto ? ansiPossible() : Boolean.getBoolean("picocli.ansi");
  11073. }
  11074. /**
  11075. * Returns a new Text object for this Ansi mode, encapsulating the specified string
  11076. * which may contain markup like {@code @|bg(red),white,underline some text|@}.
  11077. * <p>
  11078. * Calling {@code toString()} on the returned Text will either include ANSI escape codes
  11079. * (if this Ansi mode is ON), or suppress ANSI escape codes (if this Ansi mode is OFF).
  11080. * <p>
  11081. * Equivalent to {@code this.new Text(stringWithMarkup)}.
  11082. * @since 3.4 */
  11083. public Text text(String stringWithMarkup) { return this.new Text(stringWithMarkup); }
  11084. /**
  11085. * Returns a String where any markup like
  11086. * {@code @|bg(red),white,underline some text|@} is converted to ANSI escape codes
  11087. * if this Ansi is ON, or suppressed if this Ansi is OFF.
  11088. * <p>
  11089. * Equivalent to {@code this.new Text(stringWithMarkup).toString()}.
  11090. * @since 3.4 */
  11091. public String string(String stringWithMarkup) { return this.new Text(stringWithMarkup).toString(); }
  11092. /** Returns Ansi.ON if the specified {@code enabled} flag is true, Ansi.OFF otherwise.
  11093. * @since 3.4 */
  11094. public static Ansi valueOf(boolean enabled) {return enabled ? ON : OFF; }
  11095. /** Defines the interface for an ANSI escape sequence. */
  11096. public interface IStyle {
  11097. /** The Control Sequence Introducer (CSI) escape sequence {@value}. */
  11098. String CSI = "\u001B[";
  11099. /** Returns the ANSI escape code for turning this style on.
  11100. * @return the ANSI escape code for turning this style on */
  11101. String on();
  11102. /** Returns the ANSI escape code for turning this style off.
  11103. * @return the ANSI escape code for turning this style off */
  11104. String off();
  11105. }
  11106. /**
  11107. * A set of pre-defined ANSI escape code styles and colors, and a set of convenience methods for parsing
  11108. * text with embedded markup style names, as well as convenience methods for converting
  11109. * styles to strings with embedded escape codes.
  11110. */
  11111. public enum Style implements IStyle {
  11112. reset(0, 0), bold(1, 21), faint(2, 22), italic(3, 23), underline(4, 24), blink(5, 25), reverse(7, 27),
  11113. fg_black(30, 39), fg_red(31, 39), fg_green(32, 39), fg_yellow(33, 39), fg_blue(34, 39), fg_magenta(35, 39), fg_cyan(36, 39), fg_white(37, 39),
  11114. bg_black(40, 49), bg_red(41, 49), bg_green(42, 49), bg_yellow(43, 49), bg_blue(44, 49), bg_magenta(45, 49), bg_cyan(46, 49), bg_white(47, 49),
  11115. ;
  11116. private final int startCode;
  11117. private final int endCode;
  11118. Style(int startCode, int endCode) {this.startCode = startCode; this.endCode = endCode; }
  11119. public String on() { return CSI + startCode + "m"; }
  11120. public String off() { return CSI + endCode + "m"; }
  11121. /** Returns the concatenated ANSI escape codes for turning all specified styles on.
  11122. * @param styles the styles to generate ANSI escape codes for
  11123. * @return the concatenated ANSI escape codes for turning all specified styles on */
  11124. public static String on(IStyle... styles) {
  11125. StringBuilder result = new StringBuilder();
  11126. for (IStyle style : styles) {
  11127. result.append(style.on());
  11128. }
  11129. return result.toString();
  11130. }
  11131. /** Returns the concatenated ANSI escape codes for turning all specified styles off.
  11132. * @param styles the styles to generate ANSI escape codes for
  11133. * @return the concatenated ANSI escape codes for turning all specified styles off */
  11134. public static String off(IStyle... styles) {
  11135. StringBuilder result = new StringBuilder();
  11136. for (IStyle style : styles) {
  11137. result.append(style.off());
  11138. }
  11139. return result.toString();
  11140. }
  11141. /** Parses the specified style markup and returns the associated style.
  11142. * The markup may be one of the Style enum value names, or it may be one of the Style enum value
  11143. * names when {@code "fg_"} is prepended, or it may be one of the indexed colors in the 256 color palette.
  11144. * @param str the case-insensitive style markup to convert, e.g. {@code "blue"} or {@code "fg_blue"},
  11145. * or {@code "46"} (indexed color) or {@code "0;5;0"} (RGB components of an indexed color)
  11146. * @return the IStyle for the specified converter
  11147. */
  11148. public static IStyle fg(String str) {
  11149. try { return Style.valueOf(str.toLowerCase(ENGLISH)); } catch (Exception ignored) {}
  11150. try { return Style.valueOf("fg_" + str.toLowerCase(ENGLISH)); } catch (Exception ignored) {}
  11151. return new Palette256Color(true, str);
  11152. }
  11153. /** Parses the specified style markup and returns the associated style.
  11154. * The markup may be one of the Style enum value names, or it may be one of the Style enum value
  11155. * names when {@code "bg_"} is prepended, or it may be one of the indexed colors in the 256 color palette.
  11156. * @param str the case-insensitive style markup to convert, e.g. {@code "blue"} or {@code "bg_blue"},
  11157. * or {@code "46"} (indexed color) or {@code "0;5;0"} (RGB components of an indexed color)
  11158. * @return the IStyle for the specified converter
  11159. */
  11160. public static IStyle bg(String str) {
  11161. try { return Style.valueOf(str.toLowerCase(ENGLISH)); } catch (Exception ignored) {}
  11162. try { return Style.valueOf("bg_" + str.toLowerCase(ENGLISH)); } catch (Exception ignored) {}
  11163. return new Palette256Color(false, str);
  11164. }
  11165. /** Parses the specified comma-separated sequence of style descriptors and returns the associated
  11166. * styles. For each markup, strings starting with {@code "bg("} are delegated to
  11167. * {@link #bg(String)}, others are delegated to {@link #bg(String)}.
  11168. * @param commaSeparatedCodes one or more descriptors, e.g. {@code "bg(blue),underline,red"}
  11169. * @return an array with all styles for the specified descriptors
  11170. */
  11171. public static IStyle[] parse(String commaSeparatedCodes) {
  11172. String[] codes = commaSeparatedCodes.split(",");
  11173. IStyle[] styles = new IStyle[codes.length];
  11174. for(int i = 0; i < codes.length; ++i) {
  11175. if (codes[i].toLowerCase(ENGLISH).startsWith("fg(")) {
  11176. int end = codes[i].indexOf(')');
  11177. styles[i] = Style.fg(codes[i].substring(3, end < 0 ? codes[i].length() : end));
  11178. } else if (codes[i].toLowerCase(ENGLISH).startsWith("bg(")) {
  11179. int end = codes[i].indexOf(')');
  11180. styles[i] = Style.bg(codes[i].substring(3, end < 0 ? codes[i].length() : end));
  11181. } else {
  11182. styles[i] = Style.fg(codes[i]);
  11183. }
  11184. }
  11185. return styles;
  11186. }
  11187. }
  11188. /** Defines a palette map of 216 colors: 6 * 6 * 6 cube (216 colors):
  11189. * 16 + 36 * r + 6 * g + b (0 &lt;= r, g, b &lt;= 5). */
  11190. static class Palette256Color implements IStyle {
  11191. private final int fgbg;
  11192. private final int color;
  11193. Palette256Color(boolean foreground, String color) {
  11194. this.fgbg = foreground ? 38 : 48;
  11195. String[] rgb = color.split(";");
  11196. if (rgb.length == 3) {
  11197. this.color = 16 + 36 * Integer.decode(rgb[0]) + 6 * Integer.decode(rgb[1]) + Integer.decode(rgb[2]);
  11198. } else {
  11199. this.color = Integer.decode(color);
  11200. }
  11201. }
  11202. public String on() { return String.format(CSI + "%d;5;%dm", fgbg, color); }
  11203. public String off() { return CSI + (fgbg + 1) + "m"; }
  11204. }
  11205. private static class StyledSection {
  11206. int startIndex, length;
  11207. String startStyles, endStyles;
  11208. StyledSection(int start, int len, String style1, String style2) {
  11209. startIndex = start; length = len; startStyles = style1; endStyles = style2;
  11210. }
  11211. StyledSection withStartIndex(int newStart) {
  11212. return new StyledSection(newStart, length, startStyles, endStyles);
  11213. }
  11214. }
  11215. /**
  11216. * Returns a new Text object where all the specified styles are applied to the full length of the
  11217. * specified plain text.
  11218. * @param plainText the string to apply all styles to. Must not contain markup!
  11219. * @param styles the styles to apply to the full plain text
  11220. * @return a new Text object
  11221. */
  11222. public Text apply(String plainText, List<IStyle> styles) {
  11223. if (plainText.length() == 0) { return new Text(0); }
  11224. Text result = new Text(plainText.length());
  11225. IStyle[] all = styles.toArray(new IStyle[styles.size()]);
  11226. result.sections.add(new StyledSection(
  11227. 0, plainText.length(), Style.on(all), Style.off(reverse(all)) + Style.reset.off()));
  11228. result.plain.append(plainText);
  11229. result.length = result.plain.length();
  11230. return result;
  11231. }
  11232. private static <T> T[] reverse(T[] all) {
  11233. for (int i = 0; i < all.length / 2; i++) {
  11234. T temp = all[i];
  11235. all[i] = all[all.length - i - 1];
  11236. all[all.length - i - 1] = temp;
  11237. }
  11238. return all;
  11239. }
  11240. /** Encapsulates rich text with styles and colors. Text objects may be constructed with Strings containing
  11241. * markup like {@code @|bg(red),white,underline some text|@}, and this class converts the markup to ANSI
  11242. * escape codes.
  11243. * <p>
  11244. * Internally keeps both an enriched and a plain text representation to allow layout components to calculate
  11245. * text width while remaining unaware of the embedded ANSI escape codes.</p> */
  11246. public class Text implements Cloneable {
  11247. private final int maxLength;
  11248. private int from;
  11249. private int length;
  11250. private StringBuilder plain = new StringBuilder();
  11251. private List<StyledSection> sections = new ArrayList<StyledSection>();
  11252. /** Constructs a Text with the specified max length (for use in a TextTable Column).
  11253. * @param maxLength max length of this text */
  11254. public Text(int maxLength) { this.maxLength = maxLength; }
  11255. /** Copy constructor.
  11256. * @since 3.9 */
  11257. public Text(Text other) {
  11258. this.maxLength = other.maxLength;
  11259. this.from = other.from;
  11260. this.length = other.length;
  11261. this.plain = new StringBuilder(other.plain);
  11262. this.sections = new ArrayList<StyledSection>(other.sections);
  11263. }
  11264. /**
  11265. * Constructs a Text with the specified String, which may contain markup like
  11266. * {@code @|bg(red),white,underline some text|@}.
  11267. * @param input the string with markup to parse
  11268. */
  11269. public Text(String input) {
  11270. maxLength = -1;
  11271. plain.setLength(0);
  11272. int i = 0;
  11273. while (true) {
  11274. int j = input.indexOf("@|", i);
  11275. if (j == -1) {
  11276. if (i == 0) {
  11277. plain.append(input);
  11278. length = plain.length();
  11279. return;
  11280. }
  11281. plain.append(input.substring(i, input.length()));
  11282. length = plain.length();
  11283. return;
  11284. }
  11285. plain.append(input.substring(i, j));
  11286. int k = input.indexOf("|@", j);
  11287. if (k == -1) {
  11288. plain.append(input);
  11289. length = plain.length();
  11290. return;
  11291. }
  11292. j += 2;
  11293. String spec = input.substring(j, k);
  11294. String[] items = spec.split(" ", 2);
  11295. if (items.length == 1) {
  11296. plain.append(input);
  11297. length = plain.length();
  11298. return;
  11299. }
  11300. IStyle[] styles = Style.parse(items[0]);
  11301. addStyledSection(plain.length(), items[1].length(),
  11302. Style.on(styles), Style.off(reverse(styles)) + Style.reset.off());
  11303. plain.append(items[1]);
  11304. i = k + 2;
  11305. }
  11306. }
  11307. private void addStyledSection(int start, int length, String startStyle, String endStyle) {
  11308. sections.add(new StyledSection(start, length, startStyle, endStyle));
  11309. }
  11310. public Object clone() { return new Text(this); }
  11311. public Text[] splitLines() {
  11312. List<Text> result = new ArrayList<Text>();
  11313. int start = 0, end = 0;
  11314. for (int i = 0; i < plain.length(); i++, end = i) {
  11315. char c = plain.charAt(i);
  11316. boolean eol = c == '\n';
  11317. if (c == '\r' && i + 1 < plain.length() && plain.charAt(i + 1) == '\n') { eol = true; i++; } // \r\n
  11318. eol |= c == '\r';
  11319. if (eol) {
  11320. result.add(this.substring(start, end));
  11321. start = i + 1;
  11322. }
  11323. }
  11324. // add remainder (may be empty string)
  11325. result.add(this.substring(start, plain.length()));
  11326. return result.toArray(new Text[result.size()]);
  11327. }
  11328. /** Returns a new {@code Text} instance that is a substring of this Text. Does not modify this instance!
  11329. * @param start index in the plain text where to start the substring
  11330. * @return a new Text instance that is a substring of this Text */
  11331. public Text substring(int start) {
  11332. return substring(start, length);
  11333. }
  11334. /** Returns a new {@code Text} instance that is a substring of this Text. Does not modify this instance!
  11335. * @param start index in the plain text where to start the substring
  11336. * @param end index in the plain text where to end the substring
  11337. * @return a new Text instance that is a substring of this Text */
  11338. public Text substring(int start, int end) {
  11339. Text result = (Text) clone();
  11340. result.from = from + start;
  11341. result.length = end - start;
  11342. return result;
  11343. }
  11344. /** @deprecated use {@link #concat(String)} instead */
  11345. @Deprecated public Text append(String string) { return concat(string); }
  11346. /** @deprecated use {@link #concat(Text)} instead */
  11347. @Deprecated public Text append(Text text) { return concat(text); }
  11348. /** Returns a copy of this {@code Text} instance with the specified text concatenated to the end. Does not modify this instance!
  11349. * @param string the text to concatenate to the end of this Text
  11350. * @return a new Text instance
  11351. * @since 3.0 */
  11352. public Text concat(String string) { return concat(new Text(string)); }
  11353. /** Returns a copy of this {@code Text} instance with the specified text concatenated to the end. Does not modify this instance!
  11354. * @param other the text to concatenate to the end of this Text
  11355. * @return a new Text instance
  11356. * @since 3.0 */
  11357. public Text concat(Text other) {
  11358. Text result = (Text) clone();
  11359. result.plain = new StringBuilder(plain.toString().substring(from, from + length));
  11360. result.from = 0;
  11361. result.sections = new ArrayList<StyledSection>();
  11362. for (StyledSection section : sections) {
  11363. result.sections.add(section.withStartIndex(section.startIndex - from));
  11364. }
  11365. result.plain.append(other.plain.toString().substring(other.from, other.from + other.length));
  11366. for (StyledSection section : other.sections) {
  11367. int index = result.length + section.startIndex - other.from;
  11368. result.sections.add(section.withStartIndex(index));
  11369. }
  11370. result.length = result.plain.length();
  11371. return result;
  11372. }
  11373. /**
  11374. * Copies the specified substring of this Text into the specified destination, preserving the markup.
  11375. * @param from start of the substring
  11376. * @param length length of the substring
  11377. * @param destination destination Text to modify
  11378. * @param offset indentation (padding)
  11379. */
  11380. public void getStyledChars(int from, int length, Text destination, int offset) {
  11381. if (destination.length < offset) {
  11382. for (int i = destination.length; i < offset; i++) {
  11383. destination.plain.append(' ');
  11384. }
  11385. destination.length = offset;
  11386. }
  11387. for (StyledSection section : sections) {
  11388. destination.sections.add(section.withStartIndex(section.startIndex - from + destination.length));
  11389. }
  11390. destination.plain.append(plain.toString().substring(from, from + length));
  11391. destination.length = destination.plain.length();
  11392. }
  11393. /** Returns the plain text without any formatting.
  11394. * @return the plain text without any formatting */
  11395. public String plainString() { return plain.toString().substring(from, from + length); }
  11396. public boolean equals(Object obj) { return toString().equals(String.valueOf(obj)); }
  11397. public int hashCode() { return toString().hashCode(); }
  11398. /** Returns a String representation of the text with ANSI escape codes embedded, unless ANSI is
  11399. * {@linkplain Ansi#enabled()} not enabled}, in which case the plain text is returned.
  11400. * @return a String representation of the text with ANSI escape codes embedded (if enabled) */
  11401. public String toString() {
  11402. if (!Ansi.this.enabled()) {
  11403. return plain.toString().substring(from, from + length);
  11404. }
  11405. if (length == 0) { return ""; }
  11406. StringBuilder sb = new StringBuilder(plain.length() + 20 * sections.size());
  11407. StyledSection current = null;
  11408. int end = Math.min(from + length, plain.length());
  11409. for (int i = from; i < end; i++) {
  11410. StyledSection section = findSectionContaining(i);
  11411. if (section != current) {
  11412. if (current != null) { sb.append(current.endStyles); }
  11413. if (section != null) { sb.append(section.startStyles); }
  11414. current = section;
  11415. }
  11416. sb.append(plain.charAt(i));
  11417. }
  11418. if (current != null) { sb.append(current.endStyles); }
  11419. return sb.toString();
  11420. }
  11421. private StyledSection findSectionContaining(int index) {
  11422. for (StyledSection section : sections) {
  11423. if (index >= section.startIndex && index < section.startIndex + section.length) {
  11424. return section;
  11425. }
  11426. }
  11427. return null;
  11428. }
  11429. }
  11430. }
  11431. }
  11432. /**
  11433. * Utility class providing some defensive coding convenience methods.
  11434. */
  11435. private static final class Assert {
  11436. /**
  11437. * Throws a NullPointerException if the specified object is null.
  11438. * @param object the object to verify
  11439. * @param description error message
  11440. * @param <T> type of the object to check
  11441. * @return the verified object
  11442. */
  11443. static <T> T notNull(T object, String description) {
  11444. if (object == null) {
  11445. throw new NullPointerException(description);
  11446. }
  11447. return object;
  11448. }
  11449. static boolean equals(Object obj1, Object obj2) { return obj1 == null ? obj2 == null : obj1.equals(obj2); }
  11450. static int hashCode(Object obj) {return obj == null ? 0 : obj.hashCode(); }
  11451. static int hashCode(boolean bool) {return bool ? 1 : 0; }
  11452. static void assertTrue(boolean condition, String message) {
  11453. if (!condition) throw new IllegalStateException(message);
  11454. }
  11455. private Assert() {} // private constructor: never instantiate
  11456. }
  11457. private enum TraceLevel { OFF, WARN, INFO, DEBUG;
  11458. public boolean isEnabled(TraceLevel other) { return ordinal() >= other.ordinal(); }
  11459. private void print(Tracer tracer, String msg, Object... params) {
  11460. if (tracer.level.isEnabled(this)) { tracer.stream.printf(prefix(msg), params); }
  11461. }
  11462. private String prefix(String msg) { return "[picocli " + this + "] " + msg; }
  11463. static TraceLevel lookup(String key) { return key == null ? WARN : empty(key) || "true".equalsIgnoreCase(key) ? INFO : valueOf(key); }
  11464. }
  11465. static class Tracer {
  11466. TraceLevel level = TraceLevel.lookup(System.getProperty("picocli.trace"));
  11467. PrintStream stream = System.err;
  11468. void warn (String msg, Object... params) { TraceLevel.WARN.print(this, msg, params); }
  11469. void info (String msg, Object... params) { TraceLevel.INFO.print(this, msg, params); }
  11470. void debug(String msg, Object... params) { TraceLevel.DEBUG.print(this, msg, params); }
  11471. boolean isWarn() { return level.isEnabled(TraceLevel.WARN); }
  11472. boolean isInfo() { return level.isEnabled(TraceLevel.INFO); }
  11473. boolean isDebug() { return level.isEnabled(TraceLevel.DEBUG); }
  11474. }
  11475. /**
  11476. * Uses cosine similarity to find matches from a candidate set for a specified input.
  11477. * Based on code from http://www.nearinfinity.com/blogs/seth_schroeder/groovy_cosine_similarity_in_grails.html
  11478. *
  11479. * @author Burt Beckwith
  11480. */
  11481. private static class CosineSimilarity {
  11482. static List<String> mostSimilar(String pattern, Iterable<String> candidates) { return mostSimilar(pattern, candidates, 0); }
  11483. static List<String> mostSimilar(String pattern, Iterable<String> candidates, double threshold) {
  11484. pattern = pattern.toLowerCase();
  11485. SortedMap<Double, String> sorted = new TreeMap<Double, String>();
  11486. for (String candidate : candidates) {
  11487. double score = similarity(pattern, candidate.toLowerCase(), 2);
  11488. if (score > threshold) { sorted.put(score, candidate); }
  11489. }
  11490. return reverseList(new ArrayList<String>(sorted.values()));
  11491. }
  11492. private static double similarity(String sequence1, String sequence2, int degree) {
  11493. Map<String, Integer> m1 = countNgramFrequency(sequence1, degree);
  11494. Map<String, Integer> m2 = countNgramFrequency(sequence2, degree);
  11495. return dotProduct(m1, m2) / Math.sqrt(dotProduct(m1, m1) * dotProduct(m2, m2));
  11496. }
  11497. private static Map<String, Integer> countNgramFrequency(String sequence, int degree) {
  11498. Map<String, Integer> m = new HashMap<String, Integer>();
  11499. for (int i = 0; i + degree <= sequence.length(); i++) {
  11500. String gram = sequence.substring(i, i + degree);
  11501. m.put(gram, 1 + (m.containsKey(gram) ? m.get(gram) : 0));
  11502. }
  11503. return m;
  11504. }
  11505. private static double dotProduct(Map<String, Integer> m1, Map<String, Integer> m2) {
  11506. double result = 0;
  11507. for (String key : m1.keySet()) { result += m1.get(key) * (m2.containsKey(key) ? m2.get(key) : 0); }
  11508. return result;
  11509. }
  11510. }
  11511. /** Base class of all exceptions thrown by {@code picocli.CommandLine}.
  11512. * <h2>Class Diagram of the Picocli Exceptions</h2>
  11513. * <p>
  11514. * <img src="doc-files/class-diagram-exceptions.png" alt="Class Diagram of the Picocli Exceptions">
  11515. * </p>
  11516. * @since 2.0 */
  11517. public static class PicocliException extends RuntimeException {
  11518. private static final long serialVersionUID = -2574128880125050818L;
  11519. public PicocliException(String msg) { super(msg); }
  11520. public PicocliException(String msg, Throwable t) { super(msg, t); }
  11521. }
  11522. /** Exception indicating a problem during {@code CommandLine} initialization.
  11523. * @since 2.0 */
  11524. public static class InitializationException extends PicocliException {
  11525. private static final long serialVersionUID = 8423014001666638895L;
  11526. public InitializationException(String msg) { super(msg); }
  11527. public InitializationException(String msg, Exception ex) { super(msg, ex); }
  11528. }
  11529. /** Exception indicating a problem while invoking a command or subcommand.
  11530. * @since 2.0 */
  11531. public static class ExecutionException extends PicocliException {
  11532. private static final long serialVersionUID = 7764539594267007998L;
  11533. private final CommandLine commandLine;
  11534. public ExecutionException(CommandLine commandLine, String msg) {
  11535. super(msg);
  11536. this.commandLine = Assert.notNull(commandLine, "commandLine");
  11537. }
  11538. public ExecutionException(CommandLine commandLine, String msg, Throwable t) {
  11539. super(msg, t);
  11540. this.commandLine = Assert.notNull(commandLine, "commandLine");
  11541. }
  11542. /** Returns the {@code CommandLine} object for the (sub)command that could not be invoked.
  11543. * @return the {@code CommandLine} object for the (sub)command where invocation failed.
  11544. */
  11545. public CommandLine getCommandLine() { return commandLine; }
  11546. }
  11547. /** Exception thrown by {@link ITypeConverter} implementations to indicate a String could not be converted. */
  11548. public static class TypeConversionException extends PicocliException {
  11549. private static final long serialVersionUID = 4251973913816346114L;
  11550. public TypeConversionException(String msg) { super(msg); }
  11551. }
  11552. /** Exception indicating something went wrong while parsing command line options. */
  11553. public static class ParameterException extends PicocliException {
  11554. private static final long serialVersionUID = 1477112829129763139L;
  11555. private final CommandLine commandLine;
  11556. private ArgSpec argSpec = null;
  11557. private String value = null;
  11558. /** Constructs a new ParameterException with the specified CommandLine and error message.
  11559. * @param commandLine the command or subcommand whose input was invalid
  11560. * @param msg describes the problem
  11561. * @since 2.0 */
  11562. public ParameterException(CommandLine commandLine, String msg) {
  11563. super(msg);
  11564. this.commandLine = Assert.notNull(commandLine, "commandLine");
  11565. }
  11566. /** Constructs a new ParameterException with the specified CommandLine and error message.
  11567. * @param commandLine the command or subcommand whose input was invalid
  11568. * @param msg describes the problem
  11569. * @param t the throwable that caused this ParameterException
  11570. * @since 2.0 */
  11571. public ParameterException(CommandLine commandLine, String msg, Throwable t) {
  11572. super(msg, t);
  11573. this.commandLine = Assert.notNull(commandLine, "commandLine");
  11574. }
  11575. /** Constructs a new ParameterException with the specified CommandLine and error message.
  11576. * @param commandLine the command or subcommand whose input was invalid
  11577. * @param msg describes the problem
  11578. * @param t the throwable that caused this ParameterException
  11579. * @param argSpec the argSpec that caused this ParameterException
  11580. * @param value the value that caused this ParameterException
  11581. * @since 3.2 */
  11582. public ParameterException(CommandLine commandLine, String msg, Throwable t, ArgSpec argSpec, String value) {
  11583. super(msg, t);
  11584. this.commandLine = Assert.notNull(commandLine, "commandLine");
  11585. if (argSpec == null && value == null) { throw new IllegalArgumentException("ArgSpec and value cannot both be null"); }
  11586. this.argSpec = argSpec;
  11587. this.value = value;
  11588. }
  11589. /** Constructs a new ParameterException with the specified CommandLine and error message.
  11590. * @param commandLine the command or subcommand whose input was invalid
  11591. * @param msg describes the problem
  11592. * @param argSpec the argSpec that caused this ParameterException
  11593. * @param value the value that caused this ParameterException
  11594. * @since 3.2 */
  11595. public ParameterException(CommandLine commandLine, String msg, ArgSpec argSpec, String value) {
  11596. super(msg);
  11597. this.commandLine = Assert.notNull(commandLine, "commandLine");
  11598. if (argSpec == null && value == null) { throw new IllegalArgumentException("ArgSpec and value cannot both be null"); }
  11599. this.argSpec = argSpec;
  11600. this.value = value;
  11601. }
  11602. /** Returns the {@code CommandLine} object for the (sub)command whose input could not be parsed.
  11603. * @return the {@code CommandLine} object for the (sub)command where parsing failed.
  11604. * @since 2.0
  11605. */
  11606. public CommandLine getCommandLine() { return commandLine; }
  11607. /** Returns the {@code ArgSpec} object for the (sub)command whose input could not be parsed.
  11608. * @return the {@code ArgSpec} object for the (sub)command where parsing failed.
  11609. * @since 3.2
  11610. */
  11611. public ArgSpec getArgSpec() { return argSpec; }
  11612. /** Returns the {@code String} value for the (sub)command whose input could not be parsed.
  11613. * @return the {@code String} value for the (sub)command where parsing failed.
  11614. * @since 3.2
  11615. */
  11616. public String getValue() { return value; }
  11617. private static ParameterException create(CommandLine cmd, Exception ex, String arg, int i, String[] args) {
  11618. String msg = ex.getClass().getSimpleName() + ": " + ex.getLocalizedMessage()
  11619. + " while processing argument at or before arg[" + i + "] '" + arg + "' in " + Arrays.toString(args) + ": " + ex.toString();
  11620. return new ParameterException(cmd, msg, ex, null, arg);
  11621. }
  11622. }
  11623. /**
  11624. * Exception indicating that a required parameter was not specified.
  11625. */
  11626. public static class MissingParameterException extends ParameterException {
  11627. private static final long serialVersionUID = 5075678535706338753L;
  11628. private final List<ArgSpec> missing;
  11629. public MissingParameterException(CommandLine commandLine, ArgSpec missing, String msg) { this(commandLine, Arrays.asList(missing), msg); }
  11630. public MissingParameterException(CommandLine commandLine, Collection<ArgSpec> missing, String msg) {
  11631. super(commandLine, msg);
  11632. this.missing = Collections.unmodifiableList(new ArrayList<ArgSpec>(missing));
  11633. }
  11634. public List<ArgSpec> getMissing() { return missing; }
  11635. private static MissingParameterException create(CommandLine cmd, Collection<ArgSpec> missing, String separator) {
  11636. if (missing.size() == 1) {
  11637. return new MissingParameterException(cmd, missing, "Missing required option '"
  11638. + ArgSpec.describe(missing.iterator().next(), separator) + "'");
  11639. }
  11640. List<String> names = new ArrayList<String>(missing.size());
  11641. for (ArgSpec argSpec : missing) {
  11642. names.add(ArgSpec.describe(argSpec, separator));
  11643. }
  11644. return new MissingParameterException(cmd, missing, "Missing required options " + names.toString());
  11645. }
  11646. }
  11647. /** Exception indicating that the user input included multiple arguments from a mutually exclusive group.
  11648. * @since 4.0 */
  11649. public static class MutuallyExclusiveArgsException extends ParameterException {
  11650. private static final long serialVersionUID = -5557715106221420986L;
  11651. public MutuallyExclusiveArgsException(CommandLine commandLine, String msg) { super(commandLine, msg); }
  11652. }
  11653. /** Exception indicating that multiple named elements have incorrectly used the same name.
  11654. * @since 4.0 */
  11655. public static class DuplicateNameException extends InitializationException {
  11656. private static final long serialVersionUID = -4126747467955626054L;
  11657. public DuplicateNameException(String msg) { super(msg); }
  11658. }
  11659. /**
  11660. * Exception indicating that multiple fields have been annotated with the same Option name.
  11661. */
  11662. public static class DuplicateOptionAnnotationsException extends DuplicateNameException {
  11663. private static final long serialVersionUID = -3355128012575075641L;
  11664. public DuplicateOptionAnnotationsException(String msg) { super(msg); }
  11665. private static DuplicateOptionAnnotationsException create(String name, ArgSpec argSpec1, ArgSpec argSpec2) {
  11666. return new DuplicateOptionAnnotationsException("Option name '" + name + "' is used by both " +
  11667. argSpec1.toString() + " and " + argSpec2.toString());
  11668. }
  11669. }
  11670. /** Exception indicating that there was a gap in the indices of the fields annotated with {@link Parameters}. */
  11671. public static class ParameterIndexGapException extends InitializationException {
  11672. private static final long serialVersionUID = -1520981133257618319L;
  11673. public ParameterIndexGapException(String msg) { super(msg); }
  11674. }
  11675. /** Exception indicating that a command line argument could not be mapped to any of the fields annotated with
  11676. * {@link Option} or {@link Parameters}. */
  11677. public static class UnmatchedArgumentException extends ParameterException {
  11678. private static final long serialVersionUID = -8700426380701452440L;
  11679. private List<String> unmatched = Collections.<String>emptyList();
  11680. public UnmatchedArgumentException(CommandLine commandLine, String msg) { super(commandLine, msg); }
  11681. public UnmatchedArgumentException(CommandLine commandLine, Stack<String> args) { this(commandLine, new ArrayList<String>(reverse(args))); }
  11682. public UnmatchedArgumentException(CommandLine commandLine, List<String> args) {
  11683. this(commandLine, describe(args, commandLine) + (args.size() == 1 ? ": " : "s: ") + str(args));
  11684. unmatched = args == null ? Collections.<String>emptyList() : args;
  11685. }
  11686. /** Returns {@code true} and prints suggested solutions to the specified stream if such solutions exist, otherwise returns {@code false}.
  11687. * @since 3.3.0 */
  11688. public static boolean printSuggestions(ParameterException ex, PrintStream out) {
  11689. return ex instanceof UnmatchedArgumentException && ((UnmatchedArgumentException) ex).printSuggestions(out);
  11690. }
  11691. /** Returns the unmatched command line arguments.
  11692. * @since 3.3.0 */
  11693. public List<String> getUnmatched() { return stripErrorMessage(unmatched); }
  11694. static List<String> stripErrorMessage(List<String> unmatched) {
  11695. List<String> result = new ArrayList<String>();
  11696. for (String s : unmatched) {
  11697. if (s == null) { result.add(null); }
  11698. int pos = s.indexOf(" (while processing option:");
  11699. result.add(pos < 0 ? s : s.substring(0, pos));
  11700. }
  11701. return Collections.unmodifiableList(result);
  11702. }
  11703. /** Returns {@code true} if the first unmatched command line arguments resembles an option, {@code false} otherwise.
  11704. * @since 3.3.0 */
  11705. public boolean isUnknownOption() { return isUnknownOption(unmatched, getCommandLine()); }
  11706. /** Returns {@code true} and prints suggested solutions to the specified stream if such solutions exist, otherwise returns {@code false}.
  11707. * @since 3.3.0 */
  11708. public boolean printSuggestions(PrintStream out) {
  11709. List<String> suggestions = getSuggestions();
  11710. if (!suggestions.isEmpty()) {
  11711. out.println(isUnknownOption()
  11712. ? "Possible solutions: " + str(suggestions)
  11713. : "Did you mean: " + str(suggestions).replace(", ", " or ") + "?");
  11714. }
  11715. return !suggestions.isEmpty();
  11716. }
  11717. /** Returns suggested solutions if such solutions exist, otherwise returns an empty list.
  11718. * @since 3.3.0 */
  11719. public List<String> getSuggestions() {
  11720. if (unmatched == null || unmatched.isEmpty()) { return Collections.emptyList(); }
  11721. String arg = unmatched.get(0);
  11722. String stripped = CommandSpec.stripPrefix(arg);
  11723. CommandSpec spec = getCommandLine().getCommandSpec();
  11724. if (spec.resemblesOption(arg, null)) {
  11725. return spec.findOptionNamesWithPrefix(stripped.substring(0, Math.min(2, stripped.length())));
  11726. } else if (!spec.subcommands().isEmpty()) {
  11727. List<String> mostSimilar = CosineSimilarity.mostSimilar(arg, spec.subcommands().keySet());
  11728. return mostSimilar.subList(0, Math.min(3, mostSimilar.size()));
  11729. }
  11730. return Collections.emptyList();
  11731. }
  11732. private static boolean isUnknownOption(List<String> unmatch, CommandLine cmd) {
  11733. return unmatch != null && !unmatch.isEmpty() && cmd.getCommandSpec().resemblesOption(unmatch.get(0), null);
  11734. }
  11735. private static String describe(List<String> unmatch, CommandLine cmd) {
  11736. return isUnknownOption(unmatch, cmd) ? "Unknown option" : "Unmatched argument";
  11737. }
  11738. static String str(List<String> list) {
  11739. String s = list.toString();
  11740. return s.substring(0, s.length() - 1).substring(1);
  11741. }
  11742. }
  11743. /** Exception indicating that more values were specified for an option or parameter than its {@link Option#arity() arity} allows. */
  11744. public static class MaxValuesExceededException extends ParameterException {
  11745. private static final long serialVersionUID = 6536145439570100641L;
  11746. public MaxValuesExceededException(CommandLine commandLine, String msg) { super(commandLine, msg); }
  11747. }
  11748. /** Exception indicating that an option for a single-value option field has been specified multiple times on the command line. */
  11749. public static class OverwrittenOptionException extends ParameterException {
  11750. private static final long serialVersionUID = 1338029208271055776L;
  11751. private final ArgSpec overwrittenArg;
  11752. public OverwrittenOptionException(CommandLine commandLine, ArgSpec overwritten, String msg) {
  11753. super(commandLine, msg);
  11754. overwrittenArg = overwritten;
  11755. }
  11756. /** Returns the {@link ArgSpec} for the option which was being overwritten.
  11757. * @since 3.8 */
  11758. public ArgSpec getOverwritten() { return overwrittenArg; }
  11759. }
  11760. /**
  11761. * Exception indicating that an annotated field had a type for which no {@link ITypeConverter} was
  11762. * {@linkplain #registerConverter(Class, ITypeConverter) registered}.
  11763. */
  11764. public static class MissingTypeConverterException extends ParameterException {
  11765. private static final long serialVersionUID = -6050931703233083760L;
  11766. public MissingTypeConverterException(CommandLine commandLine, String msg) { super(commandLine, msg); }
  11767. }
  11768. }