Skip to content

Commit

Permalink
mockgen: Sanitize the "any" package name (#132)
Browse files Browse the repository at this point in the history
When a package name is "any" mockgen will use that as a package name in
the generated code which causes issues due to colliding with Go's "any"
type. Update the sanitization logic to prevent this collision.
  • Loading branch information
r-hang authored Dec 20, 2023
1 parent 6dd8fe5 commit 37f6db3
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 1 deletion.
5 changes: 5 additions & 0 deletions mockgen/internal/tests/sanitization/any/any.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package any

// Any is a type of a package that tests the sanitization of imported packages
// named any.
type Any struct {}
11 changes: 11 additions & 0 deletions mockgen/internal/tests/sanitization/interface.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package sanitization

import (
"go.uber.org/mock/mockgen/internal/tests/sanitization/any"
)

//go:generate mockgen -destination mockout/mock.go -package mockout . AnyMock

type AnyMock interface {
Do(a *any.Any, b int)
}
52 changes: 52 additions & 0 deletions mockgen/internal/tests/sanitization/mockout/mock.go

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

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

import (
"testing"

"go.uber.org/mock/gomock"
any0 "go.uber.org/mock/mockgen/internal/tests/sanitization/any"
"go.uber.org/mock/mockgen/internal/tests/sanitization/mockout"
)

func TestSanitization(t *testing.T) {
ctrl := gomock.NewController(t)
m := mockout.NewMockAnyMock(ctrl)
m.EXPECT().Do(gomock.Any(), 1)
m.Do(&any0.Any{}, 1)
}
2 changes: 1 addition & 1 deletion mockgen/mockgen.go
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac
}

i := 0
for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() {
for localNames[pkgName] || token.Lookup(pkgName).IsKeyword() || pkgName == "any" {
pkgName = base + strconv.Itoa(i)
i++
}
Expand Down

0 comments on commit 37f6db3

Please sign in to comment.