2024-02-12 03:26:05 +00:00
|
|
|
# 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.
|
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
{.push raises: [].}
|
|
|
|
|
2018-11-21 13:25:53 +00:00
|
|
|
import
|
2023-04-19 09:54:48 +00:00
|
|
|
os,
|
2024-10-30 10:49:34 +00:00
|
|
|
std/[enumutils, options, strutils, wordwrap],
|
2019-08-23 15:52:32 +00:00
|
|
|
stew/shims/macros,
|
2020-10-31 10:44:03 +00:00
|
|
|
confutils/[defs, cli_parser, config_file]
|
2018-11-21 13:25:53 +00:00
|
|
|
|
|
|
|
export
|
2024-10-30 10:49:34 +00:00
|
|
|
options, defs, config_file
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
const
|
2024-10-30 10:49:34 +00:00
|
|
|
hasSerialization = not defined(nimscript)
|
2019-10-23 00:30:40 +00:00
|
|
|
useBufferedOutput = defined(nimscript)
|
2019-08-23 15:52:32 +00:00
|
|
|
noColors = useBufferedOutput or defined(confutils_no_colors)
|
2019-12-02 21:31:29 +00:00
|
|
|
hasCompletions = not defined(nimscript)
|
2019-11-11 16:10:28 +00:00
|
|
|
descPadding = 6
|
|
|
|
minNameWidth = 24 - descPadding
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
when hasSerialization:
|
|
|
|
import serialization
|
|
|
|
export serialization
|
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
when not defined(nimscript):
|
2019-10-23 00:30:40 +00:00
|
|
|
import
|
2024-02-12 05:39:19 +00:00
|
|
|
terminal,
|
2019-10-23 00:30:40 +00:00
|
|
|
confutils/shell_completion
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-01-23 11:49:10 +00:00
|
|
|
type
|
2019-08-23 15:52:32 +00:00
|
|
|
HelpAppInfo = ref object
|
|
|
|
appInvocation: string
|
2019-11-11 14:42:08 +00:00
|
|
|
copyrightBanner: string
|
2019-11-11 16:10:28 +00:00
|
|
|
hasAbbrs: bool
|
|
|
|
maxNameLen: int
|
2019-08-23 15:52:32 +00:00
|
|
|
terminalWidth: int
|
2019-11-11 16:10:28 +00:00
|
|
|
namesWidth: int
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
CmdInfo = ref object
|
2019-01-23 11:49:10 +00:00
|
|
|
name: string
|
2020-03-10 11:38:29 +00:00
|
|
|
desc: string
|
2021-01-29 21:17:15 +00:00
|
|
|
isHidden: bool
|
2019-08-23 15:52:32 +00:00
|
|
|
opts: seq[OptInfo]
|
2019-01-23 11:49:10 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
OptKind = enum
|
|
|
|
Discriminator
|
|
|
|
CliSwitch
|
|
|
|
Arg
|
|
|
|
|
|
|
|
OptInfo = ref object
|
2019-11-11 14:46:51 +00:00
|
|
|
name, abbr, desc, typename: string
|
2021-09-02 08:12:38 +00:00
|
|
|
separator: string
|
2021-09-14 09:45:01 +00:00
|
|
|
longDesc: string
|
2019-08-23 15:52:32 +00:00
|
|
|
idx: int
|
2021-01-29 21:17:15 +00:00
|
|
|
isHidden: bool
|
2021-05-18 08:01:11 +00:00
|
|
|
hasDefault: bool
|
|
|
|
defaultInHelpText: string
|
2019-08-23 15:52:32 +00:00
|
|
|
case kind: OptKind
|
|
|
|
of Discriminator:
|
|
|
|
isCommand: bool
|
|
|
|
isImplicitlySelectable: bool
|
|
|
|
subCmds: seq[CmdInfo]
|
|
|
|
defaultSubCmd: int
|
|
|
|
else:
|
|
|
|
discard
|
2019-06-14 16:51:40 +00:00
|
|
|
|
2020-06-23 14:37:03 +00:00
|
|
|
const
|
|
|
|
confutils_description_width {.intdefine.} = 80
|
|
|
|
confutils_narrow_terminal_width {.intdefine.} = 36
|
|
|
|
|
2024-02-12 05:39:19 +00:00
|
|
|
{.push gcsafe, raises: [].}
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func getFieldName(caseField: NimNode): NimNode =
|
2019-08-23 15:52:32 +00:00
|
|
|
result = caseField
|
|
|
|
if result.kind == nnkIdentDefs: result = result[0]
|
|
|
|
if result.kind == nnkPragmaExpr: result = result[0]
|
|
|
|
if result.kind == nnkPostfix: result = result[1]
|
2019-06-14 16:33:59 +00:00
|
|
|
|
|
|
|
when defined(nimscript):
|
2019-10-29 11:56:53 +00:00
|
|
|
func scriptNameParamIdx: int =
|
|
|
|
for i in 1 ..< paramCount():
|
|
|
|
var param = paramStr(i)
|
|
|
|
if param.len > 0 and param[0] != '-':
|
|
|
|
return i
|
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
proc appInvocation: string =
|
2019-10-29 11:56:53 +00:00
|
|
|
let scriptNameIdx = scriptNameParamIdx()
|
|
|
|
"nim " & (if paramCount() > scriptNameIdx: paramStr(scriptNameIdx) else: "<nims-script>")
|
2019-06-14 16:33:59 +00:00
|
|
|
|
|
|
|
type stderr = object
|
|
|
|
|
|
|
|
template writeLine(T: type stderr, msg: string) =
|
|
|
|
echo msg
|
|
|
|
|
|
|
|
proc commandLineParams(): seq[string] =
|
2019-10-29 11:56:53 +00:00
|
|
|
for i in scriptNameParamIdx() + 1 .. paramCount():
|
2019-06-14 16:33:59 +00:00
|
|
|
result.add paramStr(i)
|
|
|
|
|
|
|
|
# TODO: Why isn't this available in NimScript?
|
|
|
|
proc getCurrentExceptionMsg(): string =
|
|
|
|
""
|
2019-01-23 11:49:10 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
template terminalWidth: int =
|
|
|
|
100000
|
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
else:
|
|
|
|
template appInvocation: string =
|
2023-06-08 13:30:46 +00:00
|
|
|
try:
|
|
|
|
getAppFilename().splitFile.name
|
|
|
|
except OSError:
|
|
|
|
""
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
when noColors:
|
2019-10-23 00:30:40 +00:00
|
|
|
const
|
|
|
|
styleBright = ""
|
|
|
|
fgYellow = ""
|
|
|
|
fgWhite = ""
|
|
|
|
fgGreen = ""
|
|
|
|
fgCyan = ""
|
|
|
|
fgBlue = ""
|
2019-11-08 17:49:44 +00:00
|
|
|
resetStyle = ""
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
when useBufferedOutput:
|
|
|
|
template helpOutput(args: varargs[string]) =
|
2019-06-14 16:33:59 +00:00
|
|
|
for arg in args:
|
2019-08-23 15:52:32 +00:00
|
|
|
help.add arg
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-11-08 17:49:44 +00:00
|
|
|
template errorOutput(args: varargs[string]) =
|
|
|
|
helpOutput(args)
|
|
|
|
|
2019-11-12 12:07:29 +00:00
|
|
|
template flushOutput =
|
2019-08-23 15:52:32 +00:00
|
|
|
echo help
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-01-23 11:49:10 +00:00
|
|
|
else:
|
2019-11-08 17:49:44 +00:00
|
|
|
template errorOutput(args: varargs[untyped]) =
|
2023-06-08 13:26:06 +00:00
|
|
|
try:
|
|
|
|
styledWrite stderr, args
|
|
|
|
except IOError, ValueError:
|
|
|
|
discard
|
2019-11-08 17:49:44 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
template helpOutput(args: varargs[untyped]) =
|
2023-06-08 13:26:06 +00:00
|
|
|
try:
|
|
|
|
styledWrite stdout, args
|
|
|
|
except IOError, ValueError:
|
|
|
|
discard
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-11-12 12:07:29 +00:00
|
|
|
template flushOutput =
|
2019-08-23 15:52:32 +00:00
|
|
|
discard
|
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
const
|
|
|
|
fgSection = fgYellow
|
2020-07-02 14:06:31 +00:00
|
|
|
fgDefault = fgWhite
|
2019-10-23 00:30:40 +00:00
|
|
|
fgCommand = fgCyan
|
|
|
|
fgOption = fgBlue
|
2020-06-16 15:22:41 +00:00
|
|
|
fgArg = fgBlue
|
|
|
|
|
2019-11-08 17:57:44 +00:00
|
|
|
# TODO: Start using these:
|
|
|
|
# fgValue = fgGreen
|
|
|
|
# fgType = fgYellow
|
2019-10-23 00:30:40 +00:00
|
|
|
|
2019-11-12 12:07:29 +00:00
|
|
|
template flushOutputAndQuit(exitCode: int) =
|
|
|
|
flushOutput
|
|
|
|
quit exitCode
|
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
func isCliSwitch(opt: OptInfo): bool =
|
|
|
|
opt.kind == CliSwitch or
|
|
|
|
(opt.kind == Discriminator and opt.isCommand == false)
|
|
|
|
|
|
|
|
func hasOpts(cmd: CmdInfo): bool =
|
2021-01-29 21:17:15 +00:00
|
|
|
for opt in cmd.opts:
|
|
|
|
if opt.isCliSwitch and not opt.isHidden:
|
|
|
|
return true
|
|
|
|
|
|
|
|
return false
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
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
|
2020-06-16 15:22:41 +00:00
|
|
|
dec result
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
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
|
2019-01-23 11:49:10 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
iterator subCmds(cmd: CmdInfo): CmdInfo =
|
|
|
|
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
|
|
|
|
if subCmdDiscriminator != nil:
|
|
|
|
for cmd in subCmdDiscriminator.subCmds:
|
|
|
|
yield cmd
|
2019-01-23 11:49:10 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
template isSubCommand(cmd: CmdInfo): bool =
|
2019-06-14 16:33:59 +00:00
|
|
|
cmd.name.len > 0
|
|
|
|
|
2019-11-11 16:10:28 +00:00
|
|
|
func maxNameLen(cmd: CmdInfo): int =
|
2019-08-23 15:52:32 +00:00
|
|
|
result = 0
|
|
|
|
for opt in cmd.opts:
|
|
|
|
if opt.kind == Arg or opt.kind == Discriminator and opt.isCommand:
|
|
|
|
continue
|
2019-11-11 14:46:51 +00:00
|
|
|
result = max(result, opt.name.len)
|
2019-08-23 15:52:32 +00:00
|
|
|
if opt.kind == Discriminator:
|
|
|
|
for subCmd in opt.subCmds:
|
2019-11-11 16:10:28 +00:00
|
|
|
result = max(result, subCmd.maxNameLen)
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-11-11 16:10:28 +00:00
|
|
|
func hasAbbrs(cmd: CmdInfo): bool =
|
2019-08-23 15:52:32 +00:00
|
|
|
for opt in cmd.opts:
|
|
|
|
if opt.kind == Arg or opt.kind == Discriminator and opt.isCommand:
|
|
|
|
continue
|
2019-11-11 14:46:51 +00:00
|
|
|
if opt.abbr.len > 0:
|
2019-08-23 15:52:32 +00:00
|
|
|
return true
|
|
|
|
if opt.kind == Discriminator:
|
|
|
|
for subCmd in opt.subCmds:
|
2019-11-11 16:10:28 +00:00
|
|
|
if hasAbbrs(subCmd):
|
2019-08-23 15:52:32 +00:00
|
|
|
return true
|
|
|
|
|
|
|
|
func humaneName(opt: OptInfo): string =
|
2019-11-11 14:46:51 +00:00
|
|
|
if opt.name.len > 0: opt.name
|
|
|
|
else: opt.abbr
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
template padding(output: string, desiredWidth: int): string =
|
|
|
|
spaces(max(desiredWidth - output.len, 0))
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2021-05-16 18:42:12 +00:00
|
|
|
proc writeDesc(help: var string,
|
|
|
|
appInfo: HelpAppInfo,
|
|
|
|
desc, defaultValue: string) =
|
2019-10-28 19:03:46 +00:00
|
|
|
const descSpacing = " "
|
2019-08-23 15:52:32 +00:00
|
|
|
let
|
2019-11-11 16:10:28 +00:00
|
|
|
descIndent = (5 + appInfo.namesWidth + descSpacing.len)
|
2019-10-28 19:03:46 +00:00
|
|
|
remainingColumns = appInfo.terminalWidth - descIndent
|
2021-05-16 18:42:12 +00:00
|
|
|
defaultValSuffix = if defaultValue.len == 0: ""
|
2021-05-17 17:40:57 +00:00
|
|
|
else: " [=" & defaultValue & "]"
|
2021-05-16 18:42:12 +00:00
|
|
|
fullDesc = desc & defaultValSuffix & "."
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2020-06-23 14:37:03 +00:00
|
|
|
if remainingColumns < confutils_narrow_terminal_width:
|
2021-05-16 18:42:12 +00:00
|
|
|
helpOutput "\p ", wrapWords(fullDesc, appInfo.terminalWidth - 2,
|
2019-08-23 15:52:32 +00:00
|
|
|
newLine = "\p ")
|
|
|
|
else:
|
2020-06-23 14:37:03 +00:00
|
|
|
let wrappingWidth = min(remainingColumns, confutils_description_width)
|
2021-05-16 18:42:12 +00:00
|
|
|
helpOutput descSpacing, wrapWords(fullDesc, wrappingWidth,
|
2019-10-28 19:03:46 +00:00
|
|
|
newLine = "\p" & spaces(descIndent))
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2021-09-14 09:45:01 +00:00
|
|
|
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, ""
|
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
proc describeInvocation(help: var string,
|
|
|
|
cmd: CmdInfo, cmdInvocation: string,
|
|
|
|
appInfo: HelpAppInfo) =
|
|
|
|
helpOutput styleBright, "\p", fgCommand, cmdInvocation
|
2019-08-23 15:52:32 +00:00
|
|
|
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:
|
2019-11-11 14:46:51 +00:00
|
|
|
helpOutput " <", arg.name, ">"
|
|
|
|
longestArg = max(longestArg, arg.name.len)
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
helpOutput "\p"
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2020-03-10 11:38:29 +00:00
|
|
|
if cmd.desc.len > 0:
|
2020-06-23 14:37:03 +00:00
|
|
|
helpOutput "\p", cmd.desc, ".\p"
|
2020-06-16 15:22:41 +00:00
|
|
|
|
|
|
|
var argsSectionStarted = false
|
2020-03-10 11:38:29 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
for arg in cmd.args:
|
|
|
|
if arg.desc.len > 0:
|
2020-06-16 15:22:41 +00:00
|
|
|
if not argsSectionStarted:
|
|
|
|
helpOutput "\p"
|
|
|
|
argsSectionStarted = true
|
|
|
|
|
|
|
|
let cliArg = " <" & arg.humaneName & ">"
|
|
|
|
helpOutput fgArg, styleBright, cliArg
|
|
|
|
helpOutput padding(cliArg, 6 + appInfo.namesWidth)
|
2021-05-18 08:01:11 +00:00
|
|
|
help.writeDesc appInfo, arg.desc, arg.defaultInHelpText
|
2021-09-14 09:45:01 +00:00
|
|
|
help.writeLongDesc appInfo, arg.longDesc
|
2020-06-16 15:22:41 +00:00
|
|
|
helpOutput "\p"
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-10-28 19:03:46 +00:00
|
|
|
type
|
|
|
|
OptionsType = enum
|
|
|
|
normalOpts
|
|
|
|
defaultCmdOpts
|
|
|
|
conditionalOpts
|
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
proc describeOptions(help: var string,
|
|
|
|
cmd: CmdInfo, cmdInvocation: string,
|
2019-10-28 19:03:46 +00:00
|
|
|
appInfo: HelpAppInfo, optionsType = normalOpts) =
|
2019-08-23 15:52:32 +00:00
|
|
|
if cmd.hasOpts:
|
2019-10-28 19:03:46 +00:00
|
|
|
case optionsType
|
|
|
|
of normalOpts:
|
2019-10-23 00:30:40 +00:00
|
|
|
helpOutput "\pThe following options are available:\p\p"
|
2019-10-28 19:03:46 +00:00
|
|
|
of conditionalOpts:
|
|
|
|
helpOutput ", the following additional options are available:\p\p"
|
|
|
|
of defaultCmdOpts:
|
|
|
|
discard
|
2019-10-23 00:30:40 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
for opt in cmd.opts:
|
2021-01-29 21:17:15 +00:00
|
|
|
if opt.kind == Arg or
|
|
|
|
opt.kind == Discriminator or
|
|
|
|
opt.isHidden: continue
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2021-09-02 08:12:38 +00:00
|
|
|
if opt.separator.len > 0:
|
|
|
|
helpOutput opt.separator
|
|
|
|
helpOutput "\p"
|
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
# Indent all command-line switches
|
|
|
|
helpOutput " "
|
|
|
|
|
2019-11-11 14:46:51 +00:00
|
|
|
if opt.abbr.len > 0:
|
|
|
|
helpOutput fgOption, styleBright, "-", opt.abbr, ", "
|
2019-11-11 16:10:28 +00:00
|
|
|
elif appInfo.hasAbbrs:
|
|
|
|
# Add additional indentatition, so all names are aligned
|
2019-08-23 15:52:32 +00:00
|
|
|
helpOutput " "
|
|
|
|
|
2019-11-11 14:46:51 +00:00
|
|
|
if opt.name.len > 0:
|
|
|
|
let switch = "--" & opt.name
|
2019-10-23 00:30:40 +00:00
|
|
|
helpOutput fgOption, styleBright,
|
2019-11-11 16:10:28 +00:00
|
|
|
switch, padding(switch, appInfo.namesWidth)
|
2019-08-23 15:52:32 +00:00
|
|
|
else:
|
2019-11-11 16:10:28 +00:00
|
|
|
helpOutput spaces(2 + appInfo.namesWidth)
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
if opt.desc.len > 0:
|
2021-05-16 18:42:12 +00:00
|
|
|
help.writeDesc appInfo,
|
|
|
|
opt.desc.replace("%t", opt.typename),
|
2021-05-18 08:01:11 +00:00
|
|
|
opt.defaultInHelpText
|
2021-09-14 09:45:01 +00:00
|
|
|
help.writeLongDesc appInfo, opt.longDesc
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
helpOutput "\p"
|
|
|
|
|
|
|
|
if opt.kind == Discriminator:
|
|
|
|
for i, subCmd in opt.subCmds:
|
2019-10-23 00:30:40 +00:00
|
|
|
if not subCmd.hasOpts: continue
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-11-08 17:49:44 +00:00
|
|
|
helpOutput "\pWhen ", styleBright, fgBlue, opt.humaneName, resetStyle, " = ", fgGreen, subCmd.name
|
2019-10-23 00:30:40 +00:00
|
|
|
|
|
|
|
if i == opt.defaultSubCmd: helpOutput " (default)"
|
2019-10-28 19:03:46 +00:00
|
|
|
help.describeOptions subCmd, cmdInvocation, appInfo, conditionalOpts
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
|
|
|
|
if subCmdDiscriminator != nil:
|
|
|
|
let defaultCmdIdx = subCmdDiscriminator.defaultSubCmd
|
|
|
|
if defaultCmdIdx != -1:
|
|
|
|
let defaultCmd = subCmdDiscriminator.subCmds[defaultCmdIdx]
|
2019-10-28 19:03:46 +00:00
|
|
|
help.describeOptions defaultCmd, cmdInvocation, appInfo, defaultCmdOpts
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
helpOutput fgSection, "\pAvailable sub-commands:\p"
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
for i, subCmd in subCmdDiscriminator.subCmds:
|
|
|
|
if i != subCmdDiscriminator.defaultSubCmd:
|
|
|
|
let subCmdInvocation = cmdInvocation & " " & subCmd.name
|
2019-10-23 00:30:40 +00:00
|
|
|
help.describeInvocation subCmd, subCmdInvocation, appInfo
|
|
|
|
help.describeOptions subCmd, subCmdInvocation, appInfo
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-11-08 17:49:44 +00:00
|
|
|
proc showHelp(help: var string,
|
|
|
|
appInfo: HelpAppInfo,
|
2022-02-24 20:43:04 +00:00
|
|
|
activeCmds: openArray[CmdInfo]) =
|
2019-11-11 15:05:22 +00:00
|
|
|
if appInfo.copyrightBanner.len > 0:
|
|
|
|
helpOutput appInfo.copyrightBanner, "\p\p"
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
let cmd = activeCmds[^1]
|
|
|
|
|
2019-11-11 16:10:28 +00:00
|
|
|
appInfo.maxNameLen = cmd.maxNameLen
|
|
|
|
appInfo.hasAbbrs = cmd.hasAbbrs
|
2023-06-08 13:28:44 +00:00
|
|
|
appInfo.terminalWidth =
|
|
|
|
try:
|
|
|
|
terminalWidth()
|
|
|
|
except ValueError:
|
|
|
|
int.high # https://github.com/nim-lang/Nim/pull/21968
|
2019-11-11 16:10:28 +00:00
|
|
|
appInfo.namesWidth = min(minNameWidth, appInfo.maxNameLen) + descPadding
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
var cmdInvocation = appInfo.appInvocation
|
|
|
|
for i in 1 ..< activeCmds.len:
|
|
|
|
cmdInvocation.add " "
|
|
|
|
cmdInvocation.add activeCmds[i].name
|
|
|
|
|
|
|
|
# Write out the app or script name
|
2019-10-23 00:30:40 +00:00
|
|
|
helpOutput fgSection, "Usage: \p"
|
|
|
|
help.describeInvocation cmd, cmdInvocation, appInfo
|
|
|
|
help.describeOptions cmd, cmdInvocation, appInfo
|
|
|
|
helpOutput "\p"
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-11-12 12:07:29 +00:00
|
|
|
flushOutputAndQuit QuitSuccess
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
func getNextArgIdx(cmd: CmdInfo, consumedArgIdx: int): int =
|
2021-05-17 20:08:18 +00:00
|
|
|
for i in 0 ..< cmd.opts.len:
|
|
|
|
if cmd.opts[i].kind == Arg and cmd.opts[i].idx > consumedArgIdx:
|
2019-10-31 17:58:49 +00:00
|
|
|
return cmd.opts[i].idx
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
-1
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2023-06-09 19:16:55 +00:00
|
|
|
proc noMoreArgsError(cmd: CmdInfo): string {.raises: [].} =
|
|
|
|
result =
|
|
|
|
if cmd.isSubCommand:
|
2024-10-30 10:49:34 +00:00
|
|
|
"The command '" & cmd.name & "'"
|
2023-06-09 19:16:55 +00:00
|
|
|
else:
|
|
|
|
appInvocation()
|
2019-06-14 16:33:59 +00:00
|
|
|
result.add " does not accept"
|
2019-08-23 15:52:32 +00:00
|
|
|
if cmd.hasArgs: result.add " additional"
|
2019-06-14 16:33:59 +00:00
|
|
|
result.add " arguments"
|
2019-03-25 23:18:02 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func findOpt(opts: openArray[OptInfo], name: string): OptInfo =
|
2019-08-23 15:52:32 +00:00
|
|
|
for opt in opts:
|
2019-11-11 14:46:51 +00:00
|
|
|
if cmpIgnoreStyle(opt.name, name) == 0 or
|
|
|
|
cmpIgnoreStyle(opt.abbr, name) == 0:
|
2019-08-23 15:52:32 +00:00
|
|
|
return opt
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func findOpt(activeCmds: openArray[CmdInfo], name: string): OptInfo =
|
2019-08-23 15:52:32 +00:00
|
|
|
for i in countdown(activeCmds.len - 1, 0):
|
|
|
|
let found = findOpt(activeCmds[i].opts, name)
|
|
|
|
if found != nil: return found
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func findCmd(cmds: openArray[CmdInfo], name: string): CmdInfo =
|
2019-08-23 15:52:32 +00:00
|
|
|
for cmd in cmds:
|
|
|
|
if cmpIgnoreStyle(cmd.name, name) == 0:
|
|
|
|
return cmd
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func findSubCmd(cmd: CmdInfo, name: string): CmdInfo =
|
2019-08-23 15:52:32 +00:00
|
|
|
let subCmdDiscriminator = cmd.getSubCmdDiscriminator
|
|
|
|
if subCmdDiscriminator != nil:
|
|
|
|
let cmd = findCmd(subCmdDiscriminator.subCmds, name)
|
|
|
|
if cmd != nil: return cmd
|
2019-06-14 16:33:59 +00:00
|
|
|
|
|
|
|
return nil
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func startsWithIgnoreStyle(s: string, prefix: string): bool =
|
2019-07-03 15:58:09 +00:00
|
|
|
# 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
|
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
when defined(debugCmdTree):
|
2019-08-23 15:52:32 +00:00
|
|
|
proc printCmdTree(cmd: CmdInfo, indent = 0) =
|
|
|
|
let blanks = spaces(indent)
|
2019-06-14 16:33:59 +00:00
|
|
|
echo blanks, "> ", cmd.name
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
for opt in cmd.opts:
|
|
|
|
if opt.kind == Discriminator:
|
|
|
|
for subcmd in opt.subCmds:
|
|
|
|
printCmdTree(subcmd, indent + 2)
|
|
|
|
else:
|
2019-11-11 14:46:51 +00:00
|
|
|
echo blanks, " - ", opt.name, ": ", opt.typename
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
else:
|
2019-08-23 15:52:32 +00:00
|
|
|
template printCmdTree(cmd: CmdInfo) = discard
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-03-18 02:01:07 +00:00
|
|
|
# TODO remove the overloads here to get better "missing overload" error message
|
2023-06-08 13:25:05 +00:00
|
|
|
proc parseCmdArg*(T: type InputDir, p: string): T {.raises: [ValueError].} =
|
2023-02-15 08:26:53 +00:00
|
|
|
if not dirExists(p):
|
2019-03-18 02:01:07 +00:00
|
|
|
raise newException(ValueError, "Directory doesn't exist")
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
T(p)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
proc parseCmdArg*(T: type InputFile, p: string): T {.raises: [ValueError].} =
|
2019-03-18 02:01:07 +00:00
|
|
|
# TODO this is needed only because InputFile cannot be made
|
|
|
|
# an alias of TypedInputFile at the moment, because of a generics
|
|
|
|
# caching issue
|
2023-02-15 08:26:53 +00:00
|
|
|
if not fileExists(p):
|
2019-03-18 02:01:07 +00:00
|
|
|
raise newException(ValueError, "File doesn't exist")
|
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
when not defined(nimscript):
|
|
|
|
try:
|
2023-02-15 08:26:53 +00:00
|
|
|
let f = system.open(p, fmRead)
|
2019-06-14 16:33:59 +00:00
|
|
|
close f
|
|
|
|
except IOError:
|
|
|
|
raise newException(ValueError, "File not accessible")
|
2019-03-18 02:01:07 +00:00
|
|
|
|
2023-02-15 08:26:53 +00:00
|
|
|
T(p)
|
2019-03-18 02:01:07 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
proc parseCmdArg*(
|
|
|
|
T: type TypedInputFile, p: string): T {.raises: [ValueError].} =
|
2022-06-03 18:24:59 +00:00
|
|
|
var path = p
|
2019-03-18 02:01:07 +00:00
|
|
|
when T.defaultExt.len > 0:
|
|
|
|
path = path.addFileExt(T.defaultExt)
|
|
|
|
|
|
|
|
if not fileExists(path):
|
|
|
|
raise newException(ValueError, "File doesn't exist")
|
|
|
|
|
2019-06-14 16:33:59 +00:00
|
|
|
when not defined(nimscript):
|
|
|
|
try:
|
2019-11-08 15:03:55 +00:00
|
|
|
let f = system.open(path, fmRead)
|
2019-06-14 16:33:59 +00:00
|
|
|
close f
|
|
|
|
except IOError:
|
|
|
|
raise newException(ValueError, "File not accessible")
|
2019-03-18 02:01:07 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
T(path)
|
2019-03-18 02:01:07 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func parseCmdArg*(T: type[OutDir|OutFile|OutPath], p: string): T =
|
|
|
|
T(p)
|
2018-12-19 12:51:00 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
proc parseCmdArg*[T](
|
|
|
|
_: type Option[T], s: string): Option[T] {.raises: [ValueError].} =
|
2022-06-03 18:24:59 +00:00
|
|
|
some(parseCmdArg(T, s))
|
2018-12-19 12:51:00 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
template parseCmdArg*(T: type string, s: string): string =
|
|
|
|
s
|
2018-11-22 21:15:50 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
func parseCmdArg*(
|
|
|
|
T: type SomeSignedInt, s: string): T {.raises: [ValueError].} =
|
2023-02-15 08:26:53 +00:00
|
|
|
T parseBiggestInt(s)
|
2018-11-22 21:15:50 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
func parseCmdArg*(
|
|
|
|
T: type SomeUnsignedInt, s: string): T {.raises: [ValueError].} =
|
2023-02-15 08:26:53 +00:00
|
|
|
T parseBiggestUInt(s)
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
func parseCmdArg*(T: type SomeFloat, p: string): T {.raises: [ValueError].} =
|
2022-06-03 18:24:59 +00:00
|
|
|
parseFloat(p)
|
2019-01-23 16:11:24 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
func parseCmdArg*(T: type bool, p: string): T {.raises: [ValueError].} =
|
2019-11-08 17:49:44 +00:00
|
|
|
try:
|
2022-06-03 18:24:59 +00:00
|
|
|
p.len == 0 or parseBool(p)
|
2019-11-08 17:49:44 +00:00
|
|
|
except CatchableError:
|
2023-02-15 08:26:53 +00:00
|
|
|
raise newException(ValueError, "'" & p & "' is not a valid boolean value. Supported values are on/off, yes/no, true/false or 1/0")
|
2019-01-23 16:11:24 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
func parseCmdArg*(T: type enum, s: string): T {.raises: [ValueError].} =
|
2023-02-15 08:26:53 +00:00
|
|
|
parseEnum[T](s)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
proc parseCmdArgAux(T: type, s: string): T {.raises: [ValueError].} =
|
2019-03-18 02:01:07 +00:00
|
|
|
# The parseCmdArg procs are allowed to raise only `ValueError`.
|
|
|
|
# If you have provided your own specializations, please handle
|
|
|
|
# all other exception types.
|
2018-12-19 10:52:32 +00:00
|
|
|
mixin parseCmdArg
|
2024-02-12 05:39:19 +00:00
|
|
|
try:
|
|
|
|
parseCmdArg(T, s)
|
|
|
|
except CatchableError as exc:
|
|
|
|
raise newException(ValueError, exc.msg)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func completeCmdArg*(T: type enum, val: string): seq[string] =
|
2019-07-03 15:37:59 +00:00
|
|
|
for e in low(T)..high(T):
|
|
|
|
let as_str = $e
|
2019-07-03 15:58:09 +00:00
|
|
|
if startsWithIgnoreStyle(as_str, val):
|
2019-07-03 15:37:59 +00:00
|
|
|
result.add($e)
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func completeCmdArg*(T: type SomeNumber, val: string): seq[string] =
|
|
|
|
@[]
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func completeCmdArg*(T: type bool, val: string): seq[string] =
|
|
|
|
@[]
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func completeCmdArg*(T: type string, val: string): seq[string] =
|
|
|
|
@[]
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2019-07-09 11:43:31 +00:00
|
|
|
proc completeCmdArg*(T: type[InputFile|TypedInputFile|InputDir|OutFile|OutDir|OutPath],
|
2022-06-03 18:24:59 +00:00
|
|
|
val: string): seq[string] =
|
2019-10-23 00:30:40 +00:00
|
|
|
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] == '.'
|
|
|
|
|
2020-03-24 20:51:54 +00:00
|
|
|
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
|
2019-07-03 15:37:59 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func completeCmdArg*[T](_: type seq[T], val: string): seq[string] =
|
|
|
|
@[]
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
proc completeCmdArg*[T](_: type Option[T], val: string): seq[string] =
|
2020-03-16 21:47:48 +00:00
|
|
|
mixin completeCmdArg
|
2019-07-03 15:37:59 +00:00
|
|
|
return completeCmdArg(type(T), val)
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
proc completeCmdArgAux(T: type, val: string): seq[string] =
|
2020-03-16 21:47:48 +00:00
|
|
|
mixin completeCmdArg
|
2019-07-03 15:37:59 +00:00
|
|
|
return completeCmdArg(T, val)
|
2019-07-01 15:41:35 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
template setField[T](
|
|
|
|
loc: var T, val: Option[string], defaultVal: untyped): untyped =
|
2019-03-18 02:01:07 +00:00
|
|
|
type FieldType = type(loc)
|
2019-11-08 15:55:25 +00:00
|
|
|
loc = if isSome(val): parseCmdArgAux(FieldType, val.get)
|
2018-12-19 10:52:32 +00:00
|
|
|
else: FieldType(defaultVal)
|
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
template setField[T](
|
|
|
|
loc: var seq[T], val: Option[string], defaultVal: untyped): untyped =
|
2021-05-16 14:49:56 +00:00
|
|
|
if val.isSome:
|
|
|
|
loc.add parseCmdArgAux(type(loc[0]), val.get)
|
|
|
|
else:
|
|
|
|
type FieldType = type(loc)
|
|
|
|
loc = FieldType(defaultVal)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func makeDefaultValue*(T: type): T =
|
2023-08-20 10:40:32 +00:00
|
|
|
default(T)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func requiresInput*(T: type): bool =
|
2019-11-08 15:55:25 +00:00
|
|
|
not ((T is seq) or (T is Option) or (T is bool))
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func acceptsMultipleValues*(T: type): bool =
|
2019-08-23 15:52:32 +00:00
|
|
|
T is seq
|
2018-12-19 12:51:00 +00:00
|
|
|
|
2019-01-23 11:49:10 +00:00
|
|
|
template debugMacroResult(macroName: string) {.dirty.} =
|
|
|
|
when defined(debugMacros) or defined(debugConfutils):
|
|
|
|
echo "\n-------- ", macroName, " ----------------------"
|
|
|
|
echo result.repr
|
|
|
|
|
2023-06-08 13:25:05 +00:00
|
|
|
func parseEnumNormalized[T: enum](s: string): T {.raises: [ValueError].} =
|
2023-01-26 09:42:14 +00:00
|
|
|
# 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.
|
2023-05-31 15:37:01 +00:00
|
|
|
genEnumCaseStmt(T, s, default = nil, ord(low(T)), ord(high(T)), normalize)
|
2023-01-26 09:42:14 +00:00
|
|
|
|
2020-06-16 15:22:41 +00:00
|
|
|
proc generateFieldSetters(RecordType: NimNode): NimNode =
|
|
|
|
var recordDef = getImpl(RecordType)
|
2019-10-23 00:30:40 +00:00
|
|
|
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
|
2020-07-02 13:33:00 +00:00
|
|
|
namePragma = field.readPragma"name"
|
|
|
|
paramName = if namePragma != nil: namePragma
|
|
|
|
else: fieldName
|
2019-10-23 00:30:40 +00:00
|
|
|
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,
|
2020-07-02 13:33:00 +00:00
|
|
|
newLit($paramName),
|
2019-10-23 00:30:40 +00:00
|
|
|
setterName, completerName,
|
|
|
|
newCall(bindSym"requiresInput", fixedFieldType),
|
|
|
|
newCall(bindSym"acceptsMultipleValues", fixedFieldType))
|
|
|
|
|
2023-05-31 15:37:01 +00:00
|
|
|
result.add quote do:
|
|
|
|
{.push hint[XCannotRaiseY]: off.}
|
2023-02-15 08:26:53 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
result.add quote do:
|
2022-06-03 18:24:59 +00:00
|
|
|
proc `completerName`(val: string): seq[string] {.
|
2020-03-24 20:51:54 +00:00
|
|
|
nimcall
|
|
|
|
gcsafe
|
|
|
|
sideEffect
|
2023-06-12 14:25:39 +00:00
|
|
|
raises: []
|
2020-03-24 20:51:54 +00:00
|
|
|
.} =
|
2019-10-23 00:30:40 +00:00
|
|
|
return completeCmdArgAux(`fixedFieldType`, val)
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
proc `setterName`(`configVar`: var `RecordType`, val: Option[string]) {.
|
2020-03-24 20:51:54 +00:00
|
|
|
nimcall
|
|
|
|
gcsafe
|
|
|
|
sideEffect
|
2023-06-12 14:25:39 +00:00
|
|
|
raises: [ValueError]
|
2020-03-24 20:51:54 +00:00
|
|
|
.} =
|
2019-10-23 00:30:40 +00:00
|
|
|
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.
|
2019-11-12 00:33:20 +00:00
|
|
|
if isSome(val):
|
2023-02-15 08:26:53 +00:00
|
|
|
`configField` = parseEnumNormalized[type(`configField`)](val.get)
|
2019-10-23 00:30:40 +00:00
|
|
|
else:
|
|
|
|
`configField` = `defaultValue`
|
|
|
|
else:
|
|
|
|
setField(`configField`, val, `defaultValue`)
|
|
|
|
|
2023-02-15 08:26:53 +00:00
|
|
|
result.add quote do:
|
|
|
|
{.pop.}
|
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
result.add settersArray
|
|
|
|
debugMacroResult "Field Setters"
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func checkDuplicate(cmd: CmdInfo, opt: OptInfo, fieldName: NimNode) =
|
2021-09-02 08:12:38 +00:00
|
|
|
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
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func validPath(path: var seq[CmdInfo], parent, node: CmdInfo): bool =
|
2021-09-02 08:12:38 +00:00
|
|
|
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
|
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func findPath(parent, node: CmdInfo): seq[CmdInfo] =
|
2021-09-02 08:12:38 +00:00
|
|
|
# find valid path from parent to node
|
|
|
|
result = newSeq[CmdInfo]()
|
|
|
|
doAssert validPath(result, parent, node)
|
|
|
|
result.add parent
|
|
|
|
|
2021-09-02 08:12:38 +00:00
|
|
|
func toText(n: NimNode): string =
|
|
|
|
if n == nil: ""
|
|
|
|
elif n.kind in {nnkStrLit..nnkTripleStrLit}: n.strVal
|
|
|
|
else: repr(n)
|
|
|
|
|
2020-06-16 15:22:41 +00:00
|
|
|
proc cmdInfoFromType(T: NimNode): CmdInfo =
|
|
|
|
result = CmdInfo()
|
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
var
|
2020-06-16 15:22:41 +00:00
|
|
|
recordDef = getImpl(T)
|
2019-10-23 00:30:40 +00:00
|
|
|
discriminatorFields = newSeq[OptInfo]()
|
|
|
|
fieldIdx = 0
|
|
|
|
|
|
|
|
for field in recordFields(recordDef):
|
|
|
|
let
|
|
|
|
isImplicitlySelectable = field.readPragma"implicitlySelectable" != nil
|
|
|
|
defaultValue = field.readPragma"defaultValue"
|
2021-05-16 18:42:12 +00:00
|
|
|
defaultValueDesc = field.readPragma"defaultValueDesc"
|
2021-05-18 08:01:11 +00:00
|
|
|
defaultInHelp = if defaultValueDesc != nil: defaultValueDesc
|
|
|
|
else: defaultValue
|
2021-09-02 08:12:38 +00:00
|
|
|
defaultInHelpText = toText(defaultInHelp)
|
|
|
|
separator = field.readPragma"separator"
|
2021-09-14 09:45:01 +00:00
|
|
|
longDesc = field.readPragma"longDesc"
|
2021-09-02 08:12:38 +00:00
|
|
|
|
2021-01-29 21:17:15 +00:00
|
|
|
isHidden = field.readPragma("hidden") != nil
|
2019-11-11 14:46:51 +00:00
|
|
|
abbr = field.readPragma"abbr"
|
|
|
|
name = field.readPragma"name"
|
2019-10-23 00:30:40 +00:00
|
|
|
desc = field.readPragma"desc"
|
2019-10-28 19:16:01 +00:00
|
|
|
optKind = if field.isDiscriminator: Discriminator
|
|
|
|
elif field.readPragma("argument") != nil: Arg
|
|
|
|
else: CliSwitch
|
2019-10-23 00:30:40 +00:00
|
|
|
|
2019-10-28 19:16:01 +00:00
|
|
|
var opt = OptInfo(kind: optKind,
|
2019-10-23 00:30:40 +00:00
|
|
|
idx: fieldIdx,
|
2019-11-11 14:46:51 +00:00
|
|
|
name: $field.name,
|
2021-01-29 21:17:15 +00:00
|
|
|
isHidden: isHidden,
|
2021-05-18 08:01:11 +00:00
|
|
|
hasDefault: defaultValue != nil,
|
|
|
|
defaultInHelpText: defaultInHelpText,
|
2019-10-23 00:30:40 +00:00
|
|
|
typename: field.typ.repr)
|
|
|
|
|
|
|
|
if desc != nil: opt.desc = desc.strVal
|
2019-11-11 14:46:51 +00:00
|
|
|
if name != nil: opt.name = name.strVal
|
|
|
|
if abbr != nil: opt.abbr = abbr.strVal
|
2021-09-14 09:45:01 +00:00
|
|
|
if separator != nil: opt.separator = separator.strVal
|
|
|
|
if longDesc != nil: opt.longDesc = longDesc.strVal
|
2019-10-23 00:30:40 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
|
2019-11-08 17:57:44 +00:00
|
|
|
opt.isImplicitlySelectable = isImplicitlySelectable
|
2019-10-23 00:30:40 +00:00
|
|
|
opt.isCommand = field.readPragma"command" != nil
|
|
|
|
|
|
|
|
for i in 1 ..< cmdType.len:
|
2020-03-10 11:38:29 +00:00
|
|
|
let enumVal = cmdType[i]
|
|
|
|
var name, desc: string
|
|
|
|
if enumVal.kind == nnkEnumFieldDef:
|
|
|
|
name = $enumVal[0]
|
|
|
|
desc = $enumVal[1]
|
|
|
|
else:
|
|
|
|
name = $enumVal
|
2019-10-23 00:30:40 +00:00
|
|
|
if defaultValue != nil and eqIdent(name, defaultValue):
|
|
|
|
opt.defaultSubCmd = i - 1
|
2020-03-10 11:38:29 +00:00
|
|
|
opt.subCmds.add CmdInfo(name: name, desc: desc)
|
2019-10-23 00:30:40 +00:00
|
|
|
|
|
|
|
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)
|
2020-06-16 15:22:41 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
if discriminator == nil:
|
|
|
|
error "Unable to find " & $fieldName
|
2020-06-16 15:22:41 +00:00
|
|
|
|
|
|
|
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]
|
|
|
|
|
2020-06-23 14:11:22 +00:00
|
|
|
var branchEnumVal = field.caseBranch[0]
|
|
|
|
if branchEnumVal.kind == nnkDotExpr:
|
|
|
|
branchEnumVal = branchEnumVal[1]
|
2019-10-23 00:30:40 +00:00
|
|
|
var cmd = findCmd(discriminator.subCmds, $branchEnumVal)
|
2021-09-02 08:12:38 +00:00
|
|
|
# we respect subcommand hierarchy when looking for duplicate
|
|
|
|
let path = findPath(result, cmd)
|
|
|
|
for n in path:
|
|
|
|
checkDuplicate(n, opt, field.name)
|
2021-11-30 07:35:18 +00:00
|
|
|
|
|
|
|
# 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
|
2020-06-16 15:22:41 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
else:
|
2021-09-02 08:12:38 +00:00
|
|
|
checkDuplicate(result, opt, field.name)
|
2021-11-30 07:35:18 +00:00
|
|
|
|
|
|
|
if field.readPragma("ignore") == nil:
|
|
|
|
result.opts.add opt
|
2020-06-16 15:22:41 +00:00
|
|
|
|
|
|
|
macro configurationRtti(RecordType: type): untyped =
|
|
|
|
let
|
|
|
|
T = RecordType.getType[1]
|
|
|
|
cmdInfo = cmdInfoFromType T
|
|
|
|
fieldSetters = generateFieldSetters T
|
2019-10-23 00:30:40 +00:00
|
|
|
|
2020-06-16 15:22:41 +00:00
|
|
|
result = newTree(nnkPar, newLitFixed cmdInfo, fieldSetters)
|
2019-10-23 00:30:40 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
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,
|
2022-03-09 15:13:09 +00:00
|
|
|
type(secondarySources.data[0]))
|
2024-10-30 10:49:34 +00:00
|
|
|
except SerializationError as err:
|
|
|
|
raise newException(ConfigurationError, err.formatMsg("<content>"), err)
|
|
|
|
except IOError:
|
|
|
|
raiseAssert "This should not be possible"
|
2023-03-14 15:24:38 +00:00
|
|
|
|
2023-06-09 19:16:55 +00:00
|
|
|
func constructEnvKey*(prefix: string, key: string): string {.raises: [].} =
|
2023-04-19 09:54:48 +00:00
|
|
|
## 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
|
2024-10-30 10:49:34 +00:00
|
|
|
(prefix & "_" & key).toUpperAscii.multiReplace(("-", "_"), (" ", "_"))
|
2023-04-19 09:54:48 +00:00
|
|
|
|
2024-01-25 12:18:50 +00:00
|
|
|
# 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
|
2024-02-12 03:26:05 +00:00
|
|
|
|
2022-02-27 18:41:25 +00:00
|
|
|
proc loadImpl[C, SecondarySources](
|
|
|
|
Configuration: typedesc[C],
|
|
|
|
cmdLine = commandLineParams(),
|
|
|
|
version = "",
|
|
|
|
copyrightBanner = "",
|
|
|
|
printUsage = true,
|
|
|
|
quitOnFailure = true,
|
|
|
|
secondarySourcesRef: ref SecondarySources,
|
2023-08-17 11:32:47 +00:00
|
|
|
secondarySources: proc (
|
|
|
|
config: Configuration, sources: ref SecondarySources
|
|
|
|
) {.gcsafe, raises: [ConfigurationError].} = nil,
|
2024-10-30 10:49:34 +00:00
|
|
|
envVarsPrefix = appInvocation()
|
2023-08-17 11:32:47 +00:00
|
|
|
): Configuration {.raises: [ConfigurationError].} =
|
2018-11-21 13:25:53 +00:00
|
|
|
## 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.
|
2020-06-16 15:22:41 +00:00
|
|
|
let (rootCmd, fieldSetters) = configurationRtti(Configuration)
|
2019-08-23 15:52:32 +00:00
|
|
|
var fieldCounters: array[fieldSetters.len, int]
|
|
|
|
|
2019-03-25 23:18:02 +00:00
|
|
|
printCmdTree rootCmd
|
|
|
|
|
2019-06-14 16:51:40 +00:00
|
|
|
var activeCmds = @[rootCmd]
|
2019-03-26 08:45:19 +00:00
|
|
|
template lastCmd: auto = activeCmds[^1]
|
2019-08-23 15:52:32 +00:00
|
|
|
var nextArgIdx = lastCmd.getNextArgIdx(-1)
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2019-11-08 17:49:44 +00:00
|
|
|
var help = ""
|
|
|
|
|
|
|
|
proc suggestCallingHelp =
|
2024-10-30 10:49:34 +00:00
|
|
|
errorOutput "Try ", fgCommand, appInvocation() & " --help"
|
2019-11-08 17:49:44 +00:00
|
|
|
errorOutput " for more information.\p"
|
2019-11-12 12:07:29 +00:00
|
|
|
flushOutputAndQuit QuitFailure
|
2019-11-08 17:49:44 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
template fail(args: varargs[untyped]): untyped =
|
2018-11-21 13:25:53 +00:00
|
|
|
if quitOnFailure:
|
2019-11-08 17:49:44 +00:00
|
|
|
errorOutput args
|
|
|
|
errorOutput "\p"
|
|
|
|
suggestCallingHelp()
|
2018-11-21 13:25:53 +00:00
|
|
|
else:
|
2019-11-08 17:49:44 +00:00
|
|
|
# TODO: populate this string
|
|
|
|
raise newException(ConfigurationError, "")
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
template applySetter(
|
|
|
|
conf: Configuration, setterIdx: int, cmdLineVal: string): untyped =
|
2023-03-20 19:06:25 +00:00
|
|
|
when defined(nimHasWarnBareExcept):
|
|
|
|
{.push warning[BareExcept]:off.}
|
2023-02-15 08:26:53 +00:00
|
|
|
|
2019-03-18 02:01:07 +00:00
|
|
|
try:
|
2024-10-30 10:49:34 +00:00
|
|
|
fieldSetters[setterIdx][1](conf, some(cmdLineVal))
|
2019-08-23 15:52:32 +00:00
|
|
|
inc fieldCounters[setterIdx]
|
2019-03-18 02:01:07 +00:00
|
|
|
except:
|
2021-05-17 16:52:35 +00:00
|
|
|
fail("Error while processing the ",
|
|
|
|
fgOption, fieldSetters[setterIdx][0],
|
2023-02-15 08:26:53 +00:00
|
|
|
"=", cmdLineVal, resetStyle, " parameter: ",
|
2019-03-18 02:01:07 +00:00
|
|
|
getCurrentExceptionMsg())
|
|
|
|
|
2023-03-20 19:06:25 +00:00
|
|
|
when defined(nimHasWarnBareExcept):
|
|
|
|
{.pop.}
|
2023-02-15 08:26:53 +00:00
|
|
|
|
2019-12-02 21:31:29 +00:00
|
|
|
when hasCompletions:
|
2022-06-03 18:24:59 +00:00
|
|
|
template getArgCompletions(opt: OptInfo, prefix: string): seq[string] =
|
2019-12-02 21:31:29 +00:00
|
|
|
fieldSetters[opt.idx][2](prefix)
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
template required(opt: OptInfo): bool =
|
|
|
|
fieldSetters[opt.idx][3] and not opt.hasDefault
|
2018-12-19 12:51:00 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
template activateCmd(
|
|
|
|
conf: Configuration, discriminator: OptInfo, activatedCmd: CmdInfo) =
|
2019-03-26 08:45:19 +00:00
|
|
|
let cmd = activatedCmd
|
2024-10-30 10:49:34 +00:00
|
|
|
conf.applySetter(discriminator.idx, if cmd.desc.len > 0: cmd.desc
|
|
|
|
else: cmd.name)
|
2019-03-26 08:45:19 +00:00
|
|
|
activeCmds.add cmd
|
2019-08-23 15:52:32 +00:00
|
|
|
nextArgIdx = cmd.getNextArgIdx(-1)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
2019-12-02 21:31:29 +00:00
|
|
|
when hasCompletions:
|
|
|
|
type
|
|
|
|
ArgKindFilter = enum
|
|
|
|
argName
|
|
|
|
argAbbr
|
2019-06-29 11:22:46 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
proc showMatchingOptions(cmd: CmdInfo, prefix: string, filterKind: set[ArgKindFilter]) =
|
|
|
|
var matchingOptions: seq[OptInfo]
|
|
|
|
|
|
|
|
if len(prefix) > 0:
|
|
|
|
# Filter the options according to the input prefix
|
|
|
|
for opt in cmd.opts:
|
2019-11-11 14:46:51 +00:00
|
|
|
if argName in filterKind and len(opt.name) > 0:
|
|
|
|
if startsWithIgnoreStyle(opt.name, prefix):
|
2019-10-23 00:30:40 +00:00
|
|
|
matchingOptions.add(opt)
|
2019-11-11 14:46:51 +00:00
|
|
|
if argAbbr in filterKind and len(opt.abbr) > 0:
|
|
|
|
if startsWithIgnoreStyle(opt.abbr, prefix):
|
2019-10-23 00:30:40 +00:00
|
|
|
matchingOptions.add(opt)
|
|
|
|
else:
|
|
|
|
matchingOptions = cmd.opts
|
|
|
|
|
|
|
|
for opt in matchingOptions:
|
|
|
|
# The trailing '=' means the switch accepts an argument
|
|
|
|
let trailing = if opt.typename != "bool": "=" else: ""
|
2019-06-29 11:22:46 +00:00
|
|
|
|
2019-11-11 14:46:51 +00:00
|
|
|
if argName in filterKind and len(opt.name) > 0:
|
2023-06-08 13:26:06 +00:00
|
|
|
try:
|
|
|
|
stdout.writeLine("--", opt.name, trailing)
|
|
|
|
except IOError:
|
|
|
|
discard
|
2019-11-11 14:46:51 +00:00
|
|
|
if argAbbr in filterKind and len(opt.abbr) > 0:
|
2023-06-08 13:26:06 +00:00
|
|
|
try:
|
|
|
|
stdout.writeLine('-', opt.abbr, trailing)
|
|
|
|
except IOError:
|
|
|
|
discard
|
2019-10-23 00:30:40 +00:00
|
|
|
|
|
|
|
let completion = splitCompletionLine()
|
|
|
|
# If we're not asked to complete a command line the result is an empty list
|
|
|
|
if len(completion) != 0:
|
|
|
|
var cmdStack = @[rootCmd]
|
|
|
|
# Try to understand what the active chain of commands is without parsing the
|
|
|
|
# whole command line
|
|
|
|
for tok in completion[1..^1]:
|
|
|
|
if not tok.startsWith('-'):
|
2019-11-08 17:57:44 +00:00
|
|
|
let subCmd = findSubCmd(cmdStack[^1], tok)
|
2019-10-23 00:30:40 +00:00
|
|
|
if subCmd != nil: cmdStack.add(subCmd)
|
|
|
|
|
|
|
|
let cur_word = completion[^1]
|
|
|
|
let prev_word = if len(completion) > 2: completion[^2] else: ""
|
|
|
|
let prev_prev_word = if len(completion) > 3: completion[^3] else: ""
|
|
|
|
|
|
|
|
if cur_word.startsWith('-'):
|
|
|
|
# Show all the options matching the prefix input by the user
|
2019-11-11 16:10:28 +00:00
|
|
|
let isFullName = cur_word.startsWith("--")
|
2019-10-23 00:30:40 +00:00
|
|
|
var option_word = cur_word
|
|
|
|
option_word.removePrefix('-')
|
|
|
|
|
|
|
|
for i in countdown(cmdStack.len - 1, 0):
|
|
|
|
let argFilter =
|
2019-11-11 16:10:28 +00:00
|
|
|
if isFullName:
|
2019-11-11 14:46:51 +00:00
|
|
|
{argName}
|
2019-10-23 00:30:40 +00:00
|
|
|
elif len(cur_word) > 1:
|
|
|
|
# If the user entered a single hypen then we show both long & short
|
|
|
|
# variants
|
2019-11-11 14:46:51 +00:00
|
|
|
{argAbbr}
|
2019-10-23 00:30:40 +00:00
|
|
|
else:
|
2019-11-11 14:46:51 +00:00
|
|
|
{argName, argAbbr}
|
2019-10-23 00:30:40 +00:00
|
|
|
|
|
|
|
showMatchingOptions(cmdStack[i], option_word, argFilter)
|
|
|
|
elif (prev_word.startsWith('-') or
|
|
|
|
(prev_word == "=" and prev_prev_word.startsWith('-'))):
|
|
|
|
# Handle cases where we want to complete a switch choice
|
|
|
|
# -switch
|
|
|
|
# -switch=
|
|
|
|
var option_word = if len(prev_word) == 1: prev_prev_word else: prev_word
|
|
|
|
option_word.removePrefix('-')
|
|
|
|
|
2019-11-08 17:57:44 +00:00
|
|
|
let opt = findOpt(cmdStack, option_word)
|
2019-10-23 00:30:40 +00:00
|
|
|
if opt != nil:
|
|
|
|
for arg in getArgCompletions(opt, cur_word):
|
2023-06-08 13:26:06 +00:00
|
|
|
try:
|
|
|
|
stdout.writeLine(arg)
|
|
|
|
except IOError:
|
|
|
|
discard
|
2019-10-23 00:30:40 +00:00
|
|
|
elif cmdStack[^1].hasSubCommands:
|
|
|
|
# Show all the available subcommands
|
|
|
|
for subCmd in subCmds(cmdStack[^1]):
|
|
|
|
if startsWithIgnoreStyle(subCmd.name, cur_word):
|
2023-06-08 13:26:06 +00:00
|
|
|
try:
|
|
|
|
stdout.writeLine(subCmd.name)
|
|
|
|
except IOError:
|
|
|
|
discard
|
2019-10-23 00:30:40 +00:00
|
|
|
else:
|
|
|
|
# Full options listing
|
|
|
|
for i in countdown(cmdStack.len - 1, 0):
|
2019-11-11 14:46:51 +00:00
|
|
|
showMatchingOptions(cmdStack[i], "", {argName, argAbbr})
|
2019-06-29 11:22:46 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
stdout.flushFile()
|
2019-06-29 11:22:46 +00:00
|
|
|
|
2019-10-23 00:30:40 +00:00
|
|
|
return
|
2019-06-29 11:22:46 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
proc lazyHelpAppInfo: HelpAppInfo =
|
2019-11-11 14:42:08 +00:00
|
|
|
HelpAppInfo(
|
|
|
|
copyrightBanner: copyrightBanner,
|
|
|
|
appInvocation: appInvocation())
|
|
|
|
|
|
|
|
template processHelpAndVersionOptions(optKey: string) =
|
|
|
|
let key = optKey
|
|
|
|
if cmpIgnoreStyle(key, "help") == 0:
|
|
|
|
help.showHelp lazyHelpAppInfo(), activeCmds
|
|
|
|
elif version.len > 0 and cmpIgnoreStyle(key, "version") == 0:
|
2019-11-11 15:05:22 +00:00
|
|
|
help.helpOutput version, "\p"
|
2019-11-12 12:07:29 +00:00
|
|
|
flushOutputAndQuit QuitSuccess
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2018-11-21 13:25:53 +00:00
|
|
|
for kind, key, val in getopt(cmdLine):
|
2023-02-15 08:26:53 +00:00
|
|
|
when key isnot string:
|
|
|
|
let key = string(key)
|
2018-12-19 10:52:32 +00:00
|
|
|
case kind
|
|
|
|
of cmdLongOption, cmdShortOption:
|
2019-11-11 14:42:08 +00:00
|
|
|
processHelpAndVersionOptions key
|
2019-03-26 08:45:19 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
var opt = findOpt(activeCmds, key)
|
|
|
|
if opt == nil:
|
2019-03-26 08:45:19 +00:00
|
|
|
# We didn't find the option.
|
|
|
|
# Check if it's from the default command and activate it if necessary:
|
2019-08-23 15:52:32 +00:00
|
|
|
let subCmdDiscriminator = lastCmd.getSubCmdDiscriminator
|
|
|
|
if subCmdDiscriminator != nil:
|
|
|
|
if subCmdDiscriminator.defaultSubCmd != -1:
|
|
|
|
let defaultCmd = subCmdDiscriminator.subCmds[subCmdDiscriminator.defaultSubCmd]
|
|
|
|
opt = findOpt(defaultCmd.opts, key)
|
|
|
|
if opt != nil:
|
2024-10-30 10:49:34 +00:00
|
|
|
result.activateCmd(subCmdDiscriminator, defaultCmd)
|
2019-08-23 15:52:32 +00:00
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
|
|
|
if opt != nil:
|
2024-10-30 10:49:34 +00:00
|
|
|
result.applySetter(opt.idx, val)
|
2018-11-21 13:25:53 +00:00
|
|
|
else:
|
2024-10-30 10:49:34 +00:00
|
|
|
fail "Unrecognized option '" & key & "'"
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2018-12-19 10:52:32 +00:00
|
|
|
of cmdArgument:
|
2019-11-11 14:42:08 +00:00
|
|
|
if lastCmd.hasSubCommands:
|
|
|
|
processHelpAndVersionOptions key
|
2019-01-23 11:49:10 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
block processArg:
|
|
|
|
let subCmdDiscriminator = lastCmd.getSubCmdDiscriminator
|
|
|
|
if subCmdDiscriminator != nil:
|
|
|
|
let subCmd = findCmd(subCmdDiscriminator.subCmds, key)
|
|
|
|
if subCmd != nil:
|
2024-10-30 10:49:34 +00:00
|
|
|
result.activateCmd(subCmdDiscriminator, subCmd)
|
2019-08-23 15:52:32 +00:00
|
|
|
break processArg
|
2019-06-14 16:33:59 +00:00
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
if nextArgIdx == -1:
|
|
|
|
fail lastCmd.noMoreArgsError
|
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
result.applySetter(nextArgIdx, key)
|
2019-08-23 15:52:32 +00:00
|
|
|
|
|
|
|
if not fieldSetters[nextArgIdx][4]:
|
|
|
|
nextArgIdx = lastCmd.getNextArgIdx(nextArgIdx)
|
2018-12-19 10:52:32 +00:00
|
|
|
|
|
|
|
else:
|
|
|
|
discard
|
|
|
|
|
2019-08-23 15:52:32 +00:00
|
|
|
let subCmdDiscriminator = lastCmd.getSubCmdDiscriminator
|
|
|
|
if subCmdDiscriminator != nil and
|
|
|
|
subCmdDiscriminator.defaultSubCmd != -1 and
|
|
|
|
fieldCounters[subCmdDiscriminator.idx] == 0:
|
|
|
|
let defaultCmd = subCmdDiscriminator.subCmds[subCmdDiscriminator.defaultSubCmd]
|
2024-10-30 10:49:34 +00:00
|
|
|
result.activateCmd(subCmdDiscriminator, defaultCmd)
|
2019-08-23 15:52:32 +00:00
|
|
|
|
2024-10-30 10:49:34 +00:00
|
|
|
# https://github.com/status-im/nim-confutils/pull/109#discussion_r1820076739
|
|
|
|
if not isNil(secondarySources): # Nim v2.0.10: `!= nil` broken in nimscript
|
2023-08-17 11:32:47 +00:00
|
|
|
try:
|
|
|
|
secondarySources(result, secondarySourcesRef)
|
|
|
|
except ConfigurationError as err:
|
2024-10-30 10:49:34 +00:00
|
|
|
fail "Failed to load secondary sources: '" & err.msg & "'"
|
2022-02-27 18:41:25 +00:00
|
|
|
|
2023-06-12 14:25:39 +00:00
|
|
|
proc processMissingOpts(
|
|
|
|
conf: var Configuration, cmd: CmdInfo) {.raises: [ConfigurationError].} =
|
2022-02-27 18:41:25 +00:00
|
|
|
for opt in cmd.opts:
|
|
|
|
if fieldCounters[opt.idx] == 0:
|
2023-04-19 09:54:48 +00:00
|
|
|
let envKey = constructEnvKey(envVarsPrefix, opt.name)
|
|
|
|
|
2023-06-12 14:25:39 +00:00
|
|
|
try:
|
|
|
|
if existsEnv(envKey):
|
|
|
|
let envContent = getEnv(envKey)
|
2024-10-30 10:49:34 +00:00
|
|
|
conf.applySetter(opt.idx, envContent)
|
2023-06-12 14:25:39 +00:00
|
|
|
elif secondarySourcesRef.setters[opt.idx](conf, secondarySourcesRef):
|
|
|
|
# all work is done in the config file setter,
|
|
|
|
# there is nothing left to do here.
|
|
|
|
discard
|
|
|
|
elif opt.hasDefault:
|
|
|
|
fieldSetters[opt.idx][1](conf, none[string]())
|
|
|
|
elif opt.required:
|
2024-10-30 10:49:34 +00:00
|
|
|
fail "The required option '" & opt.name & "' was not specified"
|
2023-06-12 14:25:39 +00:00
|
|
|
except ValueError as err:
|
2024-10-30 10:49:34 +00:00
|
|
|
fail "Option '" & opt.name & "' failed to parse: '" & err.msg & "'"
|
2022-02-27 18:41:25 +00:00
|
|
|
|
2019-03-25 23:18:02 +00:00
|
|
|
for cmd in activeCmds:
|
2019-08-23 15:52:32 +00:00
|
|
|
result.processMissingOpts(cmd)
|
2019-01-23 11:49:10 +00:00
|
|
|
|
2022-02-27 18:41:25 +00:00
|
|
|
template load*(
|
|
|
|
Configuration: type,
|
|
|
|
cmdLine = commandLineParams(),
|
|
|
|
version = "",
|
|
|
|
copyrightBanner = "",
|
|
|
|
printUsage = true,
|
|
|
|
quitOnFailure = true,
|
2023-04-19 09:54:48 +00:00
|
|
|
secondarySources: untyped = nil,
|
2024-10-30 10:49:34 +00:00
|
|
|
envVarsPrefix = appInvocation()): untyped =
|
2022-02-27 18:41:25 +00:00
|
|
|
block:
|
2024-10-30 10:49:34 +00:00
|
|
|
let secondarySourcesRef = generateSecondarySources(Configuration)
|
2022-02-27 18:41:25 +00:00
|
|
|
loadImpl(Configuration, cmdLine, version,
|
|
|
|
copyrightBanner, printUsage, quitOnFailure,
|
2023-04-19 09:54:48 +00:00
|
|
|
secondarySourcesRef, secondarySources, envVarsPrefix)
|
2022-02-27 18:41:25 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func defaults*(Configuration: type): Configuration =
|
2019-06-10 19:42:42 +00:00
|
|
|
load(Configuration, cmdLine = @[], printUsage = false, quitOnFailure = false)
|
|
|
|
|
2019-01-23 11:49:10 +00:00
|
|
|
proc dispatchImpl(cliProcSym, cliArgs, loadArgs: NimNode): NimNode =
|
|
|
|
# Here, we'll create a configuration object with fields matching
|
2019-06-14 16:33:59 +00:00
|
|
|
# the CLI proc params. We'll also generate a call to the designated proc
|
2019-01-23 11:49:10 +00:00
|
|
|
let configType = genSym(nskType, "CliConfig")
|
|
|
|
let configFields = newTree(nnkRecList)
|
|
|
|
let configVar = genSym(nskLet, "config")
|
|
|
|
var dispatchCall = newCall(cliProcSym)
|
|
|
|
|
|
|
|
# The return type of the proc is skipped over
|
|
|
|
for i in 1 ..< cliArgs.len:
|
|
|
|
var arg = copy cliArgs[i]
|
|
|
|
|
|
|
|
# If an argument doesn't specify a type, we infer it from the default value
|
|
|
|
if arg[1].kind == nnkEmpty:
|
|
|
|
if arg[2].kind == nnkEmpty:
|
|
|
|
error "Please provide either a default value or type of the parameter", arg
|
|
|
|
arg[1] = newCall(bindSym"typeof", arg[2])
|
|
|
|
|
|
|
|
# Turn any default parameters into the confutils's `defaultValue` pragma
|
|
|
|
if arg[2].kind != nnkEmpty:
|
|
|
|
if arg[0].kind != nnkPragmaExpr:
|
2019-01-23 16:11:24 +00:00
|
|
|
arg[0] = newTree(nnkPragmaExpr, arg[0], newTree(nnkPragma))
|
|
|
|
arg[0][1].add newColonExpr(bindSym"defaultValue", arg[2])
|
2019-01-23 11:49:10 +00:00
|
|
|
arg[2] = newEmptyNode()
|
|
|
|
|
|
|
|
configFields.add arg
|
|
|
|
dispatchCall.add newTree(nnkDotExpr, configVar, skipPragma arg[0])
|
|
|
|
|
|
|
|
let cliConfigType = nnkTypeSection.newTree(
|
|
|
|
nnkTypeDef.newTree(
|
|
|
|
configType,
|
|
|
|
newEmptyNode(),
|
|
|
|
nnkObjectTy.newTree(
|
|
|
|
newEmptyNode(),
|
|
|
|
newEmptyNode(),
|
|
|
|
configFields)))
|
|
|
|
|
|
|
|
var loadConfigCall = newCall(bindSym"load", configType)
|
|
|
|
for p in loadArgs: loadConfigCall.add p
|
|
|
|
|
|
|
|
result = quote do:
|
|
|
|
`cliConfigType`
|
|
|
|
let `configVar` = `loadConfigCall`
|
|
|
|
`dispatchCall`
|
|
|
|
|
|
|
|
macro dispatch*(fn: typed, args: varargs[untyped]): untyped =
|
|
|
|
if fn.kind != nnkSym or
|
|
|
|
fn.symKind notin {nskProc, nskFunc, nskMacro, nskTemplate}:
|
|
|
|
error "The first argument to `confutils.dispatch` should be a callable symbol"
|
|
|
|
|
|
|
|
let fnImpl = fn.getImpl
|
|
|
|
result = dispatchImpl(fnImpl.name, fnImpl.params, args)
|
|
|
|
debugMacroResult "Dispatch Code"
|
|
|
|
|
|
|
|
macro cli*(args: varargs[untyped]): untyped =
|
|
|
|
if args.len == 0:
|
|
|
|
error "The cli macro expects a do block", args
|
|
|
|
|
|
|
|
let doBlock = args[^1]
|
|
|
|
if doBlock.kind notin {nnkDo, nnkLambda}:
|
|
|
|
error "The last argument to `confutils.cli` should be a do block", doBlock
|
|
|
|
|
|
|
|
args.del(args.len - 1)
|
|
|
|
|
|
|
|
# Create a new anonymous proc we'll dispatch to
|
|
|
|
let cliProcName = genSym(nskProc, "CLI")
|
|
|
|
var cliProc = newTree(nnkProcDef, cliProcName)
|
|
|
|
# Copy everything but the name from the do block:
|
|
|
|
for i in 1 ..< doBlock.len: cliProc.add doBlock[i]
|
|
|
|
|
|
|
|
# Generate the final code
|
|
|
|
result = newStmtList(cliProc, dispatchImpl(cliProcName, cliProc.params, args))
|
2019-01-23 16:11:24 +00:00
|
|
|
|
|
|
|
# TODO: remove this once Nim supports custom pragmas on proc params
|
|
|
|
for p in cliProc.params:
|
|
|
|
if p.kind == nnkEmpty: continue
|
|
|
|
p[0] = skipPragma p[0]
|
|
|
|
|
2019-01-23 11:49:10 +00:00
|
|
|
debugMacroResult "CLI Code"
|
2018-11-21 13:25:53 +00:00
|
|
|
|
2022-06-03 18:24:59 +00:00
|
|
|
func load*(f: TypedInputFile): f.ContentType =
|
2019-03-18 02:01:07 +00:00
|
|
|
when f.Format is Unspecified or f.ContentType is Unspecified:
|
|
|
|
{.fatal: "To use `InputFile.load`, please specify the Format and ContentType of the file".}
|
|
|
|
|
|
|
|
when f.Format is Txt:
|
|
|
|
# TODO: implement a proper Txt serialization format
|
|
|
|
mixin init
|
|
|
|
f.ContentType.init readFile(f.string).string
|
|
|
|
else:
|
|
|
|
mixin loadFile
|
|
|
|
loadFile(f.Format, f.string, f.ContentType)
|
2024-02-12 05:39:19 +00:00
|
|
|
|
|
|
|
{.pop.}
|