Skip to content

Commit b324191

Browse files
zolotovrobpike
authored andcommitted
cmd/go: run gofmt from current GOROOT
The existing implementation executes `gofmt` binary from PATH environment variable on invocation `go fmt` command. Relying on PATH might lead to confusions for users with several Go installations. It's more appropriate to run `gofmt` from GOBIN (if defined) or GOROOT. Fixes #10755 Change-Id: I56d42a747319c766f2911508fab3994c3a366d12 Reviewed-on: https://go-review.googlesource.com/9900 Reviewed-by: Rob Pike <[email protected]>
1 parent 8b83306 commit b324191

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

src/cmd/go/fmt.go

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44

55
package main
66

7+
import (
8+
"os"
9+
"path/filepath"
10+
"runtime"
11+
)
12+
713
func init() {
814
addBuildFlagsNX(cmdFmt)
915
}
@@ -29,10 +35,31 @@ See also: go fix, go vet.
2935
}
3036

3137
func runFmt(cmd *Command, args []string) {
38+
gofmt := gofmtPath()
3239
for _, pkg := range packages(args) {
3340
// Use pkg.gofiles instead of pkg.Dir so that
3441
// the command only applies to this package,
3542
// not to packages in subdirectories.
36-
run(stringList("gofmt", "-l", "-w", relPaths(pkg.allgofiles)))
43+
run(stringList(gofmt, "-l", "-w", relPaths(pkg.allgofiles)))
3744
}
3845
}
46+
47+
func gofmtPath() string {
48+
gofmt := "gofmt"
49+
if toolIsWindows {
50+
gofmt += toolWindowsExtension
51+
}
52+
53+
gofmtPath := filepath.Join(gobin, gofmt)
54+
if _, err := os.Stat(gofmtPath); err == nil {
55+
return gofmtPath
56+
}
57+
58+
gofmtPath = filepath.Join(goroot, "bin", gofmt)
59+
if _, err := os.Stat(gofmtPath); err == nil {
60+
return gofmtPath
61+
}
62+
63+
// fallback to looking for gofmt in $PATH
64+
return "gofmt"
65+
}

0 commit comments

Comments
 (0)