aboutsummaryrefslogtreecommitdiffhomepage
path: root/command/builder.go
blob: 174010ea388d22ef67b9de3b9e9c7135048f8232 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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
}