diff --git a/cmd/goimports/goimports.go b/cmd/goimports/goimports.go index 01fb237de0a..8ab61b8ca48 100644 --- a/cmd/goimports/goimports.go +++ b/cmd/goimports/goimports.go @@ -49,6 +49,7 @@ var ( func init() { flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)") + flag.StringVar(&imports.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages") } func report(err error) { diff --git a/imports/fix.go b/imports/fix.go index 880c1690a8c..4d7dfebf977 100644 --- a/imports/fix.go +++ b/imports/fix.go @@ -32,9 +32,19 @@ var ( testMu sync.RWMutex // guards globals reset by tests; used only if inTests ) +// If set, LocalPrefix instructs Process to sort import paths with the given +// prefix into another group after 3rd-party packages. +var LocalPrefix string + // importToGroup is a list of functions which map from an import path to // a group number. var importToGroup = []func(importPath string) (num int, ok bool){ + func(importPath string) (num int, ok bool) { + if LocalPrefix != "" && strings.HasPrefix(importPath, LocalPrefix) { + return 3, true + } + return + }, func(importPath string) (num int, ok bool) { if strings.HasPrefix(importPath, "appengine") { return 2, true diff --git a/imports/fix_test.go b/imports/fix_test.go index e1179e9c816..0a05f584ebc 100644 --- a/imports/fix_test.go +++ b/imports/fix_test.go @@ -1257,6 +1257,38 @@ const Y = bar.X }) } +// Tests that the LocalPrefix option causes imports +// to be added into a later group (num=3). +func TestLocalPrefix(t *testing.T) { + defer func(s string) { LocalPrefix = s }(LocalPrefix) + LocalPrefix = "foo/" + + testConfig{ + gopathFiles: map[string]string{ + "foo/bar/bar.go": "package bar \n const X = 1", + }, + }.test(t, func(t *goimportTest) { + buf, err := Process(t.gopath+"/src/test/t.go", []byte("package main \n const Y = bar.X \n const _ = runtime.GOOS"), &Options{}) + if err != nil { + t.Fatal(err) + } + const want = `package main + +import ( + "runtime" + + "foo/bar" +) + +const Y = bar.X +const _ = runtime.GOOS +` + if string(buf) != want { + t.Errorf("Got:\n%s\nWant:\n%s", buf, want) + } + }) +} + // Tests that running goimport on files in GOROOT (for people hacking // on Go itself) don't cause the GOPATH to be scanned (which might be // much bigger).