|
| 1 | +// Package command provides pure utilities for manipulating cobra command |
| 2 | +// trees: matching commands against console filters, hiding filtered or internal |
| 3 | +// commands, resetting reused flag state, and locating the command targeted by a |
| 4 | +// line of input. None of these functions depend on console state, so they can be |
| 5 | +// tested in isolation; the root console package wraps them in its own methods. |
| 6 | +package command |
| 7 | + |
| 8 | +import ( |
| 9 | + "encoding/csv" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "github.com/spf13/cobra" |
| 13 | + "github.com/spf13/pflag" |
| 14 | +) |
| 15 | + |
| 16 | +// FilterKey is the cobra annotation key whose comma-separated value marks a |
| 17 | +// command with the filters that hide it. The console re-exports this as |
| 18 | +// CommandFilterKey for application use. |
| 19 | +const FilterKey = "console-hidden" |
| 20 | + |
| 21 | +// ActiveFilters returns the console filters that cmd (or its nearest annotated |
| 22 | +// ancestor) declares itself incompatible with. A non-empty result means the |
| 23 | +// command is currently hidden/unavailable under the given console filters. |
| 24 | +func ActiveFilters(cmd *cobra.Command, consoleFilters []string) []string { |
| 25 | + if cmd.Annotations == nil { |
| 26 | + if cmd.HasParent() { |
| 27 | + return ActiveFilters(cmd.Parent(), consoleFilters) |
| 28 | + } |
| 29 | + |
| 30 | + return nil |
| 31 | + } |
| 32 | + |
| 33 | + // Get the filters declared on the command. |
| 34 | + filterStr := cmd.Annotations[FilterKey] |
| 35 | + var filters []string |
| 36 | + |
| 37 | + for _, cmdFilter := range strings.Split(filterStr, ",") { |
| 38 | + for _, filter := range consoleFilters { |
| 39 | + if cmdFilter != "" && cmdFilter == filter { |
| 40 | + filters = append(filters, cmdFilter) |
| 41 | + } |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + if len(filters) > 0 || !cmd.HasParent() { |
| 46 | + return filters |
| 47 | + } |
| 48 | + |
| 49 | + // Any parent that is hidden makes its whole subtree hidden also. |
| 50 | + return ActiveFilters(cmd.Parent(), consoleFilters) |
| 51 | +} |
| 52 | + |
| 53 | +// HideFiltered hides every subcommand of root that matches an active console |
| 54 | +// filter, so it is not shown in help strings or offered as a completion. |
| 55 | +// Commands already hidden are left untouched. |
| 56 | +func HideFiltered(root *cobra.Command, consoleFilters []string) { |
| 57 | + for _, cmd := range root.Commands() { |
| 58 | + // Don't override commands if they are already hidden. |
| 59 | + if cmd.Hidden { |
| 60 | + continue |
| 61 | + } |
| 62 | + |
| 63 | + if filters := ActiveFilters(cmd, consoleFilters); len(filters) > 0 { |
| 64 | + cmd.Hidden = true |
| 65 | + } |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +// HideCarapace recursively hides carapace's internal _carapace completion |
| 70 | +// command so it is never offered as a normal user command. |
| 71 | +func HideCarapace(root *cobra.Command) { |
| 72 | + if root == nil { |
| 73 | + return |
| 74 | + } |
| 75 | + |
| 76 | + for _, cmd := range root.Commands() { |
| 77 | + if cmd.Name() == "_carapace" { |
| 78 | + cmd.Hidden = true |
| 79 | + continue |
| 80 | + } |
| 81 | + |
| 82 | + HideCarapace(cmd) |
| 83 | + } |
| 84 | +} |
| 85 | + |
| 86 | +// ResetFlagsDefaults resets every flag on target back to its registered default |
| 87 | +// value and clears its Changed state. Console reuses cobra command trees across |
| 88 | +// completions and executions; when the application supplies a command tree |
| 89 | +// directly (no generator), flag state parsed by an earlier run would otherwise |
| 90 | +// leak into later ones. |
| 91 | +func ResetFlagsDefaults(target *cobra.Command) { |
| 92 | + if target == nil { |
| 93 | + return |
| 94 | + } |
| 95 | + |
| 96 | + target.Flags().VisitAll(func(flag *pflag.Flag) { |
| 97 | + flag.Changed = false |
| 98 | + |
| 99 | + switch value := flag.Value.(type) { |
| 100 | + case pflag.SliceValue: |
| 101 | + _ = value.Replace(parseSliceDefault(flag.DefValue)) |
| 102 | + default: |
| 103 | + _ = flag.Value.Set(flag.DefValue) |
| 104 | + } |
| 105 | + }) |
| 106 | +} |
| 107 | + |
| 108 | +// parseSliceDefault turns a pflag slice flag's DefValue string representation |
| 109 | +// (e.g. "[a,b]") back into the individual default elements. |
| 110 | +func parseSliceDefault(defValue string) []string { |
| 111 | + if defValue == "" || defValue == "[]" { |
| 112 | + return nil |
| 113 | + } |
| 114 | + if strings.HasPrefix(defValue, "[") && strings.HasSuffix(defValue, "]") { |
| 115 | + defValue = defValue[1 : len(defValue)-1] |
| 116 | + } |
| 117 | + if defValue == "" { |
| 118 | + return nil |
| 119 | + } |
| 120 | + |
| 121 | + values, err := csv.NewReader(strings.NewReader(defValue)).Read() |
| 122 | + if err != nil { |
| 123 | + return []string{defValue} |
| 124 | + } |
| 125 | + |
| 126 | + return values |
| 127 | +} |
| 128 | + |
| 129 | +// ResetCompletionFlagState clears flag state left over from a previous |
| 130 | +// completion or execution on a reused command tree, before carapace parses the |
| 131 | +// current input. It restores the target command's flag defaults (shared with |
| 132 | +// the execution path) and resets ArgsLenAtDash along the command's lineage. |
| 133 | +func ResetCompletionFlagState(root *cobra.Command, args []string) { |
| 134 | + if root == nil { |
| 135 | + return |
| 136 | + } |
| 137 | + |
| 138 | + target := findCompletionTarget(root, args) |
| 139 | + |
| 140 | + // Force cobra to merge persistent/inherited flags into the full flag set |
| 141 | + // so ResetFlagsDefaults sees them all. |
| 142 | + _ = target.LocalFlags() |
| 143 | + |
| 144 | + ResetFlagsDefaults(target) |
| 145 | + resetArgsLenAtDash(target) |
| 146 | +} |
| 147 | + |
| 148 | +// resetArgsLenAtDash clears the "-- seen at index" bookkeeping on the target |
| 149 | +// command and every parent, which a previous parse may have left set. |
| 150 | +func resetArgsLenAtDash(target *cobra.Command) { |
| 151 | + for cmd := target; cmd != nil; cmd = cmd.Parent() { |
| 152 | + resetFlagSetArgsLenAtDash(cmd.Flags(), cmd.DisplayName()) |
| 153 | + resetFlagSetArgsLenAtDash(cmd.PersistentFlags(), cmd.DisplayName()) |
| 154 | + } |
| 155 | +} |
| 156 | + |
| 157 | +func resetFlagSetArgsLenAtDash(fs *pflag.FlagSet, name string) { |
| 158 | + if fs == nil { |
| 159 | + return |
| 160 | + } |
| 161 | + |
| 162 | + // FlagSet.Init resets argsLenAtDash to -1 without discarding registered |
| 163 | + // flags; it is the only exported way to clear that internal state. |
| 164 | + fs.Init(name, pflag.ContinueOnError) |
| 165 | +} |
| 166 | + |
| 167 | +// findCompletionTarget walks the command tree following the positional words in |
| 168 | +// args, stopping at the first flag or "--", to locate the command being completed. |
| 169 | +func findCompletionTarget(root *cobra.Command, args []string) *cobra.Command { |
| 170 | + cmd := root |
| 171 | + for _, arg := range args { |
| 172 | + if arg == "--" || strings.HasPrefix(arg, "-") { |
| 173 | + break |
| 174 | + } |
| 175 | + |
| 176 | + next := findSubcommand(cmd, arg) |
| 177 | + if next == nil { |
| 178 | + break |
| 179 | + } |
| 180 | + cmd = next |
| 181 | + } |
| 182 | + |
| 183 | + return cmd |
| 184 | +} |
| 185 | + |
| 186 | +func findSubcommand(cmd *cobra.Command, name string) *cobra.Command { |
| 187 | + if cmd == nil { |
| 188 | + return nil |
| 189 | + } |
| 190 | + |
| 191 | + for _, sub := range cmd.Commands() { |
| 192 | + if sub.Name() == name || sub.HasAlias(name) { |
| 193 | + return sub |
| 194 | + } |
| 195 | + } |
| 196 | + |
| 197 | + return nil |
| 198 | +} |
0 commit comments