aboutsummaryrefslogtreecommitdiffhomepage
path: root/command/parse.go
diff options
context:
space:
mode:
authorOphestra <cat@gensokyo.uk>2025-02-23 00:55:18 +0900
committerOphestra <cat@gensokyo.uk>2025-02-23 00:55:18 +0900
commit312753924be1109a22269ebde81fa244ef9b6379 (patch)
tree4d2d7e4f1b07f675eeac82dad55478714981a597 /command/parse.go
parent54308f79d206f89807aba3bc998fc770d01efed1 (diff)
command: root early handler func special case
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>
Diffstat (limited to 'command/parse.go')
-rw-r--r--command/parse.go14
1 files changed, 11 insertions, 3 deletions
diff --git a/command/parse.go b/command/parse.go
index 6081ca63..02120464 100644
--- a/command/parse.go
+++ b/command/parse.go
@@ -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()
}