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

Removed unused package import logic #490

Merged
merged 1 commit into from Nov 15, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
70 changes: 1 addition & 69 deletions pkg/generator.go
Expand Up @@ -6,11 +6,9 @@ import (
"errors"
"fmt"
"go/ast"
"go/build"
"go/types"
"io"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
Expand Down Expand Up @@ -40,27 +38,17 @@ type Generator struct {
localizationCache map[string]string
packagePathToName map[string]string
nameToPackagePath map[string]string

packageRoots []string
}

// NewGenerator builds a Generator.
func NewGenerator(ctx context.Context, c config.Config, iface *Interface, pkg string) *Generator {

var roots []string

for _, root := range filepath.SplitList(build.Default.GOPATH) {
roots = append(roots, filepath.Join(root, "src"))
}

g := &Generator{
Config: c,
iface: iface,
pkg: pkg,
localizationCache: make(map[string]string),
packagePathToName: make(map[string]string),
nameToPackagePath: make(map[string]string),
packageRoots: roots,
}

g.addPackageImportWithName(ctx, "github.com/stretchr/testify/mock", "mock")
Expand Down Expand Up @@ -121,7 +109,6 @@ func (g *Generator) addPackageImport(ctx context.Context, pkg *types.Package) st
}

func (g *Generator) addPackageImportWithName(ctx context.Context, path, name string) string {
path = g.getLocalizedPath(ctx, path)
if existingName, pathExists := g.packagePathToName[path]; pathExists {
return existingName
}
Expand All @@ -138,8 +125,7 @@ func (g *Generator) getNonConflictingName(path, name string) string {
return name
}

// The path will always contain '/' because it is enforced in getLocalizedPath
// regardless of OS.
// The path will always contain '/' because it is enforced by Go import system
directories := strings.Split(path, "/")

cleanedDirectories := make([]string, 0, len(directories))
Expand Down Expand Up @@ -172,60 +158,6 @@ func (g *Generator) importNameExists(name string) bool {
return nameExists
}

func calculateImport(ctx context.Context, set []string, path string) string {
log := zerolog.Ctx(ctx).With().Str(logging.LogKeyPath, path).Logger()
ctx = log.WithContext(ctx)

for _, root := range set {
if strings.HasPrefix(path, root) {
packagePath, err := filepath.Rel(root, path)
if err == nil {
return packagePath
}
log.Err(err).Msgf("Unable to localize path")
}
}
return path
}

// getLocalizedPath, given a path to a file or an importable URL,
// returns the proper string needed to import the package. See tests
// for specific examples of what this should return.
func (g *Generator) getLocalizedPath(ctx context.Context, path string) string {
log := zerolog.Ctx(ctx).With().Str(logging.LogKeyPath, path).Logger()
ctx = log.WithContext(ctx)

if strings.HasSuffix(path, ".go") {
path, _ = filepath.Split(path)
}
if localized, ok := g.localizationCache[path]; ok {
return localized
}
directories := strings.Split(path, string(filepath.Separator))
numDirectories := len(directories)
vendorIndex := -1
for i := 1; i <= numDirectories; i++ {
dir := directories[numDirectories-i]
if dir == "vendor" {
vendorIndex = numDirectories - i
break
}
}

toReturn := path
if vendorIndex >= 0 {
toReturn = filepath.Join(directories[vendorIndex+1:]...)
} else if filepath.IsAbs(path) {
toReturn = calculateImport(ctx, g.packageRoots, path)
}

// Enforce '/' slashes for import paths in every OS.
toReturn = filepath.ToSlash(toReturn)

g.localizationCache[path] = toReturn
return toReturn
}

func (g *Generator) maybeMakeNameExported(name string, export bool) string {
if export && !ast.IsExported(name) {
return g.makeNameExported(name)
Expand Down
78 changes: 0 additions & 78 deletions pkg/generator_test.go
Expand Up @@ -2,7 +2,6 @@ package pkg

import (
"bufio"
"bytes"
"context"
"go/format"
"io"
Expand Down Expand Up @@ -117,14 +116,6 @@ func (s *GeneratorSuite) checkPrologueGeneration(
)
}

func (s *GeneratorSuite) TestCalculateImport() {
gp := []string{"a/src", "b/src"}

s.Equal("c", calculateImport(ctx, gp, "a/src/c"))
s.Equal("c", calculateImport(ctx, gp, "b/src/c"))
s.Equal("d/src/c", calculateImport(ctx, gp, "d/src/c"))
}

func (s *GeneratorSuite) TestGenerator() {
expected := `// Requester is an autogenerated mock type for the Requester type
type Requester struct {
Expand Down Expand Up @@ -2621,72 +2612,3 @@ func TestGeneratorSuite(t *testing.T) {
generatorSuite := new(GeneratorSuite)
suite.Run(t, generatorSuite)
}

func TestGenerator_getLocalizedPath(t *testing.T) {
type fields struct {
Config config.Config
buf bytes.Buffer
iface *Interface
pkg string
localizationCache map[string]string
packagePathToName map[string]string
nameToPackagePath map[string]string
packageRoots []string
}
type args struct {
ctx context.Context
path string
}
tests := []struct {
name string
fields fields
args args
want string
}{
{
name: "test on-disk",
fields: fields{localizationCache: make(map[string]string)},
args: args{ctx: context.Background(), path: "path/to/file.go"},
want: "path/to/",
},
{
name: "test vendored",
fields: fields{localizationCache: make(map[string]string)},
args: args{ctx: context.Background(), path: "vendor/path/to/file.go"},
want: "path/to",
},
{
name: "test URL",
fields: fields{localizationCache: make(map[string]string)},
args: args{ctx: context.Background(), path: "github.com/vektra/mockery"},
want: "github.com/vektra/mockery",
},
{
// NOTE: This test is currently testing for behavior that _should_ be
// fixed. This is a special case where the import path ends in .go,
// but we should be getting the full importable URL here.
// https://github.com/vektra/mockery/pull/487
name: "test nats.go",
fields: fields{localizationCache: make(map[string]string)},
args: args{ctx: context.Background(), path: "github.com/nats-io/nats.go"},
want: "github.com/nats-io/",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
g := &Generator{
Config: tt.fields.Config,
buf: tt.fields.buf,
iface: tt.fields.iface,
pkg: tt.fields.pkg,
localizationCache: tt.fields.localizationCache,
packagePathToName: tt.fields.packagePathToName,
nameToPackagePath: tt.fields.nameToPackagePath,
packageRoots: tt.fields.packageRoots,
}
if got := g.getLocalizedPath(tt.args.ctx, tt.args.path); got != tt.want {
t.Errorf("Generator.getLocalizedPath() = %v, want %v", got, tt.want)
}
})
}
}