Repository navigation
Expand file tree
/
Copy pathbases.go
More file actions
456 lines (405 loc) · 13.4 KB
/
Copy pathbases.go
File metadata and controls
456 lines (405 loc) · 13.4 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
package templatebuilder
import (
"bytes"
"embed"
"encoding/json"
"io/fs"
"path"
"strings"
"sync"
"text/template"
"golang.org/x/xerrors"
)
// BaseOS enumerates operating systems for base template filtering.
type BaseOS string
const (
BaseOSLinux BaseOS = "linux"
BaseOSWindows BaseOS = "windows"
)
// validBaseOS maps base.json os strings to their typed equivalents.
var validBaseOS = map[string]BaseOS{
"linux": BaseOSLinux,
"windows": BaseOSWindows,
}
//go:embed bases
var basesFS embed.FS
const basesDir = "bases"
// templateSuffix identifies Go template files that are pre-parsed at load time.
// Terraform templatefile() inputs (.tftpl) are not Go templates and are left
// as raw files in the embedded FS.
const templateSuffix = ".tf.tmpl"
// BaseManifest is the on-disk schema for a base.json file.
type BaseManifest struct {
ID string `json:"id"`
DisplayName string `json:"display_name"`
OS string `json:"os"`
DefaultContext BaseDefaultContext `json:"default_context"`
Variables []ModuleVariable `json:"variables"`
Agents []BaseAgent `json:"agents,omitempty"`
}
// BaseAgent is a coder_agent declared in base.json. Name must match the
// resource label in the base's main.tf.tmpl.
type BaseAgent struct {
Name string `json:"name"`
DisplayName string `json:"display_name,omitempty"`
// Default is the agent modules attach to when they do not name one.
Default bool `json:"default,omitempty"`
}
// BaseDefaultContext holds default render values stored in base.json.
type BaseDefaultContext struct {
ContainerImage string `json:"container_image,omitempty"`
}
// parsedBase holds the result of loading and pre-parsing a single base
// template directory.
type parsedBase struct {
Manifest BaseManifest
Templates map[string]*template.Template
FS fs.FS
Readme string // full README.md content (including frontmatter)
Prerequisites string // content between prerequisite comment markers
ExtraFiles map[string][]byte // non-template, non-manifest files (e.g. .tftpl)
}
var loadBases = sync.OnceValues(func() (map[string]*parsedBase, error) {
return parseBasesFromFS(basesFS)
})
// parseBasesFromFS reads and validates all base.json manifests and pre-parses
// Go template files from the given filesystem. Most callers should use the
// exported accessors, which read from the cached embedded catalog.
func parseBasesFromFS(fsys fs.FS) (map[string]*parsedBase, error) {
sub, err := fs.Sub(fsys, basesDir)
if err != nil {
return nil, xerrors.Errorf("open embedded base catalog: %w", err)
}
dirs, err := fs.ReadDir(sub, ".")
if err != nil {
return nil, xerrors.Errorf("list base catalog entries: %w", err)
}
bases := make(map[string]*parsedBase)
for _, dir := range dirs {
if !dir.IsDir() {
continue
}
base, err := parseBaseDir(sub, dir.Name())
if err != nil {
return nil, err
}
if bases[base.Manifest.ID] != nil {
return nil, xerrors.Errorf("duplicate base id %q", base.Manifest.ID)
}
bases[base.Manifest.ID] = base
}
return bases, nil
}
// parseBaseDir loads a single base template directory: reads the
// manifest, pre-parses Go templates, reads the README, and collects
// extra files.
func parseBaseDir(parent fs.FS, dirName string) (*parsedBase, error) {
manifest, err := parseManifest(parent, dirName)
if err != nil {
return nil, err
}
baseFS, err := fs.Sub(parent, dirName)
if err != nil {
return nil, xerrors.Errorf("sub fs for %s: %w", dirName, err)
}
templates, err := parseTemplatesFromFS(baseFS)
if err != nil {
return nil, xerrors.Errorf("parse templates for base %q: %w", manifest.ID, err)
}
readmeData, err := fs.ReadFile(baseFS, "README.md")
if err != nil {
return nil, xerrors.Errorf("read README.md for base %q: %w", manifest.ID, err)
}
readme := string(readmeData)
extraFiles, err := collectExtraFilesFromFS(baseFS)
if err != nil {
return nil, xerrors.Errorf("collect extra files for base %q: %w", manifest.ID, err)
}
return &parsedBase{
Manifest: manifest,
Templates: templates,
FS: baseFS,
Readme: readme,
Prerequisites: ExtractPrerequisites(readme),
ExtraFiles: extraFiles,
}, nil
}
// parseManifest reads and validates a base.json file from the given
// directory within parent.
func parseManifest(parent fs.FS, dirName string) (BaseManifest, error) {
manifestPath := path.Join(dirName, "base.json")
data, err := fs.ReadFile(parent, manifestPath)
if err != nil {
return BaseManifest{}, xerrors.Errorf("read %s: %w", manifestPath, err)
}
var manifest BaseManifest
dec := json.NewDecoder(bytes.NewReader(data))
dec.DisallowUnknownFields()
if err := dec.Decode(&manifest); err != nil {
return BaseManifest{}, xerrors.Errorf("decode %s: %w", manifestPath, err)
}
if manifest.ID == "" {
return BaseManifest{}, xerrors.Errorf("base in %s has empty id", dirName)
}
if _, ok := validBaseOS[manifest.OS]; !ok && manifest.OS != "" {
return BaseManifest{}, xerrors.Errorf("base %q has unknown os %q", manifest.ID, manifest.OS)
}
if err := validateBaseAgents(manifest); err != nil {
return BaseManifest{}, err
}
return manifest, nil
}
// validateBaseAgents requires a multi-agent base to mark exactly one default,
// so module wiring never depends on base.json array order.
func validateBaseAgents(manifest BaseManifest) error {
seen := make(map[string]bool, len(manifest.Agents))
defaults := 0
for i, a := range manifest.Agents {
if a.Name == "" {
return xerrors.Errorf("base %q agent %d has empty name", manifest.ID, i)
}
if seen[a.Name] {
return xerrors.Errorf("base %q has duplicate agent name %q", manifest.ID, a.Name)
}
seen[a.Name] = true
if a.Default {
defaults++
}
}
if len(manifest.Agents) > 1 && defaults != 1 {
return xerrors.Errorf("base %q declares %d agents but marks %d as default; exactly one required",
manifest.ID, len(manifest.Agents), defaults)
}
return nil
}
// parseTemplatesFromFS walks the filesystem and pre-parses all .tf.tmpl files
// into Go templates. Returned keys are paths relative to the FS root.
func parseTemplatesFromFS(fsys fs.FS) (map[string]*template.Template, error) {
templates := make(map[string]*template.Template)
err := fs.WalkDir(fsys, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() || !strings.HasSuffix(p, templateSuffix) {
return nil
}
raw, err := fs.ReadFile(fsys, p)
if err != nil {
return xerrors.Errorf("read %s: %w", p, err)
}
tmpl, err := template.New(p).Parse(string(raw))
if err != nil {
return xerrors.Errorf("parse %s: %w", p, err)
}
templates[p] = tmpl
return nil
})
if err != nil {
return nil, err
}
return templates, nil
}
// BaseTemplateOS resolves the OS for a given example ID.
// Returns empty string if the example is not a known base template.
func BaseTemplateOS(exampleID string) BaseOS {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return ""
}
return validBaseOS[bases[exampleID].Manifest.OS]
}
// DefaultBaseRenderContext returns the render context that produces the
// canonical default output for a base template.
func DefaultBaseRenderContext(exampleID string) BaseRenderContext {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return BaseRenderContext{}
}
base := bases[exampleID]
dc := base.Manifest.DefaultContext
// Populate Variables from manifest defaults so that Go template
// rendering succeeds even without caller-supplied values.
vars := make(map[string]string, len(base.Manifest.Variables))
for _, v := range base.Manifest.Variables {
if v.Computed || v.Sensitive {
continue
}
if len(v.Default) > 0 && isSimpleJSONValue(v.Default) {
vars[v.Name] = string(v.Default)
}
}
return BaseRenderContext{
ContainerImage: dc.ContainerImage,
RegistryBase: DefaultRegistryBase,
Variables: vars,
}
}
// BaseTemplateIDs returns the set of known base template example IDs.
func BaseTemplateIDs() []string {
bases, err := loadBases()
if err != nil {
return nil
}
ids := make([]string, 0, len(bases))
for id := range bases {
ids = append(ids, id)
}
return ids
}
// BaseVariables returns the user-facing variables for a given base
// template ID. Computed variables are excluded. Returns nil if the
// base is unknown or has no variables.
func BaseVariables(exampleID string) []ModuleVariable {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return nil
}
return bases[exampleID].Manifest.Variables
}
// BaseAgents returns the agents declared in a base's manifest, or nil.
func BaseAgents(exampleID string) []BaseAgent {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return nil
}
return bases[exampleID].Manifest.Agents
}
// BaseDefaultAgentName returns the default agent's name: the one marked
// default, else the first declared. Empty if the base declares none.
func BaseDefaultAgentName(exampleID string) string {
return defaultAgentName(BaseAgents(exampleID))
}
func defaultAgentName(agents []BaseAgent) string {
for _, a := range agents {
if a.Default {
return a.Name
}
}
if len(agents) > 0 {
return agents[0].Name
}
return ""
}
// baseIncludedModules derives, for each base, the catalog module IDs the base
// declares in its own rendered Terraform (e.g. "git-clone"). It renders each
// base's main.tf.tmpl once and extracts the module block labels, caching the
// result. Compose treats these names as occupied so a wizard-selected module
// cannot collide with one the base already renders.
//
// Caveat: derivation uses DefaultBaseRenderContext, so a `module` block gated
// behind a base variable would not be detected. No base declares variables
// today, so this is not currently reachable; revisit if that changes.
var baseIncludedModules = sync.OnceValues(func() (map[string][]string, error) {
bases, err := loadBases()
if err != nil {
return nil, err
}
catalog, err := loadCatalogMap()
if err != nil {
return nil, err
}
out := make(map[string][]string, len(bases))
for id := range bases {
// Only bases that render a main.tf.tmpl can declare modules.
if _, ok := bases[id].Templates["main.tf.tmpl"]; !ok {
continue
}
mainTF, err := RenderBaseTemplate(id, "main.tf.tmpl", DefaultBaseRenderContext(id))
if err != nil {
return nil, xerrors.Errorf("render base %q: %w", id, err)
}
// Keep only catalog-named module blocks: those are the module IDs a
// wizard-selected module could collide with. Non-catalog blocks a base
// renders (e.g. the azure_region helper) are never offered by the
// wizard, so they cannot collide and are not reserved.
var included []string
for _, name := range ExtractModuleNames(mainTF) {
if _, ok := catalog[name]; ok {
included = append(included, name)
}
}
out[id] = included
}
return out, nil
})
// BaseIncludedModules returns the catalog module IDs the given base declares in
// its own rendered Terraform. Returns nil if the base is unknown or declares
// none.
func BaseIncludedModules(exampleID string) []string {
all, err := baseIncludedModules()
if err != nil {
return nil
}
return all[exampleID]
}
// BaseTemplateFS returns a filesystem rooted at the given base template
// directory within the embedded bases catalog. Returns an error if
// exampleID is not a known base template.
func BaseTemplateFS(exampleID string) (fs.FS, error) {
bases, err := loadBases()
if err != nil {
return nil, xerrors.Errorf("load base catalog: %w", err)
}
base, ok := bases[exampleID]
if !ok {
return nil, xerrors.Errorf("unknown base template %q", exampleID)
}
return base.FS, nil
}
// BaseReadme returns the full README.md content for a base template.
// Returns an empty string if the base is unknown or has no README.
func BaseReadme(exampleID string) string {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return ""
}
return bases[exampleID].Readme
}
// BasePrerequisites returns the prerequisites section extracted from
// the base template README. Returns an empty string if the base is
// unknown or has no prerequisites markers.
func BasePrerequisites(exampleID string) string {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return ""
}
return bases[exampleID].Prerequisites
}
// BaseExtraFiles returns the non-template, non-manifest files embedded
// in the base template directory (e.g. cloud-init .tftpl files). Returns
// nil if the base is unknown or has no extra files.
func BaseExtraFiles(exampleID string) map[string][]byte {
bases, err := loadBases()
if err != nil || bases[exampleID] == nil {
return nil
}
return bases[exampleID].ExtraFiles
}
// collectExtraFilesFromFS walks a base template filesystem and returns
// all files that are not Go templates (.tf.tmpl), the manifest
// (base.json), or the README. These are raw files that must be included
// in the output archive (e.g. Terraform templatefile() inputs).
func collectExtraFilesFromFS(baseFS fs.FS) (map[string][]byte, error) {
files := make(map[string][]byte)
err := fs.WalkDir(baseFS, ".", func(p string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
if p == "base.json" || p == "README.md" || strings.HasSuffix(p, ".tf.tmpl") {
return nil
}
data, err := fs.ReadFile(baseFS, p)
if err != nil {
return xerrors.Errorf("read %s: %w", p, err)
}
files[p] = data
return nil
})
if err != nil {
return nil, err
}
return files, nil
}