-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwrite.go
60 lines (54 loc) · 1.73 KB
/
write.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
package kubelint
import (
"bytes"
"fmt"
"os"
"regexp"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
"k8s.io/client-go/kubernetes/scheme"
)
// Writes the passed resources to the given file in their YAML representation
// Eg. Resource{*appsv1.Deployment{..}} -> apiVersion: apps/v1\nkind:Deployment\n ...
func WriteToFile(file *os.File, resources ...*Resource) []error {
bytes, errors := Write(resources...)
_, err := file.Write(bytes)
errors = append(errors, err)
return errors
}
// Marshals the given resources, using the YAML separator between resources.
func Write(resources ...*Resource) ([]byte, []error) {
var aggregateBytes []byte
var errors []error
// serialiser tool
serialiser := json.NewYAMLSerializer(json.DefaultMetaFactory, scheme.Scheme, scheme.Scheme)
documentSeparator := []byte("---\n")
for _, resource := range resources {
if o, ok := resource.Object.(runtime.Object); ok {
bytes, err := stripAndWriteBytes(serialiser, o)
if err != nil {
errors = append(errors, err)
continue
}
if len(aggregateBytes) != 0 {
// then you should write up a separator
aggregateBytes = append(aggregateBytes, documentSeparator...)
}
aggregateBytes = append(aggregateBytes, bytes...)
} else {
errors = append(errors, fmt.Errorf("Resource could not be serialised because it doesn't conform to the runtime.Object interface"))
}
}
return aggregateBytes, errors
}
func stripAndWriteBytes(s *json.Serializer, o runtime.Object) ([]byte, error) {
var b bytes.Buffer
err := s.Encode(o, &b)
if err != nil {
return nil, err
}
str := b.String()
re := regexp.MustCompile(" *creationTimestamp: null\n")
cleaned := re.ReplaceAllString(str, "")
return []byte(cleaned), nil
}