Skip to content

Commit 5c96d6a

Browse files
committed
goimports use go.mod module path as prefix
1 parent b623539 commit 5c96d6a

File tree

1 file changed

+19
-1
lines changed

1 file changed

+19
-1
lines changed

cmd/goimports/goimports.go

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import (
2020
"runtime/pprof"
2121
"strings"
2222

23+
"golang.org/x/mod/modfile"
2324
"golang.org/x/tools/internal/gocommand"
2425
"golang.org/x/tools/internal/imports"
2526
)
@@ -51,7 +52,7 @@ var (
5152

5253
func init() {
5354
flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)")
54-
flag.StringVar(&options.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
55+
flag.StringVar(&options.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list; if set to auto, use module path from go.mod as prefix")
5556
flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.")
5657
}
5758

@@ -268,6 +269,23 @@ func gofmtMain() {
268269
return
269270
}
270271

272+
if options.LocalPrefix == "auto" {
273+
wd, err := os.Getwd()
274+
if err != nil {
275+
log.Fatal(err)
276+
}
277+
filename := filepath.Join(wd, "go.mod")
278+
data, err := os.ReadFile(filename)
279+
if err != nil {
280+
log.Fatal(err)
281+
}
282+
gomodModulePath := modfile.ModulePath(data)
283+
if err != nil {
284+
log.Fatal(err)
285+
}
286+
options.LocalPrefix = gomodModulePath
287+
}
288+
271289
if len(paths) == 0 {
272290
if err := processFile("<standard input>", os.Stdin, os.Stdout, fromStdin); err != nil {
273291
report(err)

0 commit comments

Comments
 (0)