Skip to content

Commit 9d30336

Browse files
Codelaxremyleone
andauthored
perf(core): cobra builder allocate with nb of commands and use unordered list (#2702)
Co-authored-by: Rémy Léone <[email protected]>
1 parent efb08dd commit 9d30336

File tree

2 files changed

+18
-4
lines changed

2 files changed

+18
-4
lines changed

internal/core/cobra_builder.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
func init() {
1111
// we disable cobra command sorting to position important commands at the top when looking at the usage.
1212
cobra.EnableCommandSorting = false
13+
cobra.AddTemplateFunc("orderCommands", orderCobraCommands)
1314
}
1415

1516
// cobraBuilder will transform a []*Command to a valid Cobra root command.
@@ -23,8 +24,10 @@ type cobraBuilder struct {
2324

2425
// build creates the cobra root command.
2526
func (b *cobraBuilder) build() *cobra.Command {
26-
index := map[string]*cobra.Command{}
27-
commandsIndex := map[string]*Command{}
27+
commands := b.commands.GetAll()
28+
29+
index := make(map[string]*cobra.Command, len(commands))
30+
commandsIndex := make(map[string]*Command, len(commands))
2831

2932
rootCmd := &cobra.Command{
3033
Use: b.meta.BinaryName,
@@ -41,7 +44,7 @@ func (b *cobraBuilder) build() *cobra.Command {
4144

4245
rootCmd.SetOut(b.meta.stderr)
4346

44-
for _, cmd := range b.commands.GetSortedCommand() {
47+
for _, cmd := range commands {
4548
// If namespace command has not yet been created. We create an empty cobra command to allow leaf to be attached.
4649
if _, namespaceExist := index[cmd.Namespace]; !namespaceExist {
4750
cobraCmd := &cobra.Command{Use: cmd.Namespace}
@@ -156,7 +159,7 @@ ARGS:
156159
DEPRECATED ARGS:
157160
{{.Annotations.UsageDeprecatedArgs}}{{end}}{{if .HasAvailableSubCommands}}
158161
159-
AVAILABLE COMMANDS:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
162+
AVAILABLE COMMANDS:{{range orderCommands .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
160163
{{rpad .Name .NamePadding }} {{if .Short}}{{.Short}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
161164
162165
FLAGS:

internal/core/cobra_usage_builder.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"context"
66
"fmt"
77
"io"
8+
"sort"
89
"strings"
910
"text/tabwriter"
1011

@@ -113,3 +114,13 @@ func usageFuncBuilder(cmd *cobra.Command, annotationBuilder func()) func(*cobra.
113114
return cmd.UsageFunc()(command)
114115
}
115116
}
117+
118+
func orderCobraCommands(cobraCommands []*cobra.Command) []*cobra.Command {
119+
commands := make([]*cobra.Command, len(cobraCommands))
120+
copy(commands, cobraCommands)
121+
122+
sort.Slice(commands, func(i, j int) bool {
123+
return commands[i].Use < commands[j].Use
124+
})
125+
return commands
126+
}

0 commit comments

Comments
 (0)