Skip to content

Commit

Permalink
Convert []interface{} to []string from plugins (#66)
Browse files Browse the repository at this point in the history
Convert []interface{} from plugins to []string if appropriate.
  • Loading branch information
verygoodsoftwarenotvirus authored and natefinch committed Oct 29, 2017
1 parent a894efd commit 8d67147
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 1 deletion.
31 changes: 30 additions & 1 deletion environ/funcs.go
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,34 @@ func lookUpPlugin(dirs []string, name string) (p string, err error) {
return
}

func convert(v interface{}) interface{} {
if m, ok := v.(map[string]interface{}); ok {
for k, v := range m {
m[k] = convert(v)
}
return m
}

list, ok := v.([]interface{})
if !ok {
return v
}

var str []string
for _, val := range list {
s, ok := val.(string)
if !ok {
var out []interface{}
for _, x := range list {
out = append(out, convert(x))
}
return out
}
str = append(str, s)
}
return str
}

func callPlugin(runner cmdRunner, name, function string, ctx interface{}) (interface{}, error) {
d := make(map[string]interface{})
d["data"] = ctx
Expand All @@ -171,7 +199,8 @@ func callPlugin(runner cmdRunner, name, function string, ctx interface{}) (inter
if err != nil {
return nil, err
}
return o["data"], nil

return convert(o["data"]), nil
}

type cmdRunner func(name string, args ...string) *exec.Cmd
Expand Down
28 changes: 28 additions & 0 deletions environ/funcs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,34 @@ func helperCMD(args ...string) *exec.Cmd {
return cmd
}

func TestConvert(t *testing.T) {
t.Run("ordinary use case", func(t *testing.T) {
expected := []interface{}{"things", "and", "stuff"}

actual, ok := convert(expected).([]string)
if !ok {
t.Error("convert returned an interface that couldn't be converted to []string")
}

for i, s := range expected {
if actual[i] != s {
t.Errorf("expected %s got %s", s, actual[i])
}
}
})

t.Run("early exit", func(t *testing.T) {
expected := []interface{}{"things", nil, "stuff"}
actual := convert(expected).([]interface{})

for i, x := range expected {
if actual[i] != x {
t.Errorf("expected %v got %v", x, actual[i])
}
}
})
}

func TestMain(t *testing.M) {
switch os.Getenv("GO_TEST_ENV") {
case "command":
Expand Down

0 comments on commit 8d67147

Please sign in to comment.