Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Flag-level Action #1337

Merged
merged 6 commits into from Sep 22, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
28 changes: 28 additions & 0 deletions app.go
Expand Up @@ -342,6 +342,10 @@ func (a *App) RunContext(ctx context.Context, arguments []string) (err error) {
}
}

if err = runFlagActions(cCtx, a.Flags); err != nil {
return err
}

var c *Command
args := cCtx.Args()
if args.Present() {
Expand Down Expand Up @@ -523,6 +527,10 @@ func (a *App) RunAsSubcommand(ctx *Context) (err error) {
}
}

if err = runFlagActions(cCtx, a.Flags); err != nil {
return err
}

args := cCtx.Args()
if args.Present() {
name := args.First()
Expand Down Expand Up @@ -646,6 +654,26 @@ func (a *App) argsWithDefaultCommand(oldArgs Args) Args {
return oldArgs
}

func runFlagActions(c *Context, fs []Flag) error {
for _, f := range fs {
isSet := false
xwjdsh marked this conversation as resolved.
Show resolved Hide resolved
for _, name := range f.Names() {
if c.IsSet(name) {
isSet = true
break
}
}
if isSet {
if af, ok := f.(ActionableFlag); ok {
if err := af.RunAction(c); err != nil {
return err
}
}
}
}
return nil
}

// Author represents someone who has contributed to a cli project.
type Author struct {
Name string // The Authors name
Expand Down
262 changes: 262 additions & 0 deletions app_test.go
Expand Up @@ -9,8 +9,10 @@ import (
"io/ioutil"
"os"
"reflect"
"strconv"
"strings"
"testing"
"time"
)

var (
Expand Down Expand Up @@ -2357,6 +2359,10 @@ func (c *customBoolFlag) Apply(set *flag.FlagSet) error {
return nil
}

func (c *customBoolFlag) RunAction(*Context) error {
return nil
}

func (c *customBoolFlag) IsSet() bool {
return false
}
Expand Down Expand Up @@ -2576,3 +2582,259 @@ func TestSetupInitializesOnlyNilWriters(t *testing.T) {
t.Errorf("expected a.Writer to be os.Stdout")
}
}

type stringGeneric struct {
value string
}

func (s *stringGeneric) Set(value string) error {
s.value = value
return nil
}

func (s *stringGeneric) String() string {
return s.value
}

func TestFlagAction(t *testing.T) {
stringFlag := &StringFlag{
Name: "f_string",
Action: func(c *Context, v string) error {
c.App.Writer.Write([]byte(v + " "))
return nil
},
}
app := &App{
Name: "app",
Commands: []*Command{
{
Name: "c1",
Flags: []Flag{stringFlag},
Action: func(ctx *Context) error { return nil },
Subcommands: []*Command{
{
Name: "sub1",
Action: func(ctx *Context) error { return nil },
Flags: []Flag{stringFlag},
},
},
},
},
Flags: []Flag{
stringFlag,
&StringSliceFlag{
Name: "f_string_slice",
Action: func(c *Context, v []string) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&BoolFlag{
Name: "f_bool",
Action: func(c *Context, v bool) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%t ", v)))
return nil
},
},
&DurationFlag{
Name: "f_duration",
Action: func(c *Context, v time.Duration) error {
c.App.Writer.Write([]byte(v.String() + " "))
return nil
},
},
&Float64Flag{
Name: "f_float64",
Action: func(c *Context, v float64) error {
c.App.Writer.Write([]byte(strconv.FormatFloat(v, 'f', -1, 64) + " "))
return nil
},
},
&Float64SliceFlag{
Name: "f_float64_slice",
Action: func(c *Context, v []float64) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&GenericFlag{
Name: "f_generic",
Value: new(stringGeneric),
Action: func(c *Context, v interface{}) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&IntFlag{
Name: "f_int",
Action: func(c *Context, v int) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&IntSliceFlag{
Name: "f_int_slice",
Action: func(c *Context, v []int) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&Int64Flag{
Name: "f_int64",
Action: func(c *Context, v int64) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&Int64SliceFlag{
Name: "f_int64_slice",
Action: func(c *Context, v []int64) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&PathFlag{
Name: "f_path",
Action: func(c *Context, v string) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&TimestampFlag{
Name: "f_timestamp",
Layout: "2006-01-02 15:04:05",
Action: func(c *Context, v *time.Time) error {
c.App.Writer.Write([]byte(v.Format(time.RFC3339) + " "))
return nil
},
},
&UintFlag{
Name: "f_uint",
Action: func(c *Context, v uint) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
&Uint64Flag{
Name: "f_uint64",
Action: func(c *Context, v uint64) error {
c.App.Writer.Write([]byte(fmt.Sprintf("%v ", v)))
return nil
},
},
},
Action: func(ctx *Context) error { return nil },
}

tests := []struct {
dearchap marked this conversation as resolved.
Show resolved Hide resolved
name string
args []string
exp string
}{
{
name: "flag_empty",
args: []string{"app"},
exp: "",
},
{
name: "flag_string",
args: []string{"app", "--f_string=string"},
exp: "string ",
},
{
name: "flag_string_slice",
args: []string{"app", "--f_string_slice=s1,s2,s3"},
exp: "[s1 s2 s3] ",
},
{
name: "flag_bool",
args: []string{"app", "--f_bool"},
exp: "true ",
},
{
name: "flag_duration",
args: []string{"app", "--f_duration=1h30m20s"},
exp: "1h30m20s ",
},
{
name: "flag_float64",
args: []string{"app", "--f_float64=3.14159"},
exp: "3.14159 ",
},
{
name: "flag_float64_slice",
args: []string{"app", "--f_float64_slice=1.1,2.2,3.3"},
exp: "[1.1 2.2 3.3] ",
},
{
name: "flag_generic",
args: []string{"app", "--f_generic=1"},
exp: "1 ",
},
{
name: "flag_int",
args: []string{"app", "--f_int=1"},
exp: "1 ",
},
{
name: "flag_int_slice",
args: []string{"app", "--f_int_slice=1,2,3"},
exp: "[1 2 3] ",
},
{
name: "flag_int64",
args: []string{"app", "--f_int64=1"},
exp: "1 ",
},
{
name: "flag_int64_slice",
args: []string{"app", "--f_int64_slice=1,2,3"},
exp: "[1 2 3] ",
},
{
name: "flag_path",
args: []string{"app", "--f_path=/root"},
exp: "/root ",
},
{
name: "flag_timestamp",
args: []string{"app", "--f_timestamp", "2022-05-01 02:26:20"},
exp: "2022-05-01T02:26:20Z ",
},
{
name: "flag_uint",
args: []string{"app", "--f_uint=1"},
exp: "1 ",
},
{
name: "flag_uint64",
args: []string{"app", "--f_uint64=1"},
exp: "1 ",
},
{
name: "command_flag",
args: []string{"app", "c1", "--f_string=c1"},
exp: "c1 ",
},
{
name: "subCommand_flag",
args: []string{"app", "c1", "sub1", "--f_string=sub1"},
exp: "sub1 ",
},
{
name: "mixture",
args: []string{"app", "--f_string=app", "--f_uint=1", "--f_int_slice=1,2,3", "--f_duration=1h30m20s", "c1", "--f_string=c1", "sub1", "--f_string=sub1"},
exp: "app 1h30m20s [1 2 3] 1 c1 sub1 ",
},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
buf := new(bytes.Buffer)
app.Writer = buf
err := app.Run(test.args)
expect(t, err, nil)
expect(t, buf.String(), test.exp)
})
}
}
3 changes: 0 additions & 3 deletions cmd/urfave-cli-genflags/go.sum
@@ -1,5 +1,3 @@
github.com/BurntSushi/toml v1.1.0 h1:ksErzDEI1khOiGPgpwuI7x2ebx/uXQNw7xJpn9Eq1+I=
github.com/BurntSushi/toml v1.1.0/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbicEuybxQ=
github.com/cpuguy83/go-md2man/v2 v2.0.2 h1:p1EgwI/C7NhT0JmVkwCD2ZBK8j4aeHQX2pMHHBfMQ6w=
github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
Expand All @@ -10,7 +8,6 @@ github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673 h1:bAn7/zixMGCfxrRT
github.com/xrash/smetrics v0.0.0-20201216005158-039620a65673/go.mod h1:N3UwUGtsrSj3ccvlPHLoLsHnpR27oXr4ZE984MbSER8=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
Expand Down
4 changes: 4 additions & 0 deletions command.go
Expand Up @@ -165,6 +165,10 @@ func (c *Command) Run(ctx *Context) (err error) {
}
}

if err = runFlagActions(cCtx, c.Flags); err != nil {
return err
}

if c.Action == nil {
c.Action = helpSubcommand.Action
}
Expand Down