Skip to content

Commit bb49d6c

Browse files
authored
perf(core): lazy load usage (#2700)
1 parent e42713e commit bb49d6c

File tree

2 files changed

+29
-12
lines changed

2 files changed

+29
-12
lines changed

internal/core/cobra_builder.go

Lines changed: 16 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -100,21 +100,25 @@ func (b *cobraBuilder) hydrateCobra(cobraCmd *cobra.Command, cmd *Command) {
100100
cobraCmd.Annotations = make(map[string]string)
101101
}
102102

103-
if cmd.ArgsType != nil {
104-
cobraCmd.Annotations["UsageArgs"] = buildUsageArgs(b.ctx, cmd, false)
105-
}
103+
// Use a custom function to print usage
104+
// This function will build usage to avoid building it for each commands
105+
cobraCmd.SetUsageFunc(usageFuncBuilder(cobraCmd, func() {
106+
if cmd.ArgsType != nil {
107+
cobraCmd.Annotations["UsageArgs"] = buildUsageArgs(b.ctx, cmd, false)
108+
}
106109

107-
if cmd.ArgSpecs != nil {
108-
cobraCmd.Annotations["UsageDeprecatedArgs"] = buildUsageArgs(b.ctx, cmd, true)
109-
}
110+
if cmd.ArgSpecs != nil {
111+
cobraCmd.Annotations["UsageDeprecatedArgs"] = buildUsageArgs(b.ctx, cmd, true)
112+
}
110113

111-
if cmd.Examples != nil {
112-
cobraCmd.Annotations["Examples"] = buildExamples(b.meta.BinaryName, cmd)
113-
}
114+
if cmd.Examples != nil {
115+
cobraCmd.Annotations["Examples"] = buildExamples(b.meta.BinaryName, cmd)
116+
}
114117

115-
if cmd.SeeAlsos != nil {
116-
cobraCmd.Annotations["SeeAlsos"] = cmd.seeAlsosAsStr()
117-
}
118+
if cmd.SeeAlsos != nil {
119+
cobraCmd.Annotations["SeeAlsos"] = cmd.seeAlsosAsStr()
120+
}
121+
}))
118122

119123
if cmd.Run != nil {
120124
cobraCmd.RunE = cobraRun(b.ctx, cmd)

internal/core/cobra_usage_builder.go

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010

1111
"github.com/scaleway/scaleway-cli/v2/internal/interactive"
1212
"github.com/scaleway/scaleway-sdk-go/logger"
13+
"github.com/spf13/cobra"
1314
)
1415

1516
const (
@@ -100,3 +101,15 @@ func buildExamples(binaryName string, cmd *Command) string {
100101
// Return a single string for all examples.
101102
return strings.Join(examples, "\n\n")
102103
}
104+
105+
// usageFuncBuilder returns the usage function that will be used by cobra to print usage,
106+
// the builder also takes a function that will fill annotations used by the usage template,
107+
// this is done like this to avoid build annotations for each command if not required
108+
func usageFuncBuilder(cmd *cobra.Command, annotationBuilder func()) func(*cobra.Command) error {
109+
return func(command *cobra.Command) error {
110+
annotationBuilder()
111+
// after building annotation we remove this function as we prefer to use default UsageFunc
112+
cmd.SetUsageFunc(nil)
113+
return cmd.UsageFunc()(command)
114+
}
115+
}

0 commit comments

Comments
 (0)