Skip to content
Permalink
Browse files

import rewriting

  • Loading branch information
xdg committed Nov 23, 2019
1 parent 33ecf5f commit 86f600edf5aecae0ad5f98787f4867292e4ff372
Showing with 25 additions and 8 deletions.
  1. +23 −6 internal/rewriter/rewriter.go
  2. +2 −2 internal/rewriter/rewriter_test.go
@@ -34,8 +34,8 @@ func visitor(n ast.Node) (ast.Node, bool) {
switch v := n.(type) {
case *ast.CallExpr:
return handleCallExpr(v)
case *ast.ImportSpec:
return handleImportSpec(v)
case *ast.GenDecl:
return handleImportDecl(v)
default:
return n, true
}
@@ -55,11 +55,28 @@ func handleCallExpr(ce *ast.CallExpr) (ast.Node, bool) {
}
}

func handleImportSpec(im *ast.ImportSpec) (ast.Node, bool) {
if im.Path.Value == `"github.com/pkg/errors"` {
im.Path.Value = `"errors"`
func handleImportDecl(gd *ast.GenDecl) (ast.Node, bool) {
// Ignore GenDecl's that aren't imports.
if gd.Tok != token.IMPORT {
return gd, true
}
return im, true
// Push "errors" to the front of specs so formatting will sort it with
// core libraries and discard pkg/errors.
newSpecs := []ast.Spec{
&ast.ImportSpec{Path: &ast.BasicLit{Kind: token.STRING, Value: `"errors"`}},
}
for _, s := range gd.Specs {
im, ok := s.(*ast.ImportSpec)
if !ok {
continue
}
if im.Path.Value == `"github.com/pkg/errors"` {
continue
}
newSpecs = append(newSpecs, s)
}
gd.Specs = newSpecs
return gd, true
}

func rewriteWrap(ce *ast.CallExpr) *ast.CallExpr {
@@ -70,11 +70,11 @@ func TestSubstPkg(t *testing.T) {
expect := "package main\n\nimport \"errors\"\n"
isEqual(t, string(out), expect, "Incorrect rewrite of single import")

in = "package main\n\nimport (\n\t\"bytes\"\n\t\"github.com/pkg/errors\"\n)\n"
in = "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/pkg/errors\"\n)\n"
out, err = Rewrite("test", []byte(in))
if err != nil {
t.Errorf("Rewrite error: %v", err)
}
expect = "package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n)\n"
expect = "package main\n\nimport (\n\t\"bytes\"\n\t\"errors\"\n\t\"fmt\"\n)\n"
isEqual(t, string(out), expect, "Incorrect rewrite of multi import")
}

0 comments on commit 86f600e

Please sign in to comment.
You can’t perform that action at this time.