From 7036e194a6ab4bf47ff642a718580e7253774ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Fri, 31 Jul 2020 22:54:18 +0100 Subject: [PATCH] format: test/, example/, and internal/ are non-std See https://github.com/golang/go/issues/37641, which was accepted a few months ago. Packages like internal/foo are also somewhat common, and we can know for sure that they don't belong in the standard library, as they couldn't be imported then. Updates #38. --- format/format.go | 19 +++++++++++++------ testdata/scripts/std-imports.txt | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 6 deletions(-) diff --git a/format/format.go b/format/format.go index 86ee437..e65bbc4 100644 --- a/format/format.go +++ b/format/format.go @@ -16,6 +16,7 @@ import ( "reflect" "regexp" "sort" + "strconv" "strings" "unicode" "unicode/utf8" @@ -547,14 +548,20 @@ func (f *fumpter) joinStdImports(d *ast.GenDecl) { lastEnd = spec.End() } - // First, separate the non-std imports. - if strings.Contains(spec.Path.Value, ".") { - other = append(other, spec) - continue - } + path, _ := strconv.Unquote(spec.Path.Value) + switch { + // Imports with a period are definitely third party. + case strings.Contains(path, "."): + fallthrough + // "test" and "example" are reserved as per golang.org/issue/37641. + // "internal" is unreachable. + case strings.HasPrefix(path, "test/") || + strings.HasPrefix(path, "example/") || + strings.HasPrefix(path, "internal/"): + fallthrough // To be conservative, if an import has a name or an inline // comment, and isn't part of the top group, treat it as non-std. - if !firstGroup && (spec.Name != nil || spec.Comment != nil) { + case !firstGroup && (spec.Name != nil || spec.Comment != nil): other = append(other, spec) continue } diff --git a/testdata/scripts/std-imports.txt b/testdata/scripts/std-imports.txt index 2d4d776..1d9e0f2 100644 --- a/testdata/scripts/std-imports.txt +++ b/testdata/scripts/std-imports.txt @@ -62,6 +62,16 @@ import ( "std" "non.std/pkg" ) + +// All of the extra imports below are known to not belong in std. +// For example/ and test/, see https://golang.org/issue/37641. +import ( + "io" + + "example/foo" + "internal/bar" + "test/baz" +) -- foo.go.golden -- package p @@ -118,3 +128,13 @@ import ( "non.std/pkg" ) + +// All of the extra imports below are known to not belong in std. +// For example/ and test/, see https://golang.org/issue/37641. +import ( + "io" + + "example/foo" + "internal/bar" + "test/baz" +)