Skip to content

Commit

Permalink
test FlagSet func
Browse files Browse the repository at this point in the history
  • Loading branch information
koron committed Dec 17, 2024
1 parent c7aa276 commit 038ff14
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions subcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,7 @@ func rootName() string {
return stripExeExt(exe)
}

// FlagSet creates a new flag.FlagSet with name of subcommand.
func FlagSet(ctx context.Context) *flag.FlagSet {
name := strings.Join(Names(ctx), " ")
return flag.NewFlagSet(name, flag.ExitOnError)
Expand Down
31 changes: 31 additions & 0 deletions subcmd_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,3 +174,34 @@ func TestRootSet(t *testing.T) {
t.Errorf("unexpected name: -want +got\n%s", d)
}
}

func TestFlagSet(t *testing.T) {
t.Run("no name", func(t *testing.T) {
ctx := context.Background()
fs := subcmd.FlagSet(ctx)
got := fs.Name()
if got != "" {
t.Errorf("wrong name of FlagSet: got=%q", got)
}
})

t.Run("with names", func(t *testing.T) {
var gotName string
set := subcmd.DefineSet("first", "",
subcmd.DefineSet("second", "",
subcmd.DefineCommand("third", "", func(ctx context.Context, args []string) error {
fs := subcmd.FlagSet(ctx)
gotName = fs.Name()
return nil
}),
),
)
err := subcmd.Run(set, "second", "third")
if err != nil {
t.Fatalf("failed: %s", err)
}
if gotName != "first second third" {
t.Errorf("wrong name of FlagSet: got=%q", gotName)
}
})
}

0 comments on commit 038ff14

Please sign in to comment.