1
0
mirror of https://github.com/golang/go synced 2024-11-21 22:34:48 -07:00

go/ast: don't MergeLine in SortImports when last import on the same line as RParen

This commit is contained in:
Mateusz Poliwczak 2024-08-31 16:25:05 +02:00
parent 630d4fb600
commit b04affa7e6
2 changed files with 44 additions and 4 deletions

View File

@ -33,11 +33,11 @@ func SortImports(fset *token.FileSet, f *File) {
for j, s := range d.Specs {
if j > i && lineAt(fset, s.Pos()) > 1+lineAt(fset, d.Specs[j-1].End()) {
// j begins a new run. End this one.
specs = append(specs, sortSpecs(fset, f, d.Specs[i:j])...)
specs = append(specs, sortSpecs(fset, f, d, d.Specs[i:j])...)
i = j
}
}
specs = append(specs, sortSpecs(fset, f, d.Specs[i:])...)
specs = append(specs, sortSpecs(fset, f, d, d.Specs[i:])...)
d.Specs = specs
// Deduping can leave a blank line before the rparen; clean that up.
@ -109,7 +109,7 @@ type cgPos struct {
cg *CommentGroup
}
func sortSpecs(fset *token.FileSet, f *File, specs []Spec) []Spec {
func sortSpecs(fset *token.FileSet, f *File, d *GenDecl, specs []Spec) []Spec {
// Can't short-circuit here even if specs are already sorted,
// since they might yet need deduplication.
// A lone import, however, may be safely ignored.
@ -207,7 +207,9 @@ func sortSpecs(fset *token.FileSet, f *File, specs []Spec) []Spec {
deduped = append(deduped, s)
} else {
p := s.Pos()
fset.File(p).MergeLine(lineAt(fset, p))
if l := lineAt(fset, p); l != lineAt(fset, d.Rparen) {
fset.File(p).MergeLine(l)
}
}
}
specs = deduped

View File

@ -76,3 +76,41 @@ import (
}
})
}
func TestIssue69183(t *testing.T) {
const src = `package A
import (
"a"//a
"a")
`
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, "test.go", src, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
t.Fatal(err)
}
ast.SortImports(fs, f) // should not panic
}
func TestSortImportsSameLastLine(t *testing.T) {
const src = `package A
import (
"a"//a
"a")
func a() {}
`
fs := token.NewFileSet()
f, err := parser.ParseFile(fs, "test.go", src, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
t.Fatal(err)
}
ast.SortImports(fs, f)
fd := f.Decls[1].(*ast.FuncDecl)
fdPos := fs.Position(fd.Pos())
if fdPos.Column != 1 {
t.Errorf("invalid fdPos.Column = %v; want = 1", fdPos.Column)
}
if fdPos.Line != 5 {
t.Errorf("invalid fdPos.Line = %v; want = 5", fdPos.Line)
}
}