github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/internal/imports/sortimports.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 // Hacked up copy of go/ast/import.go 6 7 package imports 8 9 import ( 10 "go/ast" 11 "go/token" 12 "log" 13 "sort" 14 "strconv" 15 ) 16 17 // sortImports sorts runs of consecutive import lines in import blocks in f. 18 // It also removes duplicate imports when it is possible to do so without data loss. 19 func sortImports(localPrefix string, fset *token.FileSet, f *ast.File) { 20 for i, d := range f.Decls { 21 d, ok := d.(*ast.GenDecl) 22 if !ok || d.Tok != token.IMPORT { 23 // Not an import declaration, so we're done. 24 // Imports are always first. 25 break 26 } 27 28 if len(d.Specs) == 0 { 29 // Empty import block, remove it. 30 f.Decls = append(f.Decls[:i], f.Decls[i+1:]...) 31 } 32 33 if !d.Lparen.IsValid() { 34 // Not a block: sorted by default. 35 continue 36 } 37 38 // Identify and sort runs of specs on successive lines. 39 i := 0 40 specs := d.Specs[:0] 41 for j, s := range d.Specs { 42 if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line { 43 // j begins a new run. End this one. 44 specs = append(specs, sortSpecs(localPrefix, fset, f, d.Specs[i:j])...) 45 i = j 46 } 47 } 48 specs = append(specs, sortSpecs(localPrefix, fset, f, d.Specs[i:])...) 49 d.Specs = specs 50 51 // Deduping can leave a blank line before the rparen; clean that up. 52 if len(d.Specs) > 0 { 53 lastSpec := d.Specs[len(d.Specs)-1] 54 lastLine := fset.PositionFor(lastSpec.Pos(), false).Line 55 if rParenLine := fset.PositionFor(d.Rparen, false).Line; rParenLine > lastLine+1 { 56 fset.File(d.Rparen).MergeLine(rParenLine - 1) 57 } 58 } 59 } 60 } 61 62 // mergeImports merges all the import declarations into the first one. 63 // Taken from github.com/powerman/golang-tools/ast/astutil. 64 // This does not adjust line numbers properly 65 func mergeImports(fset *token.FileSet, f *ast.File) { 66 if len(f.Decls) <= 1 { 67 return 68 } 69 70 // Merge all the import declarations into the first one. 71 var first *ast.GenDecl 72 for i := 0; i < len(f.Decls); i++ { 73 decl := f.Decls[i] 74 gen, ok := decl.(*ast.GenDecl) 75 if !ok || gen.Tok != token.IMPORT || declImports(gen, "C") { 76 continue 77 } 78 if first == nil { 79 first = gen 80 continue // Don't touch the first one. 81 } 82 // We now know there is more than one package in this import 83 // declaration. Ensure that it ends up parenthesized. 84 first.Lparen = first.Pos() 85 // Move the imports of the other import declaration to the first one. 86 for _, spec := range gen.Specs { 87 spec.(*ast.ImportSpec).Path.ValuePos = first.Pos() 88 first.Specs = append(first.Specs, spec) 89 } 90 f.Decls = append(f.Decls[:i], f.Decls[i+1:]...) 91 i-- 92 } 93 } 94 95 // declImports reports whether gen contains an import of path. 96 // Taken from github.com/powerman/golang-tools/ast/astutil. 97 func declImports(gen *ast.GenDecl, path string) bool { 98 if gen.Tok != token.IMPORT { 99 return false 100 } 101 for _, spec := range gen.Specs { 102 impspec := spec.(*ast.ImportSpec) 103 if importPath(impspec) == path { 104 return true 105 } 106 } 107 return false 108 } 109 110 func importPath(s ast.Spec) string { 111 t, err := strconv.Unquote(s.(*ast.ImportSpec).Path.Value) 112 if err == nil { 113 return t 114 } 115 return "" 116 } 117 118 func importName(s ast.Spec) string { 119 n := s.(*ast.ImportSpec).Name 120 if n == nil { 121 return "" 122 } 123 return n.Name 124 } 125 126 func importComment(s ast.Spec) string { 127 c := s.(*ast.ImportSpec).Comment 128 if c == nil { 129 return "" 130 } 131 return c.Text() 132 } 133 134 // collapse indicates whether prev may be removed, leaving only next. 135 func collapse(prev, next ast.Spec) bool { 136 if importPath(next) != importPath(prev) || importName(next) != importName(prev) { 137 return false 138 } 139 return prev.(*ast.ImportSpec).Comment == nil 140 } 141 142 type posSpan struct { 143 Start token.Pos 144 End token.Pos 145 } 146 147 func sortSpecs(localPrefix string, fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec { 148 // Can't short-circuit here even if specs are already sorted, 149 // since they might yet need deduplication. 150 // A lone import, however, may be safely ignored. 151 if len(specs) <= 1 { 152 return specs 153 } 154 155 // Record positions for specs. 156 pos := make([]posSpan, len(specs)) 157 for i, s := range specs { 158 pos[i] = posSpan{s.Pos(), s.End()} 159 } 160 161 // Identify comments in this range. 162 // Any comment from pos[0].Start to the final line counts. 163 lastLine := fset.Position(pos[len(pos)-1].End).Line 164 cstart := len(f.Comments) 165 cend := len(f.Comments) 166 for i, g := range f.Comments { 167 if g.Pos() < pos[0].Start { 168 continue 169 } 170 if i < cstart { 171 cstart = i 172 } 173 if fset.Position(g.End()).Line > lastLine { 174 cend = i 175 break 176 } 177 } 178 comments := f.Comments[cstart:cend] 179 180 // Assign each comment to the import spec preceding it. 181 importComment := map[*ast.ImportSpec][]*ast.CommentGroup{} 182 specIndex := 0 183 for _, g := range comments { 184 for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() { 185 specIndex++ 186 } 187 s := specs[specIndex].(*ast.ImportSpec) 188 importComment[s] = append(importComment[s], g) 189 } 190 191 // Sort the import specs by import path. 192 // Remove duplicates, when possible without data loss. 193 // Reassign the import paths to have the same position sequence. 194 // Reassign each comment to abut the end of its spec. 195 // Sort the comments by new position. 196 sort.Sort(byImportSpec{localPrefix, specs}) 197 198 // Dedup. Thanks to our sorting, we can just consider 199 // adjacent pairs of imports. 200 deduped := specs[:0] 201 for i, s := range specs { 202 if i == len(specs)-1 || !collapse(s, specs[i+1]) { 203 deduped = append(deduped, s) 204 } else { 205 p := s.Pos() 206 fset.File(p).MergeLine(fset.Position(p).Line) 207 } 208 } 209 specs = deduped 210 211 // Fix up comment positions 212 for i, s := range specs { 213 s := s.(*ast.ImportSpec) 214 if s.Name != nil { 215 s.Name.NamePos = pos[i].Start 216 } 217 s.Path.ValuePos = pos[i].Start 218 s.EndPos = pos[i].End 219 nextSpecPos := pos[i].End 220 221 for _, g := range importComment[s] { 222 for _, c := range g.List { 223 c.Slash = pos[i].End 224 nextSpecPos = c.End() 225 } 226 } 227 if i < len(specs)-1 { 228 pos[i+1].Start = nextSpecPos 229 pos[i+1].End = nextSpecPos 230 } 231 } 232 233 sort.Sort(byCommentPos(comments)) 234 235 // Fixup comments can insert blank lines, because import specs are on different lines. 236 // We remove those blank lines here by merging import spec to the first import spec line. 237 firstSpecLine := fset.Position(specs[0].Pos()).Line 238 for _, s := range specs[1:] { 239 p := s.Pos() 240 line := fset.File(p).Line(p) 241 for previousLine := line - 1; previousLine >= firstSpecLine; { 242 // MergeLine can panic. Avoid the panic at the cost of not removing the blank line 243 // golang/go#50329 244 if previousLine > 0 && previousLine < fset.File(p).LineCount() { 245 fset.File(p).MergeLine(previousLine) 246 previousLine-- 247 } else { 248 // try to gather some data to diagnose how this could happen 249 req := "Please report what the imports section of your go file looked like." 250 log.Printf("panic avoided: first:%d line:%d previous:%d max:%d. %s", 251 firstSpecLine, line, previousLine, fset.File(p).LineCount(), req) 252 } 253 } 254 } 255 return specs 256 } 257 258 type byImportSpec struct { 259 localPrefix string 260 specs []ast.Spec // slice of *ast.ImportSpec 261 } 262 263 func (x byImportSpec) Len() int { return len(x.specs) } 264 func (x byImportSpec) Swap(i, j int) { x.specs[i], x.specs[j] = x.specs[j], x.specs[i] } 265 func (x byImportSpec) Less(i, j int) bool { 266 ipath := importPath(x.specs[i]) 267 jpath := importPath(x.specs[j]) 268 269 igroup := importGroup(x.localPrefix, ipath) 270 jgroup := importGroup(x.localPrefix, jpath) 271 if igroup != jgroup { 272 return igroup < jgroup 273 } 274 275 if ipath != jpath { 276 return ipath < jpath 277 } 278 iname := importName(x.specs[i]) 279 jname := importName(x.specs[j]) 280 281 if iname != jname { 282 return iname < jname 283 } 284 return importComment(x.specs[i]) < importComment(x.specs[j]) 285 } 286 287 type byCommentPos []*ast.CommentGroup 288 289 func (x byCommentPos) Len() int { return len(x) } 290 func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] } 291 func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() }