Skip to content

Commit

Permalink
fix: Avoid package name collision with inPackage (Fixes vektra#291)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ryan Smith committed Mar 16, 2021
1 parent faa743e commit c946647
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 2 deletions.
5 changes: 5 additions & 0 deletions pkg/fixtures/example_project/bar/foo/client.go
@@ -0,0 +1,5 @@
package foo

type Client interface {
Search(query string) ([]string, error)
}
7 changes: 7 additions & 0 deletions pkg/fixtures/example_project/foo/collision.go
@@ -0,0 +1,7 @@
package foo

import "github.com/vektra/mockery/v2/pkg/fixtures/example_project/bar/foo"

type Collision interface {
NewClient() foo.Client
}
10 changes: 8 additions & 2 deletions pkg/generator.go
Expand Up @@ -103,7 +103,10 @@ func (g *Generator) addPackageImportWithName(ctx context.Context, path, name str

func (g *Generator) getNonConflictingName(path, name string) string {
if !g.importNameExists(name) {
return name
// do not allow imports with the same name as the package when inPackage
if !g.InPackage || g.iface.Pkg.Name() != name {
return name
}
}

// The path will always contain '/' because it is enforced in getLocalizedPath
Expand All @@ -120,7 +123,10 @@ func (g *Generator) getNonConflictingName(path, name string) string {
for i := 1; i <= numDirectories; i++ {
prospectiveName = strings.Join(cleanedDirectories[numDirectories-i:], "")
if !g.importNameExists(prospectiveName) {
return prospectiveName
// do not allow imports with the same name as the package when inPackage
if !g.InPackage || g.iface.Pkg.Name() != prospectiveName {
return prospectiveName
}
}
}
// Try adding numbers to the given name
Expand Down
16 changes: 16 additions & 0 deletions pkg/generator_test.go
Expand Up @@ -1402,6 +1402,22 @@ import mock "github.com/stretchr/testify/mock"
}
}

func (s *GeneratorSuite) TestInPackagePackageCollision() {
expected := `package foo
import barfoo "github.com/vektra/mockery/v2/pkg/fixtures/example_project/bar/foo"
import mock "github.com/stretchr/testify/mock"
`
generator := NewGenerator(
s.ctx,
config.Config{InPackage: true, LogLevel: "debug"},
s.getInterfaceFromFile("example_project/foo/collision.go", "Collision"),
pkg,
)
s.checkPrologueGeneration(generator, expected)
}

func TestGeneratorSuite(t *testing.T) {
generatorSuite := new(GeneratorSuite)
suite.Run(t, generatorSuite)
Expand Down

0 comments on commit c946647

Please sign in to comment.