From e1931eb8d0d9e0b2811082c772e476b8f98316d2 Mon Sep 17 00:00:00 2001 From: Reilly Watson Date: Tue, 10 May 2022 11:26:46 -0400 Subject: [PATCH] simplify anonymous import handling Anonymous imports were being special-cased and written out separately. They're not that special though, we can just count them as regular imports with the name "_". This causes them to get grouped together with the other imports like one would expect, and simplifies the generator a bit. Fixes #358. --- .../wire/testdata/PkgImport/want/wire_gen.go | 5 +-- internal/wire/wire.go | 34 ++++++------------- 2 files changed, 12 insertions(+), 27 deletions(-) diff --git a/internal/wire/testdata/PkgImport/want/wire_gen.go b/internal/wire/testdata/PkgImport/want/wire_gen.go index 7dbc4692..862c6ea8 100644 --- a/internal/wire/testdata/PkgImport/want/wire_gen.go +++ b/internal/wire/testdata/PkgImport/want/wire_gen.go @@ -6,13 +6,10 @@ package main -import ( - "example.com/bar" -) - import ( _ "example.com/anon1" _ "example.com/anon2" + "example.com/bar" ) // Injectors from wire.go: diff --git a/internal/wire/wire.go b/internal/wire/wire.go index a9b7a50d..4789402e 100644 --- a/internal/wire/wire.go +++ b/internal/wire/wire.go @@ -188,7 +188,10 @@ func generateInjectors(g *gen, pkg *packages.Package) (injectorFiles []*ast.File for _, impt := range f.Imports { if impt.Name != nil && impt.Name.Name == "_" { - g.anonImports[impt.Path.Value] = true + g.imports[strings.Trim(impt.Path.Value, `"`)] = importInfo{ + name: "_", + differs: true, + } } } } @@ -241,19 +244,17 @@ type importInfo struct { // gen is the file-wide generator state. type gen struct { - pkg *packages.Package - buf bytes.Buffer - imports map[string]importInfo - anonImports map[string]bool - values map[ast.Expr]string + pkg *packages.Package + buf bytes.Buffer + imports map[string]importInfo + values map[ast.Expr]string } func newGen(pkg *packages.Package) *gen { return &gen{ - pkg: pkg, - anonImports: make(map[string]bool), - imports: make(map[string]importInfo), - values: make(map[ast.Expr]string), + pkg: pkg, + imports: make(map[string]importInfo), + values: make(map[ast.Expr]string), } } @@ -290,19 +291,6 @@ func (g *gen) frame(tags string) []byte { } buf.WriteString(")\n\n") } - if len(g.anonImports) > 0 { - buf.WriteString("import (\n") - anonImps := make([]string, 0, len(g.anonImports)) - for path := range g.anonImports { - anonImps = append(anonImps, path) - } - sort.Strings(anonImps) - - for _, path := range anonImps { - fmt.Fprintf(&buf, "\t_ %s\n", path) - } - buf.WriteString(")\n\n") - } buf.Write(g.buf.Bytes()) return buf.Bytes() }