turn --show-command-tree into sub command, hide hidden commands (#56)

This commit is contained in:
T. von Dein
2026-06-29 08:38:03 +02:00
parent 34bf4fbed9
commit 81987b75f2
2 changed files with 57 additions and 30 deletions

View File

@@ -42,7 +42,6 @@ func Finish(err error) int {
func Main() int {
conf := cfg.NewConfig()
tree := false
cmd := &cli.Command{
Name: "esctl",
@@ -64,13 +63,6 @@ func Main() int {
Usage: "enable HTTP debugging",
Destination: &conf.DebugHTTP,
},
&cli.BoolFlag{
Name: "show-command-tree",
Value: false,
Usage: "generate a command tree",
Destination: &tree,
Hidden: true,
},
&cli.BoolFlag{
Name: "align-ints",
Aliases: []string{"I"},
@@ -125,17 +117,10 @@ func Main() int {
Version(conf),
Debug(conf),
HelpJsonPath(conf),
HelpUsage(conf),
},
Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
if tree {
if err := Tree(cmd); err != nil {
return nil, err
}
os.Exit(0)
}
if err := conf.Init(); err != nil {
if len(os.Args) > 1 {
return nil, err
@@ -261,22 +246,64 @@ func Debug(conf *cfg.Config) *cli.Command {
}
}
func Tree(cmd *cli.Command) error {
max := 20
func HelpUsage(conf *cfg.Config) *cli.Command {
return &cli.Command{
Name: "help-command-overview",
Usage: "show overview of all available commands",
Aliases: []string{"usage"},
return cmd.Walk(func(cmd *cli.Command) error {
path := cmd.Path()
command := path[len(path)-1]
Flags: []cli.Flag{
&cli.BoolFlag{
Name: "hidden",
Usage: "include hidden commands",
Destination: &conf.Hidden,
Aliases: []string{"H"},
},
},
if len(path) == 1 || command == "help" {
return nil
}
Action: func(ctx context.Context, cmd *cli.Command) error {
max := 22
indent := strings.Repeat(" ", len(path[1:])-1)
space := strings.Repeat(" ", max-(len(command)+len(indent)))
return walkVisible(conf, cmd.Root(), func(cmd *cli.Command) error {
path := cmd.Path()
command := path[len(path)-1]
fmt.Printf("%s%s %s - %s\n", indent, command, space, cmd.Usage)
if len(path) == 1 || command == "help" {
return nil
}
indent := strings.Repeat(" ", len(path[1:])-1)
space := strings.Repeat(" ", max-(len(command)+len(indent)))
fmt.Printf("%s%s %s - %s\n", indent, command, space, cmd.Usage)
return nil
})
},
}
return nil
})
}
// copy of cmd.Walk() with the exception to skip hidden commands and its siblings
// see: https://github.com/urfave/cli/issues/2372
func walkVisible(conf *cfg.Config, cmd *cli.Command, fn func(*cli.Command) error) error {
if fn == nil {
return nil
}
if !conf.Hidden && cmd.Hidden {
return nil
}
if err := fn(cmd); err != nil {
return err
}
for _, sub := range cmd.Commands {
if err := walkVisible(conf, sub, fn); err != nil {
return err
}
}
return nil
}