aboutsummaryrefslogtreecommitdiffhomepage
path: root/command/builder.go
diff options
context:
space:
mode:
authorOphestra <cat@gensokyo.uk>2025-02-22 23:11:17 +0900
committerOphestra <cat@gensokyo.uk>2025-02-22 23:11:17 +0900
commitdfa3217037d8c24181be24484892ecb950a2a5ba (patch)
treee2022ad6ce2e11bbb7b4d0b38731a6c67561235f /command/builder.go
parent8000a2febb546b3b68eddd9330d5709281068e9f (diff)
command: implement builder and parser
Signed-off-by: Ophestra <cat@gensokyo.uk>
Diffstat (limited to 'command/builder.go')
-rw-r--r--command/builder.go58
1 files changed, 58 insertions, 0 deletions
diff --git a/command/builder.go b/command/builder.go
new file mode 100644
index 00000000..ae49c56e
--- /dev/null
+++ b/command/builder.go
@@ -0,0 +1,58 @@
+package command
+
+import (
+ "flag"
+ "fmt"
+ "io"
+)
+
+// New initialises a root Node.
+func New(output io.Writer, logf LogFunc, name string) Command {
+ return rootNode{newNode(output, logf, name, "")}
+}
+
+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 n.suffix.Len() > 0 {
+ _, _ = fmt.Fprintln(output, "Flags:")
+ n.set.PrintDefaults()
+ _, _ = fmt.Fprintln(output)
+ }
+ }
+
+ return n
+}
+
+func (n *node) Command(name, usage string, f HandlerFunc) 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 n
+}
+
+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
+}