command: root early handler func special case
All checks were successful
Test / Create distribution (push) Successful in 27s
Test / Run NixOS test (push) Successful in 3m27s

This allows for early initialisation with access to flags on the root node. This can be useful for configuring global state used by subcommands.

Signed-off-by: Ophestra <cat@gensokyo.uk>
This commit is contained in:
2025-02-23 00:55:18 +09:00
parent 54308f79d2
commit 312753924b
5 changed files with 55 additions and 18 deletions

View File

@@ -34,9 +34,6 @@ func (n *node) Parse(arguments []string) error {
match:
if n.child != nil {
if n.f != nil {
panic("invalid subcommand tree state")
}
// propagate help prefix early: flag set usage dereferences help
n.child.prefix = append(n.prefix, n.name)
}
@@ -50,6 +47,17 @@ match:
args := n.set.Args()
if n.child != nil {
if n.f != nil {
if n.usage != "" { // root node early special case
panic("invalid subcommand tree state")
}
// special case: root node calls HandlerFunc for initialisation
if err := n.f(nil); err != nil {
return err
}
}
if len(args) == 0 {
return n.writeHelp()
}