Test / Create distribution (push) Successful in 53s
Test / Sandbox (push) Successful in 2m51s
Test / Hakurei (push) Successful in 4m29s
Test / Sandbox (race detector) (push) Successful in 5m53s
Test / Hakurei (race detector) (push) Successful in 7m2s
Test / ShareFS (push) Successful in 7m19s
Test / Flake checks (push) Successful in 1m8s
This greatly improves readability when lots of flags are registered. Signed-off-by: Ophestra <cat@gensokyo.uk>
67 lines
1.4 KiB
Go
67 lines
1.4 KiB
Go
package command
|
|
|
|
import (
|
|
"flag"
|
|
"fmt"
|
|
"io"
|
|
)
|
|
|
|
// New initialises a root Node.
|
|
func New(output io.Writer, logf LogFunc, name string, early HandlerFunc) Command {
|
|
c := rootNode{newNode(output, logf, name, "")}
|
|
c.f = early
|
|
return c
|
|
}
|
|
|
|
// newNode initialises a subcommand tree and returns its address.
|
|
func newNode(output io.Writer, logf LogFunc, name, usage string) *node {
|
|
n := &node{
|
|
name: name, usage: usage,
|
|
out: output, logf: logf,
|
|
set: flag.NewFlagSet(name, flag.ContinueOnError),
|
|
}
|
|
n.set.SetOutput(output)
|
|
n.set.Usage = func() {
|
|
_ = n.writeHelp()
|
|
if len(n.suffix) > 0 {
|
|
_, _ = fmt.Fprintln(output, "flags:")
|
|
n.set.PrintDefaults()
|
|
_, _ = fmt.Fprintln(output)
|
|
}
|
|
}
|
|
|
|
return n
|
|
}
|
|
|
|
func (n *node) Command(name, usage string, f HandlerFunc) Node {
|
|
n.NewCommand(name, usage, f)
|
|
return n
|
|
}
|
|
|
|
func (n *node) NewCommand(name, usage string, f HandlerFunc) Flag[Node] {
|
|
if f == nil {
|
|
panic("invalid handler")
|
|
}
|
|
if name == "" || usage == "" {
|
|
panic("invalid subcommand")
|
|
}
|
|
|
|
s := newNode(n.out, n.logf, name, usage)
|
|
s.f = f
|
|
if !n.adopt(s) {
|
|
panic("attempted to initialise subcommand with non-unique name")
|
|
}
|
|
return s
|
|
}
|
|
|
|
func (n *node) New(name, usage string) Node {
|
|
if name == "" || usage == "" {
|
|
panic("invalid subcommand tree")
|
|
}
|
|
s := newNode(n.out, n.logf, name, usage)
|
|
if !n.adopt(s) {
|
|
panic("attempted to initialise subcommand tree with non-unique name")
|
|
}
|
|
return s
|
|
}
|