-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
marshall.go
80 lines (71 loc) · 1.91 KB
/
marshall.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
package v1alpha1
import (
"encoding/json"
"fmt"
"io/ioutil"
"path/filepath"
"sigs.k8s.io/yaml"
)
// MustUnmarshal is a utility function to unmarshall either a file, byte array, or string of JSON or YAMl into a object.
// text - a byte array or string, if starts with "@" it assumed to be a file and read from disk, is starts with "{" assumed to be JSON, otherwise assumed to be YAML
// v - a pointer to an object
func MustUnmarshal(text, v interface{}) {
switch x := text.(type) {
case string:
MustUnmarshal([]byte(x), v)
case []byte:
if len(x) == 0 {
panic("no text to unmarshal")
}
if x[0] == '@' {
filename := string(x[1:])
y, err := ioutil.ReadFile(filepath.Clean(filename))
if err != nil {
panic(fmt.Errorf("failed to read file %s: %w", filename, err))
}
MustUnmarshal(y, v)
} else if x[0] == '{' {
if err := json.Unmarshal(x, v); err != nil {
panic(fmt.Errorf("failed to unmarshal JSON %q: %w", string(x), err))
}
} else {
if err := yaml.UnmarshalStrict(x, v); err != nil {
panic(fmt.Errorf("failed to unmarshal YAML %q: %w", string(x), err))
}
}
default:
panic(fmt.Errorf("cannot unmarshal type %T", text))
}
}
func MustMarshallJSON(v interface{}) string {
data, err := json.Marshal(v)
if err != nil {
panic(err)
}
return string(data)
}
func MustUnmarshalClusterWorkflow(text interface{}) *ClusterWorkflowTemplate {
x := &ClusterWorkflowTemplate{}
MustUnmarshal(text, &x)
return x
}
func MustUnmarshalCronWorkflow(text interface{}) *CronWorkflow {
x := &CronWorkflow{}
MustUnmarshal(text, &x)
return x
}
func MustUnmarshalTemplate(text interface{}) *Template {
x := &Template{}
MustUnmarshal(text, &x)
return x
}
func MustUnmarshalWorkflow(text interface{}) *Workflow {
x := &Workflow{}
MustUnmarshal(text, &x)
return x
}
func MustUnmarshalWorkflowTemplate(text interface{}) *WorkflowTemplate {
x := &WorkflowTemplate{}
MustUnmarshal(text, &x)
return x
}