forked from Azure/azure-dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscaffold.go
218 lines (181 loc) · 5.58 KB
/
scaffold.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
package scaffold
import (
"bytes"
"fmt"
"io/fs"
"os"
"path"
"path/filepath"
"slices"
"strings"
"text/template"
"github.com/azure/azure-dev/cli/azd/pkg/osutil"
"github.com/azure/azure-dev/cli/azd/resources"
"github.com/psanford/memfs"
)
const baseRoot = "scaffold/base"
const templateRoot = "scaffold/templates"
// Load loads all templates as a template.Template.
//
// To execute a named template, call Execute with the defined name.
func Load() (*template.Template, error) {
funcMap := template.FuncMap{
"bicepName": BicepName,
"containerAppName": ContainerAppName,
"upper": strings.ToUpper,
"lower": strings.ToLower,
"alphaSnakeUpper": AlphaSnakeUpper,
"formatParam": FormatParameter,
}
t, err := template.New("templates").
Option("missingkey=error").
Funcs(funcMap).
ParseFS(resources.ScaffoldTemplates,
path.Join(templateRoot, "*"))
if err != nil {
return nil, fmt.Errorf("parsing templates: %w", err)
}
return t, nil
}
// Execute applies the template associated with t that has the given name
// to the specified data object and writes the output to the dest path on the filesystem.
func Execute(
t *template.Template,
name string,
data any,
dest string) error {
buf := bytes.NewBufferString("")
err := t.ExecuteTemplate(buf, name, data)
if err != nil {
return fmt.Errorf("executing template: %w", err)
}
err = os.WriteFile(dest, buf.Bytes(), osutil.PermissionFile)
if err != nil {
return fmt.Errorf("writing file: %w", err)
}
return nil
}
func supportingFiles(spec InfraSpec) []string {
files := []string{"/abbreviations.json"}
if len(spec.Services) > 0 {
files = append(files, "/modules/fetch-container-image.bicep")
}
return files
}
// ExecInfra scaffolds infrastructure files for the given spec, using the loaded templates in t. The resulting files
// are written to the target directory.
func ExecInfra(
t *template.Template,
spec InfraSpec,
target string) error {
infraRoot := target
files, err := ExecInfraFs(t, spec)
if err != nil {
return err
}
err = fs.WalkDir(files, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
target := filepath.Join(infraRoot, path)
if err := os.MkdirAll(filepath.Dir(target), osutil.PermissionDirectoryOwnerOnly); err != nil {
return err
}
contents, err := fs.ReadFile(files, path)
if err != nil {
return err
}
return os.WriteFile(target, contents, d.Type().Perm())
})
if err != nil {
return fmt.Errorf("writing infrastructure: %w", err)
}
return nil
}
// ExecInfraFs scaffolds infrastructure files for the given spec, using the loaded templates in t. The resulting files
// are written to the in-memory filesystem.
func ExecInfraFs(
t *template.Template,
spec InfraSpec) (*memfs.FS, error) {
fs := memfs.New()
// Pre-execution expansion. Additional parameters are added, derived from the initial spec.
preExecExpand(&spec)
files := supportingFiles(spec)
err := copyFsToMemFs(resources.ScaffoldBase, fs, baseRoot, ".", files)
if err != nil {
return nil, err
}
err = executeToFS(fs, t, "main.bicep", "main.bicep", spec)
if err != nil {
return nil, fmt.Errorf("scaffolding main.bicep: %w", err)
}
err = executeToFS(fs, t, "resources.bicep", "resources.bicep", spec)
if err != nil {
return nil, fmt.Errorf("scaffolding resources.bicep: %w", err)
}
err = executeToFS(fs, t, "main.parameters.json", "main.parameters.json", spec)
if err != nil {
return nil, fmt.Errorf("scaffolding main.parameters.json: %w", err)
}
return fs, nil
}
func copyFsToMemFs(embedFs fs.FS, targetFs *memfs.FS, root string, target string, files []string) error {
return fs.WalkDir(embedFs, root, func(name string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
targetPath := name[len(root):]
contains := slices.Contains(files, targetPath)
if !contains {
return nil
}
if target != "" {
targetPath = path.Join(target, name[len(root):])
}
if err := targetFs.MkdirAll(filepath.Dir(targetPath), osutil.PermissionDirectory); err != nil {
return err
}
contents, err := fs.ReadFile(embedFs, name)
if err != nil {
return fmt.Errorf("reading file: %w", err)
}
return targetFs.WriteFile(targetPath, contents, osutil.PermissionFile)
})
}
// executeToFS executes the given template with the given name and context, and writes the result to the given path in
// the given target filesystem.
func executeToFS(targetFS *memfs.FS, tmpl *template.Template, name string, path string, context any) error {
buf := bytes.NewBufferString("")
if err := tmpl.ExecuteTemplate(buf, name, context); err != nil {
return fmt.Errorf("executing template: %w", err)
}
if err := targetFS.MkdirAll(filepath.Dir(path), osutil.PermissionDirectory); err != nil {
return fmt.Errorf("creating directory: %w", err)
}
if err := targetFS.WriteFile(path, buf.Bytes(), osutil.PermissionFile); err != nil {
return fmt.Errorf("writing file: %w", err)
}
return nil
}
func preExecExpand(spec *InfraSpec) {
// postgres requires specific password seeding parameters
if spec.DbPostgres != nil {
spec.Parameters = append(spec.Parameters,
Parameter{
Name: "databasePassword",
Value: "$(secretOrRandomPassword ${AZURE_KEY_VAULT_NAME} databasePassword)",
Type: "string",
Secret: true,
})
}
for _, svc := range spec.Services {
// containerapp requires a global '_exist' parameter for each service
spec.Parameters = append(spec.Parameters,
containerAppExistsParameter(svc.Name))
spec.Parameters = append(spec.Parameters,
serviceDefPlaceholder(svc.Name))
}
}