Skip to content

Commit

Permalink
perf(core): lazy load usage (#2700)
Browse files Browse the repository at this point in the history
  • Loading branch information
Codelax authored Dec 27, 2022
1 parent e42713e commit bb49d6c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 12 deletions.
28 changes: 16 additions & 12 deletions internal/core/cobra_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,21 +100,25 @@ func (b *cobraBuilder) hydrateCobra(cobraCmd *cobra.Command, cmd *Command) {
cobraCmd.Annotations = make(map[string]string)
}

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

if cmd.ArgSpecs != nil {
cobraCmd.Annotations["UsageDeprecatedArgs"] = buildUsageArgs(b.ctx, cmd, true)
}
if cmd.ArgSpecs != nil {
cobraCmd.Annotations["UsageDeprecatedArgs"] = buildUsageArgs(b.ctx, cmd, true)
}

if cmd.Examples != nil {
cobraCmd.Annotations["Examples"] = buildExamples(b.meta.BinaryName, cmd)
}
if cmd.Examples != nil {
cobraCmd.Annotations["Examples"] = buildExamples(b.meta.BinaryName, cmd)
}

if cmd.SeeAlsos != nil {
cobraCmd.Annotations["SeeAlsos"] = cmd.seeAlsosAsStr()
}
if cmd.SeeAlsos != nil {
cobraCmd.Annotations["SeeAlsos"] = cmd.seeAlsosAsStr()
}
}))

if cmd.Run != nil {
cobraCmd.RunE = cobraRun(b.ctx, cmd)
Expand Down
13 changes: 13 additions & 0 deletions internal/core/cobra_usage_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (

"github.com/scaleway/scaleway-cli/v2/internal/interactive"
"github.com/scaleway/scaleway-sdk-go/logger"
"github.com/spf13/cobra"
)

const (
Expand Down Expand Up @@ -100,3 +101,15 @@ func buildExamples(binaryName string, cmd *Command) string {
// Return a single string for all examples.
return strings.Join(examples, "\n\n")
}

// usageFuncBuilder returns the usage function that will be used by cobra to print usage,
// the builder also takes a function that will fill annotations used by the usage template,
// this is done like this to avoid build annotations for each command if not required
func usageFuncBuilder(cmd *cobra.Command, annotationBuilder func()) func(*cobra.Command) error {
return func(command *cobra.Command) error {
annotationBuilder()
// after building annotation we remove this function as we prefer to use default UsageFunc
cmd.SetUsageFunc(nil)
return cmd.UsageFunc()(command)
}
}

0 comments on commit bb49d6c

Please sign in to comment.