// Package command provides pure utilities for manipulating cobra command// trees: matching commands against console filters, hiding filtered or internal// commands, resetting reused flag state, and locating the command targeted by a// line of input. None of these functions depend on console state, so they can be// tested in isolation; the root console package wraps them in its own methods.
package commandimport ()// FilterKey is the cobra annotation key whose comma-separated value marks a// command with the filters that hide it. The console re-exports this as// CommandFilterKey for application use.constFilterKey = "console-hidden"// ActiveFilters returns the console filters that cmd (or its nearest annotated// ancestor) declares itself incompatible with. A non-empty result means the// command is currently hidden/unavailable under the given console filters.func ( *cobra.Command, []string) []string {if .Annotations == nil {if .HasParent() {return (.Parent(), ) }returnnil }// Get the filters declared on the command. := .Annotations[FilterKey]var []stringfor , := rangestrings.Split(, ",") {for , := range {if != "" && == { = append(, ) } } }iflen() > 0 || !.HasParent() {return }// Any parent that is hidden makes its whole subtree hidden also.return (.Parent(), )}// HideFiltered hides every subcommand of root that matches an active console// filter, so it is not shown in help strings or offered as a completion.// Commands already hidden are left untouched.func ( *cobra.Command, []string) {for , := range .Commands() {// Don't override commands if they are already hidden.if .Hidden {continue }if := ActiveFilters(, ); len() > 0 { .Hidden = true } }}// HideCarapace recursively hides carapace's internal _carapace completion// command so it is never offered as a normal user command.func ( *cobra.Command) {if == nil {return }for , := range .Commands() {if .Name() == "_carapace" { .Hidden = truecontinue } () }}// ResetFlagsDefaults resets every flag on target back to its registered default// value and clears its Changed state. Console reuses cobra command trees across// completions and executions; when the application supplies a command tree// directly (no generator), flag state parsed by an earlier run would otherwise// leak into later ones.func ( *cobra.Command) {if == nil {return } .Flags().VisitAll(func( *pflag.Flag) { .Changed = falseswitch value := .Value.(type) {casepflag.SliceValue: _ = .Replace(parseSliceDefault(.DefValue))default: _ = .Value.Set(.DefValue) } })}// parseSliceDefault turns a pflag slice flag's DefValue string representation// (e.g. "[a,b]") back into the individual default elements.func parseSliceDefault( string) []string {if == "" || == "[]" {returnnil }ifstrings.HasPrefix(, "[") && strings.HasSuffix(, "]") { = [1 : len()-1] }if == "" {returnnil } , := csv.NewReader(strings.NewReader()).Read()if != nil {return []string{} }return}// ResetCompletionFlagState clears flag state left over from a previous// completion or execution on a reused command tree, before carapace parses the// current input. It restores the target command's flag defaults (shared with// the execution path) and resets ArgsLenAtDash along the command's lineage.func ( *cobra.Command, []string) {if == nil {return } := findCompletionTarget(, )// Force cobra to merge persistent/inherited flags into the full flag set // so ResetFlagsDefaults sees them all. _ = .LocalFlags()ResetFlagsDefaults()resetArgsLenAtDash()}// resetArgsLenAtDash clears the "-- seen at index" bookkeeping on the target// command and every parent, which a previous parse may have left set.func resetArgsLenAtDash( *cobra.Command) {for := ; != nil; = .Parent() {resetFlagSetArgsLenAtDash(.Flags(), .DisplayName())resetFlagSetArgsLenAtDash(.PersistentFlags(), .DisplayName()) }}func resetFlagSetArgsLenAtDash( *pflag.FlagSet, string) {if == nil {return }// FlagSet.Init resets argsLenAtDash to -1 without discarding registered // flags; it is the only exported way to clear that internal state. .Init(, pflag.ContinueOnError)}// findCompletionTarget walks the command tree following the positional words in// args, stopping at the first flag or "--", to locate the command being completed.func findCompletionTarget( *cobra.Command, []string) *cobra.Command { := for , := range {if == "--" || strings.HasPrefix(, "-") {break } := findSubcommand(, )if == nil {break } = }return}func findSubcommand( *cobra.Command, string) *cobra.Command {if == nil {returnnil }for , := range .Commands() {if .Name() == || .HasAlias() {return } }returnnil}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.