diff --git a/imports/fix.go b/imports/fix.go index b7662db8..e556dfeb 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -19,6 +19,7 @@ import ( "path" "path/filepath" "sort" + "strconv" "strings" "sync" @@ -367,9 +368,19 @@ func fixImports(fset *token.FileSet, f *ast.File, filename string) (added []stri // importPathToName returns the package name for the given import path. var importPathToName func(importPath, srcDir string) (packageName string) = importPathToNameGoPath -// importPathToNameBasic assumes the package name is the base of import path. +// importPathToNameBasic assumes the package name is the base of import path, +// except that if the path ends in foo/vN, it assumes the package name is foo. func importPathToNameBasic(importPath, srcDir string) (packageName string) { - return path.Base(importPath) + base := path.Base(importPath) + if strings.HasPrefix(base, "v") { + if _, err := strconv.Atoi(base[1:]); err == nil { + dir := path.Dir(importPath) + if dir != "." { + return path.Base(dir) + } + } + } + return base } // importPathToNameGoPath finds out the actual package name, as declared in its .go files. diff --git a/imports/fix_test.go b/imports/fix_test.go index 654d6559..68996ed2 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -1140,6 +1140,32 @@ var ( } +// Test for x/y/v2 convention for package y. +func TestFixModuleVersion(t *testing.T) { + testConfig{}.test(t, func(t *goimportTest) { + input := `package p + +import ( + "fmt" + + "foo/v2" +) + +var ( + _ = fmt.Print + _ = foo.Foo +) +` + buf, err := Process(filepath.Join(t.gopath, "src/mypkg.com/outpkg/toformat.go"), []byte(input), &Options{}) + if err != nil { + t.Fatal(err) + } + if got := string(buf); got != input { + t.Fatalf("results differ\nGOT:\n%s\nWANT:\n%s\n", got, input) + } + }) +} + // Test for correctly identifying the name of a vendored package when it // differs from its directory name. In this test, the import line // "mypkg.com/mypkg.v1" would be removed if goimports wasn't able to detect @@ -1670,8 +1696,8 @@ func TestImportPathToNameGoPathParse(t *testing.T) { func TestIgnoreConfiguration(t *testing.T) { testConfig{ gopathFiles: map[string]string{ - ".goimportsignore": "# comment line\n\n example.net", // tests comment, blank line, whitespace trimming - "example.net/pkg/pkg.go": "package pkg\nconst X = 1", + ".goimportsignore": "# comment line\n\n example.net", // tests comment, blank line, whitespace trimming + "example.net/pkg/pkg.go": "package pkg\nconst X = 1", "otherwise-longer-so-worse.example.net/foo/pkg/pkg.go": "package pkg\nconst X = 1", }, }.test(t, func(t *goimportTest) {