Fix test cases for context, docs, errors, fish, flags and funcs

This commit is contained in:
Ajitem Sahasrabuddhe 2019-09-15 11:01:20 +05:30
parent f29d98aa2d
commit 2024bed22a
No known key found for this signature in database
GPG Key ID: 782DEBC01D3967A5
16 changed files with 235 additions and 228 deletions

View File

@ -33,6 +33,9 @@ func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
c.Context = parentCtx.Context
c.shellComplete = parentCtx.shellComplete
}
c.Command = &Command{}
if c.Context == nil {
ctx, cancel := context.WithCancel(context.Background())
go func() {
@ -60,12 +63,17 @@ func (c *Context) Set(name, value string) error {
// IsSet determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if fs := lookupFlagSet(name, c); fs != nil {
isSet := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
isSet = true
if fs := lookupFlagSet(name, c); fs != nil {
isSet := false
fs.Visit(func(f *flag.Flag) {
if f.Name == name {
isSet = true
}
})
if isSet {
return true
}
})
}
// XXX hack to support IsSet for flags with EnvVar
//
@ -78,45 +86,28 @@ func (c *Context) IsSet(name string) bool {
// variables is available.
//
// See https://github.com/urfave/cli/issues/294 for additional discussion
flags := c.Command.Flags
if c.Command.Name == "" { // cannot == Command{} since it contains slice types
if c.App != nil {
flags = c.App.Flags
}
f := lookupFlag(name, c)
if f == nil {
return false
}
for _, f := range flags {
for _, name := range f.Names() {
if isSet, ok := c.setFlags[name]; isSet || !ok {
continue
}
val := reflect.ValueOf(f)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
filePathValue := val.FieldByName("FilePath")
if filePathValue.IsValid() {
eachName(filePathValue.String(), func(filePath string) {
if _, err := os.Stat(filePath); err == nil {
c.setFlags[name] = true
return
}
})
}
envVarValues := val.FieldByName("EnvVars")
if envVarValues.IsValid() {
for _, envVar := range envVarValues.Interface().([]string) {
envVar = strings.TrimSpace(envVar)
if _, ok := syscall.Getenv(envVar); ok {
c.setFlags[name] = true
continue
}
}
}
}
val := reflect.ValueOf(f)
if val.Kind() == reflect.Ptr {
val = val.Elem()
}
filePathValue := val.FieldByName("FilePath")
if !filePathValue.IsValid() {
return false
}
envVarValues := val.FieldByName("EnvVars")
if !envVarValues.IsValid() {
return false
}
_, ok := flagFromEnvOrFile(envVarValues.Interface().([]string), filePathValue.Interface().(string))
return ok
}
return false

View File

@ -452,7 +452,7 @@ func TestCheckRequiredFlags(t *testing.T) {
{
testCase: "required_and_present_via_env_var",
flags: []Flag{
&StringFlag{Name: "requiredFlag", Required: true, EnvVar: "REQUIRED_FLAG"},
&StringFlag{Name: "requiredFlag", Required: true, EnvVars: []string{"REQUIRED_FLAG"}},
},
envVarInput: [2]string{"REQUIRED_FLAG", "true"},
},
@ -477,7 +477,7 @@ func TestCheckRequiredFlags(t *testing.T) {
testCase: "required_and_optional_and_optional_present_via_env_var",
flags: []Flag{
&StringFlag{Name: "requiredFlag", Required: true},
&StringFlag{Name: "optionalFlag", EnvVar: "OPTIONAL_FLAG"},
&StringFlag{Name: "optionalFlag", EnvVars: []string{"OPTIONAL_FLAG"}},
},
envVarInput: [2]string{"OPTIONAL_FLAG", "true"},
expectedAnError: true,
@ -519,14 +519,14 @@ func TestCheckRequiredFlags(t *testing.T) {
{
testCase: "required_flag_with_short_name",
flags: []Flag{
&StringSliceFlag{Name: "names, N", Required: true},
&StringSliceFlag{Name: "names", Aliases: []string{"N"}, Required: true},
},
parseInput: []string{"-N", "asd", "-N", "qwe"},
},
{
testCase: "required_flag_with_multiple_short_names",
flags: []Flag{
&StringSliceFlag{Name: "names, N, n", Required: true},
&StringSliceFlag{Name: "names", Aliases: []string{"N", "n"}, Required: true},
},
parseInput: []string{"-n", "asd", "-n", "qwe"},
},
@ -543,12 +543,12 @@ func TestCheckRequiredFlags(t *testing.T) {
os.Clearenv()
_ = os.Setenv(test.envVarInput[0], test.envVarInput[1])
}
ctx := &Context{}
context := NewContext(ctx.App, set, ctx)
context.Command.Flags = test.flags
c := &Context{}
ctx := NewContext(c.App, set, c)
ctx.Command.Flags = test.flags
// logic under test
err := checkRequiredFlags(test.flags, context)
err := checkRequiredFlags(test.flags, ctx)
// assertions
if test.expectedAnError && err == nil {

View File

@ -53,10 +53,9 @@ func (a *App) writeDocTemplate(w io.Writer) error {
})
}
func prepareCommands(commands []Command, level int) []string {
coms := []string{}
for i := range commands {
command := &commands[i]
func prepareCommands(commands []*Command, level int) []string {
var coms []string
for _, command := range commands {
if command.Hidden {
continue
}
@ -110,7 +109,7 @@ func prepareFlags(
continue
}
modifiedArg := opener
for _, s := range strings.Split(flag.GetName(), ",") {
for _, s := range flag.Names() {
trimmed := strings.TrimSpace(s)
if len(modifiedArg) > len(opener) {
modifiedArg += sep

View File

@ -9,39 +9,44 @@ func testApp() *App {
app := NewApp()
app.Name = "greet"
app.Flags = []Flag{
StringFlag{
Name: "socket, s",
&StringFlag{
Name: "socket",
Aliases: []string{"s"},
Usage: "some 'usage' text",
Value: "value",
TakesFile: true,
},
StringFlag{Name: "flag, fl, f"},
BoolFlag{
Name: "another-flag, b",
Usage: "another usage text",
&StringFlag{Name: "flag", Aliases: []string{" fl", "f"}},
&BoolFlag{
Name: "another-flag",
Aliases: []string{"b"},
Usage: "another usage text",
},
}
app.Commands = []Command{{
app.Commands = []*Command{{
Aliases: []string{"c"},
Flags: []Flag{
StringFlag{
Name: "flag, fl, f",
&StringFlag{
Name: "flag",
Aliases: []string{" fl", "f"},
TakesFile: true,
},
BoolFlag{
Name: "another-flag, b",
Usage: "another usage text",
&BoolFlag{
Name: "another-flag",
Aliases: []string{"b"},
Usage: "another usage text",
},
},
Name: "config",
Usage: "another usage test",
Subcommands: []Command{{
Subcommands: []*Command{{
Aliases: []string{"s", "ss"},
Flags: []Flag{
StringFlag{Name: "sub-flag, sub-fl, s"},
BoolFlag{
Name: "sub-command-flag, s",
Usage: "some usage text",
&StringFlag{Name: "sub-flag", Aliases: []string{"sub-fl", "s"}},
&BoolFlag{
Name: "sub-command-flag",
Aliases: []string{"s"},
Usage: "some usage text",
},
},
Name: "sub-config",
@ -59,9 +64,7 @@ func testApp() *App {
}}
app.UsageText = "app [first_arg] [second_arg]"
app.Usage = "Some app"
app.Author = "Harrison"
app.Email = "harrison@lolwut.com"
app.Authors = []Author{{Name: "Oliver Allen", Email: "oliver@toyshop.com"}}
app.Authors = []*Author{{Name: "Harrison", Email: "harrison@lolwut.com"}, {Name: "Oliver Allen", Email: "oliver@toyshop.com"}}
return app
}

View File

@ -59,33 +59,30 @@ type ExitCoder interface {
ExitCode() int
}
type ExitError struct {
type exitError struct {
exitCode int
message interface{}
}
// NewExitError makes a new *ExitError
func NewExitError(message interface{}, exitCode int) *ExitError {
return &ExitError{
exitCode: exitCode,
message: message,
}
// NewExitError makes a new *exitError
func NewExitError(message interface{}, exitCode int) ExitCoder {
return Exit(message, exitCode)
}
// Exit wraps a message and exit code into an ExitCoder suitable for handling by
// HandleExitCoder
func Exit(message interface{}, exitCode int) ExitCoder {
return &ExitError{
return &exitError{
exitCode: exitCode,
message: message,
}
}
func (ee *ExitError) Error() string {
func (ee *exitError) Error() string {
return fmt.Sprintf("%v", ee.message)
}
func (ee *ExitError) ExitCode() int {
func (ee *exitError) ExitCode() int {
return ee.exitCode
}

14
fish.go
View File

@ -64,11 +64,9 @@ func (a *App) writeFishCompletionTemplate(w io.Writer) error {
})
}
func (a *App) prepareFishCommands(commands []Command, allCommands *[]string, previousCommands []string) []string {
func (a *App) prepareFishCommands(commands []*Command, allCommands *[]string, previousCommands []string) []string {
completions := []string{}
for i := range commands {
command := &commands[i]
for _, command := range commands {
if command.Hidden {
continue
}
@ -131,7 +129,7 @@ func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string
fishAddFileFlag(f, completion)
for idx, opt := range strings.Split(flag.GetName(), ",") {
for idx, opt := range flag.Names() {
if idx == 0 {
completion.WriteString(fmt.Sprintf(
" -l %s", strings.TrimSpace(opt),
@ -161,15 +159,15 @@ func (a *App) prepareFishFlags(flags []Flag, previousCommands []string) []string
func fishAddFileFlag(flag Flag, completion *strings.Builder) {
switch f := flag.(type) {
case GenericFlag:
case *GenericFlag:
if f.TakesFile {
return
}
case StringFlag:
case *StringFlag:
if f.TakesFile {
return
}
case StringSliceFlag:
case *StringSliceFlag:
if f.TakesFile {
return
}

View File

@ -49,7 +49,8 @@ var BashCompletionFlag Flag = &BoolFlag{
// VersionFlag prints the version for the application
var VersionFlag Flag = &BoolFlag{
Name: "version, v",
Name: "version",
Aliases: []string{"v"},
Usage: "print the version",
}
@ -57,7 +58,8 @@ var VersionFlag Flag = &BoolFlag{
// Set to nil to disable the flag. The subcommand
// will still be added unless HideHelp is set to true.
var HelpFlag Flag = &BoolFlag{
Name: "help, h",
Name: "help",
Aliases: []string{"h"},
Usage: "show help",
}

View File

@ -78,7 +78,10 @@ func (f *IntFlag) Apply(set *flag.FlagSet) error {
// Int looks up the value of a local IntFlag, returns
// 0 if not found
func (c *Context) Int(name string) int {
return lookupInt(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupInt(name, fs)
}
return 0
}
// GlobalInt looks up the value of a global IntFlag, returns

View File

@ -78,7 +78,10 @@ func (f *Int64Flag) Apply(set *flag.FlagSet) error {
// Int64 looks up the value of a local Int64Flag, returns
// 0 if not found
func (c *Context) Int64(name string) int64 {
return lookupInt64(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupInt64(name, fs)
}
return 0
}
// GlobalInt64 looks up the value of a global Int64Flag, returns

View File

@ -7,7 +7,6 @@ type PathFlag struct {
Aliases []string
Usage string
EnvVars []string
EnvVar string
FilePath string
Required bool
Hidden bool
@ -58,7 +57,7 @@ func (f *PathFlag) Apply(set *flag.FlagSet) error {
for _, name := range f.Names() {
if f.Destination != nil {
set.StringVar(f.Destination, name, f.Value, f.Usage)
return
continue
}
set.String(name, f.Value, f.Usage)
}
@ -69,7 +68,11 @@ func (f *PathFlag) Apply(set *flag.FlagSet) error {
// String looks up the value of a local PathFlag, returns
// "" if not found
func (c *Context) Path(name string) string {
return lookupPath(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupPath(name, fs)
}
return ""
}
func lookupPath(name string, set *flag.FlagSet) string {

View File

@ -8,7 +8,6 @@ type StringFlag struct {
Aliases []string
Usage string
EnvVars []string
EnvVar string
FilePath string
Required bool
Hidden bool
@ -59,7 +58,7 @@ func (s *StringFlag) Apply(set *flag.FlagSet) error {
for _, name := range s.Names() {
if s.Destination != nil {
set.StringVar(s.Destination, name, s.Value, s.Usage)
return
continue
}
set.String(name, s.Value, s.Usage)
}
@ -70,7 +69,10 @@ func (s *StringFlag) Apply(set *flag.FlagSet) error {
// String looks up the value of a local StringFlag, returns
// "" if not found
func (c *Context) String(name string) string {
return lookupString(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupString(name, fs)
}
return ""
}
// GlobalString looks up the value of a global StringFlag, returns

View File

@ -130,7 +130,10 @@ func (f *StringSliceFlag) Apply(set *flag.FlagSet) error {
// StringSlice looks up the value of a local StringSliceFlag, returns
// nil if not found
func (c *Context) StringSlice(name string) []string {
return lookupStringSlice(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupStringSlice(name, fs)
}
return nil
}
// GlobalStringSlice looks up the value of a global StringSliceFlag, returns

View File

@ -24,8 +24,8 @@ var boolFlagTests = []struct {
func TestBoolFlagHelpOutput(t *testing.T) {
for _, test := range boolFlagTests {
flag := &BoolFlag{Name: test.name}
output := flag.String()
fl := &BoolFlag{Name: test.name}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -37,7 +37,7 @@ func TestBoolFlagApply_SetsAllNames(t *testing.T) {
v := false
fl := BoolFlag{Name: "wat", Aliases: []string{"W", "huh"}, Destination: &v}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--wat", "-W", "--huh"})
expect(t, err, nil)
@ -113,16 +113,16 @@ func TestFlagsFromEnv(t *testing.T) {
{"foo,bar", &Parser{"foo", "bar"}, &GenericFlag{Name: "names", Value: &Parser{}, EnvVars: []string{"NAMES"}}, ""},
}
//<<<<<<< HEAD
// for i, test := range flagTests {
// os.Clearenv()
// envVarSlice := reflect.Indirect(reflect.ValueOf(test.flag)).FieldByName("EnvVars").Slice(0, 1)
// os.Setenv(envVarSlice.Index(0).String(), test.input)
//=======
//<<<<<<< HEAD
// for i, test := range flagTests {
// os.Clearenv()
// envVarSlice := reflect.Indirect(reflect.ValueOf(test.flag)).FieldByName("EnvVars").Slice(0, 1)
// os.Setenv(envVarSlice.Index(0).String(), test.input)
//=======
for i, test := range flagTests {
os.Clearenv()
_ = os.Setenv(reflect.ValueOf(test.flag).FieldByName("EnvVar").String(), test.input)
//>>>>>>> master
//>>>>>>> master
a := App{
Flags: []Flag{test.flag},
Action: func(ctx *Context) error {
@ -168,8 +168,8 @@ var stringFlagTests = []struct {
func TestStringFlagHelpOutput(t *testing.T) {
for _, test := range stringFlagTests {
flag := &StringFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: test.value}
output := flag.String()
fl := &StringFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: test.value}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -178,9 +178,9 @@ func TestStringFlagHelpOutput(t *testing.T) {
}
func TestStringFlagDefaultText(t *testing.T) {
flag := &StringFlag{Name: "foo", Aliases: nil, Usage: "amount of `foo` requested", Value: "none", DefaultText: "all of it"}
fl := &StringFlag{Name: "foo", Aliases: nil, Usage: "amount of `foo` requested", Value: "none", DefaultText: "all of it"}
expected := "--foo foo\tamount of foo requested (default: all of it)"
output := flag.String()
output := fl.String()
if output != expected {
t.Errorf("%q does not match %q", output, expected)
@ -193,8 +193,8 @@ func TestStringFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_FOO", "derp")
for _, test := range stringFlagTests {
flag := &StringFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_FOO"}}
output := flag.String()
fl := &StringFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_FOO"}}
output := fl.String()
expectedSuffix := " [$APP_FOO]"
if runtime.GOOS == "windows" {
@ -213,22 +213,22 @@ var prefixStringFlagTests = []struct {
prefixer FlagNamePrefixFunc
expected string
}{
{"foo", "", "", func(a, b string) string {
{"foo", "", "", func(a []string, b string) string {
return fmt.Sprintf("name: %s, ph: %s", a, b)
}, "name: foo, ph: value\t"},
{"f", "", "", func(a, b string) string {
{"f", "", "", func(a []string, b string) string {
return fmt.Sprintf("name: %s, ph: %s", a, b)
}, "name: f, ph: value\t"},
{"f", "The total `foo` desired", "all", func(a, b string) string {
{"f", "The total `foo` desired", "all", func(a []string, b string) string {
return fmt.Sprintf("name: %s, ph: %s", a, b)
}, "name: f, ph: foo\tThe total foo desired (default: \"all\")"},
{"test", "", "Something", func(a, b string) string {
{"test", "", "Something", func(a []string, b string) string {
return fmt.Sprintf("name: %s, ph: %s", a, b)
}, "name: test, ph: value\t(default: \"Something\")"},
{"config,c", "Load configuration from `FILE`", "", func(a, b string) string {
{"config,c", "Load configuration from `FILE`", "", func(a []string, b string) string {
return fmt.Sprintf("name: %s, ph: %s", a, b)
}, "name: config,c, ph: FILE\tLoad configuration from FILE"},
{"config,c", "Load configuration from `CONFIG`", "config.json", func(a, b string) string {
{"config,c", "Load configuration from `CONFIG`", "config.json", func(a []string, b string) string {
return fmt.Sprintf("name: %s, ph: %s", a, b)
}, "name: config,c, ph: CONFIG\tLoad configuration from CONFIG (default: \"config.json\")"},
}
@ -240,8 +240,8 @@ func TestFlagNamePrefixer(t *testing.T) {
for _, test := range prefixStringFlagTests {
FlagNamePrefixer = test.prefixer
flag := StringFlag{Name: test.name, Usage: test.usage, Value: test.value}
output := flag.String()
fl := StringFlag{Name: test.name, Usage: test.usage, Value: test.value}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
}
@ -252,7 +252,7 @@ func TestStringFlagApply_SetsAllNames(t *testing.T) {
v := "mmm"
fl := StringFlag{Name: "hay", Aliases: []string{"H", "hayyy"}, Destination: &v}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--hay", "u", "-H", "yuu", "--hayyy", "YUUUU"})
expect(t, err, nil)
@ -272,9 +272,8 @@ var pathFlagTests = []struct {
func TestPathFlagHelpOutput(t *testing.T) {
for _, test := range pathFlagTests {
flag := &PathFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: test.value}
output := flag.String()
fl := &PathFlag{Name: test.name, Aliases: test.aliases, Usage: test.usage, Value: test.value}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -284,10 +283,10 @@ func TestPathFlagHelpOutput(t *testing.T) {
func TestPathFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_PATH", "/path/to/file")
_ = os.Setenv("APP_PATH", "/path/to/file")
for _, test := range pathFlagTests {
flag := &PathFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_PATH"}}
output := flag.String()
fl := &PathFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_PATH"}}
output := fl.String()
expectedSuffix := " [$APP_PATH]"
if runtime.GOOS == "windows" {
@ -303,7 +302,7 @@ func TestPathFlagApply_SetsAllNames(t *testing.T) {
v := "mmm"
fl := PathFlag{Name: "path", Aliases: []string{"p", "PATH"}, Destination: &v}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--path", "/path/to/file/path", "-p", "/path/to/file/p", "--PATH", "/path/to/file/PATH"})
expect(t, err, nil)
@ -316,16 +315,16 @@ var envHintFlagTests = []struct {
hinter FlagEnvHintFunc
expected string
}{
{"foo", "", func(a, b string) string {
{"foo", "", func(a []string, b string) string {
return fmt.Sprintf("env: %s, str: %s", a, b)
}, "env: , str: --foo value\t"},
{"f", "", func(a, b string) string {
{"f", "", func(a []string, b string) string {
return fmt.Sprintf("env: %s, str: %s", a, b)
}, "env: , str: -f value\t"},
{"foo", "ENV_VAR", func(a, b string) string {
{"foo", "ENV_VAR", func(a []string, b string) string {
return fmt.Sprintf("env: %s, str: %s", a, b)
}, "env: ENV_VAR, str: --foo value\t"},
{"f", "ENV_VAR", func(a, b string) string {
{"f", "ENV_VAR", func(a []string, b string) string {
return fmt.Sprintf("env: %s, str: %s", a, b)
}, "env: ENV_VAR, str: -f value\t"},
}
@ -337,8 +336,8 @@ func TestFlagEnvHinter(t *testing.T) {
for _, test := range envHintFlagTests {
FlagEnvHinter = test.hinter
flag := StringFlag{Name: test.name, EnvVar: test.env}
output := flag.String()
fl := StringFlag{Name: test.name, EnvVars: []string{test.env}}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
}
@ -357,13 +356,12 @@ var stringSliceFlagTests = []struct {
{"f", nil, NewStringSlice("Lipstick"), "-f value\t(default: \"Lipstick\")"},
{"test", nil, NewStringSlice("Something"), "--test value\t(default: \"Something\")"},
{"dee", []string{"d"}, NewStringSlice("Inka", "Dinka", "dooo"), "--dee value, -d value\t(default: \"Inka\", \"Dinka\", \"dooo\")"},
}
func TestStringSliceFlagHelpOutput(t *testing.T) {
for _, test := range stringSliceFlagTests {
flag := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := flag.String()
f := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := f.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -376,8 +374,8 @@ func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_QWWX", "11,4")
for _, test := range stringSliceFlagTests {
flag := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_QWWX"}}
output := flag.String()
fl := &StringSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_QWWX"}}
output := fl.String()
expectedSuffix := " [$APP_QWWX]"
if runtime.GOOS == "windows" {
@ -392,7 +390,7 @@ func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {
func TestStringSliceFlagApply_SetsAllNames(t *testing.T) {
fl := StringSliceFlag{Name: "goat", Aliases: []string{"G", "gooots"}}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--goat", "aaa", "-G", "bbb", "--gooots", "eeeee"})
expect(t, err, nil)
@ -408,8 +406,8 @@ var intFlagTests = []struct {
func TestIntFlagHelpOutput(t *testing.T) {
for _, test := range intFlagTests {
flag := &IntFlag{Name: test.name, Value: 9}
output := flag.String()
fl := &IntFlag{Name: test.name, Value: 9}
output := fl.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
@ -419,12 +417,11 @@ func TestIntFlagHelpOutput(t *testing.T) {
func TestIntFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_BAR", "2")
_ = os.Setenv("APP_BAR", "2")
for _, test := range intFlagTests {
flag := &IntFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := flag.String()
fl := &IntFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := fl.String()
expectedSuffix := " [$APP_BAR]"
if runtime.GOOS == "windows" {
@ -440,7 +437,7 @@ func TestIntFlagApply_SetsAllNames(t *testing.T) {
v := 3
fl := IntFlag{Name: "banana", Aliases: []string{"B", "banannanana"}, Destination: &v}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--banana", "1", "-B", "2", "--banannanana", "5"})
expect(t, err, nil)
@ -457,8 +454,8 @@ var int64FlagTests = []struct {
func TestInt64FlagHelpOutput(t *testing.T) {
for _, test := range int64FlagTests {
flag := Int64Flag{Name: test.name, Value: 8589934592}
output := flag.String()
fl := Int64Flag{Name: test.name, Value: 8589934592}
output := fl.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
@ -471,8 +468,8 @@ func TestInt64FlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_BAR", "2")
for _, test := range int64FlagTests {
flag := IntFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := flag.String()
fl := IntFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := fl.String()
expectedSuffix := " [$APP_BAR]"
if runtime.GOOS == "windows" {
@ -494,8 +491,8 @@ var uintFlagTests = []struct {
func TestUintFlagHelpOutput(t *testing.T) {
for _, test := range uintFlagTests {
flag := UintFlag{Name: test.name, Value: 41}
output := flag.String()
fl := UintFlag{Name: test.name, Value: 41}
output := fl.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
@ -508,8 +505,8 @@ func TestUintFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_BAR", "2")
for _, test := range uintFlagTests {
flag := UintFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := flag.String()
fl := UintFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := fl.String()
expectedSuffix := " [$APP_BAR]"
if runtime.GOOS == "windows" {
@ -531,8 +528,8 @@ var uint64FlagTests = []struct {
func TestUint64FlagHelpOutput(t *testing.T) {
for _, test := range uint64FlagTests {
flag := Uint64Flag{Name: test.name, Value: 8589934582}
output := flag.String()
fl := Uint64Flag{Name: test.name, Value: 8589934582}
output := fl.String()
if output != test.expected {
t.Errorf("%s does not match %s", output, test.expected)
@ -545,8 +542,8 @@ func TestUint64FlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_BAR", "2")
for _, test := range uint64FlagTests {
flag := UintFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := flag.String()
fl := UintFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := fl.String()
expectedSuffix := " [$APP_BAR]"
if runtime.GOOS == "windows" {
@ -568,8 +565,8 @@ var durationFlagTests = []struct {
func TestDurationFlagHelpOutput(t *testing.T) {
for _, test := range durationFlagTests {
flag := &DurationFlag{Name: test.name, Value: 1 * time.Second}
output := flag.String()
fl := &DurationFlag{Name: test.name, Value: 1 * time.Second}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -582,8 +579,8 @@ func TestDurationFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_BAR", "2h3m6s")
for _, test := range durationFlagTests {
flag := &DurationFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := flag.String()
fl := &DurationFlag{Name: test.name, EnvVars: []string{"APP_BAR"}}
output := fl.String()
expectedSuffix := " [$APP_BAR]"
if runtime.GOOS == "windows" {
@ -599,7 +596,7 @@ func TestDurationFlagApply_SetsAllNames(t *testing.T) {
v := time.Second * 20
fl := DurationFlag{Name: "howmuch", Aliases: []string{"H", "whyyy"}, Destination: &v}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--howmuch", "30s", "-H", "5m", "--whyyy", "30h"})
expect(t, err, nil)
@ -619,8 +616,8 @@ var intSliceFlagTests = []struct {
func TestIntSliceFlagHelpOutput(t *testing.T) {
for _, test := range intSliceFlagTests {
flag := &IntSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := flag.String()
fl := &IntSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -633,8 +630,8 @@ func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_SMURF", "42,3")
for _, test := range intSliceFlagTests {
flag := &IntSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_SMURF"}}
output := flag.String()
fl := &IntSliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value, EnvVars: []string{"APP_SMURF"}}
output := fl.String()
expectedSuffix := " [$APP_SMURF]"
if runtime.GOOS == "windows" {
@ -649,7 +646,7 @@ func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {
func TestIntSliceFlagApply_SetsAllNames(t *testing.T) {
fl := IntSliceFlag{Name: "bits", Aliases: []string{"B", "bips"}}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--bits", "23", "-B", "3", "--bips", "99"})
expect(t, err, nil)
@ -669,8 +666,8 @@ var int64SliceFlagTests = []struct {
func TestInt64SliceFlagHelpOutput(t *testing.T) {
for _, test := range int64SliceFlagTests {
flag := Int64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := flag.String()
fl := Int64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -683,8 +680,8 @@ func TestInt64SliceFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_SMURF", "42,17179869184")
for _, test := range int64SliceFlagTests {
flag := Int64SliceFlag{Name: test.name, Value: test.value, EnvVars: []string{"APP_SMURF"}}
output := flag.String()
fl := Int64SliceFlag{Name: test.name, Value: test.value, EnvVars: []string{"APP_SMURF"}}
output := fl.String()
expectedSuffix := " [$APP_SMURF]"
if runtime.GOOS == "windows" {
@ -720,8 +717,8 @@ func TestFloat64FlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_BAZ", "99.4")
for _, test := range float64FlagTests {
flag := &Float64Flag{Name: test.name, EnvVars: []string{"APP_BAZ"}}
output := flag.String()
fl := &Float64Flag{Name: test.name, EnvVars: []string{"APP_BAZ"}}
output := fl.String()
expectedSuffix := " [$APP_BAZ]"
if runtime.GOOS == "windows" {
@ -737,7 +734,7 @@ func TestFloat64FlagApply_SetsAllNames(t *testing.T) {
v := 99.1
fl := Float64Flag{Name: "noodles", Aliases: []string{"N", "nurbles"}, Destination: &v}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--noodles", "1.3", "-N", "11", "--nurbles", "43.33333"})
expect(t, err, nil)
@ -752,14 +749,14 @@ var float64SliceFlagTests = []struct {
}{
{"heads", nil, NewFloat64Slice(), "--heads value\t"},
{"H", nil, NewFloat64Slice(), "-H value\t"},
{"heads", []string{"H"}, NewFloat64Slice(float64(0.1234), float64(-10.5)),
{"heads", []string{"H"}, NewFloat64Slice(0.1234, -10.5),
"--heads value, -H value\t(default: 0.1234, -10.5)"},
}
func TestFloat64SliceFlagHelpOutput(t *testing.T) {
for _, test := range float64SliceFlagTests {
flag := Float64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := flag.String()
fl := Float64SliceFlag{Name: test.name, Aliases: test.aliases, Value: test.value}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -769,10 +766,10 @@ func TestFloat64SliceFlagHelpOutput(t *testing.T) {
func TestFloat64SliceFlagWithEnvVarHelpOutput(t *testing.T) {
os.Clearenv()
os.Setenv("APP_SMURF", "0.1234,-10.5")
_ = os.Setenv("APP_SMURF", "0.1234,-10.5")
for _, test := range float64SliceFlagTests {
flag := Float64SliceFlag{Name: test.name, Value: test.value, EnvVars: []string{"APP_SMURF"}}
output := flag.String()
fl := Float64SliceFlag{Name: test.name, Value: test.value, EnvVars: []string{"APP_SMURF"}}
output := fl.String()
expectedSuffix := " [$APP_SMURF]"
if runtime.GOOS == "windows" {
@ -795,8 +792,8 @@ var genericFlagTests = []struct {
func TestGenericFlagHelpOutput(t *testing.T) {
for _, test := range genericFlagTests {
flag := &GenericFlag{Name: test.name, Value: test.value, Usage: "test flag"}
output := flag.String()
fl := &GenericFlag{Name: test.name, Value: test.value, Usage: "test fl"}
output := fl.String()
if output != test.expected {
t.Errorf("%q does not match %q", output, test.expected)
@ -809,8 +806,8 @@ func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {
_ = os.Setenv("APP_ZAP", "3")
for _, test := range genericFlagTests {
flag := &GenericFlag{Name: test.name, EnvVars: []string{"APP_ZAP"}}
output := flag.String()
fl := &GenericFlag{Name: test.name, EnvVars: []string{"APP_ZAP"}}
output := fl.String()
expectedSuffix := " [$APP_ZAP]"
if runtime.GOOS == "windows" {
@ -825,7 +822,7 @@ func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {
func TestGenericFlagApply_SetsAllNames(t *testing.T) {
fl := GenericFlag{Name: "orbs", Aliases: []string{"O", "obrs"}, Value: &Parser{}}
set := flag.NewFlagSet("test", 0)
fl.Apply(set)
_ = fl.Apply(set)
err := set.Parse([]string{"--orbs", "eleventy,3", "-O", "4,bloop", "--obrs", "19,s"})
expect(t, err, nil)
@ -1424,8 +1421,8 @@ func TestParseBoolShortOptionHandle(t *testing.T) {
return nil
},
Flags: []Flag{
BoolFlag{Name: "serve, s"},
BoolFlag{Name: "option, o"},
&BoolFlag{Name: "serve", Aliases: []string{"s"}},
&BoolFlag{Name: "option", Aliases: []string{"o"}},
},
},
},
@ -1471,7 +1468,7 @@ func TestParseMultiBoolFromEnv(t *testing.T) {
func TestParseMultiBoolFromEnvCascade(t *testing.T) {
os.Clearenv()
os.Setenv("APP_DEBUG", "1")
_ = os.Setenv("APP_DEBUG", "1")
_ = (&App{
Flags: []Flag{
&BoolFlag{Name: "debug", Aliases: []string{"d"}, EnvVars: []string{"COMPAT_DEBUG", "APP_DEBUG"}},
@ -1504,7 +1501,7 @@ func TestParseBoolTFromEnv(t *testing.T) {
_ = os.Setenv("DEBUG", test.input)
_ = (&App{
Flags: []Flag{
BoolTFlag{Name: "debug, d", EnvVar: "DEBUG"},
&BoolFlag{Name: "debug", Aliases: []string{"d"}, Value: true, EnvVars: []string{"DEBUG"}},
},
Action: func(ctx *Context) error {
if ctx.Bool("debug") != test.output {
@ -1521,19 +1518,19 @@ func TestParseBoolTFromEnv(t *testing.T) {
func TestParseMultiBoolT(t *testing.T) {
_ = (&App{
Flags: []Flag{
&BoolFlag{Name: "implode", Aliases: []string{"i"}, Value: true},
},
Action: func(ctx *Context) error {
if ctx.Bool("implode") {
t.Errorf("main name not set")
}
if ctx.Bool("i") {
t.Errorf("short name not set")
}
return nil
},
}).Run([]string{"run", "--implode=false"})
Flags: []Flag{
&BoolFlag{Name: "implode", Aliases: []string{"i"}, Value: true},
},
Action: func(ctx *Context) error {
if ctx.Bool("implode") {
t.Errorf("main name not set")
}
if ctx.Bool("i") {
t.Errorf("short name not set")
}
return nil
},
}).Run([]string{"run", "--implode=false"})
}
func TestParseMultiBoolTFromEnv(t *testing.T) {
@ -1541,13 +1538,13 @@ func TestParseMultiBoolTFromEnv(t *testing.T) {
_ = os.Setenv("APP_DEBUG", "0")
_ = (&App{
Flags: []Flag{
&BoolTFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
&BoolFlag{Name: "debug", Aliases: []string{"d"}, Value: true, EnvVars: []string{"DEBUG"}},
},
Action: func(ctx *Context) error {
if ctx.BoolT("debug") != false {
if ctx.Bool("debug") != false {
t.Errorf("main name not set from env")
}
if ctx.BoolT("d") != false {
if ctx.Bool("d") != false {
t.Errorf("short name not set from env")
}
return nil
@ -1560,13 +1557,13 @@ func TestParseMultiBoolTFromEnvCascade(t *testing.T) {
_ = os.Setenv("APP_DEBUG", "0")
_ = (&App{
Flags: []Flag{
&BoolTFlag{Name: "debug, d", EnvVar: "COMPAT_DEBUG,APP_DEBUG"},
&BoolFlag{Name: "debug", Aliases: []string{"d"}, Value: true, EnvVars: []string{"DEBUG"}},
},
Action: func(ctx *Context) error {
if ctx.BoolT("debug") != false {
if ctx.Bool("debug") != false {
t.Errorf("main name not set from env")
}
if ctx.BoolT("d") != false {
if ctx.Bool("d") != false {
t.Errorf("short name not set from env")
}
return nil
@ -1675,14 +1672,14 @@ func TestFlagFromFile(t *testing.T) {
var filePathTests = []struct {
path string
name string
name []string
expected string
}{
{"file-does-not-exist", "APP_BAR", ""},
{"file-does-not-exist", "APP_FOO", "123"},
{"file-does-not-exist", "APP_FOO,APP_BAR", "123"},
{temp.Name(), "APP_FOO", "123"},
{temp.Name(), "APP_BAR", "abc"},
{"file-does-not-exist", []string{"APP_BAR"}, ""},
{"file-does-not-exist", []string{"APP_FOO"}, "123"},
{"file-does-not-exist", []string{"APP_FOO", "APP_BAR"}, "123"},
{temp.Name(), []string{"APP_FOO"}, "123"},
{temp.Name(), []string{"APP_BAR"}, "abc"},
}
for _, filePathTest := range filePathTests {
@ -1702,7 +1699,7 @@ func TestStringSlice_Serialized_Set(t *testing.T) {
}
sl1 := NewStringSlice("c", "d")
sl1.Set(ser0)
_ = sl1.Set(ser0)
if sl0.String() != sl1.String() {
t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1)
@ -1718,7 +1715,7 @@ func TestIntSlice_Serialized_Set(t *testing.T) {
}
sl1 := NewIntSlice(3, 4)
sl1.Set(ser0)
_ = sl1.Set(ser0)
if sl0.String() != sl1.String() {
t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1)
@ -1734,7 +1731,7 @@ func TestInt64Slice_Serialized_Set(t *testing.T) {
}
sl1 := NewInt64Slice(int64(3), int64(4))
sl1.Set(ser0)
_ = sl1.Set(ser0)
if sl0.String() != sl1.String() {
t.Fatalf("pre and post serialization do not match: %v != %v", sl0, sl1)

View File

@ -79,7 +79,10 @@ func (f *UintFlag) GetValue() string {
// Uint looks up the value of a local UintFlag, returns
// 0 if not found
func (c *Context) Uint(name string) uint {
return lookupUint(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupUint(name, fs)
}
return 0
}
// GlobalUint looks up the value of a global UintFlag, returns

View File

@ -79,7 +79,10 @@ func (f *Uint64Flag) GetValue() string {
// Uint64 looks up the value of a local Uint64Flag, returns
// 0 if not found
func (c *Context) Uint64(name string) uint64 {
return lookupUint64(name, c.flagSet)
if fs := lookupFlagSet(name, c); fs != nil {
return lookupUint64(name, fs)
}
return 0
}
// GlobalUint64 looks up the value of a global Uint64Flag, returns

View File

@ -23,7 +23,7 @@ type CommandNotFoundFunc func(*Context, string)
// is displayed and the execution is interrupted.
type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error
// ExitErrHandlerFunc is executed if provided in order to handle ExitError values
// ExitErrHandlerFunc is executed if provided in order to handle exitError values
// returned by Actions and Before/After functions.
type ExitErrHandlerFunc func(context *Context, err error)