Index backend commands for path lookup

This commit is contained in:
2026-10-09 01:28:19 +00:00
parent 628dc78083
commit ae656d8fa9
3 changed files with 101 additions and 40 deletions

View File

@@ -2,6 +2,7 @@ package cobra
import (
"context"
"fmt"
"io"
"reflect"
"strings"
@@ -130,3 +131,51 @@ func TestParseReturnsNeutralFailuresAndFreshState(t *testing.T) {
t.Fatalf("unknown flag failure = %#v", failed.Failure)
}
}
func TestSelectedPathsResolveThroughBackendParents(t *testing.T) {
root := &Command{Name: "app"}
for index := 0; index < 128; index++ {
root.Children = append(root.Children, &Command{Name: fmt.Sprintf("wide%03d", index), Runnable: true})
}
path := make([]string, 24)
current := root
for index := range path {
path[index] = fmt.Sprintf("deep%02d", index)
child := &Command{Name: path[index]}
if index == len(path)-1 {
child.Runnable = true
}
current.Children = append(current.Children, child)
current = child
}
result := Parse(root, path, ParseOptions{})
if result.Failure != nil || !reflect.DeepEqual(result.Path, path) {
t.Fatalf("deep parse path = %#v", result)
}
rootResult := Parse(root, nil, ParseOptions{})
if rootResult.Failure != nil || len(rootResult.Path) != 0 {
t.Fatalf("root parse path = %#v", rootResult)
}
help, failure := RenderHelp(root, path)
if failure != nil || !strings.Contains(help, path[len(path)-1]) {
t.Fatalf("deep help = %q, %v", help, failure)
}
if _, failure := RenderHelp(root, []string{"wide128"}); failure == nil {
t.Fatal("help accepted an unknown sibling")
}
line, failure := UsageLine(root, path)
if failure != nil || !strings.Contains(line, path[len(path)-1]) {
t.Fatalf("deep usage line = %q, %v", line, failure)
}
if _, failure := UsageLine(root, []string{"wide128"}); failure == nil {
t.Fatal("usage accepted an unknown sibling")
}
if _, failure := RenderHelp(root, nil); failure != nil {
t.Fatalf("root help failed: %v", failure)
}
if _, failure := UsageLine(root, nil); failure != nil {
t.Fatalf("root usage failed: %v", failure)
}
}