-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathphase_worktree_integration_test.go
More file actions
2614 lines (2048 loc) · 82.4 KB
/
Copy pathphase_worktree_integration_test.go
File metadata and controls
2614 lines (2048 loc) · 82.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package discovery_test
import (
"context"
"fmt"
"io/fs"
"os"
"path/filepath"
"testing"
"time"
gogit "github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/plumbing/object"
"github.com/gruntwork-io/terragrunt/internal/component"
"github.com/gruntwork-io/terragrunt/internal/discovery"
"github.com/gruntwork-io/terragrunt/internal/experiment"
"github.com/gruntwork-io/terragrunt/internal/filter"
"github.com/gruntwork-io/terragrunt/internal/git"
"github.com/gruntwork-io/terragrunt/internal/stacks/generate"
"github.com/gruntwork-io/terragrunt/internal/worktrees"
"github.com/gruntwork-io/terragrunt/pkg/options"
"github.com/gruntwork-io/terragrunt/test/helpers"
"github.com/gruntwork-io/terragrunt/test/helpers/logger"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// TestWorktreePhase_Integration_UnitLifecycle tests the full worktree discovery flow
// for created, modified, removed, and untouched units.
func TestWorktreePhase_Integration_UnitLifecycle(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create initial units
createUnit(t, tmpDir, "unit-to-be-modified", `# Unit to be modified`)
createUnit(t, tmpDir, "unit-to-be-removed", `# Unit to be removed`)
createUnit(t, tmpDir, "unit-to-be-untouched", `# Unit to be untouched`)
commitChanges(t, runner, "Initial commit")
// Modify the unit
err := os.WriteFile(filepath.Join(tmpDir, "unit-to-be-modified", "terragrunt.hcl"), []byte(`# Unit modified`), 0o644)
require.NoError(t, err)
// Remove the unit
err = os.RemoveAll(filepath.Join(tmpDir, "unit-to-be-removed"))
require.NoError(t, err)
// Add a new unit
createUnit(t, tmpDir, "unit-to-be-created", `# Unit created`)
// Do nothing to the untouched unit
commitChanges(t, runner, "Create, modify, and remove units")
// Run worktree discovery
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, w := runWorktreeDiscovery(t, tmpDir, gitExpressions, "", nil)
// Verify worktrees were created
assert.NotEmpty(t, w.WorktreePairs, "Worktrees should be created")
assert.Contains(t, w.WorktreePairs, "[HEAD~1...HEAD]", "Worktree should exist")
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
fromWorktree := worktreePair.FromWorktree.Path
toWorktree := worktreePair.ToWorktree.Path
// Verify units were discovered
units := components.Filter(component.UnitKind)
unitPaths := units.Paths()
expectedUnitToBeCreated := filepath.Join(toWorktree, "unit-to-be-created")
expectedUnitToBeModified := filepath.Join(toWorktree, "unit-to-be-modified")
expectedUnitToBeRemoved := filepath.Join(fromWorktree, "unit-to-be-removed")
expectedUnitToBeUntouched := filepath.Join(toWorktree, "unit-to-be-untouched")
assert.Contains(t, unitPaths, expectedUnitToBeCreated, "Unit should be discovered as it was created")
assert.DirExists(t, expectedUnitToBeCreated)
assert.Contains(t, unitPaths, expectedUnitToBeModified, "Unit should be discovered as it was modified")
assert.DirExists(t, expectedUnitToBeModified)
assert.Contains(t, unitPaths, expectedUnitToBeRemoved, "Unit should be discovered as it was removed")
assert.DirExists(t, expectedUnitToBeRemoved)
assert.NotContains(t, unitPaths, expectedUnitToBeUntouched, "Unit should not be discovered as it was untouched")
assert.DirExists(t, expectedUnitToBeUntouched)
}
// TestWorktreePhase_Integration_CommandArgs tests command argument handling for worktrees.
func TestWorktreePhase_Integration_CommandArgs(t *testing.T) {
t.Parallel()
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
tests := []struct {
name string
cmd string
expectedErrorMsg string
description string
args []string
expectError bool
}{
{
name: "plan_command_removed_unit_has_destroy_flag",
cmd: "plan",
args: []string{},
expectError: false,
description: "Plan command should add '-destroy' flag for removed units",
},
{
name: "apply_command_removed_unit_has_destroy_flag",
cmd: "apply",
args: []string{},
expectError: false,
description: "Apply command should add '-destroy' flag for removed units",
},
{
name: "plan_command_with_destroy_throws_error",
cmd: "plan",
args: []string{"-destroy"},
expectError: true,
description: "Plan command with '-destroy' already present should error",
},
{
name: "empty_command_allowed",
cmd: "",
args: []string{},
expectError: false,
description: "Empty command should be allowed for discovery commands",
},
{
name: "unsupported_command_returns_error",
cmd: "destroy",
args: []string{},
expectError: true,
expectedErrorMsg: "Git-based filtering is not supported with the command 'destroy'",
description: "Unsupported command should return error",
},
{
name: "plan_with_other_args_allowed",
cmd: "plan",
args: []string{"-out", "plan.out"},
expectError: false,
description: "Plan command with other args should be allowed",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// Each subtest creates its own git repository
tmpDir, runner := setupGitRepo(t)
// Create initial units
createUnit(t, tmpDir, "unit-to-be-modified", `# Unit to be modified`)
createUnit(t, tmpDir, "unit-to-be-removed", `# Unit to be removed`)
commitChanges(t, runner, "Initial commit")
// Modify the unit
err := os.WriteFile(filepath.Join(tmpDir, "unit-to-be-modified", "terragrunt.hcl"), []byte(`# Modified`), 0o644)
require.NoError(t, err)
// Remove the unit
err = os.RemoveAll(filepath.Join(tmpDir, "unit-to-be-removed"))
require.NoError(t, err)
// Add a new unit
createUnit(t, tmpDir, "unit-to-be-created", `# Created`)
commitChanges(t, runner, "Update units")
// Set up discovery
l := logger.CreateLogger()
w, err := worktrees.NewWorktrees(t.Context(), l, worktrees.WorktreeOpts{WorkingDir: tmpDir, GitExpressions: gitExpressions})
require.NoError(t, err)
t.Cleanup(func() {
cleanupErr := w.Cleanup(context.WithoutCancel(t.Context()), l)
require.NoError(t, cleanupErr)
})
opts := options.NewTerragruntOptions()
opts.WorkingDir = tmpDir
opts.RootWorkingDir = tmpDir
discoveryContext := &component.DiscoveryContext{
WorkingDir: tmpDir,
Cmd: tt.cmd,
Args: tt.args,
}
discovery := discovery.NewDiscovery(tmpDir).
WithDiscoveryContext(discoveryContext).
WithWorktrees(w)
filters := make(filter.Filters, 0, len(gitExpressions))
for _, gitExpr := range gitExpressions {
f := filter.NewFilter(gitExpr, gitExpr.String())
filters = append(filters, f)
}
discovery = discovery.WithFilters(filters)
components, err := discovery.Discover(t.Context(), l, opts)
if tt.expectError {
require.Error(t, err, "Expected error for: %s", tt.description)
if tt.expectedErrorMsg != "" {
assert.Contains(t, err.Error(), tt.expectedErrorMsg)
}
return
}
require.NoError(t, err, "Should not error for: %s", tt.description)
// Verify worktrees were created
assert.NotEmpty(t, w.WorktreePairs, "Worktrees should be created")
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
fromWorktree := worktreePair.FromWorktree.Path
toWorktree := worktreePair.ToWorktree.Path
// Verify units were discovered
units := components.Filter(component.UnitKind)
expectedUnitToBeCreated := filepath.Join(toWorktree, "unit-to-be-created")
expectedUnitToBeModified := filepath.Join(toWorktree, "unit-to-be-modified")
expectedUnitToBeRemoved := filepath.Join(fromWorktree, "unit-to-be-removed")
// Verify discovery context args for each unit
for _, unit := range units {
ctx := unit.DiscoveryContext()
require.NotNil(t, ctx, "Component should have discovery context")
unitPath := unit.Path()
// Check removed unit (discovered in "from" worktree)
if unitPath == expectedUnitToBeRemoved {
if tt.cmd == "plan" || tt.cmd == "apply" {
assert.Contains(t, ctx.Args, "-destroy",
"Removed unit should have '-destroy' flag for %s command", tt.cmd)
}
}
// Check added unit (discovered in "to" worktree)
if unitPath == expectedUnitToBeCreated {
if tt.cmd == "plan" || tt.cmd == "apply" {
assert.NotContains(t, ctx.Args, "-destroy",
"Added unit should NOT have '-destroy' flag for %s command", tt.cmd)
}
}
// Check modified unit (discovered in "to" worktree)
if unitPath == expectedUnitToBeModified {
if tt.cmd == "plan" || tt.cmd == "apply" {
assert.NotContains(t, ctx.Args, "-destroy",
"Modified unit should NOT have '-destroy' flag for %s command", tt.cmd)
}
}
}
})
}
}
// TestWorktreePhase_Integration_EmptyFilters tests that discovery produces no results
// when git diff contains no terragrunt files.
func TestWorktreePhase_Integration_EmptyFilters(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create initial empty commit
err := runner.GoCommit("Initial commit", &gogit.CommitOptions{
AllowEmptyCommits: true,
Author: &object.Signature{
Name: "Test User",
Email: "test@example.com",
When: time.Now(),
},
})
require.NoError(t, err)
// Create a second commit with only non-terragrunt files
readmePath := filepath.Join(tmpDir, "README.md")
err = os.WriteFile(readmePath, []byte("# Test"), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Update README")
// Run worktree discovery
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, _ := runWorktreeDiscovery(t, tmpDir, gitExpressions, "", nil)
// Verify that no components were discovered
assert.Empty(t, components, "No components should be discovered when filters are empty")
}
// TestWorktreePhase_Integration_EmptyDiffs tests that discovery produces no results
// when there are no changes between commits.
func TestWorktreePhase_Integration_EmptyDiffs(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create initial empty commit
err := runner.GoCommit("Initial commit", &gogit.CommitOptions{
AllowEmptyCommits: true,
Author: &object.Signature{
Name: "Test User",
Email: "test@example.com",
When: time.Now(),
},
})
require.NoError(t, err)
// Create a second empty commit
err = runner.GoCommit("Empty commit", &gogit.CommitOptions{
AllowEmptyCommits: true,
Author: &object.Signature{
Name: "Test User",
Email: "test@example.com",
When: time.Now(),
},
})
require.NoError(t, err)
// Run worktree discovery
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, _ := runWorktreeDiscovery(t, tmpDir, gitExpressions, "", nil)
// Verify that no components were discovered
assert.Empty(t, components, "No components should be discovered when there are no diffs")
}
// TestWorktreePhase_Integration_Stacks tests stack discovery with generated units.
func TestWorktreePhase_Integration_Stacks(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create a catalog of units
legacyUnitDir := filepath.Join(tmpDir, "catalog", "units", "legacy")
err := os.MkdirAll(legacyUnitDir, 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(legacyUnitDir, "terragrunt.hcl"), []byte(`# Legacy unit`), 0o644)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(legacyUnitDir, "main.tf"), []byte(`# Intentionally empty`), 0o644)
require.NoError(t, err)
modernUnitDir := filepath.Join(tmpDir, "catalog", "units", "modern")
err = os.MkdirAll(modernUnitDir, 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(modernUnitDir, "terragrunt.hcl"), []byte(`# Modern unit`), 0o644)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(modernUnitDir, "main.tf"), []byte(`# Intentionally empty`), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Create catalog units")
// Create stacks
stackFileContents := `unit "unit_to_be_modified" {
source = "${get_repo_root()}/catalog/units/legacy"
path = "unit_to_be_modified"
}
unit "unit_to_be_removed" {
source = "${get_repo_root()}/catalog/units/legacy"
path = "unit_to_be_removed"
}
unit "unit_to_be_untouched" {
source = "${get_repo_root()}/catalog/units/legacy"
path = "unit_to_be_untouched"
}
`
stackToBeModifiedDir := filepath.Join(tmpDir, "live", "stack-to-be-modified")
err = os.MkdirAll(stackToBeModifiedDir, 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(stackToBeModifiedDir, "terragrunt.stack.hcl"), []byte(stackFileContents), 0o644)
require.NoError(t, err)
stackToBeRemovedDir := filepath.Join(tmpDir, "live", "stack-to-be-removed")
err = os.MkdirAll(stackToBeRemovedDir, 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(stackToBeRemovedDir, "terragrunt.stack.hcl"), []byte(stackFileContents), 0o644)
require.NoError(t, err)
stackToBeUntouchedDir := filepath.Join(tmpDir, "live", "stack-to-be-untouched")
err = os.MkdirAll(stackToBeUntouchedDir, 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(stackToBeUntouchedDir, "terragrunt.stack.hcl"), []byte(stackFileContents), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Create stacks")
// Add a new stack
stackToBeAddedDir := filepath.Join(tmpDir, "live", "stack-to-be-added")
err = os.MkdirAll(stackToBeAddedDir, 0o755)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(stackToBeAddedDir, "terragrunt.stack.hcl"), []byte(stackFileContents), 0o644)
require.NoError(t, err)
// Modify the first stack
modifiedStackContents := `unit "unit_to_be_added" {
source = "${get_repo_root()}/catalog/units/modern"
path = "unit_to_be_added"
}
unit "unit_to_be_modified" {
source = "${get_repo_root()}/catalog/units/modern"
path = "unit_to_be_modified"
}
unit "unit_to_be_untouched" {
source = "${get_repo_root()}/catalog/units/legacy"
path = "unit_to_be_untouched"
}
`
err = os.WriteFile(filepath.Join(stackToBeModifiedDir, "terragrunt.stack.hcl"), []byte(modifiedStackContents), 0o644)
require.NoError(t, err)
// Remove the second stack
err = os.RemoveAll(stackToBeRemovedDir)
require.NoError(t, err)
commitChanges(t, runner, "Modify and remove stacks")
// Set up discovery with worktrees
l := logger.CreateLogger()
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
w, err := worktrees.NewWorktrees(t.Context(), l, worktrees.WorktreeOpts{WorkingDir: tmpDir, GitExpressions: gitExpressions})
require.NoError(t, err)
t.Cleanup(func() {
cleanupErr := w.Cleanup(context.WithoutCancel(t.Context()), l)
require.NoError(t, cleanupErr)
})
// Generate stacks in worktrees
opts := options.NewTerragruntOptions()
opts.WorkingDir = tmpDir
opts.RootWorkingDir = tmpDir
parsedFilters, parseErr := filter.ParseFilterQueries(l, []string{"[HEAD~1...HEAD]"})
require.NoError(t, parseErr)
opts.Filters = parsedFilters
opts.Experiments = experiment.NewExperiments()
err = opts.Experiments.EnableExperiment(experiment.FilterFlag)
require.NoError(t, err)
err = generate.GenerateStacks(t.Context(), l, opts, w)
require.NoError(t, err)
// Run discovery
discoveryContext := &component.DiscoveryContext{
WorkingDir: tmpDir,
Cmd: "plan",
}
discovery := discovery.NewDiscovery(tmpDir).
WithDiscoveryContext(discoveryContext).
WithWorktrees(w)
filters := make(filter.Filters, 0, len(gitExpressions))
for _, gitExpr := range gitExpressions {
f := filter.NewFilter(gitExpr, gitExpr.String())
filters = append(filters, f)
}
discovery = discovery.WithFilters(filters)
components, err := discovery.Discover(t.Context(), l, opts)
require.NoError(t, err)
// Verify that components were discovered
assert.NotEmpty(t, components)
// Get worktree paths
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
require.NotEmpty(t, worktreePair)
fromWorktree := worktreePair.FromWorktree.Path
toWorktree := worktreePair.ToWorktree.Path
// Get relative paths
stackToBeAddedRel, err := filepath.Rel(tmpDir, stackToBeAddedDir)
require.NoError(t, err)
stackToBeRemovedRel, err := filepath.Rel(tmpDir, stackToBeRemovedDir)
require.NoError(t, err)
// Verify added stack and its units are in toWorktree
addedStackPath := filepath.Join(toWorktree, stackToBeAddedRel)
foundAddedStack := false
for _, c := range components {
if c.Path() == addedStackPath {
foundAddedStack = true
dc := c.DiscoveryContext()
assert.NotNil(t, dc)
assert.Equal(t, "HEAD", dc.Ref)
break
}
}
assert.True(t, foundAddedStack, "Added stack should be discovered")
// Verify removed stack is in fromWorktree
removedStackPath := filepath.Join(fromWorktree, stackToBeRemovedRel)
foundRemovedStack := false
for _, c := range components {
if c.Path() == removedStackPath {
foundRemovedStack = true
dc := c.DiscoveryContext()
assert.NotNil(t, dc)
assert.Equal(t, "HEAD~1", dc.Ref)
assert.Contains(t, dc.Args, "-destroy", "Removed stack should have -destroy flag")
break
}
}
assert.True(t, foundRemovedStack, "Removed stack should be discovered")
}
// TestWorktreePhase_Integration_FileRename tests that file renames are detected.
func TestWorktreePhase_Integration_FileRename(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create a unit with a file
unitDir := createUnit(t, tmpDir, "unit", `# Unit config`)
err := os.WriteFile(filepath.Join(unitDir, "original.tf"), []byte(`# Same content before and after rename`), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Initial commit with original.tf")
// Rename the file (same content, different name)
err = os.Rename(
filepath.Join(unitDir, "original.tf"),
filepath.Join(unitDir, "renamed.tf"),
)
require.NoError(t, err)
commitChanges(t, runner, "Rename original.tf to renamed.tf")
// Run worktree discovery
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, w := runWorktreeDiscovery(t, tmpDir, gitExpressions, "plan", nil)
// The unit should be detected as changed because the file was renamed
assert.NotEmpty(t, components, "Unit with renamed file should be detected as changed")
// Verify we have the unit
toWorktree := w.WorktreePairs["[HEAD~1...HEAD]"].ToWorktree.Path
expectedUnitPath := filepath.Join(toWorktree, "unit")
unitPaths := components.Paths()
assert.Contains(t, unitPaths, expectedUnitPath, "Should discover the unit with renamed file")
}
// TestWorktreePhase_Integration_FileMove tests that file moves are detected.
func TestWorktreePhase_Integration_FileMove(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create a unit with a file in root
unitDir := createUnit(t, tmpDir, "unit", `# Unit config`)
err := os.WriteFile(filepath.Join(unitDir, "module.tf"), []byte(`# Module content`), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Initial commit with module.tf in root")
// Move file to subdirectory (same content, different path)
subDir := filepath.Join(unitDir, "modules")
err = os.MkdirAll(subDir, 0o755)
require.NoError(t, err)
err = os.Rename(
filepath.Join(unitDir, "module.tf"),
filepath.Join(subDir, "module.tf"),
)
require.NoError(t, err)
commitChanges(t, runner, "Move module.tf to modules/ subdirectory")
// Run worktree discovery
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, _ := runWorktreeDiscovery(t, tmpDir, gitExpressions, "plan", nil)
// The unit should be detected as changed because the file was moved
assert.NotEmpty(t, components, "Unit with moved file should be detected as changed")
// Verify we have the unit
foundUnit := false
for _, c := range components {
if _, ok := c.(*component.Unit); ok {
foundUnit = true
break
}
}
assert.True(t, foundUnit, "Should discover the unit with moved file")
}
// TestWorktreePhase_Integration_NestedUnits tests discovery of nested units.
func TestWorktreePhase_Integration_NestedUnits(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create nested unit structure
createUnit(t, tmpDir, "apps/frontend", `# Frontend unit`)
createUnit(t, tmpDir, "apps/backend", `# Backend unit`)
createUnit(t, tmpDir, "apps/backend/db", `# Database unit`)
commitChanges(t, runner, "Initial commit")
// Modify the nested unit
err := os.WriteFile(
filepath.Join(tmpDir, "apps/backend/db", "terragrunt.hcl"),
[]byte(`# Modified database unit`),
0o644,
)
require.NoError(t, err)
commitChanges(t, runner, "Modify nested unit")
// Run worktree discovery
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, w := runWorktreeDiscovery(t, tmpDir, gitExpressions, "", nil)
// Verify the nested unit was discovered
units := components.Filter(component.UnitKind)
assert.Len(t, units, 1, "Only the modified nested unit should be discovered")
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
toWorktree := worktreePair.ToWorktree.Path
expectedPath := filepath.Join(toWorktree, "apps/backend/db")
unitPaths := units.Paths()
assert.Contains(t, unitPaths, expectedPath, "Nested unit should be discovered")
}
// TestWorktreePhase_Integration_MultipleGitExpressions tests discovery with multiple git expressions.
func TestWorktreePhase_Integration_MultipleGitExpressions(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create initial unit
createUnit(t, tmpDir, "unit-a", `# Unit A`)
commitChanges(t, runner, "Initial commit")
// Create second unit
createUnit(t, tmpDir, "unit-b", `# Unit B`)
commitChanges(t, runner, "Add unit B")
// Create third unit
createUnit(t, tmpDir, "unit-c", `# Unit C`)
commitChanges(t, runner, "Add unit C")
// Run worktree discovery with expression covering last commit
gitExpressions := filter.GitExpressions{filter.NewGitExpression("HEAD~1", "HEAD")}
components, w := runWorktreeDiscovery(t, tmpDir, gitExpressions, "", nil)
// Should only discover unit-c (added in last commit)
units := components.Filter(component.UnitKind)
assert.Len(t, units, 1, "Only unit-c should be discovered")
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
toWorktree := worktreePair.ToWorktree.Path
expectedPath := filepath.Join(toWorktree, "unit-c")
unitPaths := units.Paths()
assert.Contains(t, unitPaths, expectedPath, "Unit C should be discovered")
}
// TestWorktreePhase_Integration_GitFilterCombinedWithOtherFilters tests git filters combined
// with other filter types (path, name, type, negation).
func TestWorktreePhase_Integration_GitFilterCombinedWithOtherFilters(t *testing.T) {
t.Parallel()
tests := []struct {
name string
filterQueries func(fromRef, toRef string) []string
wantUnits func(fromDir, toDir string) []string
wantStacks []string
expectedChanged []string // which units are expected to be changed in the test setup
}{
{
name: "Git filter combined with path filter",
filterQueries: func(fromRef, toRef string) []string {
return []string{"[" + fromRef + "..." + toRef + "] | ./app"}
},
wantUnits: func(_, toDir string) []string {
return []string{filepath.Join(toDir, "app")}
},
wantStacks: []string{},
expectedChanged: []string{"app", "new"},
},
{
name: "Git filter combined with name filter",
filterQueries: func(fromRef, toRef string) []string {
return []string{"[" + fromRef + "..." + toRef + "] | name=new"}
},
wantUnits: func(_, toDir string) []string {
return []string{filepath.Join(toDir, "new")}
},
wantStacks: []string{},
expectedChanged: []string{"app", "new"},
},
{
name: "Git filter with negation",
filterQueries: func(fromRef, toRef string) []string {
return []string{"[" + fromRef + "..." + toRef + "] | !name=new"}
},
wantUnits: func(fromDir, toDir string) []string {
return []string{
filepath.Join(fromDir, "cache"),
filepath.Join(toDir, "app"),
}
},
wantStacks: []string{},
expectedChanged: []string{"app", "new", "cache"},
},
{
name: "Git filter - single reference (compared to HEAD)",
filterQueries: func(fromRef, _ string) []string {
return []string{"[" + fromRef + "]"}
},
wantUnits: func(fromDir, toDir string) []string {
return []string{
filepath.Join(fromDir, "cache"),
filepath.Join(toDir, "app"),
filepath.Join(toDir, "new"),
}
},
wantStacks: []string{},
expectedChanged: []string{"app", "new", "cache"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create initial components
createUnit(t, tmpDir, "app", `# App unit`)
createUnit(t, tmpDir, "db", `# DB unit`)
createUnit(t, tmpDir, "cache", `# Cache unit`)
commitChanges(t, runner, "Initial commit")
// Modify app component
err := os.WriteFile(filepath.Join(tmpDir, "app", "terragrunt.hcl"), []byte(`
locals {
modified = true
}
`), 0o644)
require.NoError(t, err)
// Add new component
createUnit(t, tmpDir, "new", `# New unit`)
// Remove cache component
err = os.RemoveAll(filepath.Join(tmpDir, "cache"))
require.NoError(t, err)
commitChanges(t, runner, "Changes: modified app, added new, removed cache")
// Parse filter queries
l := logger.CreateLogger()
filterQueries := tt.filterQueries("HEAD~1", "HEAD")
filters, err := filter.ParseFilterQueries(l, filterQueries)
require.NoError(t, err)
// Create worktrees
w, err := worktrees.NewWorktrees(t.Context(), l, worktrees.WorktreeOpts{WorkingDir: tmpDir, GitExpressions: filters.UniqueGitFilters()})
require.NoError(t, err)
t.Cleanup(func() {
cleanupErr := w.Cleanup(context.WithoutCancel(t.Context()), l)
require.NoError(t, cleanupErr)
})
opts := options.NewTerragruntOptions()
opts.WorkingDir = tmpDir
opts.RootWorkingDir = tmpDir
discoveryContext := &component.DiscoveryContext{
WorkingDir: tmpDir,
}
discovery := discovery.NewDiscovery(tmpDir).
WithDiscoveryContext(discoveryContext).
WithWorktrees(w).
WithFilters(filters)
components, err := discovery.Discover(t.Context(), l, opts)
require.NoError(t, err)
// Filter results by type
units := components.Filter(component.UnitKind).Paths()
stacks := components.Filter(component.StackKind).Paths()
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
require.NotEmpty(t, worktreePair)
wantUnits := tt.wantUnits(worktreePair.FromWorktree.Path, worktreePair.ToWorktree.Path)
// Verify results
assert.ElementsMatch(t, wantUnits, units, "Units mismatch for test: %s", tt.name)
assert.ElementsMatch(t, tt.wantStacks, stacks, "Stacks mismatch for test: %s", tt.name)
})
}
}
// TestWorktreePhase_Integration_FromSubdirectory tests that git filter discovery works correctly
// when running from a subdirectory of the git root. This is a regression test for the bug where
// paths were incorrectly duplicated (e.g., "basic/basic/basic-2" instead of "basic/basic-2").
func TestWorktreePhase_Integration_FromSubdirectory(t *testing.T) {
t.Parallel()
tmpDir, runner := setupGitRepo(t)
// Create subdirectory structure: basic/basic-1, basic/basic-2
basicDir := filepath.Join(tmpDir, "basic")
basic1Dir := filepath.Join(basicDir, "basic-1")
basic2Dir := filepath.Join(basicDir, "basic-2")
// Also create a component outside the subdirectory
otherDir := filepath.Join(tmpDir, "other")
testDirs := []string{basic1Dir, basic2Dir, otherDir}
for _, dir := range testDirs {
err := os.MkdirAll(dir, 0o755)
require.NoError(t, err)
}
// Create initial files
initialFiles := map[string]string{
filepath.Join(basic1Dir, "terragrunt.hcl"): ``,
filepath.Join(basic2Dir, "terragrunt.hcl"): ``,
filepath.Join(otherDir, "terragrunt.hcl"): ``,
}
for path, content := range initialFiles {
err := os.WriteFile(path, []byte(content), 0o644)
require.NoError(t, err)
}
commitChanges(t, runner, "Initial commit")
// Modify basic-2 component
err := os.WriteFile(filepath.Join(basic2Dir, "terragrunt.hcl"), []byte(`
locals {
modified = true
}
`), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Modified basic-2")
// Now run discovery FROM THE SUBDIRECTORY (basic)
l := logger.CreateLogger()
// Parse filter with Git reference
filters, err := filter.ParseFilterQueries(l, []string{"[HEAD~1]"})
require.NoError(t, err)
// Create worktrees from the subdirectory
w, err := worktrees.NewWorktrees(t.Context(), l, worktrees.WorktreeOpts{WorkingDir: basicDir, GitExpressions: filters.UniqueGitFilters()})
require.NoError(t, err)
t.Cleanup(func() {
cleanupErr := w.Cleanup(context.WithoutCancel(t.Context()), l)
require.NoError(t, cleanupErr)
})
opts := options.NewTerragruntOptions()
opts.WorkingDir = basicDir
opts.RootWorkingDir = basicDir
discoveryContext := &component.DiscoveryContext{
WorkingDir: basicDir,
}
discovery := discovery.NewDiscovery(basicDir).
WithDiscoveryContext(discoveryContext).
WithWorktrees(w).
WithFilters(filters)
components, err := discovery.Discover(t.Context(), l, opts)
require.NoError(t, err)
// Filter results by type
units := components.Filter(component.UnitKind).Paths()
// With worktree-based execution, discovery runs directly in the worktree path
worktreePair := w.WorktreePairs["[HEAD~1...HEAD]"]
require.NotEmpty(t, worktreePair)
expectedPath := filepath.Join(worktreePair.ToWorktree.Path, "basic", "basic-2")
assert.ElementsMatch(t, []string{expectedPath}, units,
"Should discover basic-2 with correct path when running from subdirectory")
// Verify the path doesn't have duplicated directory names
for _, unitPath := range units {
assert.NotContains(t, unitPath, "basic"+string(filepath.Separator)+"basic"+string(filepath.Separator)+"basic-",
"Path should not have duplicated directory names")
}
}
// setupMultiCommitTestRepo creates a git repository with 4 commits for testing
// git filter discovery from a subdirectory. Returns the basicDir (subdirectory).
func setupMultiCommitTestRepo(t *testing.T) string {
t.Helper()
tmpDir, runner := setupGitRepo(t)
// Create subdirectory structure: basic/basic-1, basic/basic-2, basic/basic-3
basicDir := filepath.Join(tmpDir, "basic")
basic1Dir := filepath.Join(basicDir, "basic-1")
basic2Dir := filepath.Join(basicDir, "basic-2")
basic3Dir := filepath.Join(basicDir, "basic-3")
// Also create components outside the subdirectory
otherDir := filepath.Join(tmpDir, "other")
anotherDir := filepath.Join(tmpDir, "another")
testDirs := []string{basic1Dir, basic2Dir, basic3Dir, otherDir, anotherDir}
for _, dir := range testDirs {
err := os.MkdirAll(dir, 0o755)
require.NoError(t, err)
}
// Commit 1: Initial state with all components
initialFiles := map[string]string{
filepath.Join(basic1Dir, "terragrunt.hcl"): ``,
filepath.Join(basic2Dir, "terragrunt.hcl"): ``,
filepath.Join(basic3Dir, "terragrunt.hcl"): ``,
filepath.Join(otherDir, "terragrunt.hcl"): ``,
filepath.Join(anotherDir, "terragrunt.hcl"): ``,
}
for path, content := range initialFiles {
err := os.WriteFile(path, []byte(content), 0o644)
require.NoError(t, err)
}
commitChanges(t, runner, "Initial commit")
// Commit 2: Modify basic-1 and other (outside subdirectory)
err := os.WriteFile(filepath.Join(basic1Dir, "terragrunt.hcl"), []byte(`
locals {
version = "v1"
}
`), 0o644)
require.NoError(t, err)
err = os.WriteFile(filepath.Join(otherDir, "terragrunt.hcl"), []byte(`
locals {
modified = true
}
`), 0o644)
require.NoError(t, err)
commitChanges(t, runner, "Commit 2: modify basic-1 and other")