Skip to content

Commit

Permalink
format: test/, example/, and internal/ are non-std
Browse files Browse the repository at this point in the history
See golang/go#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.
  • Loading branch information
mvdan committed Jul 31, 2020
1 parent 4fd085c commit 7036e19
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
19 changes: 13 additions & 6 deletions format/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"reflect"
"regexp"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
Expand Down Expand Up @@ -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
}
Expand Down
20 changes: 20 additions & 0 deletions testdata/scripts/std-imports.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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"
)

0 comments on commit 7036e19

Please sign in to comment.