Skip to content

Commit

Permalink
add StringLongVar and StringShortVar helpers
Browse files Browse the repository at this point in the history
Add helper functions to avoid repeating the `0` and/or `""`
in the case of `Var` flagset method calls.
  • Loading branch information
lopezator committed Apr 9, 2024
1 parent 4e42878 commit 283cc7d
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
8 changes: 7 additions & 1 deletion command_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,14 +64,16 @@ func TestCommandReset(t *testing.T) {
})

t.Run("second run after reset", func(t *testing.T) {
args := []string{"--config-file=my.conf", "foo", "bar", "-a3", "hello world"}
args := []string{"--config-file=my.conf", "foo", "bar", "-a3", "--dseta=baz", "-tqux", "hello world"}
if err := rootcmd.ParseAndRun(ctx, args); err != nil {
t.Fatalf("second run: %v", err)
}

want := defaults // copy
want.ConfigFile = "my.conf"
want.Alpha = 3
want.Dseta = "baz"
want.Eta = "qux"

compareTestCommandVars(t, want, *testvars)
})
Expand Down Expand Up @@ -107,6 +109,8 @@ func makeTestCommand(t *testing.T) (*ff.Command, *testCommandVars) {
barFlags := ff.NewFlagSet("bar").SetParent(fooFlags)
barFlags.DurationVar(&vars.Delta, 'd', "delta", 3*time.Second, "delta `δ` duration")
barFlags.Float64Var(&vars.Epsilon, 'e', "epsilon", 3.21, "epsilon float")
rootFlags.StringLongVar(&vars.Dseta, "dseta", "dseta", "dseta string")
rootFlags.StringShortVar(&vars.Eta, 't', "eta", "eta string")
barCommand := &ff.Command{
Name: "bar",
Usage: "bar [FLAGS] ...",
Expand All @@ -126,6 +130,8 @@ type testCommandVars struct {
Beta bool
Delta time.Duration
Epsilon float64
Dseta string
Eta string
}

var loremIpsum = strings.TrimSpace(`
Expand Down
10 changes: 10 additions & 0 deletions flag_set.go
Original file line number Diff line number Diff line change
Expand Up @@ -839,6 +839,16 @@ func (fs *FlagSet) StringVar(pointer *string, short rune, long string, def strin
return fs.Value(short, long, ffval.NewValueDefault(pointer, def), usage)
}

// StringShortVar defines a new flag in the flag set, and panics on any error.
func (fs *FlagSet) StringShortVar(pointer *string, short rune, def string, usage string) Flag {
return fs.Value(short, "", ffval.NewValueDefault(pointer, def), usage)
}

// StringLongVar defines a new flag in the flag set, and panics on any error.
func (fs *FlagSet) StringLongVar(pointer *string, long string, def string, usage string) Flag {
return fs.Value(0, long, ffval.NewValueDefault(pointer, def), usage)
}

// String defines a new flag in the flag set, and panics on any error.
func (fs *FlagSet) String(short rune, long string, def string, usage string) *string {
var value string
Expand Down

0 comments on commit 283cc7d

Please sign in to comment.