From b4759d5f083e028598c97d487fe8cdff8eaebec4 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Thu, 16 Nov 2023 22:58:49 -0500 Subject: [PATCH 1/2] Fix spacing on subcommand names --- help.go | 5 ++++- set.go | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/help.go b/help.go index 62c4496..cfc5129 100644 --- a/help.go +++ b/help.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + "strings" "go.fifitido.net/cmd/opt" ) @@ -43,8 +44,10 @@ func (c *Command) ShowHelp() { fmt.Println("Available subcommands:") } + paddedWidth := c.Subcommands.MaxWidth() for _, s := range c.Subcommands { - fmt.Println(" " + s.Name + " " + s.ShortDescription) + spaceSize := 2 + paddedWidth - len(s.Name) + fmt.Println(" " + s.Name + strings.Repeat(" ", spaceSize) + s.ShortDescription) } } diff --git a/set.go b/set.go index 8e756ea..e3e9557 100644 --- a/set.go +++ b/set.go @@ -25,7 +25,7 @@ func (s Set) Get(name string) (*Command, bool) { return nil, false } -func (s Set) MaxNameWidth() int { +func (s Set) MaxWidth() int { max := 0 for _, f := range s { if w := len(f.Name); w > max { From 73d7db2078bcf50aee12aefd0aea61de8e5c3079 Mon Sep 17 00:00:00 2001 From: Evan Fiordeliso Date: Thu, 16 Nov 2023 23:01:54 -0500 Subject: [PATCH 2/2] Add version option handling --- command.go | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/command.go b/command.go index c42a169..ad6a47c 100644 --- a/command.go +++ b/command.go @@ -9,6 +9,7 @@ import ( type Command struct { Name string + version string ShortDescription string LongDescription string Aliases []string @@ -20,8 +21,8 @@ type Command struct { isRoot bool } -func NewRoot(name string, options ...Option) *Command { - cmd := &Command{Name: name, isRoot: true} +func NewRoot(name string, version string, options ...Option) *Command { + cmd := &Command{Name: name, version: version, isRoot: true} cmd.ApplyOptions(options...) return cmd } @@ -91,6 +92,12 @@ func (c *Command) Execute(args []string) { os.Exit(1) } + versionOpt, ok := opt.Globals().GetBool("version") + if ok && versionOpt.Value() { + c.ShowVersion() + return + } + helpOpt, ok := opt.Globals().GetBool("help") if ok && helpOpt.Value() { c.ShowHelp() @@ -104,3 +111,8 @@ func (c *Command) Execute(args []string) { c.ShowHelp() } + +func (c *Command) ShowVersion() { + rootName := c.Root().Name + fmt.Printf("%s %s\n", rootName, c.version) +}