Skip to content
Myr

Micro-optimizations (#1957)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Avoid redundant string splits There likely isn't actually more than once to split in the source strings in these cases, but avoid doing so anyway as we're only interested in the first. * Avoid redundant completion output target evaluations The target is not to be changed while outputting completions, so resolve it only once. * Avoid redundant active help enablement evaluations The enablement state is not to be changed during completion output, so evaluate it only once. * Preallocate some slices and maps with known size * Avoid some unnecessary looping * Use strings.Builder to construct suggestions

authored by Ville Skyttä · committed by GitHub · parent 283e32d · Browse files · 6 files+23 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+23 added−25 removed

  • other:+23 added−25 removed

6 files+23 added−25 removed

modified:args.go+2 added-2 removed
50 unmodified lines
51func OnlyValidArgs(cmd *Command, args []string) error {52 if len(cmd.ValidArgs) > 0 {53 // Remove any description that may be included in ValidArgs.54 // A description is following a tab character.55 var validArgs []string55 validArgs := make([]string, 0, len(cmd.ValidArgs))56 for _, v := range cmd.ValidArgs {57 validArgs = append(validArgs, strings.Split(v, "\t")[0])57 validArgs = append(validArgs, strings.SplitN(v, "\t", 2)[0])58 }59 for _, v := range args {60 if !stringInSlice(v, validArgs) {61 return fmt.Errorf("invalid argument %q for %q%s", v, cmd.CommandPath(), cmd.findSuggestions(args[0]))
70 unmodified lines
modified:bash_completions.go+1 added-1 removed
619 unmodified lines
620 sort.Strings(cmd.ValidArgs)621 for _, value := range cmd.ValidArgs {622 // Remove any description that may be included following a tab character.623 // Descriptions are not supported by bash completion.624 value = strings.Split(value, "\t")[0]624 value = strings.SplitN(value, "\t", 2)[0]625 WriteStringAndCheck(buf, fmt.Sprintf(" must_have_one_noun+=(%q)\n", value))626 }627 if cmd.ValidArgsFunction != nil {628 WriteStringAndCheck(buf, " has_completion_function=1\n")
84 unmodified lines
modified:cobra.go-2 removed
191 unmodified lines
192 }193 d := make([][]int, len(s)+1)194 for i := range d {195 d[i] = make([]int, len(t)+1)196 }197 for i := range d {196 d[i][0] = i197 }198 for j := range d[0] {199 d[0][j] = j
43 unmodified lines
modified:command.go+5 added-5 removed
704 unmodified lines
705 case !strings.HasPrefix(s, "-"):706 // This is not a flag or a flag value. Check to see if it matches what we're looking for, and if so,707 // return the args, excluding the one at this position.708 if s == x {709 ret := []string{}709 ret := make([]string, 0, len(args)-1)710 ret = append(ret, args[:pos]...)711 ret = append(ret, args[pos+1:]...)712 return ret713 }
39 unmodified lines
753 }754 if c.SuggestionsMinimumDistance <= 0 {755 c.SuggestionsMinimumDistance = 2756 }757 suggestionsString := ""757 var sb strings.Builder758 if suggestions := c.SuggestionsFor(arg); len(suggestions) > 0 {759 suggestionsString += "\n\nDid you mean this?\n"759 sb.WriteString("\n\nDid you mean this?\n")760 for _, s := range suggestions {761 suggestionsString += fmt.Sprintf("\t%v\n", s)761 _, _ = fmt.Fprintf(&sb, "\t%v\n", s)762 }763 }764 return suggestionsString764 return sb.String()765}766767func (c *Command) findNext(next string) *Command {768 matches := make([]*Command, 0)
1117 unmodified lines
modified:completions.go+10 added-10 removed
210 unmodified lines
211 // 2- Even without completions, we need to print the directive212 }213214 noDescriptions := (cmd.CalledAs() == ShellCompNoDescRequestCmd)215 noActiveHelp := GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable216 out := finalCmd.OutOrStdout()217 for _, comp := range completions {216 if GetActiveHelpConfig(finalCmd) == activeHelpGlobalDisable {217 // Remove all activeHelp entries in this case218 if strings.HasPrefix(comp, activeHelpMarker) {219 continue220 }218 if noActiveHelp && strings.HasPrefix(comp, activeHelpMarker) {219 // Remove all activeHelp entries if it's disabled.220 continue221 }222 if noDescriptions {223 // Remove any description that may be included following a tab character.224 comp = strings.Split(comp, "\t")[0]224 comp = strings.SplitN(comp, "\t", 2)[0]225 }226227 // Make sure we only write the first line to the output.228 // This is needed if a description contains a linebreak.229 // Otherwise the shell scripts will interpret the other lines as new flags230 // and could therefore provide a wrong completion.231 comp = strings.Split(comp, "\n")[0]231 comp = strings.SplitN(comp, "\n", 2)[0]232233 // Finally trim the completion. This is especially important to get rid234 // of a trailing tab when there are no description following it.235 // For example, a sub-command without a description should not be completed236 // with a tab at the end (or else zsh will show a -- following it237 // although there is no description).238 comp = strings.TrimSpace(comp)239240 // Print each possible completion to stdout for the completion script to consume.241 fmt.Fprintln(finalCmd.OutOrStdout(), comp)240 // Print each possible completion to the output for the completion script to consume.241 fmt.Fprintln(out, comp)242 }243244 // As the last printout, print the completion directive for the completion script to parse.245 // The directive integer must be that last character following a single colon (:).246 // The completion script expects :<directive>247 fmt.Fprintf(finalCmd.OutOrStdout(), ":%d\n", directive)247 fmt.Fprintf(out, ":%d\n", directive)248249 // Print some helpful info to stderr for the user to understand.250 // Output from stderr must be ignored by the completion script.251 fmt.Fprintf(finalCmd.ErrOrStderr(), "Completion ended with directive: %s\n", directive.string())
650 unmodified lines
modified:flag_groups.go+5 added-5 removed
128 unmodified lines
129 if !hasAllFlags(flags, flagnames...) {130 continue131 }132133 groupStatus[group] = map[string]bool{}133 groupStatus[group] = make(map[string]bool, len(flagnames))134 for _, name := range flagnames {135 groupStatus[group][name] = false136 }137 }
114 unmodified lines
252253 // If none of the flags of a one-required group are present, we make all the flags254 // of that group required so that the shell completion suggests them automatically255 for flagList, flagnameAndStatus := range oneRequiredGroupStatus {256 set := 0256 isSet := false257258 for _, isSet := range flagnameAndStatus {258 for _, isSet = range flagnameAndStatus {259 if isSet {260 set++260 break261 }262 }263264 // None of the flags of the group are set, mark all flags in the group265 // as required266 if set == 0 {266 if !isSet {267 for _, fName := range strings.Split(flagList, " ") {268 _ = c.MarkFlagRequired(fName)269 }270 }
20 unmodified lines