github.com/sanprasirt/go@v0.0.0-20170607001320-a027466e4b6d/src/cmd/go/internal/fmtcmd/fmt.go (about) 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 fmtcmd implements the ``go fmt'' command. 6 package fmtcmd 7 8 import ( 9 "os" 10 "path/filepath" 11 12 "cmd/go/internal/base" 13 "cmd/go/internal/cfg" 14 "cmd/go/internal/load" 15 "cmd/go/internal/str" 16 ) 17 18 func init() { 19 base.AddBuildFlagsNX(&CmdFmt.Flag) 20 } 21 22 var CmdFmt = &base.Command{ 23 Run: runFmt, 24 UsageLine: "fmt [-n] [-x] [packages]", 25 Short: "run gofmt on package sources", 26 Long: ` 27 Fmt runs the command 'gofmt -l -w' on the packages named 28 by the import paths. It prints the names of the files that are modified. 29 30 For more about gofmt, see 'go doc cmd/gofmt'. 31 For more about specifying packages, see 'go help packages'. 32 33 The -n flag prints commands that would be executed. 34 The -x flag prints commands as they are executed. 35 36 To run gofmt with specific options, run gofmt itself. 37 38 See also: go fix, go vet. 39 `, 40 } 41 42 func runFmt(cmd *base.Command, args []string) { 43 gofmt := gofmtPath() 44 for _, pkg := range load.Packages(args) { 45 // Use pkg.gofiles instead of pkg.Dir so that 46 // the command only applies to this package, 47 // not to packages in subdirectories. 48 base.Run(str.StringList(gofmt, "-l", "-w", base.RelPaths(pkg.Internal.AllGoFiles))) 49 } 50 } 51 52 func gofmtPath() string { 53 gofmt := "gofmt" 54 if base.ToolIsWindows { 55 gofmt += base.ToolWindowsExtension 56 } 57 58 gofmtPath := filepath.Join(cfg.GOBIN, gofmt) 59 if _, err := os.Stat(gofmtPath); err == nil { 60 return gofmtPath 61 } 62 63 gofmtPath = filepath.Join(cfg.GOROOT, "bin", gofmt) 64 if _, err := os.Stat(gofmtPath); err == nil { 65 return gofmtPath 66 } 67 68 // fallback to looking for gofmt in $PATH 69 return "gofmt" 70 }