Skip to content

Commit

Permalink
fix: import and arg collision (#219)
Browse files Browse the repository at this point in the history
This PR fixes an issue where if the name of an argument to a method that is being mocked collides with the name of a package that needs to be imported, mockgen could generate uncompilable code.

Resolves #218
  • Loading branch information
bstncartwright authored Oct 28, 2024
1 parent c205527 commit eb67641
Show file tree
Hide file tree
Showing 5 changed files with 90 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
package internalpackage

type FooExported struct{}
55 changes: 55 additions & 0 deletions mockgen/internal/tests/import_collision/p2/mocks/mocks.go

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

12 changes: 12 additions & 0 deletions mockgen/internal/tests/import_collision/p2/p2.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package p2

//go:generate mockgen -destination=mocks/mocks.go -package=internalpackage . Mything

import (
"go.uber.org/mock/mockgen/internal/tests/import_collision/internalpackage"
)

type Mything interface {
// issue here, is that the variable has the same name as an imported package.
DoThat(internalpackage int) internalpackage.FooExported
}
8 changes: 4 additions & 4 deletions mockgen/internal/tests/package_mode/mock/interfaces.go

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

18 changes: 16 additions & 2 deletions mockgen/mockgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -758,6 +758,17 @@ func (g *generator) GenerateMockReturnCallMethod(intf *model.Interface, m *model
return nil
}

// nameExistsAsPackage returns true if the name exists as a package name.
// This is used to avoid name collisions when generating mock method arguments.
func (g *generator) nameExistsAsPackage(name string) bool {
for _, symbolName := range g.packageMap {
if symbolName == name {
return true
}
}
return false
}

func (g *generator) getArgNames(m *model.Method, in bool) []string {
var params []*model.Parameter
if in {
Expand All @@ -766,16 +777,19 @@ func (g *generator) getArgNames(m *model.Method, in bool) []string {
params = m.Out
}
argNames := make([]string, len(params))

for i, p := range params {
name := p.Name
if name == "" || name == "_" {

if name == "" || name == "_" || g.nameExistsAsPackage(name) {
name = fmt.Sprintf("arg%d", i)
}
argNames[i] = name
}
if m.Variadic != nil && in {
name := m.Variadic.Name
if name == "" {

if name == "" || g.nameExistsAsPackage(name) {
name = fmt.Sprintf("arg%d", len(params))
}
argNames = append(argNames, name)
Expand Down

0 comments on commit eb67641

Please sign in to comment.