Golang go/ast.SortImports() function example

package go/ast

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.

Golang go/ast.SortImports() usage example

 var pkg string
 ...
 buf := new(bytes.Buffer)
 fset := token.NewFileSet()

 astFile, err := parser.ParseFile(fset, pkg+".go", buf, parser.ParseComments)
 if err != nil {
 return errors.New("Error parsing generated code: " + err.Error())
 }
 // Sort the import lines in the AST in the same way that gofmt does.
 ast.SortImports(fset, astFile)

References :

http://golang.org/pkg/go/ast/#SortImports

https://github.com/jacobsa/oglemock/blob/master/generate/generate.go

Advertisement