Test / Create distribution (push) Successful in 52s
Test / Sandbox (push) Successful in 2m51s
Test / Hakurei (push) Successful in 4m44s
Test / Sandbox (race detector) (push) Successful in 5m46s
Test / Hakurei (race detector) (push) Successful in 7m5s
Test / ShareFS (push) Successful in 7m5s
Test / Flake checks (push) Successful in 1m8s
This change also improves documentation. Signed-off-by: Ophestra <cat@gensokyo.uk>
76 lines
2.1 KiB
Go
76 lines
2.1 KiB
Go
// Package command implements generic nested command parsing.
|
|
package command
|
|
|
|
import (
|
|
"flag"
|
|
"strings"
|
|
)
|
|
|
|
// UsageInternal is a special usage string that hides the command from the
|
|
// generated help message.
|
|
const UsageInternal = "\x00"
|
|
|
|
type (
|
|
// HandlerFunc is called when matching a directly handled subcommand tree.
|
|
HandlerFunc = func(args []string) error
|
|
|
|
// LogFunc is the function signature of a printf function. The zero value
|
|
// implies [log.Printf].
|
|
LogFunc = func(format string, a ...any)
|
|
|
|
// FlagDefiner is a deferred flag definer value, usually encapsulating the
|
|
// default value.
|
|
FlagDefiner interface {
|
|
// Define defines the flag in set.
|
|
Define(b *strings.Builder, set *flag.FlagSet, p any, name, usage string)
|
|
}
|
|
|
|
// A Flag is satisfied by command objects capable of receiving flags.
|
|
Flag[T any] interface {
|
|
// Flag defines a generic flag type in Node's flag set.
|
|
Flag(p any, name string, value FlagDefiner, usage string) T
|
|
}
|
|
|
|
// A Command is the root of a command tree.
|
|
Command interface {
|
|
Parse(arguments []string) error
|
|
|
|
// MustParse determines exit outcomes for Parse errors and calls
|
|
// handleError if [HandlerFunc] returns a non-nil error.
|
|
MustParse(arguments []string, handleError func(error))
|
|
|
|
baseNode[Command]
|
|
}
|
|
|
|
// A Node is a subcommand under a [Command].
|
|
Node baseNode[Node]
|
|
|
|
baseNode[T any] interface {
|
|
// Command appends a subcommand with direct command handling.
|
|
Command(name, usage string, f HandlerFunc) T
|
|
|
|
// New returns a new subcommand tree.
|
|
New(name, usage string) (sub Node)
|
|
// NewCommand returns a new subcommand with direct command handling.
|
|
NewCommand(name, usage string, f HandlerFunc) (sub Flag[Node])
|
|
|
|
// PrintHelp prints a help message to the configured writer.
|
|
PrintHelp()
|
|
|
|
Flag[T]
|
|
}
|
|
)
|
|
|
|
// rootNode satisfies baseNode for [Command].
|
|
type rootNode struct{ *node }
|
|
|
|
func (r rootNode) Command(name, usage string, f HandlerFunc) Command {
|
|
r.node.Command(name, usage, f)
|
|
return r
|
|
}
|
|
|
|
func (r rootNode) Flag(p any, name string, value FlagDefiner, usage string) Command {
|
|
r.node.Flag(p, name, value, usage)
|
|
return r
|
|
}
|