-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathchange.go
More file actions
622 lines (546 loc) · 17.4 KB
/
Copy pathchange.go
File metadata and controls
622 lines (546 loc) · 17.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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
// Copyright 2025 Terramate GmbH
// SPDX-License-Identifier: MPL-2.0
package ui
import (
"cmp"
"context"
"fmt"
"os"
"path/filepath"
"reflect"
"regexp"
"slices"
"strings"
"github.com/google/uuid"
hhcl "github.com/terramate-io/hcl/v2"
"github.com/terramate-io/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
"github.com/terramate-io/terramate/config"
"github.com/terramate-io/terramate/errors"
"github.com/terramate-io/terramate/hcl"
"github.com/terramate-io/terramate/hcl/ast"
"github.com/terramate-io/terramate/project"
"github.com/terramate-io/terramate/stdlib"
"github.com/terramate-io/terramate/typeschema"
"github.com/terramate-io/terramate/yaml"
)
// ChangeKind indicates the type of change.
type ChangeKind string
// ChangeCreate and the following constants enumerate the supported change kinds.
const (
ChangeCreate ChangeKind = "change_create"
ChangeReconfig ChangeKind = "change_reconfig"
ChangePromote ChangeKind = "change_promote"
)
// Change represents a bundle change (create, reconfigure, or promote).
type Change struct {
Kind ChangeKind
HostPath string
ProjectPath string
Name string
UUID string
Source string
Alias string
DisplayName string
Metadata config.Metadata
BundleDefEntry *config.BundleDefinitionEntry
InputDefs []*config.InputDefinition // Original input definitions
Values map[string]cty.Value // Collected values at time of creation
Env *config.Environment
FromEnv *config.Environment
OriginalBundle *config.Bundle // Only set for reconfig and promote
OriginalValues map[string]cty.Value // Baseline values from disk (for change detection)
Warnings []string // Non-fatal warnings surfaced after resolving the change
}
// NewCreateChange builds a Change that represents a new bundle creation.
func NewCreateChange(
est *EngineState,
activeEnv *config.Environment,
bde *config.BundleDefinitionEntry,
schemactx typeschema.EvalContext,
inputDefs []*config.InputDefinition,
values map[string]cty.Value,
) (Change, error) {
schemactx = schemactx.ChildContext()
// Rebind bundle() functions to the current registry so that references
// to bundles created during this session (e.g. nested bundles that were
// saved immediately) are resolvable.
schemactx.Evalctx.SetFunction(stdlib.Name("bundle"), config.BundleFunc(context.TODO(), est.Registry.Registry, activeEnv, false))
schemactx.Evalctx.SetFunction(stdlib.Name("bundles"), config.BundlesFunc(est.Registry.Registry, activeEnv))
// The form may or may not contain values for all defaults.
// In this step we re-run input evaluation like it would be done if this was a bundle instance that
// has the form values as inputs. This will ensure we get all the inputs.
allValues, err := reEvalAllInputs(
schemactx,
bde.Tree.HostDir(),
bde.Define,
values,
)
if err != nil {
return Change{}, err
}
// We check if the bundle has an explicit alias and add it to the context if yes.
alias, err := setupExplicitBundleAlias(schemactx.Evalctx, bde.Define)
if err != nil {
return Change{}, err
}
bundleDef, err := config.EvalBundleDefinition(schemactx.Evalctx, bde.Define)
if err != nil {
return Change{}, err
}
outputPath := bundleDef.ScaffoldingPath
if outputPath == "" {
outputPath = extractPseudoString(values, pseudoKeyOutputPath)
}
outputName := bundleDef.ScaffoldingName
if outputName == "" {
outputName = extractPseudoString(values, pseudoKeyOutputName)
}
if outputPath == "" {
return Change{}, errors.E("Bundle path is not set.")
}
if outputName == "" {
return Change{}, errors.E("Bundle name is not set.")
}
var hostPath string
var projPath string
if filepath.IsAbs(outputPath) {
hostPath = project.NewPath(outputPath).HostPath(est.Root.HostDir())
projPath = outputPath
} else {
hostPath = filepath.Join(est.WorkingDir, outputPath)
projPath = project.PrjAbsPath(est.Root.HostDir(), hostPath).String()
}
hostPath = fixupFileExtension("yaml", hostPath)
// If there is no explicit alias, we fallback to the <path>:<name> default.
// But we must do this only after these values are known.
// If there was an explicit alias, it can actually be used in path and name.
// Sounds circular but it isn't...
if alias == "" {
alias = fmt.Sprintf("%s:%s", filepath.Dir(outputPath), outputName)
}
var env *config.Environment
if activeEnv != nil && bundleRequiresEnv(schemactx.Evalctx, bde.Define) {
env = activeEnv
}
// Final check: Is the bundle unique?
if err := est.Registry.IsBundleUnique(alias, bde.Metadata.Class, hostPath, env); err != nil {
return Change{}, err
}
return Change{
Kind: ChangeCreate,
HostPath: hostPath,
ProjectPath: projPath,
Name: outputName,
UUID: uuid.NewString(),
Source: bde.Source,
Env: env,
Alias: alias,
DisplayName: displayNameFromAlias(alias, outputName),
Metadata: *bde.Metadata,
BundleDefEntry: bde,
InputDefs: inputDefs,
Values: allValues,
}, nil
}
// NewReconfigChange builds a Change that represents reconfiguring an existing bundle.
func NewReconfigChange(
est *EngineState,
bundle *config.Bundle,
bde *config.BundleDefinitionEntry,
schemactx typeschema.EvalContext,
inputDefs []*config.InputDefinition,
values map[string]cty.Value,
) (Change, error) {
schemactx = schemactx.ChildContext()
// Rebind bundle() functions to the current registry so that references
// to bundles created/reconfigured during this session are resolvable.
schemactx.Evalctx.SetFunction(stdlib.Name("bundle"), config.BundleFunc(context.TODO(), est.Registry.Registry, bundle.Environment, false))
schemactx.Evalctx.SetFunction(stdlib.Name("bundles"), config.BundlesFunc(est.Registry.Registry, bundle.Environment))
hostPath := bundle.Info.HostPath()
projPath := project.PrjAbsPath(est.Root.HostDir(), hostPath).String()
// The form may or may not contain values for all defaults.
// In this step we re-run input evaluation like it would be done if this was a bundle instance that
// has the form values as inputs. This will ensure we get all the inputs.
allValues, err := reEvalAllInputs(
schemactx,
hostPath,
bde.Define,
values,
)
if err != nil {
return Change{}, err
}
// This will only be set if there is an explicit alias.
newAlias, err := setupExplicitBundleAlias(schemactx.Evalctx, bde.Define)
if err != nil {
return Change{}, err
}
var warnings []string
if bundle.Alias != "" && newAlias != "" && bundle.Alias != newAlias {
warnings = append(warnings, fmt.Sprintf("Alias will change from %q to %q", bundle.Alias, newAlias))
}
// The alias can change, if it's an explicit alias. If it's the implicit alias,
// it just remains path:name since neither will change.
var alias, displayName string
if newAlias == "" {
alias = bundle.Alias
displayName = bundle.Name
} else {
alias = newAlias
displayName = newAlias
}
return Change{
Kind: ChangeReconfig,
HostPath: hostPath,
ProjectPath: projPath,
Name: bundle.Name,
UUID: bundle.UUID,
Source: bundle.Source,
Env: bundle.Environment,
Alias: alias,
DisplayName: displayName,
Metadata: bundle.DefinitionMetadata,
BundleDefEntry: bde,
InputDefs: inputDefs,
Values: allValues,
OriginalBundle: bundle,
OriginalValues: inputsToValueMap(bundle.Inputs),
Warnings: warnings,
}, nil
}
// NewPromoteChange builds a Change that represents promoting a bundle to another environment.
func NewPromoteChange(
est *EngineState,
env *config.Environment,
bundle *config.Bundle,
bde *config.BundleDefinitionEntry,
schemactx typeschema.EvalContext,
inputDefs []*config.InputDefinition,
values map[string]cty.Value,
) (Change, error) {
schemactx = schemactx.ChildContext()
// Rebind bundle() functions to the current registry so that references
// to bundles promoted during this session are resolvable.
schemactx.Evalctx.SetFunction(stdlib.Name("bundle"), config.BundleFunc(context.TODO(), est.Registry.Registry, env, false))
schemactx.Evalctx.SetFunction(stdlib.Name("bundles"), config.BundlesFunc(est.Registry.Registry, env))
hostPath := bundle.Info.HostPath()
projPath := project.PrjAbsPath(est.Root.HostDir(), hostPath).String()
// The form may or may not contain values for all defaults.
// In this step we re-run input evaluation like it would be done if this was a bundle instance that
// has the form values as inputs. This will ensure we get all the inputs.
allValues, err := reEvalAllInputs(
schemactx,
hostPath,
bde.Define,
values,
)
if err != nil {
return Change{}, wrapMissingBundleRefError(err)
}
// This will only be set if there is an explicit alias.
newAlias, err := setupExplicitBundleAlias(schemactx.Evalctx, bde.Define)
if err != nil {
return Change{}, wrapMissingBundleRefError(err)
}
var warnings []string
if bundle.Alias != "" && newAlias != "" && bundle.Alias != newAlias {
warnings = append(warnings, fmt.Sprintf("Alias will change from %q to %q", bundle.Alias, newAlias))
}
// The alias can change, if it's an explicit alias. If it's the implicit alias,
// it just remains path:name since neither will change.
var alias, displayName string
if newAlias == "" {
alias = bundle.Alias
displayName = bundle.Name
} else {
alias = newAlias
displayName = newAlias
}
return Change{
Kind: ChangePromote,
HostPath: hostPath,
ProjectPath: projPath,
Name: bundle.Name,
UUID: bundle.UUID,
Source: bundle.Source,
Env: env,
FromEnv: bundle.Environment,
Alias: alias,
DisplayName: displayName,
Metadata: bundle.DefinitionMetadata,
BundleDefEntry: bde,
InputDefs: inputDefs,
Values: allValues,
OriginalBundle: bundle,
OriginalValues: inputsToValueMap(bundle.Inputs),
Warnings: warnings,
}, nil
}
// reEvalAllInputs evaluates the bundle's input definitions using the prompted
// values as a simulated inputs block, filling in defaults for any inputs that
// were not prompted.
func reEvalAllInputs(
schemactx typeschema.EvalContext,
filename string,
defineBundleHCL *hcl.DefineBundle,
values map[string]cty.Value,
) (map[string]cty.Value, error) {
inst := &hcl.Bundle{
Inputs: ast.NewMergedBlock("inputs", []string{}),
}
for k, v := range values {
if v == cty.NilVal || isPseudoKey(k) {
continue
}
r := hhcl.Range{
Filename: filename,
}
inst.Inputs.Attributes[k] = ast.NewAttribute(filename,
&hhcl.Attribute{
Name: k,
Expr: &hclsyntax.LiteralValueExpr{Val: v},
Range: r,
})
}
tempInputs, err := config.EvalInputs(
schemactx,
"bundle",
inst.Info,
inst.Inputs,
inst.InputsAttr,
defineBundleHCL.Inputs,
)
if err != nil {
return nil, err
}
result := make(map[string]cty.Value, len(values))
for k, v := range values {
if v != cty.NilVal {
result[k] = v
}
}
for k, v := range tempInputs {
if _, exists := result[k]; exists {
continue
}
vm := v.AsValueMap()
result[k] = vm["value"]
}
return result, nil
}
// wrapMissingBundleRefError adds a user-friendly message when a promote/reconfigure
// fails because a referenced bundle doesn't exist in the target environment.
// Detects the HCL error pattern for accessing attributes on a null value.
func wrapMissingBundleRefError(err error) error {
msg := err.Error()
if strings.Contains(msg, "This value is null") || strings.Contains(msg, "does not have any attributes") {
return errors.E(err, "A referenced bundle has not been promoted to this environment yet. Promote dependencies first.")
}
return err
}
// Save writes the change to disk as a YAML bundle instance file.
func (c *Change) Save(envs []*config.Environment) error {
var existing *yaml.BundleInstance
_, err := os.Stat(c.HostPath)
overwrite := err == nil
// If the change doesn't have an env, the bundle doesn't have envs, so no need for merging.
if overwrite && c.Env != nil {
var err error
existing, err = loadBundleYAMLConfig(c.HostPath)
if err != nil {
return err
}
}
content, err := c.generateBundleYAML(existing, envs)
if err != nil {
return err
}
return writeBundleInstance(c.HostPath, content)
}
func (c *Change) generateBundleYAML(existing *yaml.BundleInstance, envs []*config.Environment) (string, error) {
inputs := yaml.Map[any]{}
for _, def := range c.InputDefs {
if isPseudoKey(def.Name) {
continue
}
v, found := c.Values[def.Name]
if !found {
continue
}
// Bundle-ref values are stored as resolved objects internally
// but must be written as alias strings in the YAML config.
if _, isBundleType := def.Type.(*typeschema.BundleType); isBundleType {
if v.IsKnown() && !v.IsNull() && v.Type().IsObjectType() && v.Type().HasAttribute("alias") {
v = v.GetAttr("alias")
}
}
yv, err := yaml.ConvertFromCty(v)
if err != nil {
return "", err
}
inputs = append(inputs, yaml.MapItem[any]{
Key: yaml.Attr(def.Name, 0, 0, formatTmdoc(def.Description)),
Value: yaml.Attr(yv),
})
}
var envID string
if c.Env != nil {
envID = c.Env.ID
}
if c.UUID == "" {
c.UUID = uuid.NewString()
}
var bundle yaml.BundleInstance
if envID != "" {
envBlock := &yaml.BundleEnvironment{
Source: yaml.Attr[any](c.Source),
Inputs: yaml.Attr(inputs),
}
if existing != nil {
bundle = mergeBundleYAMLEnv(*existing, envID, envBlock, envs)
} else {
bundle = yaml.BundleInstance{
Name: yaml.Attr(c.Name),
UUID: yaml.Attr(c.UUID),
Environments: yaml.Attr(
yaml.Map[*yaml.BundleEnvironment]{
{Key: yaml.Attr(envID), Value: yaml.Attr(envBlock)},
},
),
}
}
} else {
bundle = yaml.BundleInstance{
Name: yaml.Attr(c.Name),
UUID: yaml.Attr(c.UUID),
Source: yaml.Attr[any](c.Source),
Inputs: yaml.Attr(inputs),
}
}
var b strings.Builder
err := yaml.Encode(&bundle, &b)
if err != nil {
return "", err
}
// Strip any trailling whitespace.
output := trailingWSRE.ReplaceAllString(b.String(), "")
return output, nil
}
func loadBundleYAMLConfig(p string) (*yaml.BundleInstance, error) {
if !hasYAMLConfigExt(p) {
return nil, errors.E("File %q is not a .tm.yml file.", p)
}
r, err := os.Open(p)
if err != nil {
return nil, err
}
defer func() {
_ = r.Close()
}()
var bundle yaml.BundleInstance
err = yaml.Decode(r, &bundle)
if err != nil {
loc := hhcl.Range{
Filename: p,
}
var yamlErr yaml.Error
if errors.As(err, &yamlErr) {
loc.Start = hhcl.Pos{Line: yamlErr.Line, Column: yamlErr.Column}
loc.End = hhcl.Pos{Line: yamlErr.Line, Column: yamlErr.Column}
}
return nil, errors.E(err, loc)
}
return &bundle, nil
}
func hasYAMLConfigExt(fn string) bool {
return strings.HasSuffix(fn, ".tm.yml") || strings.HasSuffix(fn, ".tm.yaml")
}
func mergeBundleYAMLEnv(existing yaml.BundleInstance, envID string, env *yaml.BundleEnvironment, envs []*config.Environment) yaml.BundleInstance {
merged := existing
// If the same entry already is in spec of the existing bundle, then don't write it.
var filteredInputs yaml.Map[any]
for _, input := range env.Inputs.V {
if !slices.ContainsFunc(merged.Inputs.V, func(other yaml.MapItem[any]) bool {
return input.Key.V == other.Key.V &&
input.Key.HeadComment == other.Key.HeadComment &&
input.Key.LineComment == other.Key.LineComment &&
input.Key.FootComment == other.Key.FootComment &&
input.Value.HeadComment == other.Value.HeadComment &&
input.Value.LineComment == other.Value.LineComment &&
input.Value.FootComment == other.Value.FootComment &&
reflect.DeepEqual(input.Value.V, other.Value.V)
}) {
filteredInputs = append(filteredInputs, input)
}
}
env.Inputs.V = filteredInputs
newMapItem := yaml.MapItem[*yaml.BundleEnvironment]{Key: yaml.Attr(envID), Value: yaml.Attr(env)}
replaceIndex := slices.IndexFunc(merged.Environments.V, func(a yaml.MapItem[*yaml.BundleEnvironment]) bool {
return a.Key.V == envID
})
if replaceIndex != -1 {
merged.Environments.V[replaceIndex] = newMapItem
} else {
indexMap := make(map[string]int, len(envs))
for i, e := range envs {
indexMap[e.ID] = i
}
merged.Environments.V = append(merged.Environments.V, newMapItem)
slices.SortFunc(merged.Environments.V, func(a, b yaml.MapItem[*yaml.BundleEnvironment]) int {
return cmp.Compare(indexMap[a.Key.V], indexMap[b.Key.V])
})
}
return merged
}
var trailingWSRE = regexp.MustCompile(`(?m)[ \t]+$`)
func formatTmdoc(in string) string {
lines := strings.Split(in, "\n")
// Remove empty last line.
if len(lines) > 1 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
for i, s := range lines {
lines[i] = "# tmdoc: " + s
}
return strings.Join(lines, "\n")
}
func writeBundleInstance(outpath string, content string) error {
if err := os.MkdirAll(filepath.Dir(outpath), 0755); err != nil {
return errors.E(err, "failed to create directory")
}
f, err := os.Create(outpath)
if err != nil {
return errors.E(err, "creating/truncating file")
}
defer func() {
errClose := f.Close()
if errClose != nil {
err = errors.L(err, errClose)
}
}()
_, err = f.WriteString(content)
return err
}
func fixupFileExtension(format, fn string) string {
switch format {
case "yaml":
if strings.HasSuffix(fn, ".hcl") {
return strings.TrimSuffix(fn, "hcl") + "yml"
}
if strings.HasSuffix(fn, ".tm") {
return fn + ".yml"
}
case "hcl":
if strings.HasSuffix(fn, ".yml") {
return strings.TrimSuffix(fn, "yml") + "hcl"
}
if strings.HasSuffix(fn, ".yaml") {
return strings.TrimSuffix(fn, "yaml") + "hcl"
}
if strings.HasSuffix(fn, ".tm") {
return fn + ".hcl"
}
}
return fn
}