-
Notifications
You must be signed in to change notification settings - Fork 16
/
confutils.nim
1302 lines (1069 loc) · 40.8 KB
/
confutils.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
# confutils
# Copyright (c) 2018-2024 Status Research & Development GmbH
# Licensed under either of
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE))
# * MIT license ([LICENSE-MIT](LICENSE-MIT))
# at your option.
# This file may not be copied, modified, or distributed except according to
# those terms.
{.push raises: [].}
import
os,
std/[enumutils, options, strutils, wordwrap],
stew/shims/macros,
confutils/[defs, cli_parser, config_file]
export
options, defs, config_file
const
hasSerialization = not defined(nimscript)
useBufferedOutput = defined(nimscript)
noColors = useBufferedOutput or defined(confutils_no_colors)
hasCompletions = not defined(nimscript)
descPadding = 6
minNameWidth = 24 - descPadding
when hasSerialization:
import serialization
export serialization
when not defined(nimscript):
import
terminal,
confutils/shell_completion
type
HelpAppInfo = ref object
appInvocation: string
copyrightBanner: string
hasAbbrs: bool
maxNameLen: int
terminalWidth: int
namesWidth: int
CmdInfo = ref object
name: string
desc: string
isHidden: bool
opts: seq[OptInfo]
OptKind = enum
Discriminator
CliSwitch
Arg
OptInfo = ref object
name, abbr, desc, typename: string
separator: string
longDesc: string
idx: int
isHidden: bool
hasDefault: bool
defaultInHelpText: string
case kind: OptKind
of Discriminator:
isCommand: bool
isImplicitlySelectable: bool
subCmds: seq[CmdInfo]
defaultSubCmd: int
else:
discard
const
confutils_description_width {.intdefine.} = 80
confutils_narrow_terminal_width {.intdefine.} = 36
{.push gcsafe, raises: [].}
func getFieldName(caseField: NimNode): NimNode =
result = caseField
if result.kind == nnkIdentDefs: result = result[0]
if result.kind == nnkPragmaExpr: result = result[0]
if result.kind == nnkPostfix: result = result[1]
when defined(nimscript):
func scriptNameParamIdx: int =
for i in 1 ..< paramCount():
var param = paramStr(i)
if param.len > 0 and param[0] != '-':
return i
proc appInvocation: string =
let scriptNameIdx = scriptNameParamIdx()
"nim " & (if paramCount() > scriptNameIdx: paramStr(scriptNameIdx) else: "<nims-script>")
type stderr = object
template writeLine(T: type stderr, msg: string) =
echo msg
proc commandLineParams(): seq[string] =
for i in scriptNameParamIdx() + 1 .. paramCount():
result.add paramStr(i)
# TODO: Why isn't this available in NimScript?
proc getCurrentExceptionMsg(): string =
""
template terminalWidth: int =
100000
else:
template appInvocation: string =
try:
getAppFilename().splitFile.name
except OSError:
""
when noColors:
const
styleBright = ""
fgYellow = ""
fgWhite = ""
fgGreen = ""
fgCyan = ""
fgBlue = ""
resetStyle = ""
when useBufferedOutput:
template helpOutput(args: varargs[string]) =
for arg in args:
help.add arg
template errorOutput(args: varargs[string]) =
helpOutput(args)
template flushOutput =
echo help
else:
template errorOutput(args: varargs[untyped]) =
try:
styledWrite stderr, args
except IOError, ValueError:
discard
template helpOutput(args: varargs[untyped]) =
try:
styledWrite stdout, args
except IOError, ValueError:
discard
template flushOutput =
discard
const
fgSection = fgYellow
fgDefault = fgWhite
fgCommand = fgCyan
fgOption = fgBlue
fgArg = fgBlue
# TODO: Start using these:
# fgValue = fgGreen
# fgType = fgYellow
template flushOutputAndQuit(exitCode: int) =
flushOutput
quit exitCode
func isCliSwitch(opt: OptInfo): bool =
opt.kind == CliSwitch or
(opt.kind == Discriminator and opt.isCommand == false)
func hasOpts(cmd: CmdInfo): bool =
for opt in cmd.opts:
if opt.isCliSwitch and not opt.isHidden:
return true
return false
func hasArgs(cmd: CmdInfo): bool =
cmd.opts.len > 0 and cmd.opts[^1].kind == Arg
func firstArgIdx(cmd: CmdInfo): int =
# This will work correctly only if the command has arguments.
result = cmd.opts.len - 1
while result > 0:
if cmd.opts[result - 1].kind != Arg:
return
dec result
iterator args(cmd: CmdInfo): OptInfo =
if cmd.hasArgs:
for i in cmd.firstArgIdx ..< cmd.opts.len:
yield cmd.opts[i]
func getSubCmdDiscriminator(cmd: CmdInfo): OptInfo =
for i in countdown(cmd.opts.len - 1, 0):
let opt = cmd.opts[i]
if opt.kind != Arg:
if opt.kind == Discriminator and opt.isCommand:
return opt
else:
return nil
template hasSubCommands(cmd: CmdInfo): bool =
getSubCmdDiscriminator(cmd) != nil
iterator subCmds(cmd: CmdInfo): CmdInfo =
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
if subCmdDiscriminator != nil:
for cmd in subCmdDiscriminator.subCmds:
yield cmd
template isSubCommand(cmd: CmdInfo): bool =
cmd.name.len > 0
func maxNameLen(cmd: CmdInfo): int =
result = 0
for opt in cmd.opts:
if opt.kind == Arg or opt.kind == Discriminator and opt.isCommand:
continue
result = max(result, opt.name.len)
if opt.kind == Discriminator:
for subCmd in opt.subCmds:
result = max(result, subCmd.maxNameLen)
func hasAbbrs(cmd: CmdInfo): bool =
for opt in cmd.opts:
if opt.kind == Arg or opt.kind == Discriminator and opt.isCommand:
continue
if opt.abbr.len > 0:
return true
if opt.kind == Discriminator:
for subCmd in opt.subCmds:
if hasAbbrs(subCmd):
return true
func humaneName(opt: OptInfo): string =
if opt.name.len > 0: opt.name
else: opt.abbr
template padding(output: string, desiredWidth: int): string =
spaces(max(desiredWidth - output.len, 0))
proc writeDesc(help: var string,
appInfo: HelpAppInfo,
desc, defaultValue: string) =
const descSpacing = " "
let
descIndent = (5 + appInfo.namesWidth + descSpacing.len)
remainingColumns = appInfo.terminalWidth - descIndent
defaultValSuffix = if defaultValue.len == 0: ""
else: " [=" & defaultValue & "]"
fullDesc = desc & defaultValSuffix & "."
if remainingColumns < confutils_narrow_terminal_width:
helpOutput "\p ", wrapWords(fullDesc, appInfo.terminalWidth - 2,
newLine = "\p ")
else:
let wrappingWidth = min(remainingColumns, confutils_description_width)
helpOutput descSpacing, wrapWords(fullDesc, wrappingWidth,
newLine = "\p" & spaces(descIndent))
proc writeLongDesc(help: var string,
appInfo: HelpAppInfo,
desc: string) =
let lines = split(desc, {'\n', '\r'})
for line in lines:
if line.len > 0:
helpOutput "\p"
helpOutput padding("", 5 + appInfo.namesWidth)
help.writeDesc appInfo, line, ""
proc describeInvocation(help: var string,
cmd: CmdInfo, cmdInvocation: string,
appInfo: HelpAppInfo) =
helpOutput styleBright, "\p", fgCommand, cmdInvocation
var longestArg = 0
if cmd.opts.len > 0:
if cmd.hasOpts: helpOutput " [OPTIONS]..."
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
if subCmdDiscriminator != nil: helpOutput " command"
for arg in cmd.args:
helpOutput " <", arg.name, ">"
longestArg = max(longestArg, arg.name.len)
helpOutput "\p"
if cmd.desc.len > 0:
helpOutput "\p", cmd.desc, ".\p"
var argsSectionStarted = false
for arg in cmd.args:
if arg.desc.len > 0:
if not argsSectionStarted:
helpOutput "\p"
argsSectionStarted = true
let cliArg = " <" & arg.humaneName & ">"
helpOutput fgArg, styleBright, cliArg
helpOutput padding(cliArg, 6 + appInfo.namesWidth)
help.writeDesc appInfo, arg.desc, arg.defaultInHelpText
help.writeLongDesc appInfo, arg.longDesc
helpOutput "\p"
type
OptionsType = enum
normalOpts
defaultCmdOpts
conditionalOpts
proc describeOptions(help: var string,
cmd: CmdInfo, cmdInvocation: string,
appInfo: HelpAppInfo, optionsType = normalOpts) =
if cmd.hasOpts:
case optionsType
of normalOpts:
helpOutput "\pThe following options are available:\p\p"
of conditionalOpts:
helpOutput ", the following additional options are available:\p\p"
of defaultCmdOpts:
discard
for opt in cmd.opts:
if opt.kind == Arg or
opt.kind == Discriminator or
opt.isHidden: continue
if opt.separator.len > 0:
helpOutput opt.separator
helpOutput "\p"
# Indent all command-line switches
helpOutput " "
if opt.abbr.len > 0:
helpOutput fgOption, styleBright, "-", opt.abbr, ", "
elif appInfo.hasAbbrs:
# Add additional indentatition, so all names are aligned
helpOutput " "
if opt.name.len > 0:
let switch = "--" & opt.name
helpOutput fgOption, styleBright,
switch, padding(switch, appInfo.namesWidth)
else:
helpOutput spaces(2 + appInfo.namesWidth)
if opt.desc.len > 0:
help.writeDesc appInfo,
opt.desc.replace("%t", opt.typename),
opt.defaultInHelpText
help.writeLongDesc appInfo, opt.longDesc
helpOutput "\p"
if opt.kind == Discriminator:
for i, subCmd in opt.subCmds:
if not subCmd.hasOpts: continue
helpOutput "\pWhen ", styleBright, fgBlue, opt.humaneName, resetStyle, " = ", fgGreen, subCmd.name
if i == opt.defaultSubCmd: helpOutput " (default)"
help.describeOptions subCmd, cmdInvocation, appInfo, conditionalOpts
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
if subCmdDiscriminator != nil:
let defaultCmdIdx = subCmdDiscriminator.defaultSubCmd
if defaultCmdIdx != -1:
let defaultCmd = subCmdDiscriminator.subCmds[defaultCmdIdx]
help.describeOptions defaultCmd, cmdInvocation, appInfo, defaultCmdOpts
helpOutput fgSection, "\pAvailable sub-commands:\p"
for i, subCmd in subCmdDiscriminator.subCmds:
if i != subCmdDiscriminator.defaultSubCmd:
let subCmdInvocation = cmdInvocation & " " & subCmd.name
help.describeInvocation subCmd, subCmdInvocation, appInfo
help.describeOptions subCmd, subCmdInvocation, appInfo
proc showHelp(help: var string,
appInfo: HelpAppInfo,
activeCmds: openArray[CmdInfo]) =
if appInfo.copyrightBanner.len > 0:
helpOutput appInfo.copyrightBanner, "\p\p"
let cmd = activeCmds[^1]
appInfo.maxNameLen = cmd.maxNameLen
appInfo.hasAbbrs = cmd.hasAbbrs
appInfo.terminalWidth =
try:
terminalWidth()
except ValueError:
int.high # https://github.com/nim-lang/Nim/pull/21968
appInfo.namesWidth = min(minNameWidth, appInfo.maxNameLen) + descPadding
var cmdInvocation = appInfo.appInvocation
for i in 1 ..< activeCmds.len:
cmdInvocation.add " "
cmdInvocation.add activeCmds[i].name
# Write out the app or script name
helpOutput fgSection, "Usage: \p"
help.describeInvocation cmd, cmdInvocation, appInfo
help.describeOptions cmd, cmdInvocation, appInfo
helpOutput "\p"
flushOutputAndQuit QuitSuccess
func getNextArgIdx(cmd: CmdInfo, consumedArgIdx: int): int =
for i in 0 ..< cmd.opts.len:
if cmd.opts[i].kind == Arg and cmd.opts[i].idx > consumedArgIdx:
return cmd.opts[i].idx
-1
proc noMoreArgsError(cmd: CmdInfo): string {.raises: [].} =
result =
if cmd.isSubCommand:
"The command '" & cmd.name & "'"
else:
appInvocation()
result.add " does not accept"
if cmd.hasArgs: result.add " additional"
result.add " arguments"
func findOpt(opts: openArray[OptInfo], name: string): OptInfo =
for opt in opts:
if cmpIgnoreStyle(opt.name, name) == 0 or
cmpIgnoreStyle(opt.abbr, name) == 0:
return opt
func findOpt(activeCmds: openArray[CmdInfo], name: string): OptInfo =
for i in countdown(activeCmds.len - 1, 0):
let found = findOpt(activeCmds[i].opts, name)
if found != nil: return found
func findCmd(cmds: openArray[CmdInfo], name: string): CmdInfo =
for cmd in cmds:
if cmpIgnoreStyle(cmd.name, name) == 0:
return cmd
func findSubCmd(cmd: CmdInfo, name: string): CmdInfo =
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
if subCmdDiscriminator != nil:
let cmd = findCmd(subCmdDiscriminator.subCmds, name)
if cmd != nil: return cmd
return nil
func startsWithIgnoreStyle(s: string, prefix: string): bool =
# Similar in spirit to cmpIgnoreStyle, but compare only the prefix.
var i = 0
var j = 0
while true:
# Skip any underscore
while i < s.len and s[i] == '_': inc i
while j < prefix.len and prefix[j] == '_': inc j
if j == prefix.len:
# The whole prefix matches
return true
elif i == s.len:
# We've reached the end of `s` without matching the prefix
return false
elif toLowerAscii(s[i]) != toLowerAscii(prefix[j]):
return false
inc i
inc j
when defined(debugCmdTree):
proc printCmdTree(cmd: CmdInfo, indent = 0) =
let blanks = spaces(indent)
echo blanks, "> ", cmd.name
for opt in cmd.opts:
if opt.kind == Discriminator:
for subcmd in opt.subCmds:
printCmdTree(subcmd, indent + 2)
else:
echo blanks, " - ", opt.name, ": ", opt.typename
else:
template printCmdTree(cmd: CmdInfo) = discard
# TODO remove the overloads here to get better "missing overload" error message
proc parseCmdArg*(T: type InputDir, p: string): T {.raises: [ValueError].} =
if not dirExists(p):
raise newException(ValueError, "Directory doesn't exist")
T(p)
proc parseCmdArg*(T: type InputFile, p: string): T {.raises: [ValueError].} =
# TODO this is needed only because InputFile cannot be made
# an alias of TypedInputFile at the moment, because of a generics
# caching issue
if not fileExists(p):
raise newException(ValueError, "File doesn't exist")
when not defined(nimscript):
try:
let f = system.open(p, fmRead)
close f
except IOError:
raise newException(ValueError, "File not accessible")
T(p)
proc parseCmdArg*(
T: type TypedInputFile, p: string): T {.raises: [ValueError].} =
var path = p
when T.defaultExt.len > 0:
path = path.addFileExt(T.defaultExt)
if not fileExists(path):
raise newException(ValueError, "File doesn't exist")
when not defined(nimscript):
try:
let f = system.open(path, fmRead)
close f
except IOError:
raise newException(ValueError, "File not accessible")
T(path)
func parseCmdArg*(T: type[OutDir|OutFile|OutPath], p: string): T =
T(p)
proc parseCmdArg*[T](
_: type Option[T], s: string): Option[T] {.raises: [ValueError].} =
some(parseCmdArg(T, s))
template parseCmdArg*(T: type string, s: string): string =
s
func parseCmdArg*(
T: type SomeSignedInt, s: string): T {.raises: [ValueError].} =
T parseBiggestInt(s)
func parseCmdArg*(
T: type SomeUnsignedInt, s: string): T {.raises: [ValueError].} =
T parseBiggestUInt(s)
func parseCmdArg*(T: type SomeFloat, p: string): T {.raises: [ValueError].} =
parseFloat(p)
func parseCmdArg*(T: type bool, p: string): T {.raises: [ValueError].} =
try:
p.len == 0 or parseBool(p)
except CatchableError:
raise newException(ValueError, "'" & p & "' is not a valid boolean value. Supported values are on/off, yes/no, true/false or 1/0")
func parseCmdArg*(T: type enum, s: string): T {.raises: [ValueError].} =
parseEnum[T](s)
proc parseCmdArgAux(T: type, s: string): T {.raises: [ValueError].} =
# The parseCmdArg procs are allowed to raise only `ValueError`.
# If you have provided your own specializations, please handle
# all other exception types.
mixin parseCmdArg
try:
parseCmdArg(T, s)
except CatchableError as exc:
raise newException(ValueError, exc.msg)
func completeCmdArg*(T: type enum, val: string): seq[string] =
for e in low(T)..high(T):
let as_str = $e
if startsWithIgnoreStyle(as_str, val):
result.add($e)
func completeCmdArg*(T: type SomeNumber, val: string): seq[string] =
@[]
func completeCmdArg*(T: type bool, val: string): seq[string] =
@[]
func completeCmdArg*(T: type string, val: string): seq[string] =
@[]
proc completeCmdArg*(T: type[InputFile|TypedInputFile|InputDir|OutFile|OutDir|OutPath],
val: string): seq[string] =
when not defined(nimscript):
let (dir, name, ext) = splitFile(val)
let tail = name & ext
# Expand the directory component for the directory walker routine
let dir_path = if dir == "": "." else: expandTilde(dir)
# Dotfiles are hidden unless the user entered a dot as prefix
let show_dotfiles = len(name) > 0 and name[0] == '.'
try:
for kind, path in walkDir(dir_path, relative=true):
if not show_dotfiles and path[0] == '.':
continue
# Do not show files if asked for directories, on the other hand we must show
# directories even if a file is requested to allow the user to select a file
# inside those
if type(T) is (InputDir or OutDir) and kind notin {pcDir, pcLinkToDir}:
continue
# Note, no normalization is needed here
if path.startsWith(tail):
var match = dir_path / path
# Add a trailing slash so that completions can be chained
if kind in {pcDir, pcLinkToDir}:
match &= DirSep
result.add(shellPathEscape(match))
except OSError:
discard
func completeCmdArg*[T](_: type seq[T], val: string): seq[string] =
@[]
proc completeCmdArg*[T](_: type Option[T], val: string): seq[string] =
mixin completeCmdArg
return completeCmdArg(type(T), val)
proc completeCmdArgAux(T: type, val: string): seq[string] =
mixin completeCmdArg
return completeCmdArg(T, val)
template setField[T](
loc: var T, val: Option[string], defaultVal: untyped): untyped =
type FieldType = type(loc)
loc = if isSome(val): parseCmdArgAux(FieldType, val.get)
else: FieldType(defaultVal)
template setField[T](
loc: var seq[T], val: Option[string], defaultVal: untyped): untyped =
if val.isSome:
loc.add parseCmdArgAux(type(loc[0]), val.get)
else:
type FieldType = type(loc)
loc = FieldType(defaultVal)
func makeDefaultValue*(T: type): T =
default(T)
func requiresInput*(T: type): bool =
not ((T is seq) or (T is Option) or (T is bool))
func acceptsMultipleValues*(T: type): bool =
T is seq
template debugMacroResult(macroName: string) {.dirty.} =
when defined(debugMacros) or defined(debugConfutils):
echo "\n-------- ", macroName, " ----------------------"
echo result.repr
func parseEnumNormalized[T: enum](s: string): T {.raises: [ValueError].} =
# Note: In Nim 1.6 `parseEnum` normalizes the string except for the first
# character. Nim 1.2 would normalize for all characters. In config options
# the latter behaviour is required so this custom function is needed.
genEnumCaseStmt(T, s, default = nil, ord(low(T)), ord(high(T)), normalize)
proc generateFieldSetters(RecordType: NimNode): NimNode =
var recordDef = getImpl(RecordType)
let makeDefaultValue = bindSym"makeDefaultValue"
result = newTree(nnkStmtListExpr)
var settersArray = newTree(nnkBracket)
for field in recordFields(recordDef):
var
setterName = ident($field.name & "Setter")
fieldName = field.name
namePragma = field.readPragma"name"
paramName = if namePragma != nil: namePragma
else: fieldName
configVar = ident "config"
configField = newTree(nnkDotExpr, configVar, fieldName)
defaultValue = field.readPragma"defaultValue"
completerName = ident($field.name & "Complete")
if defaultValue == nil:
defaultValue = newCall(makeDefaultValue, newTree(nnkTypeOfExpr, configField))
# TODO: This shouldn't be necessary. The type symbol returned from Nim should
# be typed as a tyTypeDesc[tyString] instead of just `tyString`. To be filed.
var fixedFieldType = newTree(nnkTypeOfExpr, field.typ)
settersArray.add newTree(nnkTupleConstr,
newLit($paramName),
setterName, completerName,
newCall(bindSym"requiresInput", fixedFieldType),
newCall(bindSym"acceptsMultipleValues", fixedFieldType))
result.add quote do:
{.push hint[XCannotRaiseY]: off.}
result.add quote do:
proc `completerName`(val: string): seq[string] {.
nimcall
gcsafe
sideEffect
raises: []
.} =
return completeCmdArgAux(`fixedFieldType`, val)
proc `setterName`(`configVar`: var `RecordType`, val: Option[string]) {.
nimcall
gcsafe
sideEffect
raises: [ValueError]
.} =
when `configField` is enum:
# TODO: For some reason, the normal `setField` rejects enum fields
# when they are used as case discriminators. File this as a bug.
if isSome(val):
`configField` = parseEnumNormalized[type(`configField`)](val.get)
else:
`configField` = `defaultValue`
else:
setField(`configField`, val, `defaultValue`)
result.add quote do:
{.pop.}
result.add settersArray
debugMacroResult "Field Setters"
func checkDuplicate(cmd: CmdInfo, opt: OptInfo, fieldName: NimNode) =
for x in cmd.opts:
if opt.name == x.name:
error "duplicate name detected: " & opt.name, fieldName
if opt.abbr.len > 0 and opt.abbr == x.abbr:
error "duplicate abbr detected: " & opt.abbr, fieldName
func validPath(path: var seq[CmdInfo], parent, node: CmdInfo): bool =
for x in parent.opts:
if x.kind != Discriminator: continue
for y in x.subCmds:
if y == node:
path.add y
return true
if validPath(path, y, node):
path.add y
return true
false
func findPath(parent, node: CmdInfo): seq[CmdInfo] =
# find valid path from parent to node
result = newSeq[CmdInfo]()
doAssert validPath(result, parent, node)
result.add parent
func toText(n: NimNode): string =
if n == nil: ""
elif n.kind in {nnkStrLit..nnkTripleStrLit}: n.strVal
else: repr(n)
proc cmdInfoFromType(T: NimNode): CmdInfo =
result = CmdInfo()
var
recordDef = getImpl(T)
discriminatorFields = newSeq[OptInfo]()
fieldIdx = 0
for field in recordFields(recordDef):
let
isImplicitlySelectable = field.readPragma"implicitlySelectable" != nil
defaultValue = field.readPragma"defaultValue"
defaultValueDesc = field.readPragma"defaultValueDesc"
defaultInHelp = if defaultValueDesc != nil: defaultValueDesc
else: defaultValue
defaultInHelpText = toText(defaultInHelp)
separator = field.readPragma"separator"
longDesc = field.readPragma"longDesc"
isHidden = field.readPragma("hidden") != nil
abbr = field.readPragma"abbr"
name = field.readPragma"name"
desc = field.readPragma"desc"
optKind = if field.isDiscriminator: Discriminator
elif field.readPragma("argument") != nil: Arg
else: CliSwitch
var opt = OptInfo(kind: optKind,
idx: fieldIdx,
name: $field.name,
isHidden: isHidden,
hasDefault: defaultValue != nil,
defaultInHelpText: defaultInHelpText,
typename: field.typ.repr)
if desc != nil: opt.desc = desc.strVal
if name != nil: opt.name = name.strVal
if abbr != nil: opt.abbr = abbr.strVal
if separator != nil: opt.separator = separator.strVal
if longDesc != nil: opt.longDesc = longDesc.strVal
inc fieldIdx
if field.isDiscriminator:
discriminatorFields.add opt
let cmdType = field.typ.getImpl[^1]
if cmdType.kind != nnkEnumTy:
error "Only enums are supported as case object discriminators", field.name
opt.isImplicitlySelectable = isImplicitlySelectable
opt.isCommand = field.readPragma"command" != nil
for i in 1 ..< cmdType.len:
let enumVal = cmdType[i]
var name, desc: string
if enumVal.kind == nnkEnumFieldDef:
name = $enumVal[0]
desc = $enumVal[1]
else:
name = $enumVal
if defaultValue != nil and eqIdent(name, defaultValue):
opt.defaultSubCmd = i - 1
opt.subCmds.add CmdInfo(name: name, desc: desc)
if defaultValue == nil:
opt.defaultSubCmd = -1
else:
if opt.defaultSubCmd == -1:
error "The default value is not a valid enum value", defaultValue
if field.caseField != nil and field.caseBranch != nil:
let fieldName = field.caseField.getFieldName
var discriminator = findOpt(discriminatorFields, $fieldName)
if discriminator == nil:
error "Unable to find " & $fieldName
if field.caseBranch.kind == nnkElse:
error "Sub-command parameters cannot appear in an else branch. " &
"Please specify the sub-command branch precisely", field.caseBranch[0]
var branchEnumVal = field.caseBranch[0]
if branchEnumVal.kind == nnkDotExpr:
branchEnumVal = branchEnumVal[1]
var cmd = findCmd(discriminator.subCmds, $branchEnumVal)
# we respect subcommand hierarchy when looking for duplicate
let path = findPath(result, cmd)
for n in path:
checkDuplicate(n, opt, field.name)
# the reason we check for `ignore` pragma here and not using `continue` statement
# is we do respect option hierarchy of subcommands
if field.readPragma("ignore") == nil:
cmd.opts.add opt
else:
checkDuplicate(result, opt, field.name)
if field.readPragma("ignore") == nil:
result.opts.add opt
macro configurationRtti(RecordType: type): untyped =
let
T = RecordType.getType[1]
cmdInfo = cmdInfoFromType T
fieldSetters = generateFieldSetters T
result = newTree(nnkPar, newLitFixed cmdInfo, fieldSetters)
when hasSerialization:
proc addConfigFile*(secondarySources: auto,
Format: type,
path: InputFile) {.raises: [ConfigurationError].} =
try:
secondarySources.data.add loadFile(Format, string path,
type(secondarySources.data[0]))
except SerializationError as err:
raise newException(ConfigurationError, err.formatMsg(string path), err)
except IOError as err:
raise newException(ConfigurationError,
"Failed to read config file at '" & string(path) & "': " & err.msg)
proc addConfigFileContent*(secondarySources: auto,
Format: type,
content: string) {.raises: [ConfigurationError].} =
try:
secondarySources.data.add decode(Format, content,
type(secondarySources.data[0]))
except SerializationError as err:
raise newException(ConfigurationError, err.formatMsg("<content>"), err)
except IOError:
raiseAssert "This should not be possible"
func constructEnvKey*(prefix: string, key: string): string {.raises: [].} =
## Generates env. variable names from keys and prefix following the
## IEEE Open Group env. variable spec: https://pubs.opengroup.org/onlinepubs/000095399/basedefs/xbd_chap08.html
(prefix & "_" & key).toUpperAscii.multiReplace(("-", "_"), (" ", "_"))
# On Posix there is no portable way to get the command
# line from a DLL and thus the proc isn't defined in this environment.
# See https://nim-lang.org/docs/os.html#commandLineParams
when not declared(commandLineParams):
proc commandLineParams(): seq[string] = discard
proc loadImpl[C, SecondarySources](
Configuration: typedesc[C],
cmdLine = commandLineParams(),
version = "",
copyrightBanner = "",
printUsage = true,
quitOnFailure = true,
secondarySourcesRef: ref SecondarySources,
secondarySources: proc (
config: Configuration, sources: ref SecondarySources
) {.gcsafe, raises: [ConfigurationError].} = nil,
envVarsPrefix = appInvocation()
): Configuration {.raises: [ConfigurationError].} =
## Loads a program configuration by parsing command-line arguments
## and a standard set of config files that can specify:
##
## - working directory settings
## - user settings
## - system-wide setttings
##
## Supports multiple config files format (INI/TOML, YAML, JSON).
# This is an initial naive implementation that will be improved
# over time.
let (rootCmd, fieldSetters) = configurationRtti(Configuration)
var fieldCounters: array[fieldSetters.len, int]
printCmdTree rootCmd
var activeCmds = @[rootCmd]
template lastCmd: auto = activeCmds[^1]
var nextArgIdx = lastCmd.getNextArgIdx(-1)
var help = ""
proc suggestCallingHelp =
errorOutput "Try ", fgCommand, appInvocation() & " --help"
errorOutput " for more information.\p"
flushOutputAndQuit QuitFailure
template fail(args: varargs[untyped]): untyped =
if quitOnFailure:
errorOutput args
errorOutput "\p"
suggestCallingHelp()
else:
# TODO: populate this string
raise newException(ConfigurationError, "")
template applySetter(
conf: Configuration, setterIdx: int, cmdLineVal: string): untyped =
when defined(nimHasWarnBareExcept):
{.push warning[BareExcept]:off.}
try:
fieldSetters[setterIdx][1](conf, some(cmdLineVal))
inc fieldCounters[setterIdx]
except:
fail("Error while processing the ",
fgOption, fieldSetters[setterIdx][0],
"=", cmdLineVal, resetStyle, " parameter: ",
getCurrentExceptionMsg())
when defined(nimHasWarnBareExcept):
{.pop.}
when hasCompletions:
template getArgCompletions(opt: OptInfo, prefix: string): seq[string] =
fieldSetters[opt.idx][2](prefix)
template required(opt: OptInfo): bool =
fieldSetters[opt.idx][3] and not opt.hasDefault
template activateCmd(
conf: Configuration, discriminator: OptInfo, activatedCmd: CmdInfo) =
let cmd = activatedCmd
conf.applySetter(discriminator.idx, if cmd.desc.len > 0: cmd.desc
else: cmd.name)
activeCmds.add cmd
nextArgIdx = cmd.getNextArgIdx(-1)
when hasCompletions:
type
ArgKindFilter = enum
argName
argAbbr
proc showMatchingOptions(cmd: CmdInfo, prefix: string, filterKind: set[ArgKindFilter]) =
var matchingOptions: seq[OptInfo]
if len(prefix) > 0: