]> Cypherpunks repositories - gostls13.git/commitdiff
cmd/go: run gofmt from current GOROOT
authorAlexander Zolotov <goldifit@gmail.com>
Sat, 9 May 2015 13:41:32 +0000 (16:41 +0300)
committerRob Pike <r@golang.org>
Tue, 19 May 2015 20:54:34 +0000 (20:54 +0000)
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 <r@golang.org>
src/cmd/go/fmt.go

index 65dc3ca5990bc7921993e56c311457045fc3eb19..e40b0dc65f88af546780ff0b3c6d87497562cf5f 100644 (file)
@@ -4,6 +4,12 @@
 
 package main
 
+import (
+       "os"
+       "path/filepath"
+       "runtime"
+)
+
 func init() {
        addBuildFlagsNX(cmdFmt)
 }
@@ -29,10 +35,31 @@ See also: go fix, go vet.
 }
 
 func runFmt(cmd *Command, args []string) {
+       gofmt := gofmtPath()
        for _, pkg := range packages(args) {
                // Use pkg.gofiles instead of pkg.Dir so that
                // the command only applies to this package,
                // not to packages in subdirectories.
-               run(stringList("gofmt", "-l", "-w", relPaths(pkg.allgofiles)))
+               run(stringList(gofmt, "-l", "-w", relPaths(pkg.allgofiles)))
        }
 }
+
+func gofmtPath() string {
+       gofmt := "gofmt"
+       if toolIsWindows {
+               gofmt += toolWindowsExtension
+       }
+
+       gofmtPath := filepath.Join(gobin, gofmt)
+       if _, err := os.Stat(gofmtPath); err == nil {
+               return gofmtPath
+       }
+
+       gofmtPath = filepath.Join(goroot, "bin", gofmt)
+       if _, err := os.Stat(gofmtPath); err == nil {
+               return gofmtPath
+       }
+
+       // fallback to looking for gofmt in $PATH
+       return "gofmt"
+}