mirror of
https://github.com/daylinmorgan/hwylterm.git
synced 2024-12-21 18:50:44 -06:00
Compare commits
14 commits
b6202f4f51
...
69ae06fa47
Author | SHA1 | Date | |
---|---|---|---|
69ae06fa47 | |||
206556e967 | |||
0a728d8727 | |||
a40aed047d | |||
0375acc677 | |||
a57d4ee687 | |||
77cfae4d26 | |||
8b37c0dad9 | |||
d228123195 | |||
cb231dfc94 | |||
7cf4c2f537 | |||
7f53ef5df9 | |||
16cc0b910d | |||
e964581b13 |
5 changed files with 419 additions and 334 deletions
|
@ -368,7 +368,7 @@ when isMainModule:
|
|||
|
||||
hwylCli:
|
||||
name "bbansi"
|
||||
settings NoArgsShowHelp
|
||||
settings ShowHelp
|
||||
usage "[bold]bbansi[/] [[[green]args...[/]] [[[faint]-h|-V[/]]"
|
||||
description """
|
||||
bbansi "[[yellow] yellow text!"
|
||||
|
|
|
@ -130,7 +130,7 @@ when isMainModule:
|
|||
import ./[hwylcli]
|
||||
hwylcli:
|
||||
name "hwylchoose"
|
||||
settings NoArgsShowHelp
|
||||
settings ShowHelp
|
||||
usage "[bold]hwylchoose[/] [[[green]args...[/]] [[[faint]-h[/]]"
|
||||
description """
|
||||
hwylchoose a b c d
|
||||
|
|
|
@ -8,40 +8,41 @@ import std/[
|
|||
sugar
|
||||
]
|
||||
import ./[bbansi, parseopt3]
|
||||
export parseopt3
|
||||
export parseopt3, sets, bbansi
|
||||
|
||||
type
|
||||
HwylFlagHelp = tuple
|
||||
HwylFlagHelp* = tuple
|
||||
short, long, description: string
|
||||
HwylSubCmdHelp = tuple
|
||||
HwylSubCmdHelp* = tuple
|
||||
name, desc: string
|
||||
HwylCliStyles* = object
|
||||
hdr = "bold cyan"
|
||||
shortFlag = "yellow"
|
||||
longFlag = "magenta"
|
||||
descFlag = ""
|
||||
cmd = "bold"
|
||||
header* = "bold cyan"
|
||||
flagShort* = "yellow"
|
||||
flagLong* = "magenta"
|
||||
flagDesc* = ""
|
||||
cmd* = "bold"
|
||||
HwylCliHelp* = object
|
||||
cmd*: string
|
||||
usage*: string
|
||||
desc*: string
|
||||
subcmds: seq[HwylSubCmdHelp]
|
||||
subcmds*: seq[HwylSubCmdHelp]
|
||||
flags*: seq[HwylFlagHelp]
|
||||
styles*: HwylCliStyles
|
||||
subcmdLen, subcmdDescLen, shortArgLen, longArgLen, descArgLen: int
|
||||
subcmdLen*, subcmdDescLen*, shortArgLen*, longArgLen*, descArgLen*: int
|
||||
|
||||
# NOTE: do i need both strips?
|
||||
func firstLine(s: string): string =
|
||||
s.strip().dedent().strip().splitlines()[0]
|
||||
|
||||
func newHwylCliHelp*(
|
||||
cmd = "",
|
||||
usage = "",
|
||||
desc = "",
|
||||
subcmds: openArray[HwylSubCmdHelp] = @[],
|
||||
flags: openArray[HwylFlagHelp] = @[],
|
||||
styles = HwylCliStyles()
|
||||
): HwylCliHelp =
|
||||
result.cmd = cmd
|
||||
result.desc = dedent(desc).strip()
|
||||
result.subcmds = subcmds.mapIt((it.name,it.desc.strip().dedent().strip().splitlines()[0]))
|
||||
result.subcmds =
|
||||
subcmds.mapIt((it.name, it.desc.firstLine))
|
||||
result.usage = dedent(usage).strip()
|
||||
result.flags = @flags
|
||||
result.styles = styles
|
||||
|
@ -55,10 +56,10 @@ func newHwylCliHelp*(
|
|||
result.subcmdLen = max(result.subcmdLen, s.name.len)
|
||||
result.subcmdDescLen = max(result.subcmdDescLen, s.desc.len)
|
||||
|
||||
func flagHelp(cli: HwylCliHelp, f: HwylFlagHelp): string =
|
||||
func render*(cli: HwylCliHelp, f: HwylFlagHelp): string =
|
||||
result.add " "
|
||||
if f.short != "":
|
||||
result.add "[" & cli.styles.shortFlag & "]"
|
||||
result.add "[" & cli.styles.flagShort & "]"
|
||||
result.add "-" & f.short.alignLeft(cli.shortArgLen)
|
||||
result.add "[/]"
|
||||
else:
|
||||
|
@ -66,7 +67,7 @@ func flagHelp(cli: HwylCliHelp, f: HwylFlagHelp): string =
|
|||
|
||||
result.add " "
|
||||
if f.long != "":
|
||||
result.add "[" & cli.styles.longFlag & "]"
|
||||
result.add "[" & cli.styles.flagLong & "]"
|
||||
result.add "--" & f.long.alignLeft(cli.longArgLen)
|
||||
result.add "[/]"
|
||||
else:
|
||||
|
@ -75,12 +76,12 @@ func flagHelp(cli: HwylCliHelp, f: HwylFlagHelp): string =
|
|||
result.add " "
|
||||
|
||||
if f.description != "":
|
||||
result.add "[" & cli.styles.descFlag & "]"
|
||||
result.add "[" & cli.styles.flagDesc & "]"
|
||||
result.add f.description
|
||||
result.add "[/]"
|
||||
result.add "\n"
|
||||
|
||||
func subCmdLine(cli: HwylCliHelp, subcmd: HwylSubCmdHelp): string =
|
||||
func render*(cli: HwylCliHelp, subcmd: HwylSubCmdHelp): string =
|
||||
result.add " "
|
||||
result.add "[" & cli.styles.cmd & "]"
|
||||
result.add subcmd.name.alignLeft(cli.subcmdLen)
|
||||
|
@ -89,49 +90,63 @@ func subCmdLine(cli: HwylCliHelp, subcmd: HwylSubCmdHelp): string =
|
|||
result.add subcmd.desc.alignLeft(cli.subcmdDescLen)
|
||||
result.add "\n"
|
||||
|
||||
proc bbImpl(cli: HwylCliHelp): string =
|
||||
if cli.cmd != "":
|
||||
result.add cli.cmd
|
||||
result.add "\n"
|
||||
|
||||
# TODO: split this into separate procs to make overriding more fluid
|
||||
func render*(cli: HwylCliHelp): string =
|
||||
if cli.usage != "":
|
||||
result.add "\n"
|
||||
result.add "[" & cli.styles.hdr & "]"
|
||||
result.add "[" & cli.styles.header & "]"
|
||||
result.add "usage[/]:\n"
|
||||
result.add indent(cli.usage, 2 )
|
||||
result.add "\n"
|
||||
if cli.desc != "":
|
||||
result.add "\n\n"
|
||||
result.add "\n"
|
||||
result.add cli.desc
|
||||
result.add "\n"
|
||||
if cli.subcmds.len > 0:
|
||||
result.add "\n"
|
||||
result.add "[" & cli.styles.hdr & "]"
|
||||
result.add "[" & cli.styles.header & "]"
|
||||
result.add "subcommands[/]:\n"
|
||||
for s in cli.subcmds:
|
||||
result.add cli.subcmdLine(s)
|
||||
result.add cli.render(s)
|
||||
if cli.flags.len > 0:
|
||||
result.add "\n"
|
||||
result.add "[" & cli.styles.hdr & "]"
|
||||
result.add "[" & cli.styles.header & "]"
|
||||
result.add "flags[/]:\n"
|
||||
for f in cli.flags:
|
||||
result.add flagHelp(cli,f)
|
||||
result.add render(cli,f)
|
||||
|
||||
proc bb*(cli: HwylCliHelp): BbString =
|
||||
result = bb(bbImpl(cli))
|
||||
result = bb(render(cli))
|
||||
|
||||
proc `$`*(cli: HwylCliHelp): string =
|
||||
result = $bb(cli)
|
||||
# ----------------------------------------
|
||||
|
||||
type
|
||||
CliSetting = enum
|
||||
NoHelpFlag, NoArgsShowHelp
|
||||
CliFlag = object
|
||||
Count* = object ## Count type for an incrementing flag
|
||||
val*: int
|
||||
|
||||
type
|
||||
# ----
|
||||
CliSetting* = enum
|
||||
NoHelpFlag, ## Remove the builtin help flag
|
||||
ShowHelp, ## If cmdline empty show help
|
||||
NoNormalize ## Don't normalize flags and commands
|
||||
|
||||
BuiltinFlag = object
|
||||
name*: string
|
||||
ident*: string
|
||||
default*: NimNode
|
||||
typeSym*: string
|
||||
short*: char
|
||||
long*: string
|
||||
help*: NimNode
|
||||
node: NimNode
|
||||
|
||||
CliFlag = object
|
||||
name*: string
|
||||
ident*: NimNode
|
||||
default*: NimNode
|
||||
typeNode*: NimNode
|
||||
short*: char
|
||||
long*: string
|
||||
help*: NimNode
|
||||
|
||||
CliCfg = object
|
||||
stopWords*: seq[string]
|
||||
styles: NimNode
|
||||
|
@ -144,74 +159,60 @@ type
|
|||
subName*: string # used for help the generator
|
||||
version*, usage*: NimNode
|
||||
flags*: seq[CliFlag]
|
||||
builtinFlags*: seq[BuiltinFlag]
|
||||
flagGroups: Table[string, seq[CliFlag]]
|
||||
required*: seq[string]
|
||||
globalFlags*: seq[CliFlag]
|
||||
inheritFlags*: seq[string]
|
||||
root*: bool
|
||||
|
||||
{.push hint[XDeclaredButNotUsed]:off .}
|
||||
func peekNode(n: NimNode) =
|
||||
# some debug procs I use to wrap my ahead aroung the magic of *macro*
|
||||
func `<<<`(n: NimNode) {.used.} =
|
||||
## for debugging macros
|
||||
debugEcho treeRepr n
|
||||
{.pop.}
|
||||
func `<<<`(s: string) {.used.} =
|
||||
debugEcho s
|
||||
|
||||
# TODO: do i need this?
|
||||
func newCliFlag(): CliFlag =
|
||||
result.help = newLit("")
|
||||
func bad(n: NimNode, argument: string = "") =
|
||||
var msg = "unexpected node kind: " & $n.kind
|
||||
if argument != "":
|
||||
msg &= " for argument: " & argument
|
||||
error msg
|
||||
|
||||
template badNode =
|
||||
error "unexpected node kind: " & $node.kind
|
||||
|
||||
func typeSymFromNode(node: NimNode): string =
|
||||
func getFlagParamNode(node: NimNode): NimNode =
|
||||
case node.kind
|
||||
of nnkIdent, nnkStrLit:
|
||||
result = node.strVal
|
||||
of nnkBracketExpr:
|
||||
result = node[0].strVal & "[" & node[1].strVal & "]"
|
||||
else: badNode
|
||||
|
||||
func getOptTypeSym(node: NimNode): string =
|
||||
case node.kind:
|
||||
of nnkCommand:
|
||||
result = typeSymFromNode(node[1]) # [0] is T
|
||||
of nnkCall:
|
||||
result = typeSymFromNode(node[1][0]) # [1] is stmtlist [0] is the type
|
||||
else: error "unexpected node kind: " & $node.kind
|
||||
|
||||
func getOptOptNode(optOptValue: NimNode): NimNode =
|
||||
case optOptValue.kind
|
||||
of nnkStrLit:
|
||||
result = optOptValue
|
||||
result = node
|
||||
of nnkStmtList:
|
||||
result = optOptValue[0]
|
||||
result = node[0]
|
||||
of nnkCommand:
|
||||
result = optOptValue[1]
|
||||
result = node[1]
|
||||
of nnkPrefix: # NOTE: should i double check prefix value?
|
||||
result = optOptValue[1]
|
||||
else: error "unexpected node kind: " & $optOptValue.kind
|
||||
result = node[1]
|
||||
else: bad(node, "flag param")
|
||||
|
||||
# TODO: don't use the confusing name optOpts here and above
|
||||
func parseOptOpts(opt: var CliFlag, optOpts: NimNode) =
|
||||
expectKind optOpts, nnkStmtList
|
||||
for optOpt in optOpts:
|
||||
case optOpt.kind
|
||||
func parseFlagParams(f: var CliFlag, node: NimNode) =
|
||||
expectKind node, nnkStmtList
|
||||
for n in node:
|
||||
case n.kind
|
||||
of nnkCall, nnkCommand, nnkPrefix:
|
||||
case optOpt[0].strVal
|
||||
case n[0].strVal
|
||||
of "help","?":
|
||||
opt.help = getOptOptNode(optOpt[1])
|
||||
f.help = getFlagParamNode(n[1])
|
||||
of "short", "-":
|
||||
let val = getOptOptNode(optOpt).strVal
|
||||
let val = getFlagParamNode(n).strVal
|
||||
if val.len > 1:
|
||||
error "short flag must be a char"
|
||||
opt.short = val[0].char
|
||||
f.short = val[0].char
|
||||
of "*", "default":
|
||||
opt.default = getOptOptNode(optOpt)
|
||||
f.default = getFlagParamNode(n)
|
||||
of "i", "ident":
|
||||
opt.ident = getOptOptNode(optOpt).strVal
|
||||
f.ident = getFlagParamNode(n).strVal.ident
|
||||
of "T":
|
||||
opt.typeSym = getOptTypeSym(optOpt)
|
||||
f.typeNode = n[1]
|
||||
else:
|
||||
error "unexpected option setting: " & optOpt[0].strVal
|
||||
error "unexpected setting: " & n[0].strVal
|
||||
else:
|
||||
error "unexpected option node type: " & $optOpt.kind
|
||||
bad(n, "flag params")
|
||||
|
||||
func startFlag(f: var CliFlag, n: NimNode) =
|
||||
f.name =
|
||||
|
@ -220,6 +221,8 @@ func startFlag(f: var CliFlag, n: NimNode) =
|
|||
of nnkAccQuoted: collect(for c in n[0]: c.strVal).join("")
|
||||
else: error "unexpected node kind for option"
|
||||
|
||||
f.help = newLit("") # by default no string
|
||||
|
||||
# assume a single character is a short flag
|
||||
if f.name.len == 1:
|
||||
f.short = f.name[0].char
|
||||
|
@ -228,10 +231,8 @@ func startFlag(f: var CliFlag, n: NimNode) =
|
|||
|
||||
func parseCliFlag(n: NimNode): CliFlag =
|
||||
if n.kind notin [nnkCommand, nnkCall]:
|
||||
error "unexpected node kind: " & $n.kind
|
||||
bad(n, "flags")
|
||||
|
||||
# deduplicate these...
|
||||
result = newCliFlag()
|
||||
startFlag(result, n)
|
||||
# option "some help desc"
|
||||
if n.kind == nnkCommand:
|
||||
|
@ -239,18 +240,36 @@ func parseCliFlag(n: NimNode): CliFlag =
|
|||
# option:
|
||||
# help "some help description"
|
||||
else:
|
||||
parseOptOpts(result, n[1])
|
||||
parseFlagParams(result, n[1])
|
||||
|
||||
if result.ident == "":
|
||||
result.ident = result.name
|
||||
if result.typeSym == "":
|
||||
result.typeSym = "string"
|
||||
if result.ident == nil:
|
||||
result.ident = result.name.ident
|
||||
if result.typeNode == nil:
|
||||
result.typeNode = ident"string"
|
||||
|
||||
|
||||
func parseCliFlags(flags: NimNode): seq[CliFlag] =
|
||||
expectKind flags, nnkStmtList
|
||||
for f in flags:
|
||||
result.add parseCliFlag(f)
|
||||
# TODO: change how this works?
|
||||
func parseCliFlags(cfg: var CliCfg, node: NimNode) =
|
||||
var group: string
|
||||
expectKind node, nnkStmtList
|
||||
for n in node:
|
||||
var flag: CliFlag
|
||||
case n.kind
|
||||
of nnkCall, nnkCommand:
|
||||
flag = parseCliFlag(n)
|
||||
if group == "":
|
||||
cfg.flags.add flag
|
||||
else:
|
||||
if group notin cfg.flagGroups: cfg.flagGroups[group] = @[flag]
|
||||
else: cfg.flagGroups[group].add flag
|
||||
of nnkBracket:
|
||||
group = n[0].strVal
|
||||
continue
|
||||
of nnkPrefix:
|
||||
if n[0].kind != nnkIdent and n[0].strVal != "^":
|
||||
error "unexpected node in flags: " & $n.kind
|
||||
expectKind n[1], nnkBracket
|
||||
cfg.inheritFlags.add n[1][0].strVal
|
||||
else: bad(n, "flag")
|
||||
|
||||
func parseCliSetting(s: string): CliSetting =
|
||||
try: parseEnum[CliSetting](s)
|
||||
|
@ -283,7 +302,7 @@ func parseIdentLikeList(node: NimNode): seq[string] =
|
|||
result.add n.strVal
|
||||
else: assert false
|
||||
|
||||
func parseCliBody(body: NimNode, name: string = ""): CliCfg
|
||||
func parseCliBody(body: NimNode, name: string = "", root: bool= false): CliCfg
|
||||
|
||||
func isSubMarker(node: NimNode): bool =
|
||||
if node.kind == nnkPrefix:
|
||||
|
@ -310,13 +329,25 @@ func sliceStmts(node: NimNode): seq[
|
|||
start = i + 1
|
||||
|
||||
|
||||
func addGlobalFlagsFrom(child: var CliCfg, parent: CliCfg) =
|
||||
func addInheritedFlags(child: var CliCfg, parent: CliCfg, self = false) =
|
||||
let names = child.flags.mapIt(it.name)
|
||||
for f in parent.globalFlags:
|
||||
if f.name in names:
|
||||
error "global flag " & f.name & " conflicts with command flag"
|
||||
child.flags.add f
|
||||
var groups: seq[string]
|
||||
if not self:
|
||||
groups.add child.inheritFlags
|
||||
|
||||
# autoinherit the "global" flags
|
||||
if "global" in parent.flagGroups:
|
||||
groups.add "global"
|
||||
|
||||
for g in groups:
|
||||
if g notin parent.flagGroups:
|
||||
debugEcho parent.flagGroups.keys().toSeq()
|
||||
error "expected flag group: " & g & " to exist in parent command"
|
||||
for f in parent.flagGroups[g]:
|
||||
if f.name in names:
|
||||
error "global flag " & f.name & " conflicts with command flag"
|
||||
child.flags.add f
|
||||
|
||||
func parseCliSubcommands(cfg: var CliCfg, node: NimNode) =
|
||||
expectKind node[1], nnkStmtList
|
||||
for (name, s) in sliceStmts(node[1]):
|
||||
|
@ -325,8 +356,7 @@ func parseCliSubcommands(cfg: var CliCfg, node: NimNode) =
|
|||
nnkStmtList.newTree(node[1][s]), cfg.name & " " & name
|
||||
)
|
||||
subCfg.subName = name
|
||||
subCfg.addGlobalFlagsFrom(cfg)
|
||||
|
||||
subCfg.addInheritedFlags(cfg)
|
||||
cfg.subcommands.add subCfg
|
||||
|
||||
func parseHiddenFlags(cfg: var CliCfg, node: NimNode) =
|
||||
|
@ -345,8 +375,41 @@ func parseHiddenFlags(cfg: var CliCfg, node: NimNode) =
|
|||
cfg.hidden.add n.strVal
|
||||
else: assert false
|
||||
|
||||
func parseCliBody(body: NimNode, name = ""): CliCfg =
|
||||
func addBuiltinFlags(cfg: var CliCfg) =
|
||||
# duplicated with below :/
|
||||
let shorts = cfg.flags.mapIt(it.short).toHashSet()
|
||||
|
||||
let
|
||||
name = cfg.name.replace(" ", "")
|
||||
printHelpName = ident("print" & name & "Help")
|
||||
|
||||
if NoHelpFlag notin cfg.settings:
|
||||
let helpNode = quote do:
|
||||
`printHelpName`(); quit 0
|
||||
cfg.builtinFlags.add BuiltinFlag(
|
||||
name: "help",
|
||||
long: "help",
|
||||
help: newLit("show this help"),
|
||||
short: if 'h' notin shorts: 'h' else: '\x00',
|
||||
node: helpNode
|
||||
)
|
||||
|
||||
if cfg.version != nil:
|
||||
let version = cfg.version
|
||||
let versionNode = quote do:
|
||||
echo `version`; quit 0
|
||||
|
||||
cfg.builtinFlags.add BuiltinFlag(
|
||||
name:"version",
|
||||
long: "version",
|
||||
help: newLit("print version"),
|
||||
short: if 'V' notin shorts: 'V' else: '\x00',
|
||||
node: versionNode
|
||||
)
|
||||
|
||||
func parseCliBody(body: NimNode, name = "", root = false): CliCfg =
|
||||
result.name = name
|
||||
result.root = true
|
||||
for call in body:
|
||||
if call.kind notin [nnkCall, nnkCommand, nnkPrefix]:
|
||||
error "unexpected node kind: " & $call.kind
|
||||
|
@ -361,10 +424,8 @@ func parseCliBody(body: NimNode, name = ""): CliCfg =
|
|||
result.usage = call[1]
|
||||
of "description", "...":
|
||||
result.desc = call[1]
|
||||
of "globalFlags":
|
||||
result.globalFlags = parseCliFlags(call[1])
|
||||
of "flags":
|
||||
result.flags = parseCliFlags(call[1])
|
||||
parseCliFlags(result, call[1])
|
||||
of "settings":
|
||||
parseCliSettings(result, call)
|
||||
of "stopWords":
|
||||
|
@ -390,32 +451,31 @@ func parseCliBody(body: NimNode, name = ""): CliCfg =
|
|||
sub.pre = result.preSub
|
||||
sub.post = result.postSub
|
||||
|
||||
result.addGlobalFlagsFrom(result)
|
||||
result.addInheritedFlags(result, self = true)
|
||||
|
||||
if result.name == "":
|
||||
error "missing required option: name"
|
||||
|
||||
# TODO: validate "required" flags exist here
|
||||
result.addBuiltinFlags()
|
||||
|
||||
func flagToTuple(f: CliFlag | BuiltinFlag): NimNode =
|
||||
let
|
||||
short =
|
||||
if f.short != '\x00': newLit($f.short)
|
||||
else: newLit("")
|
||||
long = newLit(f.long)
|
||||
help = f.help
|
||||
quote do:
|
||||
(`short`, `long`, `help`)
|
||||
|
||||
func flagsArray(cfg: CliCfg): NimNode =
|
||||
result = newTree(nnkBracket)
|
||||
|
||||
for f in cfg.flags:
|
||||
if f.name in cfg.hidden: continue
|
||||
let
|
||||
help = f.help
|
||||
long = newLit(f.long)
|
||||
short =
|
||||
if f.short != '\x00': newLit($f.short)
|
||||
else: newLit("")
|
||||
result.add quote do:
|
||||
(`short`, `long`, `help`)
|
||||
|
||||
if NoHelpFlag notin cfg.settings:
|
||||
result.add quote do:
|
||||
("h", "help", "show this help")
|
||||
|
||||
if cfg.version != nil:
|
||||
result.add quote do:
|
||||
("v", "version", "print version")
|
||||
result.add f.flagToTuple()
|
||||
for f in cfg.builtinFlags:
|
||||
result.add f.flagToTuple()
|
||||
|
||||
func subCmdsArray(cfg: CliCfg): NimNode =
|
||||
result = newTree(nnkBracket)
|
||||
|
@ -425,7 +485,7 @@ func subCmdsArray(cfg: CliCfg): NimNode =
|
|||
result.add quote do:
|
||||
(`cmd`, `desc`)
|
||||
|
||||
proc hwylCliError(msg: string | BbString) =
|
||||
proc hwylCliError*(msg: string | BbString) =
|
||||
quit $(bb("error ", "red") & bb(msg))
|
||||
|
||||
func defaultUsage(cfg: CliCfg): NimNode =
|
||||
|
@ -437,7 +497,6 @@ func defaultUsage(cfg: CliCfg): NimNode =
|
|||
|
||||
func generateCliHelperProc(cfg: CliCfg, printHelpName: NimNode): NimNode =
|
||||
let
|
||||
name = newLit(cfg.name)
|
||||
desc = cfg.desc or newLit("")
|
||||
usage = cfg.usage or defaultUsage(cfg)
|
||||
helpFlags = cfg.flagsArray()
|
||||
|
@ -446,193 +505,204 @@ func generateCliHelperProc(cfg: CliCfg, printHelpName: NimNode): NimNode =
|
|||
|
||||
result = quote do:
|
||||
proc `printHelpName`() =
|
||||
echo newHwylCliHelp(
|
||||
cmd = `name`,
|
||||
echo bb(render(newHwylCliHelp(
|
||||
desc = `desc`,
|
||||
usage = `usage`,
|
||||
subcmds = `subcmds`,
|
||||
flags = `helpFlags`,
|
||||
styles = `styles`,
|
||||
)
|
||||
)))
|
||||
|
||||
# NOTE: is there a better way to do this?
|
||||
proc checkVarSet[T](name: string, target: T) =
|
||||
var default: T
|
||||
if target == default:
|
||||
hwylCliError("missing required flag: [b]" & name)
|
||||
proc parse*(p: OptParser, key: string, val: string, target: var bool) =
|
||||
target = true
|
||||
|
||||
proc checkDefaultExists[T](target: T, key: string, val: string) =
|
||||
var default: T
|
||||
if target == default and val == "":
|
||||
hwylCliError("expected value for: [b]" & key)
|
||||
proc parse*(p: OptParser, key: string, val: string, target: var string) =
|
||||
target = val
|
||||
|
||||
proc tryParseInt(key: string, val: string): int =
|
||||
proc parse*(p: OptParser, key: string, val: string, target: var int) =
|
||||
try:
|
||||
result = parseInt(val)
|
||||
target = parseInt(val)
|
||||
except:
|
||||
hwylCliError(
|
||||
"failed to parse value for [b]" & key & "[/] as integer: [b]" & val
|
||||
)
|
||||
|
||||
func addOrOverwrite[T](target: var seq[T], default: seq[T], val: T) =
|
||||
if target != default:
|
||||
target.add val
|
||||
macro enumNames(a: typed): untyped =
|
||||
## unexported macro copied from std/enumutils
|
||||
result = newNimNode(nnkBracket)
|
||||
for ai in a.getType[1][1..^1]:
|
||||
assert ai.kind == nnkSym
|
||||
result.add newLit ai.strVal
|
||||
|
||||
proc parse*[E: enum](p: OptParser, key: string, val: string, target: var E) =
|
||||
try:
|
||||
target = parseEnum[E](val)
|
||||
except:
|
||||
let choices = enumNames(E).join(",")
|
||||
hwylCliError(
|
||||
"failed to parse value for [b]" & key & "[/] as enum: [b]" & val & "[/], expected one of: " & choices
|
||||
)
|
||||
|
||||
proc parse*(p: OptParser, key: string, val: string, target: var float) =
|
||||
try:
|
||||
target = parseFloat(val)
|
||||
except:
|
||||
hwylCliError(
|
||||
"failed to parse value for [b]" & key & "[/] as float: [b]" & val
|
||||
)
|
||||
|
||||
proc parse*[T](p: OptParser, key: string, val: string, target: var seq[T]) =
|
||||
var parsed: T
|
||||
parse(p, key, val, parsed)
|
||||
target.add parsed
|
||||
|
||||
proc parse*(p: OptParser, key: string, val: string, target: var Count) =
|
||||
# if value set to that otherwise increment
|
||||
if val != "":
|
||||
var num: int
|
||||
parse(p, key, val, num)
|
||||
target.val = num
|
||||
else:
|
||||
target = @[val]
|
||||
inc target.val
|
||||
|
||||
func assignField(f: CliFlag): NimNode =
|
||||
let key = ident"key"
|
||||
let varName = ident(f.ident)
|
||||
func shortLongCaseStmt(cfg: CliCfg, printHelpName: NimNode, version: NimNode): NimNode =
|
||||
var caseStmt = nnkCaseStmt.newTree()
|
||||
if NoNormalize notin cfg.settings:
|
||||
caseStmt.add nnkCall.newTree(ident"optionNormalize", ident"key")
|
||||
else:
|
||||
caseStmt.add ident"key"
|
||||
|
||||
case f.typeSym
|
||||
of "string":
|
||||
let value = ident"val"
|
||||
result = quote do:
|
||||
checkDefaultExists(`varName`, `key`, `value`)
|
||||
`varName` = `value`
|
||||
|
||||
of "bool":
|
||||
let value = ident"true"
|
||||
result = quote do:
|
||||
`varName` = `value`
|
||||
|
||||
of "int":
|
||||
let value = ident"val"
|
||||
result = quote do:
|
||||
checkDefaultExists(`varName`, `key`, `value`)
|
||||
`varName` = tryParseInt(`key`, `value`)
|
||||
|
||||
of "seq[string]":
|
||||
let value = ident"val"
|
||||
let default = f.default or (quote do: @[])
|
||||
result = quote do:
|
||||
`varName`.addOrOverwrite(`default`, `value`)
|
||||
|
||||
of "seq[int]":
|
||||
let value = ident"val"
|
||||
let default = f.default or (quote do: @[])
|
||||
result = quote do:
|
||||
`varName`.addOrOverwrite(`default`, tryParseInt(`value`))
|
||||
|
||||
else: error "unable to generate assignment for fion, type: " & f.name & "," & f.typeSym
|
||||
|
||||
func shortLongCaseStmt(cfg: CliCfg, printHelpName: NimNode, version: NimNode): NimNode =
|
||||
var caseStmt = nnkCaseStmt.newTree(ident("key"))
|
||||
caseStmt.add nnkOfBranch.newTree(newLit(""), quote do: hwylCliError("empty flag not supported currently"))
|
||||
|
||||
if NoHelpFlag notin cfg.settings:
|
||||
caseStmt.add nnkOfBranch.newTree(
|
||||
newLit("h"), newLit("help"),
|
||||
quote do:
|
||||
`printHelpName`(); quit 0
|
||||
)
|
||||
|
||||
if cfg.version != nil:
|
||||
caseStmt.add nnkOfBranch.newTree(
|
||||
newLit("V"), newLit("version"),
|
||||
quote do:
|
||||
echo `version`; quit 0
|
||||
)
|
||||
for f in cfg.builtinFlags:
|
||||
var branch = nnkOfBranch.newTree()
|
||||
if f.long != "": branch.add(newLit(f.long))
|
||||
if f.short != '\x00': branch.add(newLit($f.short))
|
||||
branch.add f.node
|
||||
caseStmt.add branch
|
||||
|
||||
# add flags
|
||||
for f in cfg.flags:
|
||||
var branch = nnkOfBranch.newTree()
|
||||
if f.long != "": branch.add(newLit(f.long))
|
||||
if f.long != "":
|
||||
branch.add newLit(
|
||||
if NoNormalize notin cfg.settings: optionNormalize(f.long)
|
||||
else: f.long
|
||||
)
|
||||
if f.short != '\x00': branch.add(newLit($f.short))
|
||||
branch.add assignField(f)
|
||||
let varName = f.ident
|
||||
let name = newLit(f.name)
|
||||
branch.add quote do:
|
||||
flagSet.incl `name`
|
||||
parse(p, key, val, `varName`)
|
||||
|
||||
caseStmt.add branch
|
||||
|
||||
caseStmt.add nnkElse.newTree(quote do: hwylCliError("unknown flag: [b]" & key))
|
||||
|
||||
result = nnkStmtList.newTree(caseStmt)
|
||||
|
||||
func isBool(f: CliFlag): bool =
|
||||
f.typeNode == ident"bool"
|
||||
|
||||
func isCount(f: CliFlag): bool =
|
||||
f.typeNode == ident"Count"
|
||||
|
||||
func getNoVals(cfg: CliCfg): tuple[long: NimNode, short: NimNode] =
|
||||
var long = nnkBracket.newTree()
|
||||
var short = nnkCurly.newTree()
|
||||
|
||||
if NoHelpFlag notin cfg.settings:
|
||||
long.add newLit("help")
|
||||
short.add newLit('h')
|
||||
|
||||
if cfg.version != nil:
|
||||
long.add newLit("version")
|
||||
short.add newLit('V')
|
||||
|
||||
for f in cfg.flags:
|
||||
if f.typeSym == "bool":
|
||||
if f.long != "":
|
||||
long.add newLit(f.long)
|
||||
if f.short != '\x00':
|
||||
short.add newLit(f.short)
|
||||
|
||||
let flagFlags = cfg.flags.filterIt(it.isBool or it.isCount)
|
||||
let long =
|
||||
nnkBracket.newTree(
|
||||
(flagFlags.mapIt(it.long) & cfg.builtinFlags.mapIt(it.long)).filterIt(it != "").mapIt(newLit(it))
|
||||
)
|
||||
let short =
|
||||
nnkCurly.newTree(
|
||||
(flagFlags.mapIt(it.short) & cfg.builtinFlags.mapIt(it.short)).filterIt(it != '\x00').mapIt(newLit(it))
|
||||
)
|
||||
result = (nnkPrefix.newTree(ident"@",long), short)
|
||||
|
||||
func setFlagVars(cfg: CliCfg): NimNode =
|
||||
result = nnkVarSection.newTree()
|
||||
# TODO: generalize this better...
|
||||
result = nnkVarSection.newTree().add(
|
||||
cfg.flags.mapIt(
|
||||
nnkIdentDefs.newTree(it.ident, it.typeNode, newEmptyNode())
|
||||
)
|
||||
)
|
||||
|
||||
func literalFlags(f: CliFlag): NimNode =
|
||||
var flags: seq[string]
|
||||
if f.short != '\x00': flags.add "[b]" & "-" & $f.short & "[/]"
|
||||
if f.long != "": flags.add "[b]" & "--" & f.long & "[/]"
|
||||
result = newLit(flags.join("|"))
|
||||
|
||||
func addPostParseCheck(cfg: CliCfg, body: NimNode) =
|
||||
## generate block to set defaults and check for required flags
|
||||
let flagSet = ident"flagSet"
|
||||
var required, default: seq[CliFlag]
|
||||
|
||||
for f in cfg.flags:
|
||||
let
|
||||
t =
|
||||
if f.typeSym == "seq[string]": nnkBracketExpr.newTree(newIdentNode("seq"),newIdentNode("string"))
|
||||
elif f.typeSym == "seq[int]" : nnkBracketExpr.newTree(newIdentNode("seq"),newIdentNode("string"))
|
||||
else: ident(f.typeSym)
|
||||
val =
|
||||
if f.default == nil: newEmptyNode() # use default here
|
||||
else: f.default
|
||||
if f.name in cfg.required and f.default == nil:
|
||||
required.add f
|
||||
elif f.default != nil:
|
||||
default.add f
|
||||
|
||||
result.add nnkIdentDefs.newTree(ident(f.ident), t, val)
|
||||
|
||||
func addRequiredFlagsCheck(cfg: CliCfg, body: NimNode) =
|
||||
let requirdFlags = cfg.flags.filterIt(it.name in cfg.required and it.default == nil)
|
||||
for f in requirdFlags:
|
||||
for f in required:
|
||||
let flagLit = f.literalFlags
|
||||
let name = newLit(f.name)
|
||||
let flag = ident(f.ident)
|
||||
body.add quote do:
|
||||
checkVarSet(`name`, `flag`)
|
||||
if `name` notin `flagSet`:
|
||||
hwylCliError("expected a value for flag: " & `flagLit`)
|
||||
|
||||
func hwylCliImpl(cfg: CliCfg, root = false): NimNode =
|
||||
for f in default:
|
||||
let
|
||||
name = newLit(f.name)
|
||||
target = f.ident
|
||||
default = f.default
|
||||
body.add quote do:
|
||||
if `name` notin `flagSet`:
|
||||
`target` = `default`
|
||||
|
||||
func hwylCliImpl(cfg: CliCfg): NimNode =
|
||||
let
|
||||
version = cfg.version or newLit("")
|
||||
name = cfg.name.replace(" ", "")
|
||||
printHelpName = ident("print" & name & "Help")
|
||||
parserProcName = ident("parse" & name)
|
||||
|
||||
result = newTree(nnkStmtList)
|
||||
|
||||
let
|
||||
args = ident"args"
|
||||
optParser = ident("p")
|
||||
cmdLine = ident"cmdLine"
|
||||
flagSet = ident"flagSet"
|
||||
kind = ident"kind"
|
||||
key = ident"key"
|
||||
val = ident"val"
|
||||
(longNoVal, shortNoVal) = cfg.getNoVals()
|
||||
printHelperProc = generateCliHelperProc(cfg, printHelpName)
|
||||
flagVars = setFlagVars(cfg)
|
||||
|
||||
# result.add setFlagVars(cfg)
|
||||
result = newTree(nnkStmtList)
|
||||
|
||||
var parserBody = nnkStmtList.newTree()
|
||||
let
|
||||
optParser = ident("p")
|
||||
cmdLine = ident"cmdLine"
|
||||
(longNoVal, shortNoVal) = cfg.getNoVals()
|
||||
var
|
||||
parserBody = nnkStmtList.newTree()
|
||||
stopWords = nnkBracket.newTree(newLit("--"))
|
||||
|
||||
var stopWords = nnkBracket.newTree(newLit("--"))
|
||||
for w in cfg.stopWords:
|
||||
stopWords.add newLit(w)
|
||||
|
||||
stopWords = nnkPrefix.newTree(ident"@", stopWords)
|
||||
|
||||
# should this a CritBitTree?
|
||||
parserBody.add quote do:
|
||||
var `flagSet`: HashSet[string]
|
||||
|
||||
parserBody.add(
|
||||
quote do:
|
||||
var `optParser` = initOptParser(
|
||||
@`cmdLine`,
|
||||
longNoVal = `longNoVal`,
|
||||
shortNoVal = `shortNoVal`,
|
||||
stopWords = `stopWords`
|
||||
stopWords = `stopWords`,
|
||||
opChars = {','}
|
||||
)
|
||||
)
|
||||
|
||||
let
|
||||
kind = ident"kind"
|
||||
key = ident"key"
|
||||
val = ident"val"
|
||||
|
||||
# TODO: first key needs to be normalized
|
||||
parserBody.add nnkForStmt.newTree(
|
||||
kind, key, val,
|
||||
nnkCall.newTree(nnkDotExpr.newTree(optParser,ident("getopt"))),
|
||||
|
@ -646,7 +716,10 @@ func hwylCliImpl(cfg: CliCfg, root = false): NimNode =
|
|||
nnkOfBranch.newTree(ident("cmdError"), quote do: hwylCliError(p.message)),
|
||||
nnkOfBranch.newTree(ident("cmdEnd"), quote do: assert false),
|
||||
# TODO: add nArgs to change how cmdArgument is handled ...
|
||||
nnkOfBranch.newTree(ident("cmdArgument"), quote do: result.add `key`),
|
||||
nnkOfBranch.newTree(ident("cmdArgument"),
|
||||
quote do:
|
||||
result.add `key`
|
||||
),
|
||||
nnkOfBranch.newTree(
|
||||
ident("cmdShortOption"), ident("cmdLongOption"),
|
||||
shortLongCaseStmt(cfg, printHelpName, version)
|
||||
|
@ -655,14 +728,14 @@ func hwylCliImpl(cfg: CliCfg, root = false): NimNode =
|
|||
)
|
||||
)
|
||||
|
||||
if NoArgsShowHelp in cfg.settings:
|
||||
if ShowHelp in cfg.settings:
|
||||
parserBody.add quote do:
|
||||
if commandLineParams().len == 0:
|
||||
`printHelpName`(); quit 1
|
||||
|
||||
let runProcName = ident("run" & name)
|
||||
let runBody = nnkStmtList.newTree()
|
||||
addRequiredFlagsCheck(cfg, runBody)
|
||||
addPostParseCheck(cfg, parserBody)
|
||||
# move to proc?
|
||||
if cfg.pre != nil:
|
||||
runBody.add cfg.pre
|
||||
|
@ -671,32 +744,31 @@ func hwylCliImpl(cfg: CliCfg, root = false): NimNode =
|
|||
if cfg.post != nil:
|
||||
runBody.add cfg.post
|
||||
|
||||
# let runBody = cfg.run or nnkStmtList.newTree(nnkDiscardStmt.newTree(newEmptyNode()))
|
||||
|
||||
let args = ident"args"
|
||||
|
||||
if cfg.subcommands.len > 0:
|
||||
var handleSubCommands = nnkStmtList.newTree()
|
||||
handleSubCommands.add quote do:
|
||||
if `args`.len == 0:
|
||||
hwylCliError("expected subcommand")
|
||||
|
||||
var subCommandCase = nnkCaseStmt.newTree(
|
||||
quote do: `args`[0]
|
||||
)
|
||||
var subCommandCase = nnkCaseStmt.newTree()
|
||||
if NoNormalize notin cfg.settings:
|
||||
subCommandCase.add(quote do: optionNormalize(`args`[0]))
|
||||
else:
|
||||
subCommandCase.add(quote do: `args`[0])
|
||||
|
||||
for sub in cfg.subcommands:
|
||||
subCommandCase.add nnkOfBranch.newTree(
|
||||
newLit(sub.subName),
|
||||
newLit(optionNormalize(sub.subName)),
|
||||
hwylCliImpl(sub)
|
||||
)
|
||||
|
||||
subcommandCase.add nnkElse.newTree(
|
||||
quote do:
|
||||
hwylCliError("unknown subcommand " & `args`[0])
|
||||
hwylCliError("unknown subcommand: [b]" & `args`[0])
|
||||
)
|
||||
|
||||
runBody.add handleSubCommands.add subCommandCase
|
||||
|
||||
|
||||
result.add quote do:
|
||||
# block:
|
||||
`printHelperProc`
|
||||
|
@ -708,7 +780,7 @@ func hwylCliImpl(cfg: CliCfg, root = false): NimNode =
|
|||
let `args` = `parserProcName`(`cmdLine`)
|
||||
`runBody`
|
||||
|
||||
if root:
|
||||
if cfg.root:
|
||||
result.add quote do:
|
||||
`runProcName`()
|
||||
else:
|
||||
|
@ -717,51 +789,6 @@ func hwylCliImpl(cfg: CliCfg, root = false): NimNode =
|
|||
|
||||
macro hwylCli*(body: untyped) =
|
||||
## generate a CLI styled by `hwylterm` and parsed by `parseopt3`
|
||||
var cfg = parseCliBody(body)
|
||||
hwylCliImpl(cfg, root = true)
|
||||
|
||||
when isMainModule:
|
||||
import std/strformat
|
||||
hwylCli:
|
||||
name "hwylterm"
|
||||
... "a description of hwylterm"
|
||||
globalFlags:
|
||||
config:
|
||||
T seq[string]
|
||||
? "path to config file"
|
||||
* @["config.yml"]
|
||||
flags:
|
||||
check:
|
||||
T bool
|
||||
? "load config and exit"
|
||||
- c
|
||||
run:
|
||||
echo "hello from the main command"
|
||||
echo fmt"{config=}, {check=}"
|
||||
subcommands:
|
||||
--- a
|
||||
... "the \"a\" subcommand"
|
||||
flags:
|
||||
`long-flag` "some help"
|
||||
flagg "some other help"
|
||||
run:
|
||||
echo "hello from hwylterm sub command!"
|
||||
--- b
|
||||
... """
|
||||
some "B" command
|
||||
|
||||
a longer mulitline description that will be visibil in the subcommand help
|
||||
it will automatically be "bb"'ed [bold]this is bold text[/]
|
||||
"""
|
||||
flags:
|
||||
aflag:
|
||||
T bool
|
||||
? "some help"
|
||||
bflag:
|
||||
? "some other flag?"
|
||||
* "wow"
|
||||
run:
|
||||
echo "hello from hwylterm sub `b` command"
|
||||
echo aflag, bflag
|
||||
|
||||
var cfg = parseCliBody(body, root = true)
|
||||
hwylCliImpl(cfg)
|
||||
|
||||
|
|
74
tests/example.nim
Normal file
74
tests/example.nim
Normal file
|
@ -0,0 +1,74 @@
|
|||
import std/[strformat, strutils]
|
||||
import hwylterm, hwylterm/hwylcli
|
||||
|
||||
|
||||
type
|
||||
Color = enum
|
||||
red, blue, green
|
||||
|
||||
|
||||
hwylCli:
|
||||
name "example"
|
||||
V "0.1.0"
|
||||
... "a description of hwylterm"
|
||||
flags:
|
||||
[global]
|
||||
yes:
|
||||
T bool
|
||||
? "set flag to yes"
|
||||
[config]
|
||||
confiG:
|
||||
T seq[string]
|
||||
? "path to config file"
|
||||
* @["config.yml"]
|
||||
preSub:
|
||||
echo "this is run after subcommand parsing but before its run block"
|
||||
run:
|
||||
echo "this is always run prior to subcommand parsing"
|
||||
subcommands:
|
||||
--- "onelonger"
|
||||
... """
|
||||
the first subcommand
|
||||
|
||||
this command features both an enum flag and a Count flag
|
||||
it also inherits the `[[config]` flag group
|
||||
"""
|
||||
|
||||
flags:
|
||||
color:
|
||||
T Color
|
||||
? "a color (red, green, blue)"
|
||||
verbose:
|
||||
T Count
|
||||
? "a count flag"
|
||||
- v
|
||||
^[config]
|
||||
run:
|
||||
echo "hello from `example one` command!"
|
||||
echo fmt"{color=}"
|
||||
echo fmt"{verbose=}"
|
||||
echo fmt"{config=}"
|
||||
|
||||
--- "two-longer"
|
||||
... """
|
||||
some second subcommand
|
||||
|
||||
a longer mulitline description that will be visible in the subcommand help
|
||||
and it will automatically be "bb"'ed [bold]this is bold text[/]
|
||||
|
||||
|
||||
|
||||
"""
|
||||
flags:
|
||||
a:
|
||||
T bool
|
||||
? "some help"
|
||||
b:
|
||||
T seq[float]
|
||||
? "multiple floats"
|
||||
h "this will override the builtin 'h' for help"
|
||||
run:
|
||||
echo "hello from `example b` command"
|
||||
echo fmt"{a=}, {b=}"
|
||||
|
||||
|
18
todo.md
18
todo.md
|
@ -14,25 +14,9 @@
|
|||
- [ ] add a `commands` option for `newHwylCli` in `hwylterm/cli`
|
||||
- [ ] console object with customizable options to apply formatting
|
||||
|
||||
### cli generato
|
||||
### cli generator
|
||||
|
||||
- [ ] add support for types(metavars)/defaults/required in help output
|
||||
- [ ] abstract the `globalFlags` argument to a `flagGroups` section with a builtin `global`
|
||||
this would allow users to "inherit" flag groups in subcommands
|
||||
```nim
|
||||
flags:
|
||||
# global flag group auto propagated down
|
||||
--- global
|
||||
config "path to config"
|
||||
--- shared
|
||||
shared:
|
||||
`a-flag` "some shared flag"
|
||||
-- sub
|
||||
flags:
|
||||
^shared
|
||||
unique "some unique flag"
|
||||
```
|
||||
|
||||
|
||||
|
||||
## features
|
||||
|
|
Loading…
Reference in a new issue