Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: import and arg collision #219

Merged
merged 1 commit into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading