Skip to content

Commit b87ebec

Browse files
authored
fix: avoid crash on empty file formatting (hashicorp#578)
1 parent 5f8799e commit b87ebec

File tree

2 files changed

+38
-5
lines changed

2 files changed

+38
-5
lines changed

internal/hcl/diff.go

+19-3
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,25 @@ func diffLines(filename string, beforeLines, afterLines source.Lines) filesystem
112112
}
113113

114114
if c.Tag == OpInsert {
115-
insertRng := &hcl.Range{}
116-
insertRng.Start = beforeLines[beforeStart-1].Range().End
117-
insertRng.End = beforeLines[beforeStart-1].Range().End
115+
insertRng := &hcl.Range{
116+
Filename: filename,
117+
Start: hcl.InitialPos,
118+
End: hcl.InitialPos,
119+
}
120+
121+
if beforeStart == beforeEnd {
122+
line := beforeLines[beforeStart]
123+
insertRng = line.Range().Ptr()
124+
} else {
125+
for i, line := range beforeLines[beforeStart:beforeEnd] {
126+
if i == 0 {
127+
insertRng = line.Range().Ptr()
128+
continue
129+
}
130+
insertRng.End = line.Range().End
131+
}
132+
}
133+
118134
var newBytes []byte
119135

120136
for _, line := range afterLines[afterStart:afterEnd] {

internal/hcl/diff_test.go

+19-2
Original file line numberDiff line numberDiff line change
@@ -147,8 +147,9 @@ ccc`,
147147
&fileChange{
148148
newText: "\n",
149149
rng: &hcl.Range{
150-
Start: hcl.Pos{Line: 3, Column: 1, Byte: 30},
151-
End: hcl.Pos{Line: 3, Column: 1, Byte: 30},
150+
Filename: "test.tf",
151+
Start: hcl.Pos{Line: 3, Column: 1, Byte: 30},
152+
End: hcl.Pos{Line: 3, Column: 1, Byte: 30},
152153
},
153154
},
154155
},
@@ -177,6 +178,22 @@ ccc`,
177178
},
178179
},
179180
},
181+
{
182+
"empty to newline",
183+
``,
184+
`
185+
`,
186+
filesystem.DocumentChanges{
187+
&fileChange{
188+
newText: "\n",
189+
rng: &hcl.Range{
190+
Filename: "test.tf",
191+
Start: hcl.Pos{Line: 1, Column: 1, Byte: 0},
192+
End: hcl.Pos{Line: 1, Column: 1, Byte: 0},
193+
},
194+
},
195+
},
196+
},
180197
}
181198

182199
for i, tc := range testCases {

0 commit comments

Comments
 (0)