Merge pull request #597 from urfave/fix-isset-for-env

Fix context.IsSet()
main
Jesse Szwedko 8 years ago committed by GitHub
commit 61c3eb6ba1

@ -78,7 +78,7 @@ func (c *Context) IsSet(name string) bool {
for _, envVar := range envVarValues.Interface().([]string) { for _, envVar := range envVarValues.Interface().([]string) {
envVar = strings.TrimSpace(envVar) envVar = strings.TrimSpace(envVar)
if envVal := os.Getenv(envVar); envVal != "" { if envVal := os.Getenv(envVar); envVal != "" {
continue return true
} }
} }

@ -2,6 +2,7 @@ package cli
import ( import (
"flag" "flag"
"os"
"sort" "sort"
"testing" "testing"
"time" "time"
@ -157,6 +158,68 @@ func TestContext_IsSet(t *testing.T) {
expect(t, ctx.IsSet("bogus"), false) expect(t, ctx.IsSet("bogus"), false)
} }
// 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) {
var (
timeoutIsSet, tIsSet, noEnvVarIsSet, nIsSet bool
globalTimeoutIsSet, TIsSet, globalNoEnvVarIsSet, NIsSet bool
)
os.Clearenv()
os.Setenv("GLOBAL_APP_TIMEOUT_SECONDS", "15.5")
os.Setenv("APP_TIMEOUT_SECONDS", "15.5")
a := App{
Flags: []Flag{
&Float64Flag{
Name: "global-timeout",
Aliases: []string{"T"},
EnvVars: []string{"GLOBAL_APP_TIMEOUT_SECONDS"},
},
&Float64Flag{
Name: "global-no-env-var",
Aliases: []string{"N"},
},
},
Commands: []*Command{
{
Name: "hello",
Flags: []Flag{
&Float64Flag{
Name: "timeout",
Aliases: []string{"t"},
EnvVars: []string{"APP_TIMEOUT_SECONDS"},
},
&Float64Flag{
Name: "no-env-var",
Aliases: []string{"n"},
},
},
Action: func(ctx *Context) error {
globalTimeoutIsSet = ctx.IsSet("global-timeout")
TIsSet = ctx.IsSet("T")
globalNoEnvVarIsSet = ctx.IsSet("global-no-env-var")
NIsSet = ctx.IsSet("N")
timeoutIsSet = ctx.IsSet("timeout")
tIsSet = ctx.IsSet("t")
noEnvVarIsSet = ctx.IsSet("no-env-var")
nIsSet = ctx.IsSet("n")
return nil
},
},
},
}
a.Run([]string{"run", "hello"})
expect(t, globalTimeoutIsSet, true)
expect(t, TIsSet, true)
expect(t, globalNoEnvVarIsSet, false)
expect(t, NIsSet, false)
expect(t, timeoutIsSet, true)
expect(t, tIsSet, true)
expect(t, noEnvVarIsSet, false)
expect(t, nIsSet, false)
}
func TestContext_NumFlags(t *testing.T) { func TestContext_NumFlags(t *testing.T) {
set := flag.NewFlagSet("test", 0) set := flag.NewFlagSet("test", 0)
set.Bool("myflag", false, "doc") set.Bool("myflag", false, "doc")

Loading…
Cancel
Save