Fix the problem with errors

This commit is contained in:
Illia Volochii 2018-05-14 22:18:05 +03:00
parent fa5fe315f8
commit 89714b6f48
2 changed files with 34 additions and 7 deletions

View File

@ -276,19 +276,28 @@ func process(specs []*spec, args []string) error {
} }
if spec.env != "" { if spec.env != "" {
if value, found := os.LookupEnv(spec.env); found { if value, found := os.LookupEnv(spec.env); found {
var err error
if spec.multiple { if spec.multiple {
// expect a CSV string in an environment // expect a CSV string in an environment
// variable in the case of multiple values // variable in the case of multiple values
values, err := csv.NewReader(strings.NewReader(value)).Read() values, err := csv.NewReader(strings.NewReader(value)).Read()
if err == nil { if err != nil {
err = setSlice(spec.dest, values, !spec.separate) return fmt.Errorf(
"error reading a CSV string from environment variable %s with multiple values: %v",
spec.env,
err,
)
}
if err = setSlice(spec.dest, values, !spec.separate); err != nil {
return fmt.Errorf(
"error processing environment variable %s with multiple values: %v",
spec.env,
err,
)
} }
} else { } else {
err = scalar.ParseValue(spec.dest, value) if err := scalar.ParseValue(spec.dest, value); err != nil {
} return fmt.Errorf("error processing environment variable %s: %v", spec.env, err)
if err != nil { }
return fmt.Errorf("error processing environment variable %s: %v", spec.env, err)
} }
spec.wasPresent = true spec.wasPresent = true
} }

View File

@ -616,6 +616,24 @@ func TestEnvironmentVariableSliceArgumentBool(t *testing.T) {
assert.Equal(t, []bool{true, false, false, true}, args.Foo) assert.Equal(t, []bool{true, false, false, true}, args.Foo)
} }
func TestEnvironmentVariableSliceArgumentWrongCsv(t *testing.T) {
var args struct {
Foo []int `arg:"env"`
}
setenv(t, "FOO", "1,99\"")
err := Parse(&args)
assert.Error(t, err)
}
func TestEnvironmentVariableSliceArgumentWrongType(t *testing.T) {
var args struct {
Foo []bool `arg:"env"`
}
setenv(t, "FOO", "one,two")
err := Parse(&args)
assert.Error(t, err)
}
type textUnmarshaler struct { type textUnmarshaler struct {
val int val int
} }