Skip to content

Commit e84bc1c

Browse files
authored
Merge pull request #6 from onmetal/feature/enhance-reading
Enhance object reading to support JSON & comments
2 parents 4f10ad4 + e0c94d4 commit e84bc1c

File tree

2 files changed

+12
-9
lines changed

2 files changed

+12
-9
lines changed

testdata/objects.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ metadata:
77
stringData:
88
foo: bar
99
---
10+
# The implementation should support comments.
1011
---
1112
apiVersion: v1
1213
kind: ConfigMap

unstructuredutils/unstructuredutils.go

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,14 @@ package unstructuredutils
1717

1818
import (
1919
"bufio"
20+
"bytes"
2021
"errors"
2122
"fmt"
2223
"io"
2324
"os"
24-
"strings"
2525

2626
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
27+
"k8s.io/apimachinery/pkg/runtime"
2728
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
2829
"k8s.io/apimachinery/pkg/util/yaml"
2930
"k8s.io/client-go/kubernetes/scheme"
@@ -44,28 +45,29 @@ func ReadFile(filename string) ([]unstructured.Unstructured, error) {
4445
return Read(f)
4546
}
4647

47-
// Read treats io.Reader as an incoming YAML stream and reads all unstructured.Unstructured objects of it.
48+
// Read treats io.Reader as an incoming YAML or JSON stream and reads all unstructured.Unstructured objects of it.
4849
//
49-
// The YAML has to be well-formed multi-document YAML separated with the separator '---'.
50+
// The document has to be well-formed. For multi-doc YAMLs, '---' is used as separator.
5051
// Empty sub-documents are filtered from the resulting list.
5152
func Read(r io.Reader) ([]unstructured.Unstructured, error) {
52-
rd := yaml.NewYAMLReader(bufio.NewReader(r))
53+
d := yaml.NewYAMLOrJSONDecoder(bufio.NewReader(r), 4096)
5354
var objs []unstructured.Unstructured
5455
for {
55-
data, err := rd.Read()
56-
if err != nil {
56+
ext := runtime.RawExtension{}
57+
if err := d.Decode(&ext); err != nil {
5758
if !errors.Is(io.EOF, err) {
58-
return nil, fmt.Errorf("error reading YAML: %w", err)
59+
return nil, fmt.Errorf("error parsing: %w", err)
5960
}
6061
return objs, nil
6162
}
6263

63-
if strings.TrimSpace(string(data)) == "" {
64+
ext.Raw = bytes.TrimSpace(ext.Raw)
65+
if len(ext.Raw) == 0 || bytes.Equal(ext.Raw, []byte("null")) {
6466
continue
6567
}
6668

6769
obj := &unstructured.Unstructured{}
68-
if _, _, err := scheme.Codecs.UniversalDeserializer().Decode(data, nil, obj); err != nil {
70+
if _, _, err := scheme.Codecs.UniversalDeserializer().Decode(ext.Raw, nil, obj); err != nil {
6971
return nil, fmt.Errorf("invalid object: %w", err)
7072
}
7173

0 commit comments

Comments
 (0)