-
Notifications
You must be signed in to change notification settings - Fork 3.1k
feat: add opt-in help-all command (ref #2362) #2370
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dpritchett
wants to merge
2
commits into
spf13:main
Choose a base branch
from
dpritchett:help-all-command
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+652
−0
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,180 @@ | ||
| // Copyright 2013-2023 The Cobra Authors | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| package cobra | ||
|
|
||
| import ( | ||
| "fmt" | ||
| "strings" | ||
|
|
||
| "github.com/spf13/pflag" | ||
| ) | ||
|
|
||
| // commandInfo is extracted data for one entry in the help-all reference output. | ||
| type commandInfo struct { | ||
| Path string // full command path, e.g. "app serve" | ||
| Args string // argument spec from Use field, e.g. "[session_id]" | ||
| Flags []string // formatted flag placeholders, e.g. "[--all]" | ||
| Short string // one-line description | ||
| } | ||
|
|
||
| // collectCommands walks the command tree and returns a commandInfo for each | ||
| // visible, runnable command (those where Runnable() is true). Hidden commands | ||
| // and their subtrees are skipped. Deprecated commands are included. | ||
| func collectCommands(root *Command) []commandInfo { | ||
| if root == nil { | ||
| return nil | ||
| } | ||
| var out []commandInfo | ||
| walkCommands(root, &out) | ||
| return out | ||
| } | ||
|
|
||
| // walkCommands recursively visits cmd and its children, appending a | ||
| // commandInfo for each visible, runnable command. Hidden commands are | ||
| // pruned along with their entire subtree. | ||
| func walkCommands(cmd *Command, out *[]commandInfo) { | ||
| if cmd.Hidden { | ||
| return | ||
| } | ||
|
|
||
| if cmd.Runnable() { | ||
| info := commandInfo{ | ||
| Path: cmd.CommandPath(), | ||
| Args: extractArgs(cmd.Use), | ||
| Short: cmd.Short, | ||
| } | ||
|
|
||
| cmd.LocalFlags().VisitAll(func(f *pflag.Flag) { | ||
| if f.Hidden { | ||
| return | ||
| } | ||
| info.Flags = append(info.Flags, formatFlag(f)) | ||
| }) | ||
|
|
||
| *out = append(*out, info) | ||
| } | ||
|
|
||
| for _, child := range cmd.Commands() { | ||
| walkCommands(child, out) | ||
| } | ||
| } | ||
|
|
||
| // extractArgs returns everything after the first space in a Use string, | ||
| // which represents the argument placeholders. | ||
| func extractArgs(use string) string { | ||
| if i := strings.IndexByte(use, ' '); i >= 0 { | ||
| return use[i+1:] | ||
| } | ||
| return "" | ||
| } | ||
|
|
||
| // formatFlag returns a bracket-wrapped flag placeholder appropriate for the | ||
| // flag's type (bool/count get no value, int/duration/string get a placeholder). | ||
| func formatFlag(f *pflag.Flag) string { | ||
| long := f.Name | ||
| short := f.Shorthand | ||
|
|
||
| switch f.Value.Type() { | ||
| case "bool", "count": | ||
| if short != "" { | ||
| return fmt.Sprintf("[-%s, --%s]", short, long) | ||
| } | ||
| return fmt.Sprintf("[--%s]", long) | ||
| case "int": | ||
| if short != "" { | ||
| return fmt.Sprintf("[-%s, --%s N]", short, long) | ||
| } | ||
| return fmt.Sprintf("[--%s N]", long) | ||
| case "duration": | ||
| if short != "" { | ||
| return fmt.Sprintf("[-%s, --%s DURATION]", short, long) | ||
| } | ||
| return fmt.Sprintf("[--%s DURATION]", long) | ||
| default: | ||
| placeholder := strings.ToUpper(long) | ||
| if short != "" { | ||
| return fmt.Sprintf("[-%s, --%s %s]", short, long, placeholder) | ||
| } | ||
| return fmt.Sprintf("[--%s %s]", long, placeholder) | ||
| } | ||
| } | ||
|
|
||
| // renderCommands formats command info into aligned, indented lines. When | ||
| // verbose is true, flag placeholders are included before the description. | ||
| func renderCommands(cmds []commandInfo, verbose bool) string { | ||
| if len(cmds) == 0 { | ||
| return "" | ||
| } | ||
|
|
||
| lefts := make([]string, len(cmds)) | ||
| maxLen := 0 | ||
| for i, c := range cmds { | ||
| parts := []string{c.Path} | ||
| if c.Args != "" { | ||
| parts = append(parts, c.Args) | ||
| } | ||
| if verbose { | ||
| parts = append(parts, c.Flags...) | ||
| } | ||
| lefts[i] = strings.Join(parts, " ") | ||
| if len(lefts[i]) > maxLen { | ||
| maxLen = len(lefts[i]) | ||
| } | ||
| } | ||
|
|
||
| var b strings.Builder | ||
| indent := " " | ||
| for i, c := range cmds { | ||
| padding := strings.Repeat(" ", maxLen-len(lefts[i])+2) | ||
| fmt.Fprintf(&b, "%s%s%s# %s", indent, lefts[i], padding, c.Short) | ||
| if i < len(cmds)-1 { | ||
| b.WriteByte('\n') | ||
| } | ||
| } | ||
| return b.String() | ||
| } | ||
|
|
||
| // NewHelpAllCommand returns a help-all command that prints a complete, aligned | ||
| // command reference. Add it to root with root.AddCommand(). Pass --verbose to | ||
| // include flag placeholders in the output. | ||
| // | ||
| // rootCmd.AddCommand(cobra.NewHelpAllCommand()) | ||
| // | ||
| // // or with a custom name: | ||
| // cmd := cobra.NewHelpAllCommand() | ||
| // cmd.Use = "my-custom-name" | ||
| // rootCmd.AddCommand(cmd) | ||
| func NewHelpAllCommand() *Command { | ||
| var verbose bool | ||
|
|
||
| cmd := &Command{ | ||
| Use: "help-all", | ||
| Short: "List all commands with their arguments and descriptions", | ||
| Args: NoArgs, | ||
| RunE: func(cmd *Command, args []string) error { | ||
| cmds := collectCommands(cmd.Root()) | ||
| out := renderCommands(cmds, verbose) | ||
| if out != "" { | ||
| _, err := fmt.Fprintln(cmd.OutOrStdout(), out) | ||
| return err | ||
| } | ||
| return nil | ||
| }, | ||
| } | ||
|
|
||
| cmd.Flags().BoolVar(&verbose, "verbose", false, "Include flags in output") | ||
|
|
||
| return cmd | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
if we go in that direction I would use something like
There is no need to fix the positional argument to be "help-all", some users may want to use "help" or whatever they want
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good point, thanks. I've added a godoc example showing that the name is customizable via
.Useon the returned*Command(see 8902815). This matches how cobra's own completion command works internally (hardcoded default name, mutable after creation).