Skip to content

Commit

Permalink
Add a Flags helper to construct SetFlags callbacks.
Browse files Browse the repository at this point in the history
  • Loading branch information
creachadair committed Aug 20, 2023
1 parent 6497f08 commit 221dc2c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
17 changes: 17 additions & 0 deletions adapt_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package command_test

import (
"flag"
"testing"

"github.com/creachadair/command"
Expand Down Expand Up @@ -75,3 +76,19 @@ func TestAdaptErrors(t *testing.T) {
})
}
}

func TestFlags(t *testing.T) {
var got int
c := &command.C{
SetFlags: command.Flags(func(fs *flag.FlagSet, v any) {
fs.IntVar(v.(*int), "test", 1, "Test flag")
}, &got),
Run: func(*command.Env) error { return nil },
}
if err := command.Run(c.NewEnv(nil), []string{"-test", "101", "ok"}); err != nil {
t.Fatalf("Run failed: %v", err)
}
if got != 101 {
t.Errorf("After Run: got %v, want 101", got)
}
}
6 changes: 6 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import (
"strings"
)

// Flags returns a SetFlags function that calls bind(fs, v) with the flag set
// and the given value v.
func Flags(bind func(*flag.FlagSet, any), v any) func(*Env, *flag.FlagSet) {
return func(_ *Env, fs *flag.FlagSet) { bind(fs, v) }
}

// usageLines parses and normalizes usage lines. The command name is stripped
// from the head of each line if it is present.
func (c *C) usageLines() []string {
Expand Down

0 comments on commit 221dc2c

Please sign in to comment.