-
Notifications
You must be signed in to change notification settings - Fork 0
/
reader.go
69 lines (53 loc) · 1.5 KB
/
reader.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package manifest
import (
"bytes"
"errors"
"fmt"
"io"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/dynamic"
"k8s.io/client-go/rest"
"sigs.k8s.io/controller-runtime/pkg/client/apiutil"
)
type Reader struct {
client dynamic.Interface
mapper meta.RESTMapper
}
func NewReader(config *rest.Config) (*Reader, error) {
httpClient, err := rest.HTTPClientFor(config)
if err != nil {
return nil, fmt.Errorf("failed to initialize the manifest reader: %w", err)
}
mapper, err := apiutil.NewDynamicRESTMapper(config, httpClient)
if err != nil {
return nil, fmt.Errorf("failed to initialize the manifest reader: %w", err)
}
client, err := dynamic.NewForConfig(config)
if err != nil {
return nil, fmt.Errorf("failed to initialize the manifest reader: %w", err)
}
return &Reader{client: client, mapper: mapper}, nil
}
func (s *Reader) FromBytes(data []byte) (List, error) {
reader := bytes.NewReader(data)
decoder := yaml.NewYAMLToJSONDecoder(reader)
var resources []*unstructured.Unstructured
var err error
for {
out := &unstructured.Unstructured{}
err = decoder.Decode(out)
if errors.Is(err, io.EOF) {
break
}
if err != nil || len(out.Object) == 0 {
continue
}
resources = append(resources, out)
}
if !errors.Is(err, io.EOF) {
return &list{}, fmt.Errorf("unable to parse manifest from bytes: %w", err)
}
return &list{resources: resources, client: s.client, mapper: s.mapper}, nil
}