Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
1999 lines (1813 loc) · 74.9 KB
/
Copy pathmain.go
File metadata and controls
1999 lines (1813 loc) · 74.9 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 main provides a CLI tool for updating Terraform module versions, Terraform versions,
// and provider versions across multiple files.
//
// The tool supports five modes of operation:
// 1. Single Module Mode: Update one module at a time via command-line flags
// 2. Config File Mode: Update multiple modules using a YAML configuration file
// 3. Config Validation Mode: Validate a YAML configuration file without updating Terraform files
// 4. Terraform Version Mode: Update Terraform required_version in terraform blocks
// 5. Provider Version Mode: Update provider versions in terraform required_providers blocks
//
// It uses the official HashiCorp HCL library to parse and modify Terraform files while retaining
// comments and HCL structure. Changed files are normalised by hclwrite.Format.
package main
import (
"bytes"
"encoding/json"
stderrors "errors"
"flag"
"fmt"
"io"
"io/fs"
"log"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"github.com/bmatcuk/doublestar/v4"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
tfaddr "github.com/hashicorp/terraform-registry-address"
"github.com/zclconf/go-cty/cty"
)
type visibleDirFS struct {
fs.ReadDirFS
}
func (f visibleDirFS) ReadDir(name string) ([]fs.DirEntry, error) {
entries, err := f.ReadDirFS.ReadDir(name)
if err != nil {
return nil, err
}
visible := entries[:0]
for _, entry := range entries {
if entry.IsDir() && strings.HasPrefix(entry.Name(), ".") {
continue
}
visible = append(visible, entry)
}
return visible, nil
}
// Build information set by ldflags
var (
version = "dev"
commit = "none"
date = "unknown"
)
var (
hookMu sync.Mutex // guards test hook variables
exitFunc = os.Exit
fatalf = func(format string, v ...interface{}) {
log.Printf(format, v...)
exitFunc(1)
}
// renameReportFile moves a written report onto its destination, the last step of publishing it.
renameReportFile = os.Rename
// removeReportFile deletes a report an earlier run left where this run's report was to go.
removeReportFile = os.Remove
// openFileForRewrite opens a Terraform file to rewrite it in place: without O_CREATE, so a file
// deleted since its parse is not recreated, and without O_TRUNC, so a failed write can be undone.
openFileForRewrite = func(name string) (rewritableFile, error) {
file, err := os.OpenFile(name, os.O_RDWR, 0)
if err != nil {
return nil, err
}
return file, nil
}
// createBackupFile creates the copy of a Terraform file's original bytes kept while it is
// rewritten. It lives in the system temporary directory, which keeps it out of the reach of a
// Terraform glob unless that directory is itself inside the tree being globbed.
createBackupFile = func(pattern string) (backupFile, error) {
file, err := os.CreateTemp("", pattern)
if err != nil {
return nil, err
}
return file, nil
}
)
// stringSliceFlag is a custom flag type that allows a flag to be specified multiple times
type stringSliceFlag []string
// String returns the string representation of the flag
func (s *stringSliceFlag) String() string {
return strings.Join(*s, ",")
}
// Set appends a value to the slice
func (s *stringSliceFlag) Set(value string) error {
*s = append(*s, value)
return nil
}
// quote formats a string with appropriate quoting based on the output format.
// For "text" output, uses single quotes. For "md" (Markdown) output, uses backticks.
//
// Parameters:
// - s: The string to quote
// - format: Output format ("text" or "md")
//
// Returns:
// - string: The quoted string
//
// Examples:
// - quote("vpc", "text") returns "'vpc'"
// - quote("vpc", "md") returns "`vpc`"
func quote(s, format string) string {
if format == "md" {
return "`" + s + "`"
}
return "'" + s + "'"
}
// cliFlags holds all command-line flags
type cliFlags struct {
pattern string
moduleSource string
toVersion string
fromVersions stringSliceFlag
ignoreVersions stringSliceFlag
ignoreModules string
branch string
configFile string
validationConfigFile string
forceAdd bool
dryRun bool
check bool
verbose bool
showVersion bool
output string
terraformVersion string
providerName string
reportFile string
auditFile string
report updateReport
}
type updateReport struct {
SchemaVersion int `json:"schema_version"`
TerraformBlocksUpdated int `json:"terraform_blocks_updated"`
ModuleBlocksUpdated int `json:"module_blocks_updated"`
ProviderBlocksUpdated int `json:"provider_blocks_updated"`
terraformBlockIDs map[string]struct{}
moduleBlockIDs map[string]struct{}
fileIdentities []fs.FileInfo
}
type preparedReportFile struct {
destination string
file *os.File
}
func (flags *cliFlags) reportRecorder() *updateReport {
if flags.reportFile == "" {
return nil
}
return &flags.report
}
func (report *updateReport) recordTerraformBlocks(filename string, blockIndexes []int) {
var recorded int
report.terraformBlockIDs, recorded = report.recordTopLevelBlocks(filename, blockIndexes, report.terraformBlockIDs)
report.TerraformBlocksUpdated += recorded
}
func (report *updateReport) recordModuleBlocks(filename string, blockIndexes []int) {
var recorded int
report.moduleBlockIDs, recorded = report.recordTopLevelBlocks(filename, blockIndexes, report.moduleBlockIDs)
report.ModuleBlocksUpdated += recorded
}
func (report *updateReport) recordTopLevelBlocks(filename string, blockIndexes []int, existingBlockIDs map[string]struct{}) (blockIDs map[string]struct{}, recordedBlocks int) {
fileID := report.fileIdentity(filename)
blockIDs = existingBlockIDs
if blockIDs == nil {
blockIDs = make(map[string]struct{})
}
for _, blockIndex := range blockIndexes {
blockID := fmt.Sprintf("%s\x00%d", fileID, blockIndex)
if _, recorded := blockIDs[blockID]; recorded {
continue
}
blockIDs[blockID] = struct{}{}
recordedBlocks++
}
return blockIDs, recordedBlocks
}
// recordProviderBlocks needs no de-duplication: a run names each provider once, and another path to
// the same file, a hard link or symlink, is read already at the target. Module entries can update
// one block more than once in a run, so modules, and Terraform blocks through the same helper, do.
func (report *updateReport) recordProviderBlocks(blockLocations []string) {
report.ProviderBlocksUpdated += len(blockLocations)
}
func (report *updateReport) fileIdentity(filename string) string {
fileInfo, err := os.Stat(filename)
if err == nil {
for index, existingIdentity := range report.fileIdentities {
if os.SameFile(fileInfo, existingIdentity) {
return fmt.Sprintf("file:%d", index)
}
}
report.fileIdentities = append(report.fileIdentities, fileInfo)
return fmt.Sprintf("file:%d", len(report.fileIdentities)-1)
}
return "path:" + canonicalFileIdentity(filename)
}
func canonicalFileIdentity(filename string) string {
absolute, err := filepath.Abs(filename)
if err == nil {
filename = absolute
}
resolved, err := filepath.EvalSymlinks(filename)
if err == nil {
return filepath.Clean(resolved)
}
return filepath.Clean(filename)
}
// parseFlags parses and validates command-line flags
func parseFlags() *cliFlags {
flags := &cliFlags{}
usageOutput := flag.CommandLine.Output()
flagSet := flag.NewFlagSet(os.Args[0], flag.ContinueOnError)
flagSet.SetOutput(io.Discard)
flag.CommandLine = flagSet
flagSet.StringVar(&flags.pattern, "pattern", "", "Glob pattern for Terraform files; '**' matches any depth (e.g., '*.tf' or 'modules/**/*.tf')")
flagSet.StringVar(&flags.moduleSource, "module", "", "Source of the module to update (e.g., 'terraform-aws-modules/vpc/aws')")
flagSet.StringVar(&flags.toVersion, "to", "", "Desired version number")
flagSet.Var(&flags.fromVersions, "from", "Optional: version to update from (can be specified multiple times, e.g., -from 3.0.0 -from '~> 3.0')")
flagSet.Var(&flags.ignoreVersions, "ignore-version", "Optional: version(s) to skip (can be specified multiple times, e.g., -ignore-version 3.0.0 -ignore-version '~> 3.0')")
flagSet.StringVar(&flags.ignoreModules, "ignore-modules", "", "Optional: comma-separated list of module names or patterns to ignore; a '<branch>/<module>' pattern requires -branch (e.g., 'vpc,legacy-*,release/*/vpc')")
flagSet.StringVar(&flags.branch, "branch", "", "Optional: current branch name, required by branch-scoped ignore patterns (e.g., 'release/2026-09')")
flagSet.StringVar(&flags.configFile, "config", "", "Path to YAML config file with multiple module updates")
flagSet.StringVar(&flags.validationConfigFile, "validate-config", "", "Validate a YAML config file without updating Terraform files")
flagSet.BoolVar(&flags.forceAdd, "force-add", false, "Add a missing version attribute to registry modules (default: skip with warning)")
flagSet.BoolVar(&flags.dryRun, "dry-run", false, "Show what changes would be made without actually modifying files")
flagSet.BoolVar(&flags.check, "check", false, "Exit 2 when updates are required without modifying files")
flagSet.BoolVar(&flags.verbose, "verbose", false, "Show verbose output including skipped modules")
flagSet.BoolVar(&flags.showVersion, "version", false, "Print version information and exit")
flagSet.StringVar(&flags.output, "output", "text", "Output format: 'text' (default) or 'md' (Markdown)")
flagSet.StringVar(&flags.terraformVersion, "terraform-version", "", "Update Terraform required_version in terraform blocks")
flagSet.StringVar(&flags.providerName, "provider", "", "Provider name to update (e.g., 'aws', 'azurerm')")
flagSet.StringVar(&flags.reportFile, "report-file", "", "Write exact updated Terraform, module, and provider block counts as JSON")
flagSet.StringVar(&flags.auditFile, "audit-file", "", "Write each configured version value's current and expected version as JSON without changing files (config mode)")
if err := flagSet.Parse(os.Args[1:]); err != nil {
if stderrors.Is(err, flag.ErrHelp) {
flagSet.SetOutput(usageOutput)
if _, writeErr := fmt.Fprintf(usageOutput, "Usage of %s:\n", os.Args[0]); writeErr != nil {
fatalf("Error writing help: %v", writeErr)
return flags
}
flagSet.PrintDefaults()
exitFunc(0)
return flags
}
fatalf("Error: %v", err)
return flags
}
flagSet.SetOutput(usageOutput)
if flagSet.NArg() > 0 {
fatalf("Error: unexpected positional argument(s): %s", strings.Join(flagSet.Args(), " "))
return flags
}
// Validate output format
if flags.output != "text" && flags.output != "md" {
fatalf("Error: Invalid output format '%s'. Must be 'text' or 'md'", flags.output)
}
flags.branch = strings.TrimSpace(flags.branch)
// Both of these name no branch, so every branch-scoped ignore pattern would be dropped
// silently. 'git rev-parse --abbrev-ref HEAD' prints HEAD on a detached checkout, and
// GITHUB_REF holds a full ref such as 'refs/heads/main'. Git permits a branch name that
// starts with 'refs/', but a real branch is not realistically named that way.
if flags.branch == "HEAD" {
fatalf("Error: -branch must be a branch name, not 'HEAD'. Use 'git branch --show-current', which is empty on a detached checkout")
}
if strings.HasPrefix(flags.branch, "refs/") {
fatalf("Error: -branch must be a branch name, not the ref '%s'. Use 'git branch --show-current' rather than a full ref such as GITHUB_REF", flags.branch)
}
return flags
}
// loadModuleUpdates loads module updates for single module CLI mode
func loadModuleUpdates(flags *cliFlags) []ModuleUpdate {
// Single module mode - validate required flags
if flags.pattern == "" || flags.moduleSource == "" || flags.toVersion == "" {
fmt.Println("Usage:")
fmt.Println(" Single module: tf-version-bump -pattern <glob> -module <source> -to <version> [-from <version>]... [-ignore-version <version>]... [-ignore-modules <patterns>] [-branch <name>]")
fmt.Println(" Config file: tf-version-bump -pattern <glob> -config <config-file>")
flag.PrintDefaults()
exitFunc(1)
}
// Parse ignore patterns from comma-separated list
var ignorePatterns []string
if flags.ignoreModules != "" {
for _, p := range strings.Split(flags.ignoreModules, ",") {
if trimmed := strings.TrimSpace(p); trimmed != "" {
ignorePatterns = append(ignorePatterns, trimmed)
}
}
}
updates := []ModuleUpdate{
{Source: flags.moduleSource, Version: flags.toVersion, From: FromVersions(flags.fromVersions), IgnoreVersions: FromVersions(flags.ignoreVersions), IgnoreModules: ignorePatterns},
}
if err := resolveBranchIgnoreModules(updates, flags.branch); err != nil {
fatalf("Error: %v", err)
return nil
}
return updates
}
// resolveBranchIgnoreModules records, for each entry, the ignore_modules patterns that apply to
// branch. A branch-scoped pattern cannot be evaluated without a branch, so it is an error rather
// than a silent no-op that would bump a module the configuration excludes.
func resolveBranchIgnoreModules(updates []ModuleUpdate, branch string) error {
for i := range updates {
if len(updates[i].IgnoreModules) == 0 {
continue
}
resolved := make([]string, 0, len(updates[i].IgnoreModules))
for _, entry := range updates[i].IgnoreModules {
branchPattern, modulePattern, err := splitIgnoreModuleEntry(entry)
switch {
case err != nil:
return err
case branchPattern == "":
resolved = append(resolved, modulePattern)
case branch == "":
return fmt.Errorf("ignore pattern '%s' is scoped to a branch, but -branch is missing or empty; a detached checkout has no current branch", entry)
case matchPattern(branch, branchPattern):
resolved = append(resolved, modulePattern)
}
}
updates[i].resolvedIgnoreModules = resolved
}
return nil
}
// loadResolvedConfig is the single entry point for reading a config into an executable form. The
// update and audit paths share it so their module filtering cannot drift apart.
func loadResolvedConfig(configFile, branch string) (*Config, error) {
config, err := loadConfig(configFile)
if err != nil {
//nolint:staticcheck // The capitalised prefix is user-facing CLI output.
return nil, fmt.Errorf("Error loading config file: %w", err)
}
if err := resolveBranchIgnoreModules(config.Modules, branch); err != nil {
//nolint:staticcheck // The capitalised prefix is user-facing CLI output.
return nil, fmt.Errorf("Error: %w", err)
}
return config, nil
}
// processFiles applies the module updates to every matching file in order, parsing each file once so
// an update meets the changes earlier updates made to it, in a dry run as in a real run. A file that
// cannot be read or parsed counts one error per update; each failed write counts one error, and the
// file is read again for the updates after it, and a file whose write kept its backup refuses that read.
func processFiles(files []string, updates []ModuleUpdate, flags *cliFlags) (totalUpdates, totalSkips, totalErrors int) {
for _, file := range files {
parsed, readErr := readTerraformFile(file)
// Entries for one source are applied to the same file in turn, so one unpinned module is
// skipped once per entry. The count speaks for modules, so the blocks are unioned.
skippedBlocks := make(map[int]struct{})
// Index rather than copy: gocritic's rangeValCopy rejects ranging over ModuleUpdate by value.
for i := range updates {
update := &updates[i]
if readErr != nil {
log.Printf("Error processing %s: %v", file, readErr)
totalErrors++
continue
}
updated, changedBlocks, blocksSkipped, err := applyModuleVersion(parsed, update.Source, update.Version, update.From, update.IgnoreVersions, update.resolvedIgnoreModules, flags.forceAdd, flags.dryRun, flags.verbose, flags.output)
for _, blockIndex := range blocksSkipped {
skippedBlocks[blockIndex] = struct{}{}
}
if err != nil {
log.Printf("Error processing %s: %v", file, err)
totalErrors++
// Read the file again rather than keep the unsaved change: a restored file gives later
// updates its original content, and a file whose backup was kept is refused.
parsed, readErr = readTerraformFile(file)
continue
}
if updated {
if report := flags.reportRecorder(); report != nil && !flags.dryRun && len(changedBlocks) > 0 {
report.recordModuleBlocks(file, changedBlocks)
}
prefix := "✓"
action := "Updated"
if flags.dryRun {
prefix = "→"
action = "Would update"
}
if len(update.From) > 0 {
fmt.Printf("%s %s module source %s from version(s) %v to %s in %s\n", prefix, action, quote(update.Source, flags.output), update.From, quote(update.Version, flags.output), file)
} else {
fmt.Printf("%s %s module source %s to version %s in %s\n", prefix, action, quote(update.Source, flags.output), quote(update.Version, flags.output), file)
}
totalUpdates++
}
}
totalSkips += len(skippedBlocks)
}
return totalUpdates, totalSkips, totalErrors
}
// failureNote reports the updates that failed, so a summary of what succeeded is never mistaken
// for the whole story of the run. Every counted failure is logged where it happens, so the count
// is also the number of diagnostics; it names stderr because the summary is on stdout, and a
// redirected stdout would otherwise end with a pointer to errors it does not contain.
func failureNote(errorCount int) string {
if errorCount == 0 {
return ""
}
return fmt.Sprintf("%d update(s) failed; see the errors on stderr\n", errorCount)
}
// skipNote reports the modules the run left unpinned, so a run that declined to act on a block
// it recognised does not read like a run with nothing to do. Every skip it counts is warned
// about, which is why it names the warnings rather than repeating them, but not every warned
// skip counts: a local module can never carry a version, so nothing is left outstanding.
func skipNote(skipCount int, kind string) string {
if skipCount == 0 {
return ""
}
return fmt.Sprintf("%d %s(s) skipped; see the warnings on stderr\n", skipCount, kind)
}
// printRunSummary prints one run's summary line followed by its failures. A run that updated
// nothing reports why instead of the line, which would otherwise claim a clean zero it cannot
// vouch for: a mistyped source, a glob over the wrong tree and an already-current file all
// counted as a success. It names every cause it cannot tell apart, including the skips the count
// below leaves out, so it never denies a skip the run has just printed. It promises no tool that
// answers "which", because -audit-file needs a config and -verbose lists only filtered modules.
func printRunSummary(line string, totalUpdates, errorCount int, skipped string, dryRun bool) {
fmt.Println()
switch {
case totalUpdates > 0:
fmt.Println(line)
case errorCount > 0:
// Nothing was updated and something failed, so the failures below are the whole summary:
// a nothing-to-do line would read as a clean result. A skip does not suppress it, because
// the line names skipping as one of the causes and the note then quantifies it.
case dryRun:
fmt.Println("No updates would be performed. Nothing matched, or every match was already at the target version or skipped.")
default:
fmt.Println("No updates were performed. Nothing matched, or every match was already at the target version or skipped.")
}
fmt.Print(failureNote(errorCount))
fmt.Print(skipped)
}
// printSummary prints the final summary of updates. A direct run carries one module operation,
// so the count is always a count of files.
func printSummary(totalUpdates, errorCount, skipCount int, dryRun bool) {
line := fmt.Sprintf("Successfully updated %d file(s)", totalUpdates)
if dryRun {
line = fmt.Sprintf("Dry run: would update %d file(s)", totalUpdates)
}
printRunSummary(line, totalUpdates, errorCount, skipNote(skipCount, "module"), dryRun)
}
func main() {
flags := parseFlags()
// Handle version flag
if flags.showVersion {
fmt.Printf("tf-version-bump %s\n", version)
fmt.Printf(" commit: %s\n", commit)
fmt.Printf(" built: %s\n", date)
exitFunc(0)
}
// Validate operation modes
validateOperationModes(flags)
if flags.validationConfigFile != "" {
if err := validateConfigFile(flags.validationConfigFile); err != nil {
fatalf("Error validating config file: %v", err)
}
fmt.Printf("Config '%s' is valid\n", flags.validationConfigFile)
exitFunc(0)
}
if flags.check {
flags.dryRun = true
}
// Find and validate matching files
files := findMatchingFiles(flags)
validateRequiredOperationFlags(flags)
if flags.auditFile != "" {
if err := runAuditMode(files, flags); err != nil {
fatalf("%v", err)
}
return
}
totalUpdates, err := runUpdateMode(files, flags)
if err != nil {
fatalf("%v", err)
}
if flags.check && totalUpdates > 0 {
exitFunc(2)
}
}
// commandInputFiles lists every file the command reads: the selected Terraform files and, in
// config mode, the config. An output destination must not overwrite any of them.
func commandInputFiles(files []string, configFile string) []string {
if configFile == "" {
return files
}
return append(append([]string(nil), files...), configFile)
}
// runUpdateMode applies the selected updates and publishes any requested update report,
// returning the update-operation total that check mode turns into its exit status.
func runUpdateMode(files []string, flags *cliFlags) (int, error) {
inputFiles := commandInputFiles(files, flags.configFile)
preparedReport, err := prepareJSONOutput(updateReportOutput, flags.reportFile, inputFiles)
if err != nil {
return 0, err
}
var totalUpdates int
if flags.configFile != "" {
totalUpdates, err = runConfigFileMode(files, flags)
} else {
totalUpdates, err = runCLIMode(files, flags)
}
if err == nil && preparedReport != nil {
flags.report.SchemaVersion = 2
if publishErr := preparedReport.publish(&flags.report); publishErr != nil {
err = fmt.Errorf("Error writing update report: %v", publishErr) //nolint:staticcheck // User-facing CLI diagnostic.
}
}
if err == nil {
return totalUpdates, nil
}
if preparedReport != nil {
if discardErr := preparedReport.discard(); discardErr != nil {
err = fmt.Errorf("%w; failed to discard prepared report: %v", err, discardErr)
}
// A report describes the tree it was written from. Only a run that changed that tree and
// then failed leaves one describing a tree that no longer exists, so only such a run takes
// it away: a run refused for its config, a run whose every file failed and a dry run all
// leave the tree, and the report, exactly as they found them. A file a write left
// untrusted counts as changed even though no update is counted for it, because it holds
// neither version for certain. The publish failure reaches here too, which is the case
// most certain to need it — the files changed and the counts describing them never
// landed.
if (totalUpdates > 0 && !flags.dryRun) || anyUntrusted() {
if removeErr := preparedReport.removeDestination(); removeErr != nil {
err = fmt.Errorf("%w; failed to remove the stale report: %v", err, removeErr)
}
}
}
return totalUpdates, err
}
func validateRequiredOperationFlags(flags *cliFlags) {
if flags.moduleSource != "" {
_ = loadModuleUpdates(flags)
}
if flags.providerName != "" && flags.toVersion == "" {
fatalf("Error: -to flag is required when using -provider")
}
}
// jsonOutput describes a JSON document the command writes through a temporary file once its
// work succeeds, and how diagnostics name it.
type jsonOutput struct {
fileLabel string // the destination, as in "report file must not overwrite input file"
documentLabel string // the document, as in "Error preparing update report"
tempPattern string
}
var (
updateReportOutput = jsonOutput{fileLabel: "report file", documentLabel: "update report", tempPattern: ".tf-version-bump-report-*"}
auditOutput = jsonOutput{fileLabel: "audit file", documentLabel: "audit", tempPattern: ".tf-version-bump-audit-*"}
)
func prepareJSONOutput(output jsonOutput, destination string, inputFiles []string) (*preparedReportFile, error) {
if destination == "" {
return nil, nil
}
if err := validateOutputDoesNotOverwriteInput(output, destination, inputFiles); err != nil {
return nil, err
}
file, err := os.CreateTemp(filepath.Dir(destination), output.tempPattern)
if err != nil {
return nil, fmt.Errorf("Error preparing %s: %w", output.documentLabel, err) //nolint:staticcheck // User-facing CLI diagnostic.
}
return &preparedReportFile{destination: destination, file: file}, nil
}
func (prepared *preparedReportFile) publish(document any) error {
var data bytes.Buffer
encoder := json.NewEncoder(&data)
// encoding/json writes <, > and & as Unicode escapes by default, which would make
// constraints such as ">= 1.5" unreadable in the audit.
encoder.SetEscapeHTML(false)
encoder.SetIndent("", " ")
if err := encoder.Encode(document); err != nil {
_ = prepared.discard()
return fmt.Errorf("create report: %w", err)
}
if _, err := prepared.file.Write(data.Bytes()); err != nil {
_ = prepared.discard()
return err
}
if err := prepared.file.Sync(); err != nil {
_ = prepared.discard()
return err
}
temporaryName := prepared.file.Name()
// Closing consumes the handle whether or not it succeeds, so the caller's discard must not
// close it again and report a failure the run did not have.
closeErr := prepared.file.Close()
prepared.file = nil
if closeErr != nil {
_ = os.Remove(temporaryName)
return closeErr
}
if err := renameReportFile(temporaryName, prepared.destination); err != nil {
_ = os.Remove(temporaryName)
return err
}
return nil
}
// removeDestination deletes a report an earlier run left at the destination. Its caller decides
// when that is right: only a failed run that changed files leaves a report describing a tree which
// no longer exists, where a consumer reading it without checking the exit status would act on
// counts for another run. Audit mode never removes its own destination, for the same reason a run
// that changed nothing does not: a failed audit changes nothing on disk, so the previous audit is
// still a true snapshot.
func (prepared *preparedReportFile) removeDestination() error {
if prepared == nil {
return nil
}
if err := removeReportFile(prepared.destination); err != nil && !stderrors.Is(err, fs.ErrNotExist) {
return err
}
return nil
}
func (prepared *preparedReportFile) discard() error {
if prepared == nil || prepared.file == nil {
return nil
}
temporaryName := prepared.file.Name()
closeErr := prepared.file.Close()
prepared.file = nil
removeErr := os.Remove(temporaryName)
if closeErr != nil {
return closeErr
}
return removeErr
}
func validateOutputDoesNotOverwriteInput(output jsonOutput, destination string, inputFiles []string) error {
if destination == "" {
return nil
}
destinationPath, err := filepath.Abs(destination)
if err != nil {
return fmt.Errorf("Error resolving %s: %w", output.fileLabel, err) //nolint:staticcheck // User-facing CLI diagnostic.
}
destinationInfo, destinationStatErr := os.Stat(destinationPath)
if destinationStatErr != nil && !os.IsNotExist(destinationStatErr) {
return fmt.Errorf("Error inspecting %s: %w", output.fileLabel, destinationStatErr) //nolint:staticcheck // User-facing CLI diagnostic.
}
if destinationStatErr == nil && destinationInfo.IsDir() {
return fmt.Errorf("Error preparing %s: destination is a directory: %s", output.documentLabel, destination) //nolint:staticcheck // User-facing CLI diagnostic.
}
for _, inputFile := range inputFiles {
inputPath, absErr := filepath.Abs(inputFile)
if absErr != nil {
return fmt.Errorf("Error resolving input file %s: %w", inputFile, absErr) //nolint:staticcheck // User-facing CLI diagnostic.
}
if filepath.Clean(destinationPath) == filepath.Clean(inputPath) {
return fmt.Errorf("Error: %s must not overwrite input file: %s", output.fileLabel, destination) //nolint:staticcheck // User-facing CLI diagnostic.
}
if destinationStatErr != nil {
continue
}
inputInfo, inputStatErr := os.Stat(inputPath)
if inputStatErr != nil {
return fmt.Errorf("Error inspecting input file %s: %w", inputFile, inputStatErr) //nolint:staticcheck // User-facing CLI diagnostic.
}
if os.SameFile(destinationInfo, inputInfo) {
return fmt.Errorf("Error: %s must not overwrite input file: %s", output.fileLabel, destination) //nolint:staticcheck // User-facing CLI diagnostic.
}
}
return nil
}
// validateOperationModes validates that the CLI flags are properly set
func validateOperationModes(flags *cliFlags) {
if flags.validationConfigFile != "" {
if configValidationHasConflicts(flags) {
fatalf("Error: Cannot use -validate-config with update or report flags")
}
return
}
if flags.auditFile != "" {
validateAuditMode(flags)
}
if flags.check && flags.dryRun {
fatalf("Error: Cannot use -check with -dry-run")
}
if flags.check && flags.reportFile != "" {
fatalf("Error: Cannot use -check with -report-file")
}
// Config file mode is exclusive with all other CLI flags
if flags.configFile != "" {
validateConfigUpdateMode(flags)
return
}
// CLI mode - validate that at least one operation is specified
modesSet := 0
if flags.moduleSource != "" {
modesSet++
}
if flags.terraformVersion != "" {
modesSet++
}
if flags.providerName != "" {
modesSet++
}
if modesSet == 0 {
fmt.Println("Usage:")
fmt.Println(" Module update: tf-version-bump -pattern <glob> -module <source> -to <version>")
fmt.Println(" Config file: tf-version-bump -pattern <glob> -config <config-file>")
fmt.Println(" Config validation: tf-version-bump -validate-config <config-file>")
fmt.Println(" Terraform version: tf-version-bump -pattern <glob> -terraform-version <version>")
fmt.Println(" Provider version: tf-version-bump -pattern <glob> -provider <name> -to <version>")
flag.PrintDefaults()
exitFunc(1)
}
if modesSet > 1 {
fatalf("Error: Cannot use -module, -terraform-version, and -provider flags together. Choose one operation mode or use a config file.")
}
}
func validateConfigUpdateMode(flags *cliFlags) {
if flags.moduleSource != "" || flags.terraformVersion != "" || flags.providerName != "" ||
flags.toVersion != "" || len(flags.fromVersions) > 0 || len(flags.ignoreVersions) > 0 || flags.ignoreModules != "" {
fatalf("Error: Cannot use -config with other operation flags (-module, -to, -terraform-version, -provider, -from, -ignore-version, -ignore-modules)")
}
}
// validateAuditMode keeps -audit-file read-only: it compares files with a config and never
// combines with flags that preview, check, report or add versions.
func validateAuditMode(flags *cliFlags) {
if flags.configFile == "" {
fatalf("Error: -audit-file requires -config")
}
if flags.dryRun || flags.check || flags.reportFile != "" || flags.forceAdd {
fatalf("Error: Cannot use -audit-file with -dry-run, -check, -report-file or -force-add")
}
}
// configValidationHasConflicts reports whether any update or report flag accompanies
// -validate-config, which validates a config on its own. It is split in two so neither half
// exceeds the cyclomatic limit as flags are added.
func configValidationHasConflicts(flags *cliFlags) bool {
return configValidationHasOperationFlags(flags) || configValidationHasBehaviourFlags(flags)
}
// configValidationHasOperationFlags covers the flags naming what to update and where to write.
func configValidationHasOperationFlags(flags *cliFlags) bool {
return flags.pattern != "" || flags.configFile != "" || flags.moduleSource != "" ||
flags.toVersion != "" || flags.terraformVersion != "" || flags.providerName != "" ||
flags.reportFile != "" || flags.auditFile != ""
}
// configValidationHasBehaviourFlags covers the filters and switches that change how an update or audit runs.
func configValidationHasBehaviourFlags(flags *cliFlags) bool {
return len(flags.fromVersions) > 0 || len(flags.ignoreVersions) > 0 || flags.ignoreModules != "" ||
flags.branch != "" || flags.forceAdd || flags.dryRun || flags.check || flags.verbose
}
// findMatchingFiles finds all files matching the pattern
func findMatchingFiles(flags *cliFlags) []string {
if flags.pattern == "" {
fatalf("Error: -pattern flag is required")
}
// doublestar rather than filepath.Glob: it supports '**', which spans zero or more
// directories. filepath.Glob treats '**' as a plain '*', silently matching only one
// level deep.
//
// The filtered filesystem prevents wildcards from walking into dot-directories, so
// '**/*.tf' skips tool-managed .terraform and .git trees without excluding dotfiles.
// Naming a dot-directory explicitly places it in the non-glob base path, so it remains
// reachable.
// - WithNoFollow: don't traverse directory symlinks, which would otherwise match the
// same physical file via both its real path and the link.
// - WithFilesOnly: '**' matches directories as readily as files; we only want files.
pattern := filepath.ToSlash(filepath.Clean(flags.pattern))
base, globPattern := doublestar.SplitPattern(pattern)
fileSystem := os.DirFS(base)
if readDirFS, ok := fileSystem.(fs.ReadDirFS); ok {
fileSystem = visibleDirFS{ReadDirFS: readDirFS}
}
matches, err := doublestar.Glob(
fileSystem,
globPattern,
doublestar.WithNoFollow(),
doublestar.WithFilesOnly(),
)
if err != nil {
fatalf("Error matching pattern: %v", err)
}
files := make([]string, 0, len(matches))
for _, match := range matches {
filename := filepath.Join(base, filepath.FromSlash(match))
info, lstatErr := os.Lstat(filename)
if lstatErr == nil && info.Mode()&os.ModeSymlink != 0 {
target, statErr := os.Stat(filename)
if statErr == nil && target.IsDir() {
continue
}
}
files = append(files, filename)
}
// doublestar walks depth-first, so results come back in traversal order rather than
// sorted. File order is user-visible in the per-file output.
slices.Sort(files)
if len(files) == 0 {
fatalf("No files matched pattern: %s", flags.pattern)
}
fmt.Printf("Found %d file(s) matching pattern %s\n", len(files), quote(flags.pattern, flags.output))
if flags.check {
fmt.Println("Running in check mode - no files will be modified")
} else if flags.dryRun {
fmt.Println("Running in dry-run mode - no files will be modified")
}
return files
}
// runConfigFileMode handles config file mode operations.
func runConfigFileMode(files []string, flags *cliFlags) (int, error) {
config, err := loadResolvedConfig(flags.configFile, flags.branch)
if err != nil {
return 0, err
}
// -validate-config rejects a config that asks for nothing, so an update run does too: a file
// truncated by a bad merge would otherwise be a cheerful no-op. The refusal lives here rather
// than in the loader, which audit mode shares and which must keep reporting such a config.
if config.declaresNoUpdates() {
return 0, fmt.Errorf("Error: %w", errConfigDeclaresNoUpdates) //nolint:staticcheck // User-facing CLI diagnostic.
}
var terraformUpdates, terraformErrors, providerUpdates, providerSkips, providerErrors, moduleUpdates, moduleSkips, moduleErrors int
// Process terraform version if specified
if config.TerraformVersion != "" {
terraformUpdates, terraformErrors = processTerraformVersion(files, config.TerraformVersion, flags.dryRun, flags.output, flags.reportRecorder())
}
// Process provider updates if specified
for _, provider := range config.Providers {
count, skips, updateErrors := processProviderVersion(files, provider.Name, provider.Version, flags.dryRun, flags.output, flags.reportRecorder())
providerUpdates += count
providerSkips += skips
providerErrors += updateErrors
}
// Process module updates if specified
if len(config.Modules) > 0 {
moduleUpdates, moduleSkips, moduleErrors = processFiles(files, config.Modules, flags)
}
// Print summary
outcome := configOutcome{
terraformUpdates: terraformUpdates, terraformErrors: terraformErrors,
providerUpdates: providerUpdates, providerErrors: providerErrors,
moduleUpdates: moduleUpdates, moduleErrors: moduleErrors,
moduleSkips: moduleSkips, providerSkips: providerSkips,
}
printConfigSummary(outcome, flags.dryRun)
if outcome.onlyModuleErrors() {
return outcome.updates(), fmt.Errorf("Error: %d module update error(s)", outcome.moduleErrors) //nolint:staticcheck // User-facing CLI diagnostic.
}
if outcome.errors() > 0 {
return outcome.updates(), fmt.Errorf("Error: %d update error(s)", outcome.errors()) //nolint:staticcheck // User-facing CLI diagnostic.
}
return outcome.updates(), nil
}
// runCLIMode handles CLI mode operations
func runCLIMode(files []string, flags *cliFlags) (int, error) {
var totalUpdates int
var updates []ModuleUpdate
switch {
case flags.terraformVersion != "":
var totalErrors int
totalUpdates, totalErrors = processTerraformVersion(files, flags.terraformVersion, flags.dryRun, flags.output, flags.reportRecorder())
printTerraformSummary(totalUpdates, totalErrors, flags.dryRun)
if totalErrors > 0 {
return totalUpdates, fmt.Errorf("Error: %d Terraform version update error(s)", totalErrors) //nolint:staticcheck // User-facing CLI diagnostic.
}
return totalUpdates, nil
case flags.providerName != "":
if flags.toVersion == "" {
fatalf("Error: -to flag is required when using -provider")
}
var totalErrors int
var totalSkips int
totalUpdates, totalSkips, totalErrors = processProviderVersion(files, flags.providerName, flags.toVersion, flags.dryRun, flags.output, flags.reportRecorder())
printProviderSummary(flags.providerName, totalUpdates, totalErrors, totalSkips, flags.dryRun, flags.output)
if totalErrors > 0 {
return totalUpdates, fmt.Errorf("Error: %d provider update error(s)", totalErrors) //nolint:staticcheck // User-facing CLI diagnostic.
}
return totalUpdates, nil
default:
updates = loadModuleUpdates(flags)
var totalErrors int
var totalSkips int
totalUpdates, totalSkips, totalErrors = processFiles(files, updates, flags)
printSummary(totalUpdates, totalErrors, totalSkips, flags.dryRun)
if totalErrors > 0 {
return totalUpdates, fmt.Errorf("Error: %d module update error(s)", totalErrors) //nolint:staticcheck // User-facing CLI diagnostic.
}
return totalUpdates, nil
}
}
// configOutcome counts what one config-mode run applied, or in a dry run would apply, and what
// it failed on. The summary needs the failures as well as the updates: without them a run whose
// every update failed cannot be told from one with nothing to do, and the operator is sent to
// the config when the files were at fault.
type configOutcome struct {
terraformUpdates, terraformErrors int
providerUpdates, providerErrors int
moduleUpdates, moduleErrors int
moduleSkips, providerSkips int
}
// updates counts the Terraform, provider and module version updates.
func (o configOutcome) updates() int {
return o.terraformUpdates + o.providerUpdates + o.moduleUpdates
}
// errors counts the failed Terraform, provider and module update operations.
func (o configOutcome) errors() int {
return o.terraformErrors + o.providerErrors + o.moduleErrors
}
// onlyModuleErrors reports whether every failure was a module update, which lets the run name the
// modules in its error rather than blame the whole config.
func (o configOutcome) onlyModuleErrors() bool {
return o.terraformErrors == 0 && o.providerErrors == 0 && o.moduleErrors > 0