1
0
mirror of https://github.com/golang/go synced 2024-09-30 18:18:32 -06:00
go/internal/lsp/source/format_test.go
Rebecca Stambler 2ad651e9e2 internal/lsp: handle bad formatting with CRLF line endings
The importPrefix logic is complicated by Windows line endings, since
go/ast isn't aware of different line endings in comment text. I made a
few changes to the way that import prefixes are computed to handle this.

Specifically, for comments, we try to make sure the range ends on a full
line as much as possible, because that addresses the line ending issue.

Fixes golang/go#40355

Change-Id: I84c1cfa0d0bae532e52ed181e8a5383157feef24
Reviewed-on: https://go-review.googlesource.com/c/tools/+/244897
Run-TryBot: Rebecca Stambler <rstambler@golang.org>
TryBot-Result: Gobot Gobot <gobot@golang.org>
Reviewed-by: Heschi Kreinick <heschi@google.com>
2020-07-28 16:05:17 +00:00

50 lines
1.6 KiB
Go

package source
import (
"fmt"
"testing"
"golang.org/x/tools/internal/lsp/diff"
"golang.org/x/tools/internal/lsp/diff/myers"
)
func TestImportPrefix(t *testing.T) {
for i, tt := range []struct {
input, want string
}{
{"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\""},
{"package foo\nimport (\n\"fmt\"\n)\n", "package foo\nimport (\n\"fmt\"\n)"},
{"\n\n\npackage foo\n", "\n\n\npackage foo\n"},
{"// hi \n\npackage foo //xx\nfunc _(){}\n", "// hi \n\npackage foo //xx\n"},
{"package foo //hi\n", "package foo //hi\n"},
{"//hi\npackage foo\n//a\n\n//b\n", "//hi\npackage foo\n//a\n\n//b\n"},
{
"package a\n\nimport (\n \"fmt\"\n)\n//hi\n",
"package a\n\nimport (\n \"fmt\"\n)\n//hi\n",
},
{`package a /*hi*/`, `package a /*hi*/`},
{"package main\r\n\r\nimport \"go/types\"\r\n\r\n/*\r\n\r\n */\r\n", "package main\r\n\r\nimport \"go/types\"\r\n\r\n/*\r\n\r\n */\r\n"},
{"package x; import \"os\"; func f() {}\n\n", "package x; import \"os\""},
{"package x; func f() {fmt.Println()}\n\n", "package x"},
} {
got := importPrefix([]byte(tt.input))
if got != tt.want {
t.Errorf("%d: failed for %q:\n%s", i, tt.input, diffStr(tt.want, got))
}
}
}
func diffStr(want, got string) string {
if want == got {
return ""
}
// Add newlines to avoid newline messages in diff.
want += "\n"
got += "\n"
d := myers.ComputeEdits("", want, got)
return fmt.Sprintf("%q", diff.ToUnified("want", "got", want, d))
}