Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return first non-empty YAML document when parsing YAML streams #683

Merged
merged 1 commit into from
Nov 16, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 31 additions & 2 deletions data/data.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"bytes"
"encoding/csv"
"encoding/json"
"io"
"strings"

"github.com/joho/godotenv"
Expand Down Expand Up @@ -84,13 +85,41 @@ func JSONArray(in string) ([]interface{}, error) {
// YAML - Unmarshal a YAML Object
func YAML(in string) (map[string]interface{}, error) {
obj := make(map[string]interface{})
return unmarshalObj(obj, in, yaml.Unmarshal)
s := strings.NewReader(in)
d := yaml.NewDecoder(s)
for {
err := d.Decode(&obj)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if obj != nil {
break
}
}
return obj, nil
}

// YAMLArray - Unmarshal a YAML Array
func YAMLArray(in string) ([]interface{}, error) {
obj := make([]interface{}, 1)
return unmarshalArray(obj, in, yaml.Unmarshal)
s := strings.NewReader(in)
d := yaml.NewDecoder(s)
for {
err := d.Decode(&obj)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
if obj != nil {
break
}
}
return obj, nil
}

// TOML - Unmarshal a TOML Object
Expand Down
23 changes: 23 additions & 0 deletions data/data_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ func TestUnmarshalObj(t *testing.T) {
bar: baz
one: 1.0
true: true
`))
test(YAML(`# this comment marks an empty (nil!) document
---
# this one too, for good measure
---
foo:
bar: baz
one: 1.0
true: true
`))

obj := make(map[string]interface{})
Expand Down Expand Up @@ -65,6 +74,20 @@ func TestUnmarshalArray(t *testing.T) {
"42": 18
corge:
"false": blah
`))
test(YAMLArray(`---
# blah blah blah ignore this!
---
- foo
- bar
- baz:
qux: true
quux:
"42": 18
corge:
"false": blah
---
this shouldn't be reached
`))

obj := make([]interface{}, 1)
Expand Down