diff --git a/internal/core/cobra_builder.go b/internal/core/cobra_builder.go index 27cb18ca47..95be892f05 100644 --- a/internal/core/cobra_builder.go +++ b/internal/core/cobra_builder.go @@ -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) diff --git a/internal/core/cobra_usage_builder.go b/internal/core/cobra_usage_builder.go index b07adea0f8..5dfca31be0 100644 --- a/internal/core/cobra_usage_builder.go +++ b/internal/core/cobra_usage_builder.go @@ -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 ( @@ -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) + } +}