proper hook behavior

This commit is contained in:
Daylin Morgan 2025-01-26 13:31:34 -06:00
parent 2915f65d15
commit 5f2fcdc4ed
Signed by: daylin
GPG key ID: 950D13E9719334AD
3 changed files with 70 additions and 23 deletions

View file

@ -628,10 +628,10 @@ func postPropagateCheck(c: CliCfg) =
func propagate(c: var CliCfg) =
for child in c.subcommands.mitems:
# push the preSub to the lowest subcommand
if child.subcommands.len != 0 and child.preSub == nil:
child.preSub = c.preSub
child.postSub = c.postSub
# push the hooks to the lowest subcommand unless another one exists on the way
if child.subcommands.len != 0:
child.preSub = child.preSub or c.preSub
child.postSub = child.postSub or c.postSub
else:
child.pre = c.preSub
child.post = c.postSub
@ -861,19 +861,17 @@ func generateCliHelpProc(cfg: CliCfg, printHelpName: NimNode): NimNode =
result = quote do:
proc `printHelpName`() =
echo bb(
render(
newHwylCliHelp(
header = `header`,
footer = `footer`,
usage = `usage`,
description = `description`,
subcmds = `subcmds`,
flags = `helpFlags`,
styles = `styles`,
)
let help =
newHwylCliHelp(
header = `header`,
footer = `footer`,
usage = `usage`,
description = `description`,
subcmds = `subcmds`,
flags = `helpFlags`,
styles = `styles`,
)
)
echo help.render().bb()
proc checkVal(p: OptParser) =
if p.val == "":
@ -1314,18 +1312,18 @@ func hwylCliImpl(cfg: CliCfg): NimNode =
let runProcName = ident("run" & name)
let runBody = nnkStmtList.newTree()
# move to proc?
if cfg.pre != nil:
runBody.add cfg.pre
if cfg.run != nil:
runBody.add cfg.run
if cfg.post != nil:
runBody.add cfg.post
# args and subcommands need to be mutually exclusive -> implement using a CommandKind?
if hasSubcommands cfg:
runBody.add genSubcommandHandler(cfg)
if cfg.run != nil:
runBody.add cfg.run
if cfg.post != nil:
runBody.add cfg.post
result = newTree(nnkStmtList)
result.add quote do:

View file

@ -0,0 +1,34 @@
import std/[strformat]
import hwylterm, hwylterm/hwylcli
hwylCli:
name "subcommands"
preSub:
echo "preSub from root!"
postSub:
echo "postSub from root!"
subcommands:
[a]
... "subcommand 'a'"
run:
echo "inside sub 'a'"
[b]
... "subcommand 'b'"
run:
echo "inside sub 'b'"
subcommands:
[a]
... "subcommand 'b a'"
run:
echo "inside sub 'b a'"
[c]
... "subcommand 'c'"
preSub:
echo "preSub from 'c'!"
run:
echo "inside sub c"
subcommands:
[a]
... "subcommand 'c a'"
run:
echo "inside sub 'c a'"

View file

@ -1,7 +1,8 @@
import std/[unittest]
import std/[os, unittest]
import ./lib
preCompileTestModules()
if commandLineParams().len == 0:
preCompileTestModules()
suite "hwylcli":
@ -68,3 +69,17 @@ flags:
output (output.txt)
-h --help
show this help""")
okWithArgs("subHooks", "a", """preSub from root!
inside sub 'a'
postSub from root!""")
okWithArgs("subHooks", "b a", """preSub from root!
inside sub 'b a'
postSub from root!
inside sub 'b'""")
okWithArgs("subHooks", "c a","""preSub from 'c'!
inside sub 'c a'
postSub from root!
inside sub c""")