Skip to content

Commit

Permalink
simplify anonymous import handling
Browse files Browse the repository at this point in the history
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 google#358.
  • Loading branch information
reillywatson committed May 10, 2022
1 parent 9d78e0a commit e1931eb
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 27 deletions.
5 changes: 1 addition & 4 deletions internal/wire/testdata/PkgImport/want/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

34 changes: 11 additions & 23 deletions internal/wire/wire.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}
}
}
}
Expand Down Expand Up @@ -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),
}
}

Expand Down Expand Up @@ -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()
}
Expand Down

0 comments on commit e1931eb

Please sign in to comment.