From 89714b6f48fc2660e3fa633ebb7b86c07ce0da01 Mon Sep 17 00:00:00 2001 From: Illia Volochii Date: Mon, 14 May 2018 22:18:05 +0300 Subject: [PATCH] Fix the problem with errors --- parse.go | 23 ++++++++++++++++------- parse_test.go | 18 ++++++++++++++++++ 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/parse.go b/parse.go index 1b534fd..3c682f5 100644 --- a/parse.go +++ b/parse.go @@ -276,19 +276,28 @@ func process(specs []*spec, args []string) error { } if spec.env != "" { if value, found := os.LookupEnv(spec.env); found { - var err error if spec.multiple { // expect a CSV string in an environment // variable in the case of multiple values values, err := csv.NewReader(strings.NewReader(value)).Read() - if err == nil { - err = setSlice(spec.dest, values, !spec.separate) + if err != nil { + 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 { - err = scalar.ParseValue(spec.dest, value) - } - if err != nil { - return fmt.Errorf("error processing environment variable %s: %v", spec.env, err) + if err := scalar.ParseValue(spec.dest, value); err != nil { + return fmt.Errorf("error processing environment variable %s: %v", spec.env, err) + } } spec.wasPresent = true } diff --git a/parse_test.go b/parse_test.go index 56b2b45..0bc97e3 100644 --- a/parse_test.go +++ b/parse_test.go @@ -616,6 +616,24 @@ func TestEnvironmentVariableSliceArgumentBool(t *testing.T) { 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 { val int }