-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
266 lines (194 loc) · 4.79 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package main
import (
"errors"
"fmt"
"io"
"io/fs"
"os"
"os/exec"
"os/signal"
"path/filepath"
"regexp"
"strings"
//"runtime"
"flag"
"syscall"
"github.com/fsnotify/fsnotify"
"gopkg.in/yaml.v3"
)
func template(path, name string) ([]map[string]interface{}, error) {
args := []string{"template"}
if name != "" {
args = append(args, name, path)
} else {
args = append(args, path)
}
args = append(args, flag.Args()...)
cmd := exec.Command("helm", args...)
r, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
cmd.Stderr = os.Stderr
if err := cmd.Start(); err != nil {
return nil, err
}
decoder := yaml.NewDecoder(r)
var manifests []map[string]interface{}
for {
var node yaml.Node
if err := decoder.Decode(&node); errors.Is(err, io.EOF) {
break
} else if err != nil {
return nil, err
}
var m map[string]interface{}
if err := node.Decode(&m); err != nil {
return nil, err
}
// must always have a kind
if m["kind"] == nil || m["apiVersion"] == nil {
continue
}
manifests = append(manifests, m)
}
return manifests, cmd.Wait()
}
func main() {
chart := flag.String("chart", "", "--chart <path to local chart>")
kinds := flag.String("kinds", "", "--kinds <kind of resource to watch> (no shorthands, separated by comma)")
names := flag.String("names", "", "--names <name of resource to watch> (regex, separated by comma)")
releaseName := flag.String("release-name", "", "--release-name <name of release> or use \"-- --generate-name\"")
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s: helm watch --chart <chart> --kinds <kinds> --names <resources> [--release-name [release]] -- [optional args for \"helm template\" command\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
tracking := []string{*chart}
args := flag.Args()
for i := 0; i < len(args); i++ {
if args[i] == "-f" || args[i] == "--values" {
for _, file := range strings.Split(args[i+1], ",") {
tracking = append(tracking, file)
}
break
}
}
if chart == nil {
fmt.Printf("--chart missing\n")
os.Exit(1)
}
if kinds == nil {
fmt.Printf("--kinds missing\n")
os.Exit(1)
}
var kindToName = make(map[string]*regexp.Regexp)
{
kinds := strings.Split(*kinds, ",")
names := strings.Split(*names, ",")
diff := len(kinds) - len(names)
// we don't care about name length being bigger
// last ones will be ignored then
if diff > 0 {
rest := make([]string, diff)
for i := 0; i < diff; i++ {
rest[i] = ".+"
}
names = append(names, rest...)
}
for i, kind := range kinds {
kindToName[kind] = regexp.MustCompile(names[i])
}
}
watcher, err := fsnotify.NewWatcher()
if err != nil {
panic(err)
}
if err := watchAll(watcher, tracking); err != nil {
panic(err)
}
fmt.Printf("watching chart %s for changes, displaying %s/%s\n", *chart, *kinds, *names)
//go func() {
// t := time.NewTicker(time.Second * 5)
// for {
// <-t.C
// runtime.GC()
// }
//}()
sig := make(chan os.Signal, 1)
signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sig
fmt.Println("exiting..")
os.Exit(0)
}()
printManifest(*chart, *releaseName, kindToName)
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if !event.Has(fsnotify.Write) && !event.Has(fsnotify.Create) {
continue
}
fmt.Printf("chart modified, regenerating template for %s/%s\n", *kinds, *names)
fmt.Println("---")
printManifest(*chart, *releaseName, kindToName)
fmt.Println("---")
case err, ok := <-watcher.Errors:
if !ok {
return
}
fmt.Printf("error: %v\n", err)
os.Exit(1)
}
}
}
func printManifest(chartPath, releaseName string, tracking map[string]*regexp.Regexp) {
manifests, err := template(chartPath, releaseName)
if err != nil {
fmt.Printf("error generating manifests: %v\n", err)
return
}
for _, manifest := range manifests {
name := manifest["metadata"].(map[string]interface{})["name"].(string)
for kind, resource := range tracking {
if strings.ToLower(manifest["kind"].(string)) != kind {
continue
}
if !resource.Match([]byte(name)) {
continue
}
output, err := yaml.Marshal(manifest)
if err != nil {
fmt.Printf("invalid YAML: %v\n", err)
break
}
fmt.Println(string(output))
}
}
}
func watchAll(watcher *fsnotify.Watcher, paths []string) error {
var walk fs.WalkDirFunc = func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
watcher.Add(path)
return nil
}
for _, path := range paths {
info, err := os.Stat(path)
if err != nil {
return fmt.Errorf("failed to understand if %s is a file or directory: %v", path, err)
}
if !info.IsDir() {
watcher.Add(path)
continue
}
if err := filepath.WalkDir(path, walk); err != nil {
return err
}
}
return nil
}