1
0
mirror of https://github.com/golang/go synced 2024-11-22 05:24:39 -07:00
Change-Id: Icfe8c0e73d5cc833c7d64ce247b35d3baf1b181e
This commit is contained in:
Mateusz Poliwczak 2024-09-30 18:24:29 +02:00
parent b2b458c5e8
commit ecd6efabaa
2 changed files with 14 additions and 8 deletions

View File

@ -14,7 +14,6 @@ import (
// SortImports sorts runs of consecutive import lines in import blocks in f.
// It also removes duplicate imports when it is possible to do so without data loss.
func SortImports(fset *token.FileSet, f *File) {
f.Imports = f.Imports[:0]
for _, d := range f.Decls {
d, ok := d.(*GenDecl)
if !ok || d.Tok != token.IMPORT {
@ -24,9 +23,6 @@ func SortImports(fset *token.FileSet, f *File) {
}
if !d.Lparen.IsValid() {
for _, v := range d.Specs {
f.Imports = append(f.Imports, v.(*ImportSpec))
}
// Not a block: sorted by default.
continue
}
@ -44,10 +40,6 @@ func SortImports(fset *token.FileSet, f *File) {
specs = append(specs, sortSpecs(fset, f, d.Specs[i:])...)
d.Specs = specs
for _, v := range specs {
f.Imports = append(f.Imports, v.(*ImportSpec))
}
// Deduping can leave a blank line before the rparen; clean that up.
if len(d.Specs) > 0 {
lastSpec := d.Specs[len(d.Specs)-1]
@ -59,6 +51,16 @@ func SortImports(fset *token.FileSet, f *File) {
}
}
}
// Make File.Imports order consistent.
f.Imports = f.Imports[:0]
for _, decl := range f.Decls {
if decl, ok := decl.(*GenDecl); ok && decl.Tok == token.IMPORT {
for _, spec := range decl.Specs {
f.Imports = append(f.Imports, spec.(*ImportSpec))
}
}
}
}
func lineAt(fset *token.FileSet, pos token.Pos) int {

View File

@ -26,11 +26,13 @@ import (
ast.SortImports(fset, f)
// Check that the duplicate import spec is eliminated.
importDeclSpecCount := len(f.Decls[0].(*ast.GenDecl).Specs)
if importDeclSpecCount != 1 {
t.Fatalf("len(f.Decls[0].(*ast.GenDecl).Specs) = %v; want = 1", importDeclSpecCount)
}
// Check that File.Imports is consistent.
if len(f.Imports) != 1 {
t.Fatalf("len(f.Imports) = %v; want = 1", len(f.Imports))
}
@ -60,6 +62,7 @@ import (
ast.SortImports(fset, f)
// Check that three single-spec import decls remain.
for i := range 3 {
importDeclSpecCount := len(f.Decls[i].(*ast.GenDecl).Specs)
if importDeclSpecCount != 1 {
@ -67,6 +70,7 @@ import (
}
}
// Check that File.Imports is consistent.
if len(f.Imports) != 3 {
t.Fatalf("len(f.Imports) = %v; want = 3", len(f.Imports))
}