Skip to content

Commit

Permalink
Merge pull request #683 from hairyhenderson/return-first-non-empty-ya…
Browse files Browse the repository at this point in the history
…ml-doc

Return first non-empty YAML document when parsing YAML streams
  • Loading branch information
hairyhenderson authored Nov 16, 2019
2 parents 4856ec1 + fb6cd4a commit a9fd2b8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 2 deletions.
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

0 comments on commit a9fd2b8

Please sign in to comment.