This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
104 lines (82 loc) · 2.32 KB
/
utils.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package kubernetes
import (
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"fmt"
"io/ioutil"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/yaml"
"strings"
"encoding/json"
"github.com/integr8ly/operator-sdk-openshift-utils/pkg/api/schemes"
)
var (
scheme = runtime.NewScheme()
codecs = serializer.NewCodecFactory(scheme)
decoderFunc = decoder
)
func init() {
schemes.AddToScheme(scheme)
}
func decoder(gv schema.GroupVersion, codecs serializer.CodecFactory) runtime.Decoder {
codec := codecs.UniversalDecoder(gv)
return codec
}
func runtimeObjectFromUnstructured(u *unstructured.Unstructured) (runtime.Object, error) {
gvk := u.GroupVersionKind()
decoder := decoderFunc(gvk.GroupVersion(), codecs)
b, err := u.MarshalJSON()
if err != nil {
return nil, fmt.Errorf("error running MarshalJSON on unstructured object: %v", err)
}
ro, _, err := decoder.Decode(b, &gvk, nil)
if err != nil {
return nil, fmt.Errorf("failed to decode json data with gvk(%v): %v", gvk.String(), err)
}
return ro, nil
}
func isYaml(filename string) bool {
for _, suffix := range []string{".yaml", "yaml"} {
if strings.HasSuffix(filename, suffix) {
return true
}
}
return false
}
func LoadKubernetesResourceFromFile(path string) (runtime.Object, error) {
data, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
data, err = JsonIfYaml(data, path)
if err != nil {
return nil, err
}
return LoadKubernetesResource(data)
}
func LoadKubernetesResource(jsonData []byte) (runtime.Object, error) {
u := unstructured.Unstructured{}
err := u.UnmarshalJSON(jsonData)
if err != nil {
return nil, err
}
return runtimeObjectFromUnstructured(&u)
}
func JsonIfYaml(source []byte, filename string) ([]byte, error) {
if isYaml(filename) {
return yaml.ToJSON(source)
}
return source, nil
}
func UnstructuredFromRuntimeObject(ro runtime.Object) (*unstructured.Unstructured, error) {
b, err := json.Marshal(ro)
if err != nil {
return nil, fmt.Errorf("error running MarshalJSON on runtime object: %v", err)
}
var u unstructured.Unstructured
if err := json.Unmarshal(b, &u.Object); err != nil {
return nil, fmt.Errorf("failed to unmarshal json into unstructured object: %v", err)
}
return &u, nil
}