carlos / platform Public

clireg: node tree, walk and Validate (CLI registry step 1)

Adds internal/clireg: Node, Dispatch (spec A2/A6), Validate (A8),
Runnable and ID, stdlib only; no callers yet.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev fb0bba0d3601780fd06ee0f8197f0a0f36ec1888 parent 8c03ace
5 files changed, +841 −0
  • internal/clireg/clireg.go +192 −0
  • internal/clireg/dispatch.go +114 −0
  • internal/clireg/dispatch_test.go +316 −0
  • internal/clireg/validate.go +114 −0
  • internal/clireg/validate_test.go +105 −0

Intent

diff --git a/internal/clireg/clireg.go b/internal/clireg/clireg.go
new file mode 100644
index 000000000..55cab9500
--- /dev/null
+++ b/internal/clireg/clireg.go
@@ -0,0 +1,192 @@
+// Package clireg is the carlos CLI's command registry: a tree of nodes,
+// one per word the binary dispatches on, the walk that runs it
+// (Dispatch) and the checks that keep it well formed (Validate).
+//
+// Spec: docs/superpowers/specs/2026-11-09-cli-registry-design.md,
+// section A.
+package clireg
+
+import "strings"
+
+// On is a set of cases in which a branch's default runs.
+type On uint8
+
+const (
+ // OnAbsent: no argument follows the branch's word.
+ OnAbsent On = 1 << iota
+ // OnFlag: the next argument starts with "-".
+ OnFlag
+ // OnWord: the next argument is any other word that matched no child.
+ OnWord
+)
+
+// Audience says who a command is for.
+type Audience string
+
+// The audiences a node may declare.
+const (
+ Customer Audience = "customer"
+ Operator Audience = "operator"
+ BoxLocal Audience = "box-local"
+ Internal Audience = "internal"
+)
+
+// Golden says how the compatibility corpus treats a node.
+type Golden struct {
+ Skip string // non-empty: no corpus cases for this node; the reason
+ SkipBare string // non-empty: no bare case (daemons, prompts); the reason
+}
+
+// Node is one word in the command tree: a branch (Children, plus a
+// default or Fallback) or a leaf (Run), never both.
+type Node struct {
+ Name string
+ Aliases []string
+ Summary string // one line
+
+ Children []*Node
+ // Default names the child to run when no child matches and
+ // DefaultOn admits the case. "" when DefaultLeaf is set or there is
+ // no default.
+ Default string
+ // DefaultLeaf is an unnamed default leaf, reachable only as the
+ // default; its ID is the branch's ID.
+ DefaultLeaf *Node
+ // DefaultOn is the set of cases in which the default runs.
+ DefaultOn On
+ // Fallback runs when no child matches and no default applies. args
+ // are the remaining arguments; consumed is every word the walk
+ // dropped, transparent words included.
+ Fallback func(args, consumed []string)
+ // OnError handles a non-nil error from a leaf at or below this node.
+ // The nearest one on the path is called, with the leaf's canonical
+ // path.
+ OnError func(path []string, err error)
+
+ // Run is the leaf's handler.
+ Run func(inv *Invocation) error
+
+ // Transparent nodes are dropped once per branch level and matching
+ // continues at the same branch's children. They have no ID.
+ Transparent bool
+ // When, if set, must return true for the node's word to match.
+ When func() bool
+ // NoUpdateHint suppresses the update hint for any path through this
+ // node.
+ NoUpdateHint bool
+ Audience Audience
+ Golden Golden
+}
+
+// Invocation is what a leaf's Run receives.
+type Invocation struct {
+ Path []string // IDs' words as typed in canonical form (aliases resolved)
+ Raw []string // every argument after the last consumed word, unchanged
+}
+
+// RawArgs adapts a handler that takes its arguments unparsed. The
+// returned Run calls f(inv.Raw) and returns nil.
+func RawArgs(f func(args []string)) func(*Invocation) error {
+ return func(inv *Invocation) error {
+ f(inv.Raw)
+ return nil
+ }
+}
+
+// RawArgsErr is RawArgs for a handler that returns an error.
+func RawArgsErr(f func(args []string) error) func(*Invocation) error {
+ return func(inv *Invocation) error {
+ return f(inv.Raw)
+ }
+}
+
+// Entry is one runnable command: a leaf, or a branch's unnamed default.
+type Entry struct {
+ ID string
+ Node *Node
+ Default bool // Node is the branch's DefaultLeaf; ID is the branch's
+}
+
+// Runnable lists every leaf and every unnamed default under root, depth
+// first in declaration order. Transparent nodes and the root itself
+// produce no entry.
+func Runnable(root *Node) []Entry {
+ var out []Entry
+ var walk func(n *Node, words []string)
+ walk = func(n *Node, words []string) {
+ id := strings.Join(words, " ")
+ if n.DefaultLeaf != nil && len(words) > 0 {
+ out = append(out, Entry{ID: id, Node: n.DefaultLeaf, Default: true})
+ }
+ for _, c := range n.Children {
+ if c == nil || c.Transparent {
+ continue
+ }
+ w := append(append([]string(nil), words...), c.Name)
+ if c.isLeaf() && !c.isBranch() {
+ out = append(out, Entry{ID: strings.Join(w, " "), Node: c})
+ continue
+ }
+ walk(c, w)
+ }
+ }
+ walk(root, nil)
+ return out
+}
+
+// ID joins a path's words with single spaces. The root (path[0]),
+// transparent nodes and a branch's unnamed default leaf add no word.
+func ID(path []*Node) string {
+ var words []string
+ for i, n := range path {
+ if i == 0 || n.Transparent || path[i-1].DefaultLeaf == n {
+ continue
+ }
+ words = append(words, n.Name)
+ }
+ return strings.Join(words, " ")
+}
+
+func (n *Node) isLeaf() bool { return n.Run != nil }
+
+func (n *Node) isBranch() bool {
+ return len(n.Children) > 0 || n.DefaultLeaf != nil || n.Default != ""
+}
+
+// matches reports whether word selects n: its name or an alias, with
+// When nil or true.
+func (n *Node) matches(word string) bool {
+ if n.When != nil && !n.When() {
+ return false
+ }
+ if n.Name == word {
+ return true
+ }
+ for _, a := range n.Aliases {
+ if a == word {
+ return true
+ }
+ }
+ return false
+}
+
+// admits reports whether DefaultOn covers the case args present.
+func (n *Node) admits(args []string) bool {
+ switch {
+ case len(args) == 0:
+ return n.DefaultOn&OnAbsent != 0
+ case strings.HasPrefix(args[0], "-"):
+ return n.DefaultOn&OnFlag != 0
+ default:
+ return n.DefaultOn&OnWord != 0
+ }
+}
+
+func (n *Node) child(name string) *Node {
+ for _, c := range n.Children {
+ if c != nil && !c.Transparent && c.Name == name {
+ return c
+ }
+ }
+ return nil
+}
diff --git a/internal/clireg/dispatch.go b/internal/clireg/dispatch.go
new file mode 100644
index 000000000..850c1ed29
--- /dev/null
+++ b/internal/clireg/dispatch.go
@@ -0,0 +1,114 @@
+package clireg
+
+import "fmt"
+
+// Dispatch walks root by args and runs what it reaches: a leaf, a
+// branch's default, or a branch's Fallback. It returns the path it ran,
+// root first; transparent nodes are not on it, and an unnamed default
+// leaf is (ID skips it).
+//
+// At a branch, args[0] is matched against non-transparent children (name,
+// then aliases, When nil or true), then against transparent children not
+// yet dropped at this level. A transparent word is dropped and matching
+// continues at the same branch. With no match, the default runs if
+// DefaultOn admits the case, with every remaining argument unchanged;
+// otherwise Fallback(args, consumed) runs.
+//
+// A leaf's Run gets the remaining arguments unchanged. If it returns an
+// error, the nearest OnError on the path (leaf first) handles it; with
+// none, Dispatch panics.
+func Dispatch(root *Node, args []string) []*Node {
+ path := []*Node{root}
+ var words, consumed []string
+ n := root
+ dropped := map[*Node]bool{} // transparent children dropped at n
+ for {
+ if n.isLeaf() && !n.isBranch() {
+ runLeaf(path, words, args)
+ return path
+ }
+ if len(args) > 0 {
+ if c := matchChild(n, args[0], false, nil); c != nil {
+ path = append(path, c)
+ words = append(words, c.Name)
+ consumed = append(consumed, c.Name)
+ args = args[1:]
+ n = c
+ dropped = map[*Node]bool{}
+ continue
+ }
+ if c := matchChild(n, args[0], true, dropped); c != nil {
+ dropped[c] = true
+ consumed = append(consumed, c.Name)
+ args = args[1:]
+ continue
+ }
+ }
+ if (n.DefaultLeaf != nil || n.Default != "") && n.admits(args) {
+ if n.DefaultLeaf != nil {
+ path = append(path, n.DefaultLeaf)
+ runLeaf(path, words, args)
+ return path
+ }
+ c := n.child(n.Default)
+ if c == nil {
+ panic(fmt.Sprintf("clireg: %s: Default %q names no child", idOrRoot(path), n.Default))
+ }
+ path = append(path, c)
+ runLeaf(path, append(words, c.Name), args)
+ return path
+ }
+ if n.Fallback == nil {
+ panic(fmt.Sprintf("clireg: %s: no child, default or Fallback for %q", idOrRoot(path), args))
+ }
+ n.Fallback(args, append([]string{}, consumed...))
+ return path
+ }
+}
+
+// matchChild finds n's child selected by word among transparent or
+// non-transparent children, skipping those in skip.
+func matchChild(n *Node, word string, transparent bool, skip map[*Node]bool) *Node {
+ for _, c := range n.Children {
+ if c == nil || c.Transparent != transparent || skip[c] {
+ continue
+ }
+ if c.matches(word) {
+ return c
+ }
+ }
+ return nil
+}
+
+// runLeaf runs the last node on path with args, routing an error to the
+// nearest OnError.
+func runLeaf(path []*Node, words, args []string) {
+ leaf := path[len(path)-1]
+ if leaf.Run == nil || leaf.isBranch() {
+ panic(fmt.Sprintf("clireg: %s: not a leaf", idOrRoot(path)))
+ }
+ if words == nil {
+ words = []string{}
+ }
+ if args == nil {
+ args = []string{}
+ }
+ err := leaf.Run(&Invocation{Path: words, Raw: args})
+ if err == nil {
+ return
+ }
+ for i := len(path) - 1; i >= 0; i-- {
+ if h := path[i].OnError; h != nil {
+ h(append([]string{}, words...), err)
+ return
+ }
+ }
+ panic(fmt.Sprintf("clireg: %s returned an error and no OnError handles it: %v", idOrRoot(path), err))
+}
+
+func idOrRoot(path []*Node) string {
+ if id := ID(path); id != "" {
+ return id
+ }
+ return "<root>"
+}
diff --git a/internal/clireg/dispatch_test.go b/internal/clireg/dispatch_test.go
new file mode 100644
index 000000000..b29650301
--- /dev/null
+++ b/internal/clireg/dispatch_test.go
@@ -0,0 +1,316 @@
+package clireg
+
+import (
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+)
+
+// record is what the fixture tree saw for one Dispatch call.
+type record struct {
+ leaf string // leaf ID reached, "" if a fallback ran
+ raw []string // the leaf's inv.Raw
+ path []string // the leaf's inv.Path
+ fallback string // ID of the branch whose Fallback ran
+ args []string // the fallback's args
+ consumed []string // the fallback's consumed
+}
+
+// fixture builds the walk test tree. hostOn drives ops host's When.
+func fixture(rec *record, hostOn *bool) *Node {
+ leaf := func(name string, aliases ...string) *Node {
+ return &Node{
+ Name: name,
+ Aliases: aliases,
+ Audience: Customer,
+ Run: func(inv *Invocation) error {
+ rec.leaf = strings.Join(inv.Path, " ")
+ rec.raw = inv.Raw
+ rec.path = inv.Path
+ return nil
+ },
+ }
+ }
+ fallback := func(id string) func(args, consumed []string) {
+ return func(args, consumed []string) {
+ rec.fallback = id
+ rec.args = args
+ rec.consumed = consumed
+ }
+ }
+ all := OnAbsent | OnFlag | OnWord
+ return &Node{
+ Name: "carlos",
+ Fallback: fallback("<root>"),
+ Children: []*Node{
+ {
+ Name: "apps",
+ Children: []*Node{leaf("set"), leaf("list", "ls")},
+ Fallback: fallback("apps"),
+ },
+ {
+ Name: "instances",
+ Children: []*Node{leaf("create")},
+ DefaultLeaf: leaf(""),
+ DefaultOn: all,
+ },
+ {
+ Name: "canary",
+ Children: []*Node{leaf("deploy"), leaf("ls", "list")},
+ Default: "deploy",
+ DefaultOn: all,
+ },
+ {
+ Name: "config",
+ Fallback: fallback("config"),
+ Children: []*Node{{
+ Name: "destinations",
+ Children: []*Node{leaf("add"), leaf("list")},
+ Default: "list",
+ DefaultOn: OnAbsent | OnFlag,
+ Fallback: fallback("config destinations"),
+ }},
+ },
+ {
+ Name: "system",
+ Children: []*Node{
+ {Name: "router", Transparent: true},
+ leaf("update"),
+ },
+ Fallback: fallback("system"),
+ },
+ {
+ Name: "ops",
+ Children: []*Node{
+ func() *Node {
+ n := leaf("host")
+ n.When = func() bool { return *hostOn }
+ return n
+ }(),
+ leaf("litestream"),
+ },
+ Fallback: fallback("ops"),
+ },
+ },
+ }
+}
+
+func TestDispatchWalk(t *testing.T) {
+ tests := []struct {
+ args []string
+ hostOn bool
+ want record
+ ran string // ID(Dispatch(...))
+ }{
+ {args: []string{"apps", "set", "x", "--y"},
+ want: record{leaf: "apps set", raw: []string{"x", "--y"}, path: []string{"apps", "set"}}, ran: "apps set"},
+ {args: []string{"apps", "ls", "-a", "b"},
+ want: record{leaf: "apps list", raw: []string{"-a", "b"}, path: []string{"apps", "list"}}, ran: "apps list"},
+ {args: []string{"instances"},
+ want: record{leaf: "instances", raw: []string{}, path: []string{"instances"}}, ran: "instances"},
+ {args: []string{"instances", "--x"},
+ want: record{leaf: "instances", raw: []string{"--x"}, path: []string{"instances"}}, ran: "instances"},
+ {args: []string{"instances", "foo", "bar"},
+ want: record{leaf: "instances", raw: []string{"foo", "bar"}, path: []string{"instances"}}, ran: "instances"},
+ {args: []string{"instances", "create", "a"},
+ want: record{leaf: "instances create", raw: []string{"a"}, path: []string{"instances", "create"}}, ran: "instances create"},
+ {args: []string{"canary", "./site"},
+ want: record{leaf: "canary deploy", raw: []string{"./site"}, path: []string{"canary", "deploy"}}, ran: "canary deploy"},
+ {args: []string{"canary"},
+ want: record{leaf: "canary deploy", raw: []string{}, path: []string{"canary", "deploy"}}, ran: "canary deploy"},
+ {args: []string{"canary", "list"},
+ want: record{leaf: "canary ls", raw: []string{}, path: []string{"canary", "ls"}}, ran: "canary ls"},
+ {args: []string{"config", "destinations", "zzz"},
+ want: record{fallback: "config destinations", args: []string{"zzz"}, consumed: []string{"config", "destinations"}}, ran: "config destinations"},
+ {args: []string{"config", "destinations", "--global"},
+ want: record{leaf: "config destinations list", raw: []string{"--global"}, path: []string{"config", "destinations", "list"}}, ran: "config destinations list"},
+ {args: []string{"config", "destinations"},
+ want: record{leaf: "config destinations list", raw: []string{}, path: []string{"config", "destinations", "list"}}, ran: "config destinations list"},
+ {args: []string{"system", "router", "update", "-y"},
+ want: record{leaf: "system update", raw: []string{"-y"}, path: []string{"system", "update"}}, ran: "system update"},
+ {args: []string{"system", "router"},
+ want: record{fallback: "system", args: []string{}, consumed: []string{"system", "router"}}, ran: "system"},
+ {args: []string{"system", "router", "router"},
+ want: record{fallback: "system", args: []string{"router"}, consumed: []string{"system", "router"}}, ran: "system"},
+ {args: []string{"system", "router", "nope"},
+ want: record{fallback: "system", args: []string{"nope"}, consumed: []string{"system", "router"}}, ran: "system"},
+ {args: []string{"system"},
+ want: record{fallback: "system", args: []string{}, consumed: []string{"system"}}, ran: "system"},
+ {args: []string{"ops", "host", "resolve"}, hostOn: false,
+ want: record{fallback: "ops", args: []string{"host", "resolve"}, consumed: []string{"ops"}}, ran: "ops"},
+ {args: []string{"ops", "host", "resolve"}, hostOn: true,
+ want: record{leaf: "ops host", raw: []string{"resolve"}, path: []string{"ops", "host"}}, ran: "ops host"},
+ {args: []string{"apps", "zz"},
+ want: record{fallback: "apps", args: []string{"zz"}, consumed: []string{"apps"}}, ran: "apps"},
+ {args: []string{"nope"},
+ want: record{fallback: "<root>", args: []string{"nope"}, consumed: []string{}}, ran: ""},
+ }
+ for _, tc := range tests {
+ t.Run(strings.Join(tc.args, "_"), func(t *testing.T) {
+ var got record
+ hostOn := tc.hostOn
+ root := fixture(&got, &hostOn)
+ ran := Dispatch(root, tc.args)
+ if !equalRecord(got, tc.want) {
+ t.Errorf("Dispatch(%q):\n got %+v\nwant %+v", tc.args, got, tc.want)
+ }
+ if ran[0] != root {
+ t.Errorf("Dispatch(%q) path does not start at the root", tc.args)
+ }
+ if id := ID(ran); id != tc.ran {
+ t.Errorf("ID(Dispatch(%q)) = %q, want %q", tc.args, id, tc.ran)
+ }
+ })
+ }
+}
+
+// equalRecord compares records treating nil and empty slices alike.
+func equalRecord(a, b record) bool {
+ norm := func(s []string) []string {
+ if s == nil {
+ return []string{}
+ }
+ return s
+ }
+ return a.leaf == b.leaf && a.fallback == b.fallback &&
+ reflect.DeepEqual(norm(a.raw), norm(b.raw)) &&
+ reflect.DeepEqual(norm(a.path), norm(b.path)) &&
+ reflect.DeepEqual(norm(a.args), norm(b.args)) &&
+ reflect.DeepEqual(norm(a.consumed), norm(b.consumed))
+}
+
+func TestDispatchRawIsUnchanged(t *testing.T) {
+ var got record
+ off := false
+ args := []string{"apps", "set", "x", "--y"}
+ Dispatch(fixture(&got, &off), args)
+ if !reflect.DeepEqual(args, []string{"apps", "set", "x", "--y"}) {
+ t.Fatalf("Dispatch changed its args: %q", args)
+ }
+}
+
+type errCall struct {
+ who string
+ path []string
+ err error
+}
+
+func TestDispatchOnError(t *testing.T) {
+ boom := errors.New("e")
+ var calls []errCall
+ onError := func(who string) func([]string, error) {
+ return func(path []string, err error) {
+ calls = append(calls, errCall{who, path, err})
+ }
+ }
+ failing := func(name string) *Node {
+ return &Node{Name: name, Audience: Customer, Run: func(*Invocation) error { return boom }}
+ }
+ ok := &Node{Name: "ok", Audience: Customer, Run: func(*Invocation) error { return nil }}
+ root := &Node{
+ Name: "carlos",
+ Children: []*Node{
+ {
+ Name: "auth",
+ OnError: onError("auth"),
+ Children: []*Node{failing("login"), ok},
+ Fallback: func(_, _ []string) {},
+ },
+ {
+ Name: "billing",
+ OnError: onError("billing"),
+ Children: []*Node{{
+ Name: "plans",
+ OnError: onError("billing plans"),
+ Children: []*Node{failing("set")},
+ Fallback: func(_, _ []string) {},
+ }, {
+ Name: "other",
+ Children: []*Node{failing("get")},
+ Fallback: func(_, _ []string) {},
+ }},
+ Fallback: func(_, _ []string) {},
+ },
+ },
+ Fallback: func(_, _ []string) {},
+ }
+
+ check := func(args []string, want []errCall) {
+ t.Helper()
+ calls = nil
+ Dispatch(root, args)
+ if !reflect.DeepEqual(calls, want) {
+ t.Errorf("Dispatch(%q) OnError calls = %+v, want %+v", args, calls, want)
+ }
+ }
+ check([]string{"auth", "login", "-x"}, []errCall{{"auth", []string{"auth", "login"}, boom}})
+ check([]string{"auth", "ok"}, nil)
+ check([]string{"billing", "plans", "set"}, []errCall{{"billing plans", []string{"billing", "plans", "set"}, boom}})
+ check([]string{"billing", "other", "get"}, []errCall{{"billing", []string{"billing", "other", "get"}, boom}})
+}
+
+func TestDispatchErrorWithoutOnErrorPanics(t *testing.T) {
+ root := &Node{
+ Name: "carlos",
+ Fallback: func(_, _ []string) {},
+ Children: []*Node{{
+ Name: "auth",
+ Fallback: func(_, _ []string) {},
+ Children: []*Node{{Name: "login", Audience: Customer, Run: func(*Invocation) error { return errors.New("e") }}},
+ }},
+ }
+ defer func() {
+ r := recover()
+ if r == nil {
+ t.Fatal("Dispatch did not panic")
+ }
+ if msg, _ := r.(string); !strings.Contains(msg, "auth login") {
+ t.Fatalf("panic %v does not name the ID", r)
+ }
+ }()
+ Dispatch(root, []string{"auth", "login"})
+}
+
+func TestRawArgs(t *testing.T) {
+ var seen []string
+ run := RawArgs(func(args []string) { seen = args })
+ if err := run(&Invocation{Path: []string{"a"}, Raw: []string{"x", "-y"}}); err != nil {
+ t.Fatalf("RawArgs run returned %v", err)
+ }
+ if !reflect.DeepEqual(seen, []string{"x", "-y"}) {
+ t.Fatalf("RawArgs passed %q", seen)
+ }
+ boom := errors.New("boom")
+ runErr := RawArgsErr(func(args []string) error { seen = args; return boom })
+ if err := runErr(&Invocation{Raw: []string{"z"}}); err != boom {
+ t.Fatalf("RawArgsErr returned %v, want %v", err, boom)
+ }
+ if !reflect.DeepEqual(seen, []string{"z"}) {
+ t.Fatalf("RawArgsErr passed %q", seen)
+ }
+}
+
+func TestRunnable(t *testing.T) {
+ var rec record
+ off := false
+ var got []string
+ for _, e := range Runnable(fixture(&rec, &off)) {
+ s := e.ID
+ if e.Default {
+ s += " (default)"
+ }
+ got = append(got, s)
+ }
+ want := []string{
+ "apps set", "apps list",
+ "instances (default)", "instances create",
+ "canary deploy", "canary ls",
+ "config destinations add", "config destinations list",
+ "system update",
+ "ops host", "ops litestream",
+ }
+ if !reflect.DeepEqual(got, want) {
+ t.Fatalf("Runnable IDs:\n got %q\nwant %q", got, want)
+ }
+}
diff --git a/internal/clireg/validate.go b/internal/clireg/validate.go
new file mode 100644
index 000000000..fbf3c0af8
--- /dev/null
+++ b/internal/clireg/validate.go
@@ -0,0 +1,114 @@
+package clireg
+
+import (
+ "fmt"
+ "strings"
+)
+
+// Validate checks the tree under root against the registry's rules
+// (spec A8) and returns every violation. Each error starts with the
+// node's ID, or "<root>" for the root. It runs in tests, never at
+// dispatch.
+func Validate(root *Node) []error {
+ v := &validator{}
+ v.node(root, "", true)
+ return v.errs
+}
+
+type validator struct{ errs []error }
+
+func (v *validator) fail(id, format string, a ...any) {
+ if id == "" {
+ id = "<root>"
+ }
+ v.errs = append(v.errs, fmt.Errorf("%s: %s", id, fmt.Sprintf(format, a...)))
+}
+
+func (v *validator) node(n *Node, id string, isRoot bool) {
+ if n.Transparent {
+ if len(n.Children) > 0 || n.Run != nil || n.Default != "" || n.DefaultLeaf != nil {
+ v.fail(id, "a transparent node has no children, Run or default")
+ }
+ return
+ }
+ if !isRoot && n.Audience == Internal && !strings.HasPrefix(n.Name, "__") {
+ v.fail(id, "audience %q on a word without the __ prefix", Internal)
+ }
+ switch {
+ case n.isLeaf() && n.isBranch():
+ v.fail(id, "both a branch and a leaf (Run set with children or a default)")
+ return
+ case !n.isLeaf() && !n.isBranch():
+ v.fail(id, "neither a branch nor a leaf (no Run, no children)")
+ return
+ case n.isLeaf():
+ if n.Audience == "" {
+ v.fail(id, "a leaf with no Audience")
+ }
+ return
+ }
+ v.branch(n, id)
+}
+
+func (v *validator) branch(n *Node, id string) {
+ hasDefault := n.Default != "" || n.DefaultLeaf != nil
+ if n.Default != "" && n.DefaultLeaf != nil {
+ v.fail(id, "Default %q and DefaultLeaf both set", n.Default)
+ }
+ if n.Default != "" {
+ switch c := n.child(n.Default); {
+ case c == nil:
+ v.fail(id, "Default %q names no child", n.Default)
+ case !c.isLeaf() || c.isBranch():
+ v.fail(id, "Default %q names a child that is not a leaf", n.Default)
+ }
+ }
+ if hasDefault && n.DefaultOn == 0 {
+ v.fail(id, "a default with an empty DefaultOn")
+ }
+ if n.Fallback == nil {
+ all := OnAbsent | OnFlag | OnWord
+ switch {
+ case !hasDefault:
+ v.fail(id, "a branch with neither a default nor a Fallback")
+ case n.DefaultOn&all != all:
+ v.fail(id, "no Fallback for the cases DefaultOn does not admit")
+ }
+ }
+ if d := n.DefaultLeaf; d != nil {
+ switch {
+ case d.Transparent || d.Run == nil || d.isBranch():
+ v.fail(id, "DefaultLeaf is not a leaf")
+ case d.Audience == "":
+ v.fail(id, "a default leaf with no Audience")
+ }
+ if d.Audience == Internal && !strings.HasPrefix(n.Name, "__") {
+ v.fail(id, "audience %q on a word without the __ prefix", Internal)
+ }
+ }
+
+ seen := map[string]string{} // word -> sibling name that claimed it
+ for i, c := range n.Children {
+ if c == nil {
+ v.fail(id, "child %d is nil", i)
+ continue
+ }
+ cid := strings.TrimSpace(id + " " + c.Name)
+ if c.Name == "" {
+ v.fail(cid, "a child with no Name")
+ }
+ own := map[string]bool{}
+ for _, w := range append([]string{c.Name}, c.Aliases...) {
+ if w == "" || own[w] {
+ continue
+ }
+ own[w] = true
+ if prev, ok := seen[w]; ok {
+ v.fail(cid, "word %q already used by sibling %q", w, prev)
+ continue
+ }
+ seen[w] = c.Name
+ }
+ v.node(c, cid, false)
+ }
+}
diff --git a/internal/clireg/validate_test.go b/internal/clireg/validate_test.go
new file mode 100644
index 000000000..4ab12ace7
--- /dev/null
+++ b/internal/clireg/validate_test.go
@@ -0,0 +1,105 @@
+package clireg
+
+import (
+ "strings"
+ "testing"
+)
+
+func TestValidate(t *testing.T) {
+ run := func(*Invocation) error { return nil }
+ fb := func(_, _ []string) {}
+ leaf := func(name string, aliases ...string) *Node {
+ return &Node{Name: name, Aliases: aliases, Run: run, Audience: Customer}
+ }
+ // under wraps n as the only child of a root with a fallback.
+ under := func(n ...*Node) *Node {
+ return &Node{Name: "carlos", Children: n, Fallback: fb}
+ }
+
+ tests := []struct {
+ name string
+ root *Node
+ want string // a substring every error must contain; the ID comes first
+ }{
+ {"branch with Run", under(&Node{Name: "apps", Children: []*Node{leaf("set")}, Fallback: fb, Run: run}),
+ "apps: "},
+ {"neither branch nor leaf", under(&Node{Name: "apps", Audience: Customer}),
+ "apps: "},
+ {"duplicate name", under(&Node{Name: "apps", Children: []*Node{leaf("set"), leaf("set")}, Fallback: fb}),
+ "apps set: "},
+ {"alias equals a sibling's name", under(&Node{Name: "apps", Children: []*Node{leaf("set"), leaf("list", "set")}, Fallback: fb}),
+ "apps list: "},
+ {"duplicate alias", under(&Node{Name: "apps", Children: []*Node{leaf("set", "s"), leaf("list", "s")}, Fallback: fb}),
+ "apps list: "},
+ {"duplicate with a transparent sibling", under(&Node{Name: "system", Children: []*Node{{Name: "router", Transparent: true}, leaf("update", "router")}, Fallback: fb}),
+ "system update: "},
+ {"Default naming no child", under(&Node{Name: "canary", Children: []*Node{leaf("deploy")}, Default: "deplo", DefaultOn: OnWord, Fallback: fb}),
+ "canary: "},
+ {"Default with empty DefaultOn", under(&Node{Name: "canary", Children: []*Node{leaf("deploy")}, Default: "deploy", Fallback: fb}),
+ "canary: "},
+ {"DefaultLeaf with empty DefaultOn", under(&Node{Name: "instances", Children: []*Node{leaf("create")}, DefaultLeaf: leaf(""), Fallback: fb}),
+ "instances: "},
+ {"DefaultLeaf and Default both set", under(&Node{Name: "canary", Children: []*Node{leaf("deploy")}, Default: "deploy", DefaultLeaf: leaf(""), DefaultOn: OnAbsent | OnFlag | OnWord}),
+ "canary: "},
+ {"branch with no default and no Fallback", under(&Node{Name: "apps", Children: []*Node{leaf("set")}}),
+ "apps: "},
+ {"partial default and no Fallback", under(&Node{Name: "config", Children: []*Node{leaf("list")}, Default: "list", DefaultOn: OnAbsent | OnFlag}),
+ "config: "},
+ {"internal audience on a plain word", under(&Node{Name: "snapshot", Run: run, Audience: Internal}),
+ "snapshot: "},
+ {"empty audience on a leaf", under(&Node{Name: "apps", Children: []*Node{{Name: "set", Run: run}}, Fallback: fb}),
+ "apps set: "},
+ {"empty audience on a default leaf", under(&Node{Name: "instances", Children: []*Node{leaf("create")}, DefaultLeaf: &Node{Run: run}, DefaultOn: OnAbsent | OnFlag | OnWord}),
+ "instances: "},
+ {"transparent with children", under(&Node{Name: "system", Children: []*Node{{Name: "router", Transparent: true, Children: []*Node{leaf("x")}}, leaf("update")}, Fallback: fb}),
+ "system router: "},
+ {"transparent with Run", under(&Node{Name: "system", Children: []*Node{{Name: "router", Transparent: true, Run: run}, leaf("update")}, Fallback: fb}),
+ "system router: "},
+ {"root with no fallback", &Node{Name: "carlos", Children: []*Node{leaf("x")}},
+ "<root>: "},
+ }
+ for _, tc := range tests {
+ t.Run(tc.name, func(t *testing.T) {
+ errs := Validate(tc.root)
+ if len(errs) == 0 {
+ t.Fatalf("Validate returned no errors, want one naming %q", tc.want)
+ }
+ found := false
+ for _, err := range errs {
+ if strings.HasPrefix(err.Error(), tc.want) {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("Validate errors %q: none starts with %q", errs, tc.want)
+ }
+ })
+ }
+}
+
+func TestValidateInternalWord(t *testing.T) {
+ root := &Node{Name: "carlos", Fallback: func(_, _ []string) {}, Children: []*Node{
+ {Name: "__demo-snapshot", Run: func(*Invocation) error { return nil }, Audience: Internal},
+ }}
+ if errs := Validate(root); len(errs) != 0 {
+ t.Fatalf("Validate(__ internal leaf) = %q, want none", errs)
+ }
+}
+
+func TestValidateWalkFixture(t *testing.T) {
+ var rec record
+ off := false
+ if errs := Validate(fixture(&rec, &off)); len(errs) != 0 {
+ t.Fatalf("Validate(walk fixture) = %q, want none", errs)
+ }
+}
+
+func TestValidateReportsEveryError(t *testing.T) {
+ root := &Node{Name: "carlos", Fallback: func(_, _ []string) {}, Children: []*Node{
+ {Name: "a"},
+ {Name: "b"},
+ }}
+ if errs := Validate(root); len(errs) != 2 {
+ t.Fatalf("Validate = %q, want two errors", errs)
+ }
+}