Skip to content

Commit

Permalink
Add opt.GetCommandName to get current command name
Browse files Browse the repository at this point in the history
  • Loading branch information
DavidGamba committed Jun 19, 2024
1 parent e791934 commit 106cbf1
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
36 changes: 36 additions & 0 deletions public_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2266,6 +2266,9 @@ OPTIONS:
if opt.Help() != expectedSynopsis+expectedCommandList+expectedOptionList {
t.Errorf("Unexpected help:\n---\n%s\n---\n", opt.Help())
}
if opt.GetCommandName() != "go-getoptions.test" {
t.Errorf("Unexpected command name: %s", opt.GetCommandName())
}
})

t.Run("", func(t *testing.T) {
Expand Down Expand Up @@ -2913,8 +2916,10 @@ Use 'go-getoptions.test help <command>' for extra details.

t.Run("command", func(t *testing.T) {
called := false
commandName := ""
fn := func(ctx context.Context, opt *getoptions.GetOpt, args []string) error {
called = true
commandName = opt.GetCommandName()
return nil
}
opt := getoptions.New()
Expand All @@ -2931,6 +2936,37 @@ Use 'go-getoptions.test help <command>' for extra details.
if !called {
t.Errorf("Fn not called")
}
if commandName != "command" {
t.Errorf("Unexpected command name: %s", commandName)
}
})

t.Run("sub-command", func(t *testing.T) {
called := false
commandName := ""
fn := func(ctx context.Context, opt *getoptions.GetOpt, args []string) error {
called = true
commandName = opt.GetCommandName()
return nil
}
opt := getoptions.New()
cmd := opt.NewCommand("command", "")
cmd.NewCommand("sub-command", "").SetCommandFn(fn)
opt.HelpCommand("help")
remaining, err := opt.Parse([]string{"command", "sub-command"})
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
err = opt.Dispatch(context.Background(), remaining)
if err != nil {
t.Errorf("Unexpected error: %s", err)
}
if !called {
t.Errorf("Fn not called")
}
if commandName != "sub-command" {
t.Errorf("Unexpected command name: %s", commandName)
}
})

t.Run("command with missing fn", func(t *testing.T) {
Expand Down
5 changes: 5 additions & 0 deletions user.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,11 @@ func (gopt *GetOpt) NewCommand(name string, description string) *GetOpt {
return cmd
}

// GetCommandName - Returns the current command name.
func (gopt *GetOpt) GetCommandName() string {
return gopt.programTree.Name
}

func copyOptionsFromParent(parent *programTree) {
for k, v := range parent.ChildOptions {
for _, command := range parent.ChildCommands {
Expand Down

0 comments on commit 106cbf1

Please sign in to comment.