1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package main 6 7 import ( 8 "os" 9 "path/filepath" 10 ) 11 12 func init() { 13 addBuildFlagsNX(cmdFmt) 14 } 15 16 var cmdFmt = &Command{ 17 Run: runFmt, 18 UsageLine: "fmt [-n] [-x] [packages]", 19 Short: "run gofmt on package sources", 20 Long: ` 21 Fmt runs the command 'gofmt -l -w' on the packages named 22 by the import paths. It prints the names of the files that are modified. 23 24 For more about gofmt, see 'go doc cmd/gofmt'. 25 For more about specifying packages, see 'go help packages'. 26 27 The -n flag prints commands that would be executed. 28 The -x flag prints commands as they are executed. 29 30 To run gofmt with specific options, run gofmt itself. 31 32 See also: go fix, go vet. 33 `, 34 } 35 36 func runFmt(cmd *Command, args []string) { 37 gofmt := gofmtPath() 38 for _, pkg := range packages(args) { 39 // Use pkg.gofiles instead of pkg.Dir so that 40 // the command only applies to this package, 41 // not to packages in subdirectories. 42 run(stringList(gofmt, "-l", "-w", relPaths(pkg.allgofiles))) 43 } 44 } 45 46 func gofmtPath() string { 47 gofmt := "gofmt" 48 if toolIsWindows { 49 gofmt += toolWindowsExtension 50 } 51 52 gofmtPath := filepath.Join(gobin, gofmt) 53 if _, err := os.Stat(gofmtPath); err == nil { 54 return gofmtPath 55 } 56 57 gofmtPath = filepath.Join(goroot, "bin", gofmt) 58 if _, err := os.Stat(gofmtPath); err == nil { 59 return gofmtPath 60 } 61 62 // fallback to looking for gofmt in $PATH 63 return "gofmt" 64 } 65