Skip to content
This repository was archived by the owner on Jun 27, 2023. It is now read-only.

Commit a23c5e7

Browse files
authored
fix issues related to source package imports (#507)
Fixes: #505 Fixes: #515
1 parent f67ce0c commit a23c5e7

File tree

5 files changed

+124
-11
lines changed

5 files changed

+124
-11
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// Package extra_import makes sure output does not import it. See #515.
2+
package extra_import
3+
4+
//go:generate mockgen -destination mock.go -package extra_import . Foo
5+
6+
type Message struct {
7+
Text string
8+
}
9+
10+
type Foo interface {
11+
Bar(channels []string, message chan<- Message)
12+
}

mockgen/internal/tests/extra_import/mock.go

+46
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

mockgen/internal/tests/missing_import/output/source_mock.go

+47
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
//go:generate mockgen -package source -destination=../output/source_mock.go -source=source.go
2+
3+
// Package source makes sure output imports its. See #505.
4+
package source
5+
6+
type Foo struct{}
7+
8+
type Bar interface {
9+
Baz(Foo)
10+
}

mockgen/mockgen.go

+9-11
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ import (
2323
"encoding/json"
2424
"flag"
2525
"fmt"
26-
"go/build"
2726
"go/token"
2827
"io"
2928
"io/ioutil"
@@ -133,15 +132,14 @@ func main() {
133132
// "package.X" since "package" is this package). This can happen if the mock
134133
// is output into an already existing package.
135134
outputPackagePath := *selfPackage
136-
if len(outputPackagePath) == 0 && len(*destination) > 0 {
137-
dst, _ := filepath.Abs(filepath.Dir(*destination))
138-
for _, prefix := range build.Default.SrcDirs() {
139-
if strings.HasPrefix(dst, prefix) {
140-
if rel, err := filepath.Rel(prefix, dst); err == nil {
141-
outputPackagePath = rel
142-
break
143-
}
144-
}
135+
if outputPackagePath == "" && *destination != "" {
136+
dstPath, err := filepath.Abs(filepath.Dir(*destination))
137+
if err != nil {
138+
log.Fatalf("Unable to determine destination file path: %v", err)
139+
}
140+
outputPackagePath, err = parsePackageImport(dstPath)
141+
if err != nil {
142+
log.Fatalf("Unable to determine destination file path: %v", err)
145143
}
146144
}
147145

@@ -330,7 +328,7 @@ func (g *generator) Generate(pkg *model.Package, outputPkgName string, outputPac
330328
}
331329

332330
// Avoid importing package if source pkg == output pkg
333-
if pth == pkg.PkgPath && outputPkgName == pkg.Name {
331+
if pth == pkg.PkgPath && outputPackagePath == pkg.PkgPath {
334332
continue
335333
}
336334

0 commit comments

Comments
 (0)