Skip to content

Instantly share code, notes, and snippets.

@prateek
Created January 24, 2018 22:56
Show Gist options
  • Save prateek/e18422badf53499c22fc0f1eacc48fc4 to your computer and use it in GitHub Desktop.
Save prateek/e18422badf53499c22fc0f1eacc48fc4 to your computer and use it in GitHub Desktop.
Golang import linter skeleton
package importlint
import (
"go/ast"
"go/token"
)
// NB(prateek): http://goast.yuroyoro.net/ is enormously helpful.
// importDecl is the collection of importGroups contained in a single import block.
type importDecl struct {
Groups []importGroup
}
// importGroup is a collection of imports that are not.
type importGroup struct {
Imports []ImportSpec
}
type ImportSpec struct {
Position token.Position
Name string
Path string
}
// Imports returns the file imports grouped by paragraph.
func Imports(fset *token.FileSet, f *ast.File) []importDecl {
var importDecls []importDecl
for _, decl := range f.Decls {
genDecl, ok := decl.(*ast.GenDecl)
if !ok || genDecl.Tok != token.IMPORT {
break
}
var (
importDecl importDecl
group importGroup
)
var lastLine int
for _, spec := range genDecl.Specs {
importSpec := spec.(*ast.ImportSpec)
pos := importSpec.Path.ValuePos
line := fset.Position(pos).Line
if lastLine > 0 && pos > 0 && line-lastLine > 1 {
importDecl.Groups = append(importDecl.Groups, group)
group = importGroup{}
}
group.Imports = append(group.Imports, newImportSpec(importSpec, line))
lastLine = line
}
importDecl.Groups = append(importDecl.Groups, group)
importDecls = append(importDecls, importDecl)
}
return importDecls
}
func newImportSpec(is *ast.ImportSpec, line int) ImportSpec {
var (
name string
path string
)
nameID := is.Name
if nameID != nil {
name = nameID.Name
}
pathLit := is.Path
if pathLit != nil {
path = pathLit.Value
}
return ImportSpec{
Name: name,
Path: path,
Line: line,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment