Skip to content

Commit

Permalink
Merge pull request #978 from urfave/context-is-set-fix-v1
Browse files Browse the repository at this point in the history
Context is set fix v1
  • Loading branch information
asahasrabuddhe authored Dec 8, 2019
2 parents 2dab01e + 023bcca commit 78ed70b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 1 deletion.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.coverprofile
node_modules/
vendor
vendor
.idea
8 changes: 8 additions & 0 deletions context.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,14 @@ func (c *Context) IsSet(name string) bool {
for _, f := range flags {
eachName(f.GetName(), func(name string) {
if isSet, ok := c.setFlags[name]; isSet || !ok {
// Check if a flag is set
if isSet {
// If the flag is set, also set its other aliases
eachName(f.GetName(), func(name string) {
c.setFlags[name] = true
})
}

return
}

Expand Down
45 changes: 45 additions & 0 deletions context_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,51 @@ func TestContext_IsSet(t *testing.T) {
expect(t, c.IsSet("myflagGlobal"), false)
}

func TestContext_IsSet_ShortAndFull_FlagNames(t *testing.T) {
var (
numberIsSet, nIsSet bool
tempIsSet, tIsSet bool
usernameIsSet, uIsSet bool
debugIsSet, dIsSet bool
)

a := App {
Flags: []Flag{
IntFlag{Name: "number, n"},
Float64Flag{Name: "temp, t"},
StringFlag{Name: "username, u"},
BoolFlag{Name: "debug, d"},
},
Action: func(ctx *Context) error {
numberIsSet = ctx.IsSet("number")
nIsSet = ctx.IsSet("n")
tempIsSet = ctx.IsSet("temp")
tIsSet = ctx.IsSet("t")
usernameIsSet = ctx.IsSet("username")
uIsSet = ctx.IsSet("u")
debugIsSet = ctx.IsSet("debug")
dIsSet = ctx.IsSet("d")
return nil
},
}

tests := []struct {
args[]string
}{
{args: []string{"", "--number", "5", "--temp", "5.2", "--username", "ajitem", "--debug"}},
{args: []string{"", "-n", "5", "-t", "5.2", "-u", "ajitem", "-d"}},
}

for _, tt := range tests {
_ = a.Run(tt.args)

expect(t, numberIsSet == nIsSet, true)
expect(t, tempIsSet == tIsSet, true)
expect(t, usernameIsSet == uIsSet, true)
expect(t, debugIsSet == dIsSet, true)
}
}

// XXX Corresponds to hack in context.IsSet for flags with EnvVar field
// Should be moved to `flag_test` in v2
func TestContext_IsSet_fromEnv(t *testing.T) {
Expand Down

0 comments on commit 78ed70b

Please sign in to comment.