From 4eec8e55a1e610747063f4aabe59a7d1c07c1051 Mon Sep 17 00:00:00 2001 From: Roberto Hidalgo Date: Thu, 29 Dec 2022 13:05:58 -0600 Subject: [PATCH] allow setting root command config --- internal/constants/constants.go | 4 +- internal/constants/help.md | 8 ++-- internal/registry/cobra.go | 70 +++++++++++++++++---------------- internal/registry/registry.go | 5 +-- main.go | 18 +++++++-- pkg/command/command.go | 7 +++- pkg/command/help.go | 2 +- pkg/command/root.go | 6 +-- pkg/runtime/runtime.go | 2 + 9 files changed, 72 insertions(+), 50 deletions(-) diff --git a/internal/constants/constants.go b/internal/constants/constants.go index 921baa5..d3ae886 100644 --- a/internal/constants/constants.go +++ b/internal/constants/constants.go @@ -82,9 +82,9 @@ var TemplateFuncs = template.FuncMap{ // TemplateCommandHelp holds a template for rendering command help. var TemplateCommandHelp *template.Template -func HelpTemplate() *template.Template { +func HelpTemplate(executableName string) *template.Template { if TemplateCommandHelp == nil { - TemplateCommandHelp = template.Must(template.New("help").Funcs(TemplateFuncs).Parse(helpTemplateText)) + TemplateCommandHelp = template.Must(template.New("help").Funcs(TemplateFuncs).Parse(strings.ReplaceAll(helpTemplateText, "@chinampa@", executableName))) } return TemplateCommandHelp diff --git a/internal/constants/help.md b/internal/constants/help.md index f884171..6590dd8 100644 --- a/internal/constants/help.md +++ b/internal/constants/help.md @@ -1,5 +1,5 @@ {{- if not .HTMLOutput }} -# {{ if and (not (eq .Spec.FullName "joao")) (not (eq .Command.Name "help")) }}joao {{ end }}{{ .Spec.FullName }}{{if eq .Command.Name "help"}} help{{end}} +# {{ if and (not .Spec.IsRoot) (not (eq .Command.Name "help")) }}@chinampa@ {{ end }}{{ .Spec.FullName }}{{if eq .Command.Name "help"}} help{{end}} {{- else }} --- description: {{ .Command.Short }} @@ -10,7 +10,7 @@ description: {{ .Command.Short }} ## Usage - ﹅{{ replace .Command.UseLine " [flags]" "" }}{{if .Command.HasAvailableSubCommands}} SUBCOMMAND{{end}}﹅ + `{{ replace .Command.UseLine " [flags]" "" }}{{if .Command.HasAvailableSubCommands}} SUBCOMMAND{{end}}` {{ if .Command.HasAvailableSubCommands -}} ## Subcommands @@ -37,7 +37,7 @@ description: {{ .Command.Short }} {{- end -}} -{{ if and (eq .Spec.FullName "joao") (not (eq .Command.Name "help")) }} +{{ if and .Spec.IsRoot (not (eq .Command.Name "help")) }} ## Description {{ .Spec.Description }} @@ -55,7 +55,7 @@ description: {{ .Command.Short }} {{ end -}} {{- end -}} -{{- if not (eq .Spec.FullName "joao") }} +{{- if not .Spec.IsRoot }} ## Description {{ if not (eq .Command.Long "") }}{{ .Command.Long }}{{ else }}{{ .Spec.Description }}{{end}} diff --git a/internal/registry/cobra.go b/internal/registry/cobra.go index 3e8e677..65347f6 100644 --- a/internal/registry/cobra.go +++ b/internal/registry/cobra.go @@ -25,43 +25,47 @@ import ( "github.com/spf13/cobra" ) -var ccRoot = &cobra.Command{ - Use: "joao [--silent|-v|--verbose] [--[no-]color] [-h|--help] [--version]", - Annotations: map[string]string{ - _c.ContextKeyRuntimeIndex: "joao", - }, - DisableAutoGenTag: true, - SilenceUsage: true, - SilenceErrors: true, - ValidArgs: []string{""}, - Args: func(cmd *cobra.Command, args []string) error { - err := cobra.OnlyValidArgs(cmd, args) - if err != nil { +func newCobraRoot(root *command.Command) *cobra.Command { + return &cobra.Command{ + Use: root.Name() + " [--silent|-v|--verbose] [--[no-]color] [-h|--help] [--version]", + Annotations: map[string]string{ + _c.ContextKeyRuntimeIndex: root.Name(), + }, + Short: root.Summary, + Long: root.Description, + DisableAutoGenTag: true, + SilenceUsage: true, + SilenceErrors: true, + ValidArgs: []string{""}, + Args: func(cmd *cobra.Command, args []string) error { + err := cobra.OnlyValidArgs(cmd, args) + if err != nil { - suggestions := []string{} - bold := color.New(color.Bold) - for _, l := range cmd.SuggestionsFor(args[len(args)-1]) { - suggestions = append(suggestions, bold.Sprint(l)) + suggestions := []string{} + bold := color.New(color.Bold) + for _, l := range cmd.SuggestionsFor(args[len(args)-1]) { + suggestions = append(suggestions, bold.Sprint(l)) + } + errMessage := fmt.Sprintf("Unknown subcommand %s", bold.Sprint(strings.Join(args, " "))) + if len(suggestions) > 0 { + errMessage += ". Perhaps you meant " + strings.Join(suggestions, ", ") + "?" + } + return errors.NotFound{Msg: errMessage, Group: []string{}} } - errMessage := fmt.Sprintf("Unknown subcommand %s", bold.Sprint(strings.Join(args, " "))) - if len(suggestions) > 0 { - errMessage += ". Perhaps you meant " + strings.Join(suggestions, ", ") + "?" + return nil + }, + RunE: func(cmd *cobra.Command, args []string) error { + if len(args) == 0 { + if ok, err := cmd.Flags().GetBool("version"); err == nil && ok { + _, err := cmd.OutOrStdout().Write([]byte(cmd.Root().Annotations["version"])) + return err + } + return errors.NotFound{Msg: "No subcommand provided", Group: []string{}} } - return errors.NotFound{Msg: errMessage, Group: []string{}} - } - return nil - }, - RunE: func(cmd *cobra.Command, args []string) error { - if len(args) == 0 { - if ok, err := cmd.Flags().GetBool("version"); err == nil && ok { - _, err := cmd.OutOrStdout().Write([]byte(cmd.Root().Annotations["version"])) - return err - } - return errors.NotFound{Msg: "No subcommand provided", Group: []string{}} - } - return nil - }, + return nil + }, + } } func toCobra(cmd *command.Command, globalOptions command.Options) *cobra.Command { diff --git a/internal/registry/registry.go b/internal/registry/registry.go index 83ea8f9..2030a89 100644 --- a/internal/registry/registry.go +++ b/internal/registry/registry.go @@ -134,8 +134,7 @@ func ChildrenNames() []string { func Execute(version string) error { cmdRoot := command.Root - ccRoot.Short = cmdRoot.Summary - ccRoot.Long = cmdRoot.Description + ccRoot := newCobraRoot(command.Root) ccRoot.Annotations["version"] = version ccRoot.CompletionOptions.HiddenDefaultCmd = true ccRoot.Flags().AddFlagSet(cmdRoot.FlagSet()) @@ -153,7 +152,7 @@ func Execute(version string) error { container := ccRoot for idx, cp := range cmd.Path { if idx == len(cmd.Path)-1 { - // logrus.Debugf("adding command %s to %s", leaf.Name(), cmd.Path[0:idx]) + logrus.Debugf("adding command %s to %s", leaf.Name(), container.Name()) container.AddCommand(leaf) break } diff --git a/main.go b/main.go index f033530..be2a570 100644 --- a/main.go +++ b/main.go @@ -15,12 +15,24 @@ package chinampa import ( "git.rob.mx/nidito/chinampa/internal/registry" "git.rob.mx/nidito/chinampa/pkg/command" + "git.rob.mx/nidito/chinampa/pkg/runtime" ) func Register(cmd *command.Command) { - registry.Register(cmd) + registry.Register(cmd.SetBindings()) } -func Execute(version string) error { - return registry.Execute(version) +type Config struct { + Name string + Version string + Summary string + Description string +} + +func Execute(config Config) error { + runtime.Executable = config.Name + command.Root.Summary = config.Summary + command.Root.Description = config.Description + command.Root.Path = []string{runtime.Executable} + return registry.Execute(config.Version) } diff --git a/pkg/command/command.go b/pkg/command/command.go index 1108238..dc228f1 100644 --- a/pkg/command/command.go +++ b/pkg/command/command.go @@ -17,6 +17,7 @@ import ( "strings" "git.rob.mx/nidito/chinampa/internal/errors" + "git.rob.mx/nidito/chinampa/pkg/runtime" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/pflag" @@ -42,6 +43,10 @@ type Command struct { Cobra *cobra.Command } +func (cmd *Command) IsRoot() bool { + return cmd.FullName() == runtime.Executable +} + func (cmd *Command) SetBindings() *Command { ptr := cmd for _, opt := range cmd.Options { @@ -114,7 +119,7 @@ func (cmd *Command) ParseInput(cc *cobra.Command, args []string) error { logrus.Debug("Validating flags") if err := cmd.Options.AreValid(); err != nil { - logrus.Debug("Invalid flags for %s: %w", cmd.FullName(), err) + logrus.Debugf("Invalid flags for %s: %w", cmd.FullName(), err) return err } } diff --git a/pkg/command/help.go b/pkg/command/help.go index 27ce81e..1f735cd 100644 --- a/pkg/command/help.go +++ b/pkg/command/help.go @@ -64,7 +64,7 @@ func (cmd *Command) ShowHelp(globalOptions Options, args []string) ([]byte, erro GlobalOptions: globalOptions, HTMLOutput: runtime.UnstyledHelpEnabled(), } - err := _c.HelpTemplate().Execute(&buf, c) + err := _c.HelpTemplate(runtime.Executable).Execute(&buf, c) if err != nil { return nil, err } diff --git a/pkg/command/root.go b/pkg/command/root.go index b9bc228..1ba86a2 100644 --- a/pkg/command/root.go +++ b/pkg/command/root.go @@ -18,9 +18,9 @@ import ( ) var Root = &Command{ - Summary: "Helps organize config for roberto", - Description: `﹅joao﹅ makes yaml, json, 1password and vault play along nicely.`, - Path: []string{"joao"}, + Summary: "Replace me with chinampa.Configure", + Description: "", + Path: []string{runtime.Executable}, Options: Options{ _c.HelpCommandName: &Option{ ShortName: "h", diff --git a/pkg/runtime/runtime.go b/pkg/runtime/runtime.go index 4175d61..855d2a8 100644 --- a/pkg/runtime/runtime.go +++ b/pkg/runtime/runtime.go @@ -19,6 +19,8 @@ import ( _c "git.rob.mx/nidito/chinampa/internal/constants" ) +var Executable = "chinampa" + var falseIshValues = []string{ "", "0",