command: Fix 0.13upgrade to preserve more comments

Previously, any comments inside the required provider configuration for
a given provider would be wiped out upon rerunning the 0.13upgrade
command. This commit attempts to preserve those comments if the existing
entry is semantically equivalent to the entry we are about to write.
This commit is contained in:
Alisdair McDiarmid 2020-06-24 15:54:46 -04:00
parent 9f455bfc55
commit b6739829e7
3 changed files with 30 additions and 2 deletions

View File

@ -404,7 +404,18 @@ command and dealing with them before running this command again.
} else {
attributesObject = cty.EmptyObjectVal
}
body.SetAttributeValue(localName, attributesObject)
// If this block already has an entry for this local name, we only
// want to replace it if it's semantically different
if existing := body.GetAttribute(localName); existing != nil {
bytes := existing.Expr().BuildTokens(nil).Bytes()
expr, _ := hclsyntax.ParseExpression(bytes, "", hcl.InitialPos)
value, _ := expr.Value(nil)
if !attributesObject.RawEquals(value) {
body.SetAttributeValue(localName, attributesObject)
}
} else {
body.SetAttributeValue(localName, attributesObject)
}
// If we don't have a source attribute, manually construct a commented
// block explaining what to do

View File

@ -9,8 +9,15 @@ terraform {
source = "hashicorp/bar"
version = "0.5.0"
}
# An explicit requirement
baz = {
# Comment inside the block should stay
source = "foo/baz"
}
# Foo is required
foo = {
source = "hashicorp/foo"
source = "hashicorp/foo"
version = "1.0.0"
}
}
}

View File

@ -6,5 +6,15 @@ terraform {
required_providers {
# Pin bar to this version
bar = "0.5.0"
# An explicit requirement
baz = {
# Comment inside the block should stay
source = "foo/baz"
}
# Foo is required
foo = {
# This comment sadly won't make it
version = "1.0.0"
}
}
}