-
Notifications
You must be signed in to change notification settings - Fork 29
/
set_namespace.go
124 lines (107 loc) · 2.73 KB
/
set_namespace.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
package chartify
import (
"fmt"
"io"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
// SetNamespace is a poor-man's `kubectl apply -f DIR --dry-run -o yaml --namespace NAMESPACE`
func (r *Runner) SetNamespace(tempDir, ns string) error {
for _, d := range ContentDirs {
a := filepath.Join(tempDir, d)
if err := filepath.Walk(a, func(path string, info os.FileInfo, err error) error {
if _, ok := err.(*os.PathError); ok {
return nil
}
if err != nil || info == nil || info.IsDir() {
return err
}
f, err := os.Open(path)
if err != nil {
return err
}
defer func() {
_ = f.Close()
}()
var docs []yaml.Node
dec := yaml.NewDecoder(f)
for {
doc := yaml.Node{}
if err := dec.Decode(&doc); err != nil {
if err == io.EOF {
break
}
return fmt.Errorf("parsing yaml from %s: %v", path, err)
}
resourceIndex := -1
metadataIndex := -1
namespaceIndex := -1
a := doc.Content[0]
if a.Kind == yaml.MappingNode {
resourceIndex = 0
DOC:
for j := 0; j < len(a.Content); j += 2 {
if a.Content[j].Value == "metadata" {
metadataIndex = j + 1
metadata := a.Content[metadataIndex]
for k := 0; k < len(metadata.Content); k += 2 {
if metadata.Content[k].Value == "namespace" {
namespaceIndex = k + 1
break DOC
}
}
break DOC
}
}
}
if resourceIndex > -1 && metadataIndex > -1 {
c := doc.Content[resourceIndex].Content[metadataIndex].Content
if namespaceIndex > -1 {
// Do not override the namespace when it's already specified,
// to replicate K8s and Helm behavior.
//
//c[namespaceIndex].Value = ns
} else {
c = append(c, &yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: "namespace",
},
&yaml.Node{
Kind: yaml.ScalarNode,
Tag: "!!str",
Value: ns,
},
)
}
doc.Content[resourceIndex].Content[metadataIndex].Content = c
} else {
r.Logf("Skipping %s as it has no resource and metadata. Maybe this is an unconventional chart template file that contains only {{ define}} blocks but not named _helpers.tpl?", f.Name())
}
docs = append(docs, doc)
}
w, err := os.OpenFile(path, os.O_TRUNC|os.O_WRONLY, 0644)
if err != nil {
return fmt.Errorf("opening file %s: %v", path, err)
}
defer func() {
_ = w.Sync()
}()
defer func() {
_ = w.Close()
}()
enc := yaml.NewEncoder(w)
enc.SetIndent(2)
for _, doc := range docs {
if err := enc.Encode(&doc); err != nil {
return fmt.Errorf("marshaling doc %+v: %v", doc, err)
}
}
return nil
}); err != nil {
return err
}
}
return nil
}