de-duped imports

This commit is contained in:
Mat Ryer 2017-07-07 14:42:53 +01:00
parent ae57d77f27
commit 3c6751fed4
3 changed files with 10 additions and 3 deletions

View File

@ -22,7 +22,7 @@ type Mocker struct {
pkgs map[string]*ast.Package
pkgName string
imports []string
imports map[string]bool
}
// New makes a new Mocker for the specified package directory.
@ -57,6 +57,7 @@ func New(src, packageName string) (*Mocker, error) {
fset: fset,
pkgs: pkgs,
pkgName: packageName,
imports: make(map[string]bool),
}, nil
}
@ -106,7 +107,9 @@ func (m *Mocker) Mock(w io.Writer, name ...string) error {
doc.Objects = append(doc.Objects, obj)
}
}
doc.Imports = append(doc.Imports, m.imports...)
for pkgToImport := range m.imports {
doc.Imports = append(doc.Imports, pkgToImport)
}
err := m.tmpl.Execute(w, doc)
if err != nil {
return err
@ -118,7 +121,7 @@ func (m *Mocker) packageQualifier(pkg *types.Package) string {
if m.pkgName == pkg.Name() {
return ""
}
m.imports = append(m.imports, pkg.Path())
m.imports[pkg.Path()] = true
return pkg.Name()
}

View File

@ -160,5 +160,8 @@ func TestImports(t *testing.T) {
if !strings.Contains(s, str) {
t.Errorf("expected by missing: \"%s\"", str)
}
if len(strings.Split(s, str)) > 2 {
t.Errorf("more than one: \"%s\"", str)
}
}
}

View File

@ -7,4 +7,5 @@ import (
// DoSomething does something.
type DoSomething interface {
Do(thing one.Thing) error
Another(thing one.Thing) error
}