-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.go
263 lines (226 loc) · 6.39 KB
/
process.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
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"os"
"path/filepath"
"runtime"
"strings"
"time"
"go.uber.org/zap"
yaml "gopkg.in/yaml.v3"
"helm.sh/helm/v3/pkg/strvals"
)
const (
CommandHelp = "help"
CommandVersion = "version"
CommandLint = "lint"
CommandProcess = "apply"
)
type (
TemplatePayload struct {
Values map[string]interface{}
}
)
var (
templateData TemplatePayload
lintMode = false
)
func run() {
switch opts.Args.Command {
case CommandHelp:
argparser.WriteHelp(os.Stdout)
os.Exit(0)
case CommandVersion:
fmt.Printf("helm-azure-tpl version: %v (%v, %v)\n", gitTag, gitCommit, runtime.Version())
os.Exit(0)
case CommandLint:
logger.Info("enabling lint mode, all functions are in dry mode")
lintMode = true
fallthrough
case CommandProcess:
printAppHeader()
if len(opts.Args.Files) == 0 {
logger.Fatal(`no files specified as arguments`)
}
if err := readValuesFiles(); err != nil {
logger.Fatal(err)
os.Exit(1)
}
templateFileList := buildSourceTargetList()
if !lintMode {
logger.Infof("detecting Azure account information")
fetchAzAccountInfo()
azAccountInfoJson, err := json.Marshal(azAccountInfo)
if err == nil {
logger.Infof(string(azAccountInfoJson))
}
}
for _, templateFile := range templateFileList {
if lintMode {
templateFile.Lint()
} else {
templateFile.Apply()
}
}
logger.With(zap.Duration("duration", time.Since(startTime))).Info("finished")
default:
fmt.Printf("invalid command '%v'\n", opts.Args.Command)
fmt.Println()
argparser.WriteHelp(os.Stdout)
os.Exit(1)
}
}
func printAppHeader() {
logger.Infof("%v v%s (%s; %s; by %v)", argparser.Command.Name, gitTag, gitCommit, runtime.Version(), Author)
logger.Info(string(opts.GetJson()))
}
// borrowed from helm/helm
// https://github.com/helm/helm/blob/main/pkg/cli/values/options.go
// Apache License, Version 2.0
func readValuesFiles() error {
templateData.Values = map[string]interface{}{}
for _, filePath := range opts.AzureTpl.ValuesFiles {
currentMap := map[string]interface{}{}
contextLogger := logger.With(zap.String(`valuesPath`, filePath))
contextLogger.Info("using .Values file")
data, err := os.ReadFile(filePath)
if err != nil {
contextLogger.Fatalf(`unable to read values file: %v`, err)
}
err = yaml.Unmarshal(data, ¤tMap)
if err != nil {
logger.Fatalf("error: %v", err)
}
// Merge with the previous map
templateData.Values = mergeMaps(templateData.Values, currentMap)
}
// User specified a value via --set-json
for _, value := range opts.AzureTpl.JSONValues {
if err := strvals.ParseJSON(value, templateData.Values); err != nil {
return fmt.Errorf(`failed parsing --set-json data %s`, value)
}
}
// User specified a value via --set
for _, value := range opts.AzureTpl.Values {
if err := strvals.ParseInto(value, templateData.Values); err != nil {
return fmt.Errorf(`failed parsing --set data: %w`, err)
}
}
// User specified a value via --set-string
for _, value := range opts.AzureTpl.StringValues {
if err := strvals.ParseIntoString(value, templateData.Values); err != nil {
return fmt.Errorf(`failed parsing --set-string data: %w`, err)
}
}
// User specified a value via --set-file
for _, value := range opts.AzureTpl.FileValues {
reader := func(rs []rune) (interface{}, error) {
bytes, err := os.ReadFile(string(rs))
if err != nil {
return nil, err
}
return string(bytes), err
}
if err := strvals.ParseIntoFile(value, templateData.Values, reader); err != nil {
return fmt.Errorf(`failed parsing --set-file data: %w`, err)
}
}
if opts.Debug {
fmt.Fprintln(os.Stderr)
fmt.Fprintln(os.Stderr, strings.Repeat("-", TermColumns))
fmt.Fprintln(os.Stderr, "--- VALUES")
fmt.Fprintln(os.Stderr, strings.Repeat("-", TermColumns))
values, _ := yaml.Marshal(templateData)
fmt.Fprintln(os.Stderr, string(values))
}
return nil
}
// borrowed from helm/helm
// https://github.com/helm/helm/blob/main/pkg/cli/values/options.go
// Apache License, Version 2.0
func mergeMaps(a, b map[string]interface{}) map[string]interface{} {
out := make(map[string]interface{}, len(a))
for k, v := range a {
out[k] = v
}
for k, v := range b {
if v, ok := v.(map[string]interface{}); ok {
if bv, ok := out[k]; ok {
if bv, ok := bv.(map[string]interface{}); ok {
out[k] = mergeMaps(bv, v)
continue
}
}
}
out[k] = v
}
return out
}
func buildSourceTargetList() (list []TemplateFile) {
ctx := context.Background()
for _, filePath := range opts.Args.Files {
var targetPath string
sourcePath := filePath
// remove protocol prefix (when using helm downloader)
sourcePath = strings.TrimPrefix(sourcePath, "azuretpl://")
sourcePath = strings.TrimPrefix(sourcePath, "azure-tpl://")
if strings.Contains(sourcePath, ":") {
// explicit target path set in argument (source:target)
parts := strings.SplitN(sourcePath, ":", 2)
sourcePath = parts[0]
targetPath = parts[1]
} else {
targetPath = sourcePath
// target not set explicit
if opts.Target.FileExt != nil {
// remove file extension
targetPath = strings.TrimSuffix(targetPath, filepath.Ext(targetPath))
// adds new file extension
targetPath = fmt.Sprintf("%s%s", targetPath, *opts.Target.FileExt)
}
// automatic target path
targetPath = fmt.Sprintf(
"%s%s%s",
opts.Target.Prefix,
targetPath,
opts.Target.Suffix,
)
}
sourcePath = filepath.Clean(sourcePath)
targetPath = filepath.Clean(targetPath)
contextLogger := logger.With(zap.String(`sourcePath`, sourcePath))
if !opts.Stdout {
contextLogger = contextLogger.With(zap.String(`targetPath`, targetPath))
if targetPath == "" || targetPath == "." || targetPath == "/" {
contextLogger.Fatalf(`invalid path '%v' detected`, targetPath)
}
}
if _, err := os.Stat(sourcePath); errors.Is(err, os.ErrNotExist) {
logger.Fatalf(err.Error())
}
var templateBasePath string
if opts.Template.BasePath != nil {
templateBasePath = *opts.Template.BasePath
} else {
if val, err := filepath.Abs(sourcePath); err == nil {
templateBasePath = filepath.Dir(val)
} else {
logger.Fatalf(`unable to resolve file: %v`, err)
}
}
list = append(
list,
TemplateFile{
Context: ctx,
SourceFile: sourcePath,
TargetFile: targetPath,
TemplateBaseDir: templateBasePath,
Logger: contextLogger,
},
)
}
return
}