Skip to content

Commit

Permalink
internal/lsp: avoid panic caused by assuming file ends with newline
Browse files Browse the repository at this point in the history
importPrefix in format.go computes the end of the package statement
including a trailing newline. This causes a panic if the user has
not typed the newline. The code now checks for that case.

Fixes golang/go#40208

Change-Id: I4c5118a5de78027e6c5e6ed91dfddca81e38f7e9
Reviewed-on: https://go-review.googlesource.com/c/tools/+/242638
Reviewed-by: Heschi Kreinick <heschi@google.com>
  • Loading branch information
pjweinbgo committed Jul 14, 2020
1 parent 6acd2ab commit 9048b46
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 1 deletion.
3 changes: 3 additions & 0 deletions internal/lsp/source/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,9 @@ func importPrefix(src []byte) string {
}
if importEnd == 0 {
importEnd = pkgEnd
if importEnd > len(src) {
importEnd-- // pkgEnd is off by 1 because Pos is 1-based
}
}
for _, c := range f.Comments {
if int(c.End()) > importEnd {
Expand Down
3 changes: 2 additions & 1 deletion internal/lsp/source/format_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ type data struct {

func TestImportPrefix(t *testing.T) {
var tdata = []data{
{"package foo", "package foo"},
{"package foo\n", "package foo\n"},
{"package foo\n\nfunc f(){}\n", "package foo\n"},
{"package foo\n\nimport \"fmt\"\n", "package foo\n\nimport \"fmt\""},
Expand All @@ -24,7 +25,7 @@ func TestImportPrefix(t *testing.T) {
for i, x := range tdata {
got := importPrefix([]byte(x.input))
if got != x.want {
t.Errorf("%d: got\n%q, wanted\n%q", i, got, x.want)
t.Errorf("%d: got\n%q, wanted\n%q for %q", i, got, x.want, x.input)
}
}
}

0 comments on commit 9048b46

Please sign in to comment.