Change format from JSON to CSV

This commit is contained in:
Illia Volochii 2018-05-01 12:02:44 +03:00
parent 488fd7e82a
commit fa5fe315f8
3 changed files with 12 additions and 28 deletions

View File

@ -94,8 +94,7 @@ $ NUM_WORKERS=4 ./example
Workers: 4
```
You should use a JSON array of strings (value will be converted if
necessary) in the case of multiple values:
You can provide multiple values using the CSV (RFC 4180) format:
```go
var args struct {
@ -106,7 +105,7 @@ fmt.Println("Workers:", args.Workers)
```
```
$ WORKERS='["1", "99"]' ./example
$ WORKERS='1,99' ./example
Workers: [1 99]
```

View File

@ -2,7 +2,7 @@ package arg
import (
"encoding"
"encoding/json"
"encoding/csv"
"errors"
"fmt"
"os"
@ -278,18 +278,12 @@ func process(specs []*spec, args []string) error {
if value, found := os.LookupEnv(spec.env); found {
var err error
if spec.multiple {
// expect a JSON array of strings in an environment
// expect a CSV string in an environment
// variable in the case of multiple values
var values []string
err = json.Unmarshal([]byte(value), &values)
if err != nil {
return fmt.Errorf(
"error processing environment variable %s (it should be a JSON array of strings):\n%v",
spec.env,
err,
)
}
values, err := csv.NewReader(strings.NewReader(value)).Read()
if err == nil {
err = setSlice(spec.dest, values, !spec.separate)
}
} else {
err = scalar.ParseValue(spec.dest, value)
}

View File

@ -584,16 +584,16 @@ func TestEnvironmentVariableSliceArgumentString(t *testing.T) {
var args struct {
Foo []string `arg:"env"`
}
setenv(t, "FOO", "[\"bar\", \"baz\"]")
setenv(t, "FOO", "bar,\"baz, qux\"")
MustParse(&args)
assert.Equal(t, []string{"bar", "baz"}, args.Foo)
assert.Equal(t, []string{"bar", "baz, qux"}, args.Foo)
}
func TestEnvironmentVariableSliceArgumentInteger(t *testing.T) {
var args struct {
Foo []int `arg:"env"`
}
setenv(t, "FOO", "[\"1\", \"99\"]")
setenv(t, "FOO", "1,99")
MustParse(&args)
assert.Equal(t, []int{1, 99}, args.Foo)
}
@ -602,7 +602,7 @@ func TestEnvironmentVariableSliceArgumentFloat(t *testing.T) {
var args struct {
Foo []float32 `arg:"env"`
}
setenv(t, "FOO", "[\"1.1\", \"99.9\"]")
setenv(t, "FOO", "1.1,99.9")
MustParse(&args)
assert.Equal(t, []float32{1.1, 99.9}, args.Foo)
}
@ -611,20 +611,11 @@ func TestEnvironmentVariableSliceArgumentBool(t *testing.T) {
var args struct {
Foo []bool `arg:"env"`
}
setenv(t, "FOO", "[\"true\", \"false\", \"0\", \"1\"]")
setenv(t, "FOO", "true,false,0,1")
MustParse(&args)
assert.Equal(t, []bool{true, false, false, true}, args.Foo)
}
func TestEnvironmentVariableSliceArgumentError(t *testing.T) {
var args struct {
Foo []int `arg:"env"`
}
setenv(t, "FOO", "[1, 99]")
err := Parse(&args)
assert.Error(t, err)
}
type textUnmarshaler struct {
val int
}