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
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
Provenance
- Commit
3d8ac43- Tree
a6e5b96- Author
Ville Skyttä <ville.skytta@upcloud.com>- Committer
GitHub <noreply@github.com>- Parent
283e32d
6 files changed+23 added−25 removed
modified:args.go+2 added-2 removed
50 unmodified lines51 func 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 linesmodified:bash_completions.go+1 added-1 removed
619 unmodified lines620 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 linesmodified:cobra.go-2 removed
191 unmodified lines192 }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] = j43 unmodified linesmodified:command.go+5 added-5 removed
704 unmodified lines705 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 lines753 }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 }766 767 func (c *Command) findNext(next string) *Command {768 matches := make([]*Command, 0)1117 unmodified linesmodified:completions.go+10 added-10 removed
210 unmodified lines211 // 2- Even without completions, we need to print the directive212 }213 214 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 }226 227 // 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]232 233 // 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)239 240- // 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 }243 244 // 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)248 249 // 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 linesmodified:flag_groups.go+5 added-5 removed
128 unmodified lines129 if !hasAllFlags(flags, flagnames...) {130 continue131 }132 133- 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 lines252 253 // 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 := false257 258- for _, isSet := range flagnameAndStatus {258+ for _, isSet = range flagnameAndStatus {259 if isSet {260- set++260+ break261 }262 }263 264 // 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