Skip to content

Commit

Permalink
hclwrite: Allow blank quoted string block labels
Browse files Browse the repository at this point in the history
The hclsyntax package permits block labels to be blank quoted strings,
and defers to the application to determine if this is valid or not. This
commit updates hclwrite to allow the same behaviour.

This is in response to an upstream bug report on Terraform, which uses
hclwrite to implement its fmt subcommand. Given a block with a blank
quoted string label, it currently deletes the label when formatting.
This is inconsistent with Terraform's behaviour when parsing HCL, which
treats empty labels differently from missing labels.
  • Loading branch information
alisdair committed Nov 18, 2020
1 parent 3de61ec commit 1818f36
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
6 changes: 6 additions & 0 deletions hclwrite/ast_block.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,12 @@ func (bl *blockLabels) Current() []string {
if !diags.HasErrors() {
labelNames = append(labelNames, labelString)
}
} else if len(tokens) == 2 &&
tokens[0].Type == hclsyntax.TokenOQuote &&
tokens[1].Type == hclsyntax.TokenCQuote {
// An open quote followed immediately by a closing quote is a
// valid but unusual blank string label.
labelNames = append(labelNames, "")
}

default:
Expand Down
9 changes: 8 additions & 1 deletion hclwrite/ast_block_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,13 @@ escape "\u0041" {
`,
[]string{"\u0041"},
},
{
`
blank "" {
}
`,
[]string{""},
},
}

for _, test := range tests {
Expand Down Expand Up @@ -414,7 +421,7 @@ func TestBlockSetLabels(t *testing.T) {
{
`foo "hoge" /* foo */ "" {}`,
"foo",
[]string{"hoge"},
[]string{"hoge", ""},
[]string{"fuga"}, // force quoted form even if the old one is unquoted.
Tokens{
{
Expand Down

0 comments on commit 1818f36

Please sign in to comment.