-
Notifications
You must be signed in to change notification settings - Fork 25
/
cligen.nim
1309 lines (1245 loc) · 66 KB
/
cligen.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
when not (defined(cgCfgNone) and defined(cgNoColor)):
{.push hint[Performance]: off.} # Silence RstToken copy warning
# Messages need `stderr` usually gotten by include clCfgInit|clCfgToml.
when defined(cgCfgNone) and not declared(stderr): import std/syncio
when (NimMajor,NimMinor,NimPatch) > (0,20,2):
{.push warning[UnusedImport]: off.} # This is only for gcarc
import std/[os, macros, tables, strutils, critbits], system/ansi_c,
cligen/[parseopt3, argcvt, textUt, sysUt, macUt, humanUt, gcarc]
export commandLineParams, lengthen, initOptParser, next, optionNormalize,
ArgcvtParams, argParse, argHelp, getDescription, join, `%`, CritBitTree,
incl, valsWithPfx, contains, addPrefix, wrap, TextTab, alignTable,
suggestions, strip, split, helpCase, postInc, delItem, fromNimble,
summaryOfModule, docFromModuleOf, docFromProc, match, wrapWidth
# NOTE: `helpTmpl`, `clCfgInit`, and `syntaxHelp` can all be overridden on a per
# client project basis with a local `cligen/` before cligen-actual in `path`.
include cligen/helpTmpl #Pull in various help template strings
include cligen/syntaxHelp
type # Main defns CLI authors need be aware of (besides top-level API calls)
ClHelpCol* = enum clOptKeys, clValType, clDflVal, clDescrip
ClSIGPIPE* = enum spRaise="raise", spPass="pass", spIsOk="isOk"
ClAlias* = tuple[long: string, short: char, helpStr: string,
dfl: seq[seq[string]]] ## User CL aliases
ClCfg* = object ## Settings tending to be program- or CLI-author-global
version*: string
hTabCols*: seq[ClHelpCol] ## selects columns to format
hTabRowSep*: string ## separates rows, e.g. "\n" double spaces
hTabColGap*: int ## number of spaces to separate cols by
hTabMinLast*: int ## narrowest rightmost col no matter term width
hTabVal4req*: string ## ``"REQUIRED"`` (or ``"NEEDED"``, etc.).
reqSep*: bool ## ``parseopt3.initOptParser`` parameter
sepChars*: set[char] ## ``parseopt3.initOptParser`` parameter
opChars*: set[char] ## ``parseopt3.initOptParser`` parameter
longPfxOk*: bool ## ``parseopt3.initOptParser`` parameter
stopPfxOk*: bool ## ``parseopt3.initOptParser`` parameter
subRowSep*: string ## separates full help dump subcmds; Eg.: "\n"
hTabSuppress*: string ## Magic val for per-param help to suppress
helpAttr*: Table[string, string] ## Text attrs for each help area
helpAttrOff*: Table[string, string] ## Text attr offs for each help area
noHelpHelp*: bool ## Elide --help, --help-syntax from help table
useHdr*: string ## Override of const usage header template
use*: string ## Override of const usage template
useMulti*: string ## Override of const subcmd table template
helpSyntax*: string ## Override of const syntaxHelp string
render*: proc(s: string): string ## string->string help transformer
widthEnv*: string ## name of environment var for width override
sigPIPE*: ClSIGPIPE ## `dispatch` use allows end-user SIGPIPE ctrl
minStrQuoting*: bool ## Only quote string defaults when necessary
trueDefaultStr*: string ## How to render a default value of "true"
falseDefaultStr*: string ## How to render a default value of "false"
wrapDoc*: int ## Terminal column to wrap at for doc-like &..
wrapTable*: int ##..Table-like sections. 0 => auto -1 => never
HelpOnly* = object of CatchableError ## Ok Ctl Flow Only For --help
VersionOnly* = object of CatchableError ## Ok Ctl Flow Only For --version
ParseError* = object of CatchableError ## CL-Syntax Err from generated code
HelpError* = object of CatchableError ## User-Syntax/Semantic Err; ${HELP}
proc descape(s: string): string =
for c, escaped in s.descape: result.add c
{.push hint[GlobalVar]: off.}
var clCfg* = ClCfg(
version: "",
hTabCols: @[ clOptKeys, clValType, clDflVal, clDescrip ],
hTabRowSep: "",
hTabColGap: 2,
hTabMinLast: 16,
hTabVal4req: "REQUIRED",
reqSep: false,
sepChars: { '=', ':' },
opChars: { '+', '-', '*', '/', '%', '@', ',', '.', '&',
'|', '~', '^', '$', '#', '<', '>', '?' },
longPfxOk: true,
stopPfxOk: true,
subRowSep: "",
hTabSuppress: "CLIGEN-NOHELP",
helpAttr: initTable[string,string](),
helpAttrOff: initTable[string,string](),
helpSyntax: syntaxHelp,
render: descape, # Often set in `clCfgInit`, eg. to `rstMdToSGR`
widthEnv: "CLIGEN_WIDTH",
sigPIPE: spIsOk,
minStrQuoting: false,
trueDefaultStr: "true",
falseDefaultStr: "false")
var cgParseErrorExitCode* = 1
{.pop.}
const builtinOptions = ["help", "helpsyntax", "version"]
proc toInts*(x: seq[ClHelpCol]): seq[int] =
##Internal routine to convert help column enums to just ints for `alignTable`.
for e in x: result.add(int(e))
when defined(cgCfgToml): # An include helpTmpl and syntaxHelp
include cligen/clCfgToml # Trade parsetoml dependency for better documention
elif not defined(cgCfgNone):
include cligen/clCfgInit # Just use stdlib parsecfg
proc onCols*(c: ClCfg): seq[string] =
##Internal routine to map help table color specs to strings for `alignTable`.
for e in ClHelpCol.low..ClHelpCol.high:
result.add c.helpAttr.getOrDefault($e, "")
proc offCols*(c: ClCfg): seq[string] =
##Internal routine to map help table color specs to strings for `alignTable`.
for e in ClHelpCol.low..ClHelpCol.high:
result.add c.helpAttrOff.getOrDefault($e, "")
proc ha0*(key: string, c=clCfg): string = c.helpAttr.getOrDefault(key, "")
## Internal routine to access `c.helpAttr`
proc ha1*(key: string, c=clCfg): string = c.helpAttrOff.getOrDefault(key, "")
## Internal routine to access `c.helpAttrOff`
type #Utility types/code for generated parser/dispatchers for parseOnly mode
ClStatus* = enum clBadKey, ## Unknown long key
clBadVal, ## Unparsable value
clNonOption, ## Unexpected non-option
clMissing, ## Required but missing
clParseOptErr, ## parseopt error
clOk, ## Option parse part ok
clPositional, ## Expected non-option
clHelpOnly, clVersionOnly ## Early Exit requests
ClParse* = tuple[paramName: string, ## Param name/long opt key
unparsedVal: string, ## Unparsed val ("" for missing)
message: string, ## default error message
status: ClStatus] ## Parse status for param
const ClErrors* = { clBadKey, clBadVal, clNonOption, clMissing }
const ClExit* = { clHelpOnly, clVersionOnly }
const ClNoCall* = ClErrors + ClExit
var setByParseDum: seq[ClParse]; let cgSetByParseNil* = setByParseDum.addr
var varSeqStrDum: seq[string] ; let cgVarSeqStrNil* = varSeqStrDum.addr
proc quits*(s: int) = quit(if s < -128: -128 elif s > 127: 127 else: s)
## quits)afe|s)aturating is for non-literal/maybe big input for compatibility
## w/older Nim stdlibs. Value is clipped to -128..127. Note that Unix shells
## often map a signaled exit to SIGNUM-128, e.g. 2-128 for SIGINT.
proc die0(s: cint) {.noconv, used.} = quit(0)
proc SIGPIPE_isOk*() =
## Install signal handler to exit success upon OS posting SIGPIPE. This is
## more or less what (non-network) programs/users "expect".
when declared(SIGPIPE): c_signal(SIGPIPE, die0)
proc SIGPIPE_pass*() =
## Restore default signal disposition to allow OS to post SIGPIPE and likely
## terminate with non-zero exit status (typically 141=128+signo13). This
## optimizes for "no surprises" behavior of exec()d code reasonably expecting
## to inherit a near default SIGPIPE disposition.
when declared(SIGPIPE) and declared(SIG_DFL): c_signal(SIGPIPE, SIG_DFL)
proc contains*(x: openArray[ClParse], paramName: string): bool =
##Test if the ``seq`` updated via ``setByParse`` contains a parameter.
for e in x:
if e.paramName == paramName: return true
proc contains*(x: openArray[ClParse], status: ClStatus): bool =
##Test if the ``seq`` updated via ``setByParse`` contains a certain status.
for e in x:
if e.status == status: return true
proc numOfStatus*(x: openArray[ClParse], stati: set[ClStatus]): int =
##Count elements in the ``setByParse seq`` with parse status in ``stati``.
for e in x:
if e.status in stati: inc(result)
proc next*(x: openArray[ClParse], stati: set[ClStatus], start=0): int =
##First index after startIx in ``setByParse seq`` w/parse status in ``stati``.
result = -1
for i, e in x:
if e.status in stati: return i
#[ Define many things used to interpolate into Overall Structure below ]#
proc dispatchId(name: string="", cmd: string="", rep: string=""): NimNode =
result = if name.len > 0: ident(name) #Nim ident for gen'd parser-dispatcher
elif cmd.len > 0: ident("dispatch" & cmd) #XXX illegal chars?
else: ident("dispatch" & rep)
proc containsParam(fpars: NimNode, key: NimNode): bool =
for declIx in 1 ..< len(fpars): #default for result=false
let idefs = fpars[declIx] #Use similar logic to formalParamExpand
for i in 0 ..< len(idefs) - 3: #..since`suppress` is a seq we check.
if maybeDestrop(idefs[i]) == key: return true
if maybeDestrop(idefs[^3]) == key: return true
proc formalParamExpand(fpars: NimNode, n: auto,
suppress: seq[NimNode]= @[]): NimNode =
# a,b,..,c:type [maybe=val] --> a:type, b:type, ..., c:type [maybe=val]
result = newNimNode(nnkFormalParams)
result.add(fpars[0]) # just copy ret value
for p in suppress:
if not fpars.containsParam(p):
error repr(n[0]) & " has no param matching `suppress` key \"" & $p & "\""
for declIx in 1 ..< len(fpars):
let idefs = fpars[declIx]
for i in 0 ..< len(idefs) - 3:
if not suppress.has(idefs[i]):
result.add(newIdentDefs(idefs[i], idefs[^2]))
if not suppress.has(idefs[^3]):
result.add(newIdentDefs(idefs[^3], idefs[^2], idefs[^1]))
proc formalParams(n: NimNode, suppress: seq[NimNode]= @[]): NimNode =
for kid in n: #Extract expanded formal parameter list from getImpl return val.
if kid.kind == nnkFormalParams:
return formalParamExpand(kid, n, suppress)
error "formalParams requires a proc argument."
iterator ids(vars: seq[NimNode], fpars: NimNode, posIx = 0): NimNode =
for v in vars: yield v # Search vars 1st so if name collides with
for i in 1 ..< len(fpars): #..formal param, more local latter wins.
if i != posIx: yield fpars[i][0] # ix cannot==0 => Like ix!=0 and etc
proc hasId(vars: seq[NimNode]; fpars, key: NimNode; posIx = 0): bool =
for id in ids(vars, fpars, posIx): (if id.maybeDestrop == key: return true)
iterator AListPairs(alist: NimNode, msg: string): (NimNode, NimNode) =
if alist.kind == nnkSym:
let imp = alist.getImpl
when (NimMajor,NimMinor,NimPatch) >= (1,7,3):
if imp.len < 3 or imp[2].len < 2 or imp[2][1].len < 2: # Be more precise?
error msg & " initializer must be a static/const {}.toTable construct"
let tups = imp[2][1][1]
else:
if imp.len < 2 or imp[1].len < 2: # This condition should be more precise
error msg & " initializer must be a static/const {}.toTable construct"
let tups = imp[1][1]
for tup in tups:
if tup[0].intVal != 0:
yield(tup[1], tup[2])
else:
for ph in alist: yield (ph[1][0], ph[1][1])
proc parseHelps(helps: NimNode, proNm: auto, vars: auto, fpars: auto):
Table[string, (string, string)] =
result = initTable[string, (string, string)]() #help key & text for any param
for ph in AListPairs(helps, "`help`"):
let k = ph[0].toString.optionNormalize
if not hasId(vars, fpars, k.ident) and k notin builtinOptions:
error $proNm & " has no param matching `help` key \"" & k & "\""
result[k] = (ph[0].toString, ph[1].toString)
proc parseShorts(shorts: NimNode, proNm: auto, vars: auto, fpars: auto):
Table[string, char] =
result = initTable[string, char]() #table giving user-specified short option
for ls in AListPairs(shorts, "`short`"):
let k = ls[0].toString.optionNormalize
if k.len>0 and not hasId(vars, fpars, k.ident) and k notin builtinOptions:
error $proNm & " has no param matching `short` key \"" & k & "\""
if ls[1].kind notin {nnkCharLit, nnkIntLit}:
error "`short` value for \"" & k & "\" not a `char` lit"
result[k] = if shorts.kind==nnkSym: ls[1].toInt.char else: ls[1].intVal.char
proc dupBlock(vars:auto, fpars: auto, posIx: int, userSpec: Table[string,char]):
Table[string, char] = # Table giving short[param] avoiding collisions
result = initTable[string, char]() # short option for param
var used: set[char] = {} # used shorts; bit vector ok
if "help" notin userSpec:
result["help"] = 'h'
used.incl('h')
if "" in userSpec: return # Empty string key==>no short opts
for lo, sh in userSpec:
result[lo] = sh
used.incl sh
for id in ids(vars, fpars, posIx): # positionals get no option char
let parNm = optionNormalize($id)
if parNm.len == 1:
if parNm notin userSpec:
result[parNm] = parNm[0]
if parNm[0] in used and result[parNm] != parNm[0]:
error "cannot use unabbreviated name '" & $parNm[0]&"' as a short option"
used.incl parNm[0]
for id in ids(vars, fpars, posIx): # positionals get no option char
let parNm = optionNormalize($id)
if parNm.len == 1 and parNm[0] == result["help"]:
error "`"&parNm&"` collides with `short[\"help\"]`. Change help short."
let sh = parNm[0] # abbreviation is 1st character
if sh notin used and parNm notin result: # still available
result[parNm] = sh
used.incl(sh)
var tmp = result #One might just put sh != '\0' above, but this lets
for k, v in tmp: #CLI authors also block -h via short={"help": '\0'}.
if v == '\0': result.del(k)
const AUTO = "\0" #Just some "impossible-ish" identifier
proc posIxGet(positional: string, fpars: NimNode): int =
if positional == "": # Find proc param slot for optional positional CL args
return -1 # Empty string means deactivate auto identification.
if positional != AUTO:
result = findByName(ident(positional), fpars)
if result == -1:
error("requested positional argument catcher " & positional &
" is not in formal parameter list")
return
result = -1 # No optional positional arg param yet found
for i in 1 ..< len(fpars):
let idef = fpars[i] # 1st typed,non-defaulted seq; Allow override?
if idef[1].kind != nnkEmpty and idef[2].kind == nnkEmpty and
typeKind(getType(idef[1])) == ntySequence:
if result != -1: # Allow multiple seq[T]s via "--" separators?
warning("cligen only supports one seq param for positional args; using"&
" `" & $fpars[result][0] & "`, not `" & $fpars[i][0] & "`. " &
"Use `positional` parameter to `dispatch` to override this.")
else:
result = i
proc got(a: NimNode): bool =
(a.len == 2 and a[1].len == 2 and a[1][0].len == 2 and a[1][1].len == 2 and
a[1][0][1].len == 4 and a[1][1][1].len == 4)
macro dispatchGen*(pro: typed{nkSym}, cmdName: string="", doc: string="",
help: typed={}, short: typed={}, usage: string=clUse, cf: ClCfg=clCfg,
echoResult=false, noAutoEcho=false, positional: static string=AUTO,
suppress: seq[string] = @[], implicitDefault: seq[string] = @[],
vars: seq[string] = @[], dispatchName="", mergeNames: seq[string] = @[],
alias: seq[ClAlias] = @[], stopWords: seq[string] = @[], noHdr=false,
docs: ptr var seq[string]=cgVarSeqStrNil,
setByParse: ptr var seq[ClParse]=cgSetByParseNil): untyped =
##Generate command-line dispatcher for proc ``pro`` named ``dispatchName``
##(defaulting to ``dispatchPro``) with generated help/syntax guided by
##``cmdName``, ``doc``, and ``cf``. Parameters with no explicit default in
##the proc become required command arguments while those with default values
##become command options. Each proc parameter type needs in-scope ``argParse``
##& ``argHelp`` procs. ``cligen/argcvt`` defines them for basic types & basic
##collections (``int``, ``string``, ``enum``, .., ``seq[T], set[T], ..``).
##
##``help`` is a ``{(paramNm, str)}`` of per-param help, eg. ``{"quiet": "be
##quiet"}``. Often, only these help strings are needed for a decent CLI.
##A row of the help table can be suppressed from showing by setting ``str``
##to a magic ``clCfg.hTabSuppress`` value (defaults to ``"CLIGEN-NOHELP"``,
##but is customizable).
##
##``short`` is a ``{(paramNm, char)}`` of per-param single-char option keys.
##Setting a parameter value to ``'\0'`` suppresses the assignment of a short
##option. Suppress all short options by passing an empty key: ``{ "": ' ' }``.
##
##``help`` & ``short`` definitions outside a call require explicit ``toTable``
## (from ``std/tables``) conversions.
##
##``usage`` is a help template interpolating $command $args $doc $options.
##
##``cf`` controls whole program aspects of generated CLIs. See ``ClCfg`` docs.
##
##Default exit protocol is: quits(int(result)) or (echo $result or discard;
##quit(0)) depending on what compiles. True ``echoResult`` forces echo while
##``noAutoEcho`` blocks it (=>int()||discard). Technically, ``cligenQuit``
##implements this behavior.
##
##By default, ``cligen`` maps the first non-defaulted ``seq[]`` proc parameter
##to any non-option/positional command args. ``positional`` selects another.
##Set ``positional`` to the empty string (``""``) to disable this entirely.
##
##``suppress`` is a list of formal parameter names to exclude from the parse-
##assign system. Such names are effectively pinned to their default values.
##
##``implicitDefault`` is a list of formal parameter names allowed to default
##to the Nim default value for a type, rather than becoming required, when
##they lack an explicit initializer.
##
##``vars`` is a ``seq[string]`` of outer scope-declared variables bound to the
##CLI (e.g., on CL, `--logLvl=X` converts & assigns to `outer.logLvl = X`).
##
##``stopWords`` is a ``seq[string]`` of words beyond which ``-.*`` no longer
##signifies an option (like the common sole ``--`` command argument).
##
##``noHdr`` is a (mostly internal) flag to suppress emitting "Usage:" header
##in generated help tables (e.g. in a multi-command).
##
##``mergeNames`` gives the ``cmdNames`` param passed to ``mergeParams``, which
##defaults to ``@[cmdName]`` if ``mergeNames`` is ``@[]``.
##
##``alias`` is ``@[]`` | 2-seq of ``(string,char,string)`` 3-tuples specifying
##(Long, Short opt keys, Help) to {Define,Reference} aliases. This lets CL
##users define aliases early in ``mergeParams`` sources (e.g. cfg files/evars)
##& reference them later. Eg. if ``alias[0][0]=="alias" and alias[1][1]=='a'``
##then ``--alias:k='-a -b' -ak`` expands to ``@["-a", "-b"]``.
##
##``docs`` is ``addr(some var seq[string])`` to which to append each main doc
##comment or its replacement doc=text. Default of ``nil`` means do nothing.
##
##``setByParse`` is ``addr(some var seq[ClParse])``. When non-nil, this var
##collects each parameter seen, keyed under its long/param name (i.e., parsed
##but not converted to native types). Wrapped procs can inspect this or even
##convert args themselves to revive ``parseopt``-like iterative interpreting.
##``cligen`` provides convenience procs to use ``setByParse``: ``contains``,
##``numOfStatus`` & ``next``. Note that ordinary Nim procs, from inside calls,
##do not know how params got their values (positional, keyword, defaulting).
##Wrapped procs accessing ``setByParse`` are inherently command-line only. So,
##this ``var seq`` needing to be declared before such procs for such access is
##ok. Ideally, keep important functionality Nim-callable. ``setByParse`` may
##also be useful combined with the ``parseOnly`` arg of generated dispatchers.
let impl = pro.getImpl
if impl == nil: error "getImpl(" & $pro & ") returned nil."
let fpars = formalParams(impl, toIdSeq(suppress))
let vrs = toIdSeq(vars)
var cmtDoc = toString(doc)
if cmtDoc.len == 0: # allow caller to override commentDoc
collectComments(cmtDoc, impl)
cmtDoc = strip(cmtDoc)
let cf = cf #sub-scope quote-do's cannot access macro args w/o shadow locals.
let setByParse = setByParse
let proNm = $pro # Name of wrapped proc
let cName = if cmdName.toString.len == 0: proNm else: cmdName.toString
let disNm = dispatchId(dispatchName.toString, cName, proNm) # Name of wrapper
let helps = parseHelps(help, proNm, vrs, fpars)
let posIx = posIxGet(positional, fpars) #param slot for positional cmd args|-1
let shOpt = dupBlock(vrs, fpars, posIx, parseShorts(short, proNm, vrs, fpars))
let shortH = shOpt["help"]
var spars = copyNimTree(fpars) # Create shadow/safe suffixed params.
var dpars = copyNimTree(fpars) # Create default suffixed params.
var mandatory = newSeq[int]() # At the same time, build metadata on..
let implDef = toIdSeq(implicitDefault)
for p in implDef:
if not fpars.containsParam(p):
error $proNm&" has no param matching `implicitDefault` key \"" & $p & "\""
var hasVsn = false
for i in 1 ..< len(fpars): #..non-defaulted/mandatory parameters.
if ident($(fpars[i][0])) == ident("version"):
hasVsn = true
dpars[i][0] = ident($(fpars[i][0]) & "ParamDefault") # unique suffix
spars[i][0] = ident($(fpars[i][0]) & "ParamDispatch") # unique suffix
if fpars[i][2].kind == nnkEmpty:
if i == posIx: # No initializer; Add @[]
spars[posIx][2] = prefix(newNimNode(nnkBracket), "@")
else:
if fpars[i][1].kind == nnkEmpty:
error("parameter `" & $(fpars[i][0]) &
"` has neither a type nor a default value")
if not implDef.has(fpars[i][0]):
mandatory.add(i)
let posNoId = ident("posNo") # positional arg number
let keyCountId = ident("keyCount") # id for keyCount table
let usageId = ident("usage") # gen proc parameter
let cmdLineId = ident("cmdline") # gen proc parameter
let vsnSh = if "version" in shOpt: $shOpt["version"] else: "\0"
let prefixId = ident("prefix") # local help prefix param
let prsOnlyId = ident("parseOnly") # flag to only produce a parse vector
let skipHelp = ident("skipHelp") # flag to control --help/--help-syntax
let noHdrId = ident("noHdr") # flag to control using `clUseHdr`
let pId = ident("p") # local OptParser result handle
let allId = ident("allParams") # local list of all parameters
let cbId = ident("crbt") # CritBitTree for prefix lengthening
let mandId = ident("mand") # local list of mandatory parameters
let apId = ident("ap") # ArgcvtParams
var callIt = newNimNode(nnkCall) # call of wrapped proc in genproc
callIt.add(pro)
let shortHlp = newStrLitNode($shortH)
let setByParseId = ident("setByP") # parse recording var seq
let b0 = ident("b0"); let b1 = ident("b1")
let g0 = ident("g0"); let g1 = ident("g1")
let es = newStrLitNode("")
let aliasesId = ident("aliases") # [key]=>seq[string] meta param table
let aliasSnId = ident("aliasSeen") # flag saying *any* alias was used
let dflSub = ident("dflSub") # default alias if *no* alias was used
let provideId = ident("provideDflAlias") # only use default alias @top level
let aliasDefL = if alias.got: alias[1][0][1][0] else: es
let aliasDefN = if alias.got:optionNormalize(alias[1][0][1][0].strVal) else:""
let aliasDefS = if alias.got: toStrIni(alias[1][0][1][1].intVal) else: es
let aliasDefH = if alias.got: alias[1][0][1][2] else: es
let aliasDefD = if alias.got: alias[1][0][1][3] else: es
let aliasRefL = if alias.got: alias[1][1][1][0] else: es
let aliasRefN = if alias.got:optionNormalize(alias[1][1][1][0].strVal) else:""
let aliasRefS = if alias.got: toStrIni(alias[1][1][1][1].intVal) else: es
let aliasRefH = if alias.got: alias[1][1][1][2] else: es
let aliasRefD = if alias.got: alias[1][1][1][3] else: es
let aliases = if alias.got: quote do:
var `aliasSnId` = false
var `aliasesId`: CritBitTree[seq[string]]
for d in `aliasDefD`:
if d.len > 1: `aliasesId`[d[0]] = d[1 .. ^1]
var `dflSub`: seq[string] = if `aliasRefD`.len>0:
`aliasRefD`[0] else: @[]
else: newNimNode(nnkEmpty)
let aliasesCallDfl = if alias.got: quote do:
if `provideId` and not `aliasSnId` and `dflSub`.len > 0:
#XXX Doing this feature right needs 2 OptParser passes. {Default alias should
#be processed first not last to not clobber earlier cfg/CL actual settings,
#but cannot know it is needed without first checking the whole CL.}
parser(move(`dflSub`), `provideId`=false)
else: newNimNode(nnkEmpty)
let helpHelp = helps.getOrDefault("help",
("help", "print this cligen-erated help"))
let helpSyn = helps.getOrDefault("helpsyntax", ("help-syntax",
"advanced: prepend,plurals,.."))
let helpVsn = helps.getOrDefault("version", ("version", "print version"))
proc initVars0(): NimNode = # init vars & build help str
result = newStmtList()
let tabId = ident("tab") # local help table var
result.add(quote do:
var `apId`: ArgcvtParams
`apId`.val4req = `cf`.hTabVal4req
let shortH = `shortHlp`
var `allId`: seq[string] =
if `cf`.helpSyntax.len > 0: @[ "help", "help-syntax" ] else: @[ "help" ]
var `cbId`: CritBitTree[string]
`cbId`.incl(optionNormalize("help"), "help")
if `cf`.helpSyntax.len > 0:
`cbId`.incl(optionNormalize("help-syntax"), "help-syntax")
var `mandId`: seq[string]
var `tabId`: TextTab = @[]
let helpHelpRow = @[ "-"&shortH&", --help", "", "", `helpHelp`[1] ]
let `skipHelp` = `skipHelp` or `cf`.noHelpHelp
if `skipHelp`: # auto-skip help help for `helpDump`
if shortH != "h" and `helpHelp`[1] != `cf`.hTabSuppress:
`tabId`.add(helpHelpRow)
elif `helpHelp`[1] != `cf`.hTabSuppress: `tabId`.add(helpHelpRow)
if `cf`.helpSyntax.len > 0 and `helpSyn`[1] != `cf`.hTabSuppress and
not `skipHelp`:
`tabId`.add(@[ "--" & `helpSyn`[0], "", "", `helpSyn`[1] ])
`apId`.shortNoVal = { shortH[0] } # argHelp(bool) updates
`apId`.longNoVal = @[ "help", "help-syntax" ] # argHelp(bool) appends
`apId`.minStrQuoting = `cf`.minStrQuoting
`apId`.trueDefaultStr = `cf`.trueDefaultStr
`apId`.falseDefaultStr = `cf`.falseDefaultStr
let `setByParseId`: ptr seq[ClParse] = `setByParse`
let `b0` = ha0("bad" , `cf`); let `b1` = ha1("bad" , `cf`)
let `g0` = ha0("good", `cf`); let `g1` = ha1("good", `cf`)
{.push warning[GCUnsafe]: off.} # See github.com/c-blake/cligen/issues/92
proc mayRend(x: string): string = # {.gcsafe.} clCfg access
if `cf`.render != nil: `cf`.render(x) else: x
{.pop.})
result.add(quote do:
if `cf`.version.len > 0:
`allId`.add "version"
`cbId`.incl(optionNormalize("version"), "version")
`apId`.parNm = "version"; `apId`.parSh = `vsnSh`
`apId`.parReq = 0; `apId`.parRend = `helpVsn`[0]
if `helpVsn`[1] != `cf`.hTabSuppress:
`tabId`.add(argHelp(false, `apId`) & `helpVsn`[1]))
for parId in vrs: # Handle user-specified variables
let pNm = optionNormalize($parId)
let sh = $shOpt.getOrDefault(pNm) # Add to perPar helpTab
let hky = helps.getOrDefault(pNm)[0]
let hlp = helps.getOrDefault(pNm)[1]
result.add(quote do:
`apId`.parNm = `pNm`; `apId`.parSh = `sh`; `apId`.parReq = ord(false)
`apId`.parRend = if `hky`.len>0: `hky` else: helpCase(`pNm`, clLongOpt)
let descr = getDescription(`parId`, `pNm`, `hlp`)
if descr != `cf`.hTabSuppress:
`tabId`.add(argHelp(`parId`, `apId`) & mayRend(descr))
`cbId`.incl(`pNm`, move(`apId`.parRend))
`allId`.add(helpCase(`pNm`, clLongOpt)))
if aliasDefL.strVal.len > 0 and aliasRefL.strVal.len > 0:
result.add(quote do: # add opts for user alias system
`cbId`.incl(optionNormalize(`aliasDefL`), `aliasDefL`)
`apId`.parNm = `aliasDefL`; `apId`.parSh = `aliasDefS`
`apId`.parReq = 0; `apId`.parRend = `apId`.parNm
`tabId`.add(argHelp("", `apId`) & `aliasDefH`)
`cbId`.incl(optionNormalize(`aliasRefL`), `aliasRefL`)
`apId`.parNm = `aliasRefL`; `apId`.parSh = `aliasRefS`
`apId`.parReq = 0; `apId`.parRend = `apId`.parNm
`tabId`.add(argHelp("", `apId`) & `aliasRefH`) )
let (posNm, posHlp, posTy) = if posIx != -1:
let kH = helps.getOrDefault(optionNormalize($fpars[posIx][0]), ("",""))
let ty = if fpars[posIx][1].kind == nnkSym: fpars[posIx][1].getImpl.repr
else: fpars[posIx][1][1].strVal
if kH[0].len != 0: (kH[0], kH[1], ty)
else: ($fpars[posIx][0], "", ty)
else: ("", "", "")
for i in 1 ..< len(fpars):
let idef = fpars[i]
let sdef = spars[i]
result.add(newNimNode(nnkVarSection).add(sdef)) #Init vars
if i != posIx:
result.add(newVarStmt(dpars[i][0], sdef[0]))
callIt.add(newNimNode(nnkExprEqExpr).add(idef[0], sdef[0])) #Add to call
if i != posIx:
let parNm = $idef[0]
let defVal = sdef[0]
let pNm = parNm.optionNormalize
let sh = $shOpt.getOrDefault(pNm) #Add to perPar helpTab
let hky = helps.getOrDefault(pNm)[0]
let hlp = helps.getOrDefault(pNm)[1]
let isReq = if i in mandatory: true else: false
result.add(quote do:
`apId`.parNm = `parNm`; `apId`.parSh = `sh`; `apId`.parReq=ord(`isReq`)
`apId`.parRend = if `hky`.len>0: `hky` else:helpCase(`parNm`,clLongOpt)
let descr = getDescription(`defVal`, `parNm`, `hlp`)
if descr != `cf`.hTabSuppress:
`tabId`.add(argHelp(`defVal`, `apId`) & mayRend(descr))
if `apId`.parReq != 0: `tabId`[^1][2] = `apId`.val4req
`cbId`.incl(optionNormalize(`parNm`), move(`apId`.parRend))
`allId`.add(helpCase(`parNm`, clLongOpt)))
if isReq:
result.add(quote do: `mandId`.add(`parNm`))
result.add(quote do: # build one large help string
let wwd = wrapWidth(`cf`.widthEnv, `cf`.wrapDoc)
let wwt = wrapWidth(`cf`.widthEnv, `cf`.wrapTable)
let indentDoc = addPrefix(`prefixId`, wrap(mayRend(`cmtDoc`), wwd,
prefixLen=`prefixId`.len))
proc hl(tag, val: string): string = # {.gcsafe.} clCfg access
(`cf`.helpAttr.getOrDefault(tag, "") & val &
`cf`.helpAttrOff.getOrDefault(tag, ""))
let posHelp = if `posHlp`.len != 0: `posHlp`
elif `posNm`.len == 0: ""
else: "[" & hl("clOptKeys", `posNm`) & ": " &
hl("clValType", `posTy`) & "...]"
let useHdr = if `cf`.useHdr.len > 0: `cf`.useHdr else: clUseHdr
var use = if `usageId`.startsWith("CG-TL") and `noHdrId`: `usageId`[5..^1]
elif `cf`.use.len > 0: `cf`.use else: `usageId`
if not `noHdrId` and not("$usehdr" in use or "${usehdr}" in use) and
clUseHdr notin use: use = useHdr & use
let argStart = "[" & (if `mandatory`.len>0: `apId`.val4req&"," else: "") &
"optional-params]"
`apId`.help = use % ["doc", hl("doc", indentDoc),
"usehdr", hl("usehdr", useHdr),
"command", hl("cmd", `cName`),
"args", hl("args",argStart & " " & posHelp.mayRend),
"options", addPrefix(`prefixId` & " ",
alignTable(`tabId`, 2*len(`prefixId`) + 2,
`cf`.hTabColGap, `cf`.hTabMinLast,
`cf`.hTabRowSep, toInts(`cf`.hTabCols),
`cf`.onCols, `cf`.offCols, width=wwt))]
if `apId`.help.len > 0 and `apId`.help[^1] != '\n': #ensure newline @end
`apId`.help &= "\n"
if len(`prefixId`) > 0: # to indent help in a multicmd context
`apId`.help = addPrefix(`prefixId`, `apId`.help))
proc optCases0(): NimNode =
result = newNimNode(nnkCaseStmt).add(quote do:
if p.kind == cmdLongOption: lengthen(`cbId`, `pId`.key, `cf`.longPfxOk)
else: `pId`.key)
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode("help"), shortHlp).add(
quote do:
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add(("help", "", `apId`.help, clHelpOnly))
if not `prsOnlyId`:
stdout.write(`apId`.help); raise newException(HelpOnly, "")))
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode("helpsyntax")).add(
quote do:
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add(("helpsyntax","", #COPY
`cf`.helpSyntax[0..^1], clHelpOnly))
if not `prsOnlyId`:
stdout.write(`cf`.helpSyntax); raise newException(HelpOnly, "")))
if not hasVsn:
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode("version"), newStrLitNode(vsnSh)).add(
quote do:
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add(("version", "", #COPY
`cf`.version[0..^1], clVersionOnly))
if not `prsOnlyId`:
if `cf`.version.len > 0:
stdout.write(`cf`.version, "\n")
raise newException(VersionOnly, "")
else:
stdout.write("Unknown version\n")
raise newException(VersionOnly, "")))
if aliasDefL.strVal.len > 0 and aliasRefL.strVal.len > 0: #CL user aliases
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode(aliasDefN), aliasDefS).add(
quote do:
let cols = `pId`.val.split('=', 1) #split on 1st '=' only
try: `aliasesId`[cols[0].strip] = parseCmdLine(cols[1].strip)
except CatchableError: stderr.write "ignored bad alias: ",
cols[0].strip, " = ", cols[1].strip, "\n"))
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode(aliasRefN), aliasRefS).add(
quote do:
`aliasSnId` = true #true for even unsuccessful attempted ref
var msg: string
let sub = `aliasesId`.match(`pId`.val, "alias ref", msg)
if msg.len > 0:
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add((move(`pId`.key), move(`pId`.val),
move(msg), clBadKey))
if not `prsOnlyId`:
stderr.write msg
let t = if msg.startsWith "Ambig": "Ambiguous" else: "Unknown"
raise newException(ParseError, t & " alias ref")
else:
parser(sub.val) ))
for i in 1 ..< len(fpars): # build per-param case clauses
if i == posIx: continue # skip variable len positionals
let parNm = $fpars[i][0]
let lopt = optionNormalize(parNm)
let spar = spars[i][0]
let dpar = dpars[i][0]
let apCall = quote do:
`apId`.key = `pId`.key
`apId`.val = `pId`.val
`apId`.sep = `pId`.sep
`apId`.parNm = `parNm`
`apId`.parRend = helpCase(`parNm`, clLongOpt)
`keyCountId`.inc(`parNm`)
`apId`.parCount = `keyCountId`[`parNm`]
if cast[pointer](`setByParseId`) != cgSetByParseNil:
if argParse(`spar`, `dpar`, `apId`):
`setByParseId`[].add((`parNm`, move(`pId`.val), "", clOk))
else:
`setByParseId`[].add((`parNm`, move(`pId`.val),
"Cannot parse arg to " & `apId`.key, clBadVal))
if not `prsOnlyId`:
if not argParse(`spar`, `dpar`, `apId`):
stderr.write `apId`.msg
raise newException(ParseError, "Cannot parse arg to " & `apId`.key)
discard delItem(`mandId`, `parNm`)
if lopt in shOpt and lopt.len > 1: # both a long and short option
let parShOpt = $shOpt.getOrDefault(lopt)
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode(lopt), newStrLitNode(parShOpt)).add(apCall))
else: # only a long option
result.add(newNimNode(nnkOfBranch).add(newStrLitNode(lopt)).add(apCall))
for parId in vrs: # add per-var cases
let parNm = $parId #XXX This COULD consult a saved-
let lopt = optionNormalize(parNm) # .. above table of used case
let apCall = quote do: # .. labels and give user a nicer
`apId`.key = `pId`.key # .. error message than "dup case
`apId`.val = `pId`.val # .. labels".
`apId`.sep = `pId`.sep
`apId`.parNm = `parNm`
`apId`.parRend = helpCase(`parNm`, clLongOpt)
`keyCountId`.inc(`parNm`)
`apId`.parCount = `keyCountId`[`parNm`]
if cast[pointer](`setByParseId`) != cgSetByParseNil:
if argParse(`parId`, `parId`, `apId`):
`setByParseId`[].add((`parNm`, move(`pId`.val), "", clOk))
else:
`setByParseId`[].add((`parNm`, move(`pId`.val),
"Cannot parse arg to " & `apId`.key, clBadVal))
if not `prsOnlyId`:
if not argParse(`parId`, `parId`, `apId`):
stderr.write `apId`.msg
raise newException(ParseError, "Cannot parse arg to " & `apId`.key)
discard delItem(`mandId`, `parNm`)
if lopt in shOpt and lopt.len > 1: # both a long and short option
let parShOpt = $shOpt.getOrDefault(lopt)
result.add(newNimNode(nnkOfBranch).add(
newStrLitNode(lopt), newStrLitNode(parShOpt)).add(apCall))
else: # only a long option
result.add(newNimNode(nnkOfBranch).add(newStrLitNode(lopt)).add(apCall))
let ambigReport = quote do:
let ks = `cbId`.valsWithPfx(p.key)
let msg=("Ambiguous long option prefix \"" & `b0` & "$1" & `b1` & "\"" &
" matches:\n " & `g0` & "$2" & `g1` & " ")%[`pId`.key,ks.join("\n ")] &
"\nRun with " & `g0` & "--help" & `g1` & " for more details.\n"
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add((move(`pId`.key), move(`pId`.val), msg, clBadKey))
if not `prsOnlyId`:
stderr.write(msg)
raise newException(ParseError, "Unknown option")
result.add(newNimNode(nnkOfBranch).add(newStrLitNode("")).add(ambigReport))
result.add(newNimNode(nnkElse).add(quote do:
var mb, k: string
k = "short"
if `pId`.kind == cmdLongOption:
k = "long"
var idNorm: seq[string]
for id in allParams: idNorm.add(optionNormalize(id))
let sugg = suggestions(optionNormalize(`pId`.key), idNorm, allParams)
if sugg.len > 0: mb &= "Maybe you meant one of:\n\t" & `g0` &
join(sugg, " ") & `g1` & "\n\n"
let msg=("Unknown "&k&" option: \"" & `b0` & `pId`.key & `b1` & "\"\n\n" &
mb & "Run with " & `g0` & "--help" & `g1` & " for full usage.\n")
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add((move(`pId`.key), move(`pId`.val), msg, clBadKey))
if not `prsOnlyId`:
stderr.write(msg)
raise newException(ParseError, "Unknown option")))
proc nonOpt0(): NimNode =
result = newStmtList()
if posIx != -1: # code to parse non-option args
result.add(newNimNode(nnkCaseStmt).add(quote do: postInc(`posNoId`)))
let posId = spars[posIx][0]
let tmpId = ident("tmp" & $posId)
result[0].add(newNimNode(nnkElse).add(quote do:
var `tmpId`: type(`posId`[0])
`apId`.key = "positional $" & $`posNoId`
`apId`.val = `pId`.key
`apId`.sep = "="
`apId`.parNm = `apId`.key
`apId`.parRend = helpCase(`apId`.key, clLongOpt)
`apId`.parCount = 1
let msg = "Cannot parse " & `apId`.key
if cast[pointer](`setByParseId`) != cgSetByParseNil:
if argParse(`tmpId`,`tmpId`,`apId`):
`setByParseId`[].add((move(`apId`.key), move(`apId`.val), "",
clPositional))
else:
`setByParseId`[].add((move(`apId`.key), move(`apId`.val), msg,
clBadVal))
if not `prsOnlyId` and not argParse(`tmpId`, `tmpId`, `apId`):
stderr.write `apId`.msg
raise newException(ParseError, msg)
`posId`.add(`tmpId`)))
else:
result.add(quote do:
let msg = "Unexpected non-option " & $`pId`.key
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add((move(`apId`.key), move(`pId`.val), msg,
clNonOption))
if not `prsOnlyId`:
stderr.write(`cName`&" does not expect non-option arguments at \"" &
$`pId`.key & "\".\nRun with --help for full usage.\n")
raise newException(ParseError, msg))
let initVars=initVars0(); let optCases=optCases0(); let nonOpt=nonOpt0()
let retType=fpars[0]
let mrgNames = if mergeNames[1].len == 0: quote do: @[ `cName` ] #default
else: mergeNames #provided
let docsVar = if docs.kind == nnkAddr: docs[0]
elif docs.kind == nnkCall: docs[1]
else: newNimNode(nnkEmpty)
let docsStmt = if docs.kind == nnkAddr or docs.kind == nnkCall:
quote do: `docsVar`.add(`cmtDoc`)
else: newNimNode(nnkEmpty)
result = quote do: #Overall Structure
case `cf`.sigPIPE
of spRaise: discard # "Nim stdlib default"; Becoming raise in devel/1.6
of spPass: SIGPIPE_pass()
of spIsOk: SIGPIPE_isOk()
if cast[pointer](`docs`) != cgVarSeqStrNil: `docsStmt`
proc `disNm`(`cmdLineId`: seq[string] = mergeParams(`mrgNames`),
`usageId`=`usage`,`prefixId`="", `prsOnlyId`=false,
`skipHelp`=false, `noHdrId`=`noHdr`): `retType`=
{.push hint[XDeclaredButNotUsed]: off.}
`initVars`
`aliases`
var `keyCountId` {.used.} = initCountTable[string]()
proc parser(args=`cmdLineId`, `provideId`=true) = #{.gcsafe.} clCfg access
var `posNoId` = 0
var `pId` = initOptParser(args, `apId`.shortNoVal, `apId`.longNoVal,
`cf`.reqSep, `cf`.sepChars, `cf`.opChars,
`stopWords`, `cf`.longPfxOk, `cf`.stopPfxOk)
while true:
next(`pId`)
if `pId`.kind == cmdEnd: break
if `pId`.kind == cmdError:
if cast[pointer](`setByParseId`) != cgSetByParseNil:
`setByParseId`[].add(("", "", move(`pId`.message), clParseOptErr))
if not `prsOnlyId`:
stderr.write(`pId`.message, "\n")
break
case `pId`.kind
of cmdLongOption, cmdShortOption:
`optCases`
else:
`nonOpt`
`aliasesCallDfl`
{.pop.}
parser()
if `mandId`.len > 0:
if cast[pointer](`setByParseId`) != cgSetByParseNil:
for m in `mandId`:
`setByParseId`[].add((m, "", "Missing " & m, clMissing))
if not `prsOnlyId`:
stderr.write "Missing these " & `apId`.val4req & " parameters:\n"
for m in `mandId`: stderr.write " ", m, "\n"
stderr.write "Run command with --help for more details.\n"
raise newException(ParseError, "Missing one/some mandatory args")
if `prsOnlyId` or (cast[pointer](`setByParseId`) != cgSetByParseNil and
`setByParseId`[].numOfStatus(ClNoCall) > 0):
return
try: `callIt`
except HelpError as e:
stderr.write e.msg % ["HELP", `apId`.help]
raise newException(ParseError, "Bad parameter user-syntax/semantics")
template discarder[T](a: T): void = # discard if possible, else identity; Name
when T is not void: discard a #..ideas: discardVoid alwaysDiscard Discard
else: a #..discarded maybeDiscard discardor..
template cligenQuit*(p: untyped, echoResult=false, noAutoEcho=false): auto =
when echoResult: #CLI author requests echo
try: echo p; quit(0) #May compile-time fail, but do..
except HelpOnly, VersionOnly: quit(0) #..want bubble up to CLI auth.
except ParseError: quits(cgParseErrorExitCode)
elif compiles(int(p)): #Can convert to int
try: quits(int(p))
except HelpOnly, VersionOnly: quit(0)
except ParseError: quits(cgParseErrorExitCode)
elif not noAutoEcho and compiles(echo p): #autoEcho && have `$`
try: echo p; quit(0)
except HelpOnly, VersionOnly: quit(0)
except ParseError: quits(cgParseErrorExitCode)
else: #void return type
try: discarder(p); quit(0)
except HelpOnly, VersionOnly: quit(0)
except ParseError: quits(cgParseErrorExitCode)
template cligenHelp*(p: untyped, hlp: untyped, use: untyped, pfx: untyped,
skipHlp: untyped, noUHdr=false): auto =
try: discarder(p(hlp, usage=use, prefix=pfx, skipHelp=skipHlp, noHdr=noUHdr))
except HelpOnly: discard
macro cligenQuitAux*(cmdLine:seq[string], dispatchName: string, cmdName: string,
pro: untyped, echoResult: bool, noAutoEcho: bool,
mergeNames: seq[string] = @[]): untyped =
let disNm = dispatchId(dispatchName.toString, cmdName.toString, repr(pro))
let cName = if cmdName.toString.len == 0: $pro else: cmdName.toString
let mergeNms = toStrSeq(mergeNames) & cName
quote do: cligenQuit(`disNm`(mergeParams(`mergeNms`, `cmdLine`)),
`echoResult`, `noAutoEcho`)
template dispatchCf*(pro: typed{nkSym}, cmdName="", doc="", help: typed={},
short:typed={},usage=clUse, cf:ClCfg=clCfg,echoResult=false,noAutoEcho=false,
positional=AUTO, suppress:seq[string] = @[], implicitDefault:seq[string] = @[],
vars: seq[string] = @[], dispatchName="", mergeNames: seq[string] = @[],
alias: seq[ClAlias] = @[], stopWords:seq[string] = @[], noHdr=false,
cmdLine=commandLineParams()): untyped =
## A convenience wrapper to both generate a command-line dispatcher and then
## call the dispatcher & exit; Params are same as the ``dispatchGen`` macro.
dispatchGen(pro, cmdName, doc, help, short, usage, cf, echoResult, noAutoEcho,
positional, suppress, implicitDefault, vars, dispatchName,
mergeNames, alias, stopWords, noHdr)
cligenQuitAux(cmdLine, dispatchName, cmdName, pro, echoResult, noAutoEcho)
template dispatch*(pro: typed{nkSym}, cmdName="", doc="", help: typed={},
short:typed={},usage=clUse,echoResult=false,noAutoEcho=false,positional=AUTO,
suppress: seq[string] = @[], implicitDefault: seq[string] = @[],
vars: seq[string] = @[], dispatchName="", mergeNames: seq[string] = @[],
alias: seq[ClAlias] = @[], stopWords: seq[string] = @[], noHdr=false): untyped=
## Convenience `dispatchCf` wrapper to silence bogus GcUnsafe warnings at
## verbosity:2. Parameters are the same as `dispatchCf` (except for no `cf`).
proc cligenScope(cf: ClCfg) =
dispatchCf(pro, cmdName, doc, help, short, usage, cf, echoResult, noAutoEcho,
positional, suppress, implicitDefault, vars, dispatchName,
mergeNames, alias, stopWords, noHdr)
cligenScope(clCfg)
proc subCmdName(p: NimNode): string =
if p.paramPresent("cmdName"): #CLI author-specified
result = $p.paramVal("cmdName")
else: #1st elt of bracket
result = if p[0].kind == nnkDotExpr: $p[0][^1] #qualified (1-level)
else: $p[0] #unqualified
template unknownSubcommand*(cmd: string, subCmds: seq[string]) =
let g0 = ha0("good"); let g1 = ha1("good"); let hlp = g0 & "help" & g1
stderr.write "Unknown subcommand \"", ha0("bad"), cmd, ha1("bad"), "\". "
let sugg = suggestions(cmd, subCmds, subCmds)
if sugg.len > 0:
stderr.write "Maybe you meant one of:\n\t", g0, join(sugg, " "), g1, "\n\n"
else:
stderr.write "It is not similar to defined subcommands.\n\n"
stderr.write "Run again with subcommand \"", hlp, "\" for detailed usage.\n"
quits(cgParseErrorExitCode)
template ambigSubcommand*(cb: CritBitTree[string], attempt: string) =
let g0 = ha0("good"); let g1 = ha1("good"); let hlp = g0 & "help" & g1
stderr.write "Ambiguous subcommand \"", ha0("bad"), attempt, ha1("bad"), "\""
stderr.write " matches:\n ",g0,cb.valsWithPfx(attempt).join("\n "),g1,"\n"
stderr.write "Run with no-argument or \"", hlp, "\" for more details.\n"
quits(cgParseErrorExitCode)
proc firstParagraph(doc: string): string =
var first = true
for line in doc.split('\n'):
if line.len == 0: return
result = result & (if first: "" else: " ") & line
first = false
proc topLevelHelp*(doc: auto, use: auto, cmd: auto, subCmds: auto,
subDocs: auto): string =
var pairs: seq[seq[string]]
for i in 0 ..< subCmds.len:
if clCfg.render != nil:
pairs.add(@[subCmds[i], clCfg.render(subDocs[i].firstParagraph)])
else:
pairs.add(@[subCmds[i], subDocs[i].firstParagraph])
let ifVsn = if clCfg.version.len > 0: "\nTop-level --version also available"
else: ""
let on = @[ clCfg.helpAttr.getOrDefault("cmd", ""),
clCfg.helpAttr.getOrDefault("doc", "") ]
let off= @[ clCfg.helpAttrOff.getOrDefault("cmd", ""),
clCfg.helpAttrOff.getOrDefault("doc", "") ]
let wwd = wrapWidth(clCfg.widthEnv, clCfg.wrapDoc)
let wwt = wrapWidth(clCfg.widthEnv, clCfg.wrapTable)
let docUse = if clCfg.render != nil: wrap(clCfg.render(doc), wwd)
else: wrap(doc, wwd)
use % [ "doc", docUse, "command", on[0] & cmd & off[0], "ifVersion", ifVsn,
"subcmds", addPrefix(" ", alignTable(pairs, 2, attrOn=on,
attrOff=off, width=wwt))]
proc docDefault(n: NimNode): NimNode =
if n.len > 1: newStrLitNode(summaryOfModule(n[1][0]))
elif n.len > 0: newStrLitNode(summaryOfModule(n[0][0]))
else: newStrLitNode("")
macro dispatchMultiGen*(procBkts: varargs[untyped]): untyped =
## Generate multi-cmd dispatch. ``procBkts`` are argLists for ``dispatchGen``.
## Eg., ``dispatchMultiGen([foo, short={"dryRun": "n"}], [bar, doc="Um"])``.
let procBrackets = if procBkts.len < 2: procBkts[0] else: procBkts
result = newStmtList()
var prefix = "multi"
if procBrackets[0][0].kind == nnkStrLit: