Skip to content

Commit f6f707c

Browse files
authored
Merge pull request #25381 from hashicorp/alisdair/013upgrade-preserves-more-comments
command: Fix 0.13upgrade to preserve more comments
2 parents 02b130c + b673982 commit f6f707c

File tree

3 files changed

+30
-2
lines changed

3 files changed

+30
-2
lines changed

command/013_config_upgrade.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,18 @@ command and dealing with them before running this command again.
404404
} else {
405405
attributesObject = cty.EmptyObjectVal
406406
}
407-
body.SetAttributeValue(localName, attributesObject)
407+
// If this block already has an entry for this local name, we only
408+
// want to replace it if it's semantically different
409+
if existing := body.GetAttribute(localName); existing != nil {
410+
bytes := existing.Expr().BuildTokens(nil).Bytes()
411+
expr, _ := hclsyntax.ParseExpression(bytes, "", hcl.InitialPos)
412+
value, _ := expr.Value(nil)
413+
if !attributesObject.RawEquals(value) {
414+
body.SetAttributeValue(localName, attributesObject)
415+
}
416+
} else {
417+
body.SetAttributeValue(localName, attributesObject)
418+
}
408419

409420
// If we don't have a source attribute, manually construct a commented
410421
// block explaining what to do

command/testdata/013upgrade-preserves-comments/expected/main.tf

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,15 @@ terraform {
99
source = "hashicorp/bar"
1010
version = "0.5.0"
1111
}
12+
# An explicit requirement
13+
baz = {
14+
# Comment inside the block should stay
15+
source = "foo/baz"
16+
}
17+
# Foo is required
1218
foo = {
13-
source = "hashicorp/foo"
19+
source = "hashicorp/foo"
20+
version = "1.0.0"
1421
}
1522
}
1623
}

command/testdata/013upgrade-preserves-comments/input/main.tf

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,5 +6,15 @@ terraform {
66
required_providers {
77
# Pin bar to this version
88
bar = "0.5.0"
9+
# An explicit requirement
10+
baz = {
11+
# Comment inside the block should stay
12+
source = "foo/baz"
13+
}
14+
# Foo is required
15+
foo = {
16+
# This comment sadly won't make it
17+
version = "1.0.0"
18+
}
919
}
1020
}

0 commit comments

Comments
 (0)