@@ -17,13 +17,14 @@ package unstructuredutils
17
17
18
18
import (
19
19
"bufio"
20
+ "bytes"
20
21
"errors"
21
22
"fmt"
22
23
"io"
23
24
"os"
24
- "strings"
25
25
26
26
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
27
+ "k8s.io/apimachinery/pkg/runtime"
27
28
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
28
29
"k8s.io/apimachinery/pkg/util/yaml"
29
30
"k8s.io/client-go/kubernetes/scheme"
@@ -44,28 +45,29 @@ func ReadFile(filename string) ([]unstructured.Unstructured, error) {
44
45
return Read (f )
45
46
}
46
47
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.
48
49
//
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 .
50
51
// Empty sub-documents are filtered from the resulting list.
51
52
func Read (r io.Reader ) ([]unstructured.Unstructured , error ) {
52
- rd := yaml .NewYAMLReader (bufio .NewReader (r ))
53
+ d := yaml .NewYAMLOrJSONDecoder (bufio .NewReader (r ), 4096 )
53
54
var objs []unstructured.Unstructured
54
55
for {
55
- data , err := rd . Read ()
56
- if err != nil {
56
+ ext := runtime. RawExtension {}
57
+ if err := d . Decode ( & ext ); err != nil {
57
58
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 )
59
60
}
60
61
return objs , nil
61
62
}
62
63
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" )) {
64
66
continue
65
67
}
66
68
67
69
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 {
69
71
return nil , fmt .Errorf ("invalid object: %w" , err )
70
72
}
71
73
0 commit comments