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.
5 // Hacked up copy of go/ast/import.go
16 // sortImports sorts runs of consecutive import lines in import blocks in f.
17 // It also removes duplicate imports when it is possible to do so without data loss.
18 func sortImports(fset *token.FileSet, f *ast.File) {
19 for i, d := range f.Decls {
20 d, ok := d.(*ast.GenDecl)
21 if !ok || d.Tok != token.IMPORT {
22 // Not an import declaration, so we're done.
23 // Imports are always first.
27 if len(d.Specs) == 0 {
28 // Empty import block, remove it.
29 f.Decls = append(f.Decls[:i], f.Decls[i+1:]...)
32 if !d.Lparen.IsValid() {
33 // Not a block: sorted by default.
37 // Identify and sort runs of specs on successive lines.
40 for j, s := range d.Specs {
41 if j > i && fset.Position(s.Pos()).Line > 1+fset.Position(d.Specs[j-1].End()).Line {
42 // j begins a new run. End this one.
43 specs = append(specs, sortSpecs(fset, f, d.Specs[i:j])...)
47 specs = append(specs, sortSpecs(fset, f, d.Specs[i:])...)
50 // Deduping can leave a blank line before the rparen; clean that up.
52 lastSpec := d.Specs[len(d.Specs)-1]
53 lastLine := fset.Position(lastSpec.Pos()).Line
54 if rParenLine := fset.Position(d.Rparen).Line; rParenLine > lastLine+1 {
55 fset.File(d.Rparen).MergeLine(rParenLine - 1)
61 func importPath(s ast.Spec) string {
62 t, err := strconv.Unquote(s.(*ast.ImportSpec).Path.Value)
69 func importName(s ast.Spec) string {
70 n := s.(*ast.ImportSpec).Name
77 func importComment(s ast.Spec) string {
78 c := s.(*ast.ImportSpec).Comment
85 // collapse indicates whether prev may be removed, leaving only next.
86 func collapse(prev, next ast.Spec) bool {
87 if importPath(next) != importPath(prev) || importName(next) != importName(prev) {
90 return prev.(*ast.ImportSpec).Comment == nil
98 func sortSpecs(fset *token.FileSet, f *ast.File, specs []ast.Spec) []ast.Spec {
99 // Can't short-circuit here even if specs are already sorted,
100 // since they might yet need deduplication.
101 // A lone import, however, may be safely ignored.
106 // Record positions for specs.
107 pos := make([]posSpan, len(specs))
108 for i, s := range specs {
109 pos[i] = posSpan{s.Pos(), s.End()}
112 // Identify comments in this range.
113 // Any comment from pos[0].Start to the final line counts.
114 lastLine := fset.Position(pos[len(pos)-1].End).Line
115 cstart := len(f.Comments)
116 cend := len(f.Comments)
117 for i, g := range f.Comments {
118 if g.Pos() < pos[0].Start {
124 if fset.Position(g.End()).Line > lastLine {
129 comments := f.Comments[cstart:cend]
131 // Assign each comment to the import spec preceding it.
132 importComment := map[*ast.ImportSpec][]*ast.CommentGroup{}
134 for _, g := range comments {
135 for specIndex+1 < len(specs) && pos[specIndex+1].Start <= g.Pos() {
138 s := specs[specIndex].(*ast.ImportSpec)
139 importComment[s] = append(importComment[s], g)
142 // Sort the import specs by import path.
143 // Remove duplicates, when possible without data loss.
144 // Reassign the import paths to have the same position sequence.
145 // Reassign each comment to abut the end of its spec.
146 // Sort the comments by new position.
147 sort.Sort(byImportSpec(specs))
149 // Dedup. Thanks to our sorting, we can just consider
150 // adjacent pairs of imports.
152 for i, s := range specs {
153 if i == len(specs)-1 || !collapse(s, specs[i+1]) {
154 deduped = append(deduped, s)
157 fset.File(p).MergeLine(fset.Position(p).Line)
162 // Fix up comment positions
163 for i, s := range specs {
164 s := s.(*ast.ImportSpec)
166 s.Name.NamePos = pos[i].Start
168 s.Path.ValuePos = pos[i].Start
169 s.EndPos = pos[i].End
170 nextSpecPos := pos[i].End
172 for _, g := range importComment[s] {
173 for _, c := range g.List {
175 nextSpecPos = c.End()
178 if i < len(specs)-1 {
179 pos[i+1].Start = nextSpecPos
180 pos[i+1].End = nextSpecPos
184 sort.Sort(byCommentPos(comments))
186 // Fixup comments can insert blank lines, because import specs are on different lines.
187 // We remove those blank lines here by merging import spec to the first import spec line.
188 firstSpecLine := fset.Position(specs[0].Pos()).Line
189 for _, s := range specs[1:] {
191 line := fset.File(p).Line(p)
192 for previousLine := line - 1; previousLine >= firstSpecLine; {
193 fset.File(p).MergeLine(previousLine)
200 type byImportSpec []ast.Spec // slice of *ast.ImportSpec
202 func (x byImportSpec) Len() int { return len(x) }
203 func (x byImportSpec) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
204 func (x byImportSpec) Less(i, j int) bool {
205 ipath := importPath(x[i])
206 jpath := importPath(x[j])
208 igroup := importGroup(ipath)
209 jgroup := importGroup(jpath)
210 if igroup != jgroup {
211 return igroup < jgroup
217 iname := importName(x[i])
218 jname := importName(x[j])
223 return importComment(x[i]) < importComment(x[j])
226 type byCommentPos []*ast.CommentGroup
228 func (x byCommentPos) Len() int { return len(x) }
229 func (x byCommentPos) Swap(i, j int) { x[i], x[j] = x[j], x[i] }
230 func (x byCommentPos) Less(i, j int) bool { return x[i].Pos() < x[j].Pos() }