forked from davecgh/go-spew
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
100 lines (83 loc) · 2.06 KB
/
main.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
package main
import (
"bufio"
"flag"
"fmt"
"io"
"io/ioutil"
"os"
"strings"
kew "github.com/goller/kew/pkg"
istiov3 "github.com/weaveworks/flagger/pkg/apis/istio/v1alpha3"
apiextensionsv1beta1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1beta1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/kubernetes/scheme"
)
var (
pkg = flag.String("pkg", "k8s", "go package for output go file")
)
func main() {
flag.Parse()
ymls := flag.Args()
if len(ymls) == 0 {
fmt.Println("yml required")
flag.Usage()
os.Exit(1)
}
for _, file := range ymls {
fmt.Println(file)
f, err := os.Open(file)
if err != nil {
panic(err)
}
r := yaml.NewYAMLReader(bufio.NewReader(f))
objs, err := parse(r)
if err != nil {
panic(err)
}
if err := f.Close(); err != nil {
panic(err)
}
if err := output(file, *pkg, objs); err != nil {
panic(err)
}
}
}
// parse reads the yaml and places all objects into the Resources
func parse(r *yaml.YAMLReader) ([]runtime.Object, error) {
objs := []runtime.Object{}
for {
doc, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
sch := runtime.NewScheme()
scheme.AddToScheme(sch)
sch.AddKnownTypes(apiextensionsv1beta1.SchemeGroupVersion, &apiextensionsv1beta1.CustomResourceDefinition{})
sch.AddKnownTypes(istiov3.SchemeGroupVersion, &istiov3.VirtualService{}, &istiov3.DestinationRule{})
d := serializer.NewCodecFactory(sch).UniversalDeserializer()
obj, _, err := d.Decode(doc, nil, nil)
if err != nil {
return nil, err
}
objs = append(objs, obj)
}
return objs, nil
}
func output(src, pkg string, objs []runtime.Object) error {
converter := kew.NewConfig(pkg)
dump := make([]interface{}, len(objs))
for i := range objs {
dump[i] = objs[i]
}
structs := []string{}
structs = append(structs, converter.Sdump(dump...))
gofile := src + ".go"
fmt.Printf("writing to %s", gofile)
return ioutil.WriteFile(gofile, []byte(strings.Join(structs, "\n")), 0600)
}