Skip to content

Commit

Permalink
pkg/encoding/yaml: implement UnmarshalStream
Browse files Browse the repository at this point in the history
Change-Id: I587ef873531e40bf673b0675460a8da87c2a6a50
Signed-off-by: Marcel van Lohuizen <mpvl@golang.org>
Reviewed-on: https://review.gerrithub.io/c/cue-lang/cue/+/532280
Unity-Result: CUEcueckoo <cueckoo@cuelang.org>
TryBot-Result: CUEcueckoo <cueckoo@cuelang.org>
Reviewed-by: Paul Jolly <paul@myitcv.io>
  • Loading branch information
mpvl committed Jan 31, 2022
1 parent 880863a commit 480b28b
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 1 deletion.
24 changes: 23 additions & 1 deletion pkg/encoding/yaml/manual.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,11 +71,33 @@ func MarshalStream(v cue.Value) (string, error) {
return buf.String(), nil
}

// Unmarshal parses the YAML to a CUE instance.
// Unmarshal parses the YAML to a CUE expression.
func Unmarshal(data []byte) (ast.Expr, error) {
return yaml.Unmarshal("", data)
}

// UnmarshalStream parses the YAML to a CUE list expression on success.
func UnmarshalStream(data []byte) (ast.Expr, error) {
d, err := yaml.NewDecoder("", data)
if err != nil {
return nil, err
}

a := []ast.Expr{}
for {
x, err := d.Decode()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
a = append(a, x)
}

return ast.NewList(a...), nil
}

// Validate validates YAML and confirms it is an instance of the schema
// specified by v. If the YAML source is a stream, every object must match v.
func Validate(b []byte, v cue.Value) (bool, error) {
Expand Down
12 changes: 12 additions & 0 deletions pkg/encoding/yaml/pkg.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

25 changes: 25 additions & 0 deletions pkg/encoding/yaml/testdata/gen.txtar
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,20 @@ t6: yaml.ValidatePartial("a: 2\n", {a:<5, b:int})
t7: yaml.MarshalStream([{a: 1}, {b: 2}])
t8: yaml.Marshal({b: int | *2})
t9: yaml.MarshalStream([{a: 1}, {b: int | *2}])

unmarshalStream: {
t1: yaml.UnmarshalStream("a: 1\n---\nb: 2")
t1: yaml.UnmarshalStream('a: 1\n---\nb: 2')
empty: yaml.UnmarshalStream('')
empty: yaml.UnmarshalStream("")
nums: yaml.UnmarshalStream('1\n---\n2')
nums: yaml.UnmarshalStream("1\n---\n2")
null1: yaml.UnmarshalStream('1\n---\n---\n2')
null1: yaml.UnmarshalStream("1\n---\n---\n2")
null2: yaml.UnmarshalStream('1\n---\n---\n2')
null2: yaml.UnmarshalStream("1\n---\n---\n2")
}

-- out/yaml --
Errors:
a: error in call to encoding/yaml.Validate: invalid value 4 (out of bound <3):
Expand Down Expand Up @@ -48,4 +62,15 @@ t9: """
b: 2

"""
unmarshalStream: {
t1: [{
a: 1
}, {
b: 2
}]
empty: []
nums: [1, 2]
null1: [1, null, 2]
null2: [1, null, 2]
}

0 comments on commit 480b28b

Please sign in to comment.