Skip to content

Commit

Permalink
Merge pull request #153 from alexflint/test-empty-map
Browse files Browse the repository at this point in the history
Fix case where an empty environment variable is parsed in a slice or map
  • Loading branch information
alexflint authored Apr 21, 2021
2 parents 9d937ba + 2e81334 commit 679be43
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 7 deletions.
18 changes: 11 additions & 7 deletions parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,13 +441,17 @@ func (p *Parser) captureEnvVars(specs []*spec, wasPresent map[*spec]bool) error
if spec.cardinality == 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 {
return fmt.Errorf(
"error reading a CSV string from environment variable %s with multiple values: %v",
spec.env,
err,
)
var values []string
var err error
if len(strings.TrimSpace(value)) > 0 {
values, err = csv.NewReader(strings.NewReader(value)).Read()
if err != nil {
return fmt.Errorf(
"error reading a CSV string from environment variable %s with multiple values: %v",
spec.env,
err,
)
}
}
if err = setSliceOrMap(p.val(spec.dest), values, !spec.separate); err != nil {
return fmt.Errorf(
Expand Down
18 changes: 18 additions & 0 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -721,6 +721,15 @@ func TestEnvironmentVariableSliceArgumentString(t *testing.T) {
assert.Equal(t, []string{"bar", "baz, qux"}, args.Foo)
}

func TestEnvironmentVariableSliceEmpty(t *testing.T) {
var args struct {
Foo []string `arg:"env"`
}
_, err := parseWithEnv("", []string{`FOO=`}, &args)
require.NoError(t, err)
assert.Len(t, args.Foo, 0)
}

func TestEnvironmentVariableSliceArgumentInteger(t *testing.T) {
var args struct {
Foo []int `arg:"env"`
Expand Down Expand Up @@ -775,6 +784,15 @@ func TestEnvironmentVariableMap(t *testing.T) {
assert.Equal(t, "ninetynine", args.Foo[99])
}

func TestEnvironmentVariableEmptyMap(t *testing.T) {
var args struct {
Foo map[int]string `arg:"env"`
}
_, err := parseWithEnv("", []string{`FOO=`}, &args)
require.NoError(t, err)
assert.Len(t, args.Foo, 0)
}

func TestEnvironmentVariableIgnored(t *testing.T) {
var args struct {
Foo string `arg:"env"`
Expand Down

0 comments on commit 679be43

Please sign in to comment.