github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/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 "fmt" 10 "os" 11 "path/filepath" 12 "runtime" 13 "strings" 14 "sync" 15 16 "cmd/go/internal/base" 17 "cmd/go/internal/cfg" 18 "cmd/go/internal/load" 19 "cmd/go/internal/modload" 20 "cmd/go/internal/str" 21 ) 22 23 func init() { 24 base.AddBuildFlagsNX(&CmdFmt.Flag) 25 } 26 27 var CmdFmt = &base.Command{ 28 Run: runFmt, 29 UsageLine: "go fmt [-n] [-x] [packages]", 30 Short: "gofmt (reformat) package sources", 31 Long: ` 32 Fmt runs the command 'gofmt -l -w' on the packages named 33 by the import paths. It prints the names of the files that are modified. 34 35 For more about gofmt, see 'go doc cmd/gofmt'. 36 For more about specifying packages, see 'go help packages'. 37 38 The -n flag prints commands that would be executed. 39 The -x flag prints commands as they are executed. 40 41 To run gofmt with specific options, run gofmt itself. 42 43 See also: go fix, go vet. 44 `, 45 } 46 47 func runFmt(cmd *base.Command, args []string) { 48 printed := false 49 gofmt := gofmtPath() 50 procs := runtime.GOMAXPROCS(0) 51 var wg sync.WaitGroup 52 wg.Add(procs) 53 fileC := make(chan string, 2*procs) 54 for i := 0; i < procs; i++ { 55 go func() { 56 defer wg.Done() 57 for file := range fileC { 58 base.Run(str.StringList(gofmt, "-l", "-w", file)) 59 } 60 }() 61 } 62 for _, pkg := range load.PackagesAndErrors(args) { 63 if modload.Enabled() && pkg.Module != nil && !pkg.Module.Main { 64 if !printed { 65 fmt.Fprintf(os.Stderr, "go: not formatting packages in dependency modules\n") 66 printed = true 67 } 68 continue 69 } 70 if pkg.Error != nil { 71 if strings.HasPrefix(pkg.Error.Err, "build constraints exclude all Go files") { 72 // Skip this error, as we will format 73 // all files regardless. 74 } else { 75 base.Errorf("can't load package: %s", pkg.Error) 76 continue 77 } 78 } 79 // Use pkg.gofiles instead of pkg.Dir so that 80 // the command only applies to this package, 81 // not to packages in subdirectories. 82 files := base.RelPaths(pkg.InternalAllGoFiles()) 83 for _, file := range files { 84 fileC <- file 85 } 86 } 87 close(fileC) 88 wg.Wait() 89 } 90 91 func gofmtPath() string { 92 gofmt := "gofmt" 93 if base.ToolIsWindows { 94 gofmt += base.ToolWindowsExtension 95 } 96 97 gofmtPath := filepath.Join(cfg.GOBIN, gofmt) 98 if _, err := os.Stat(gofmtPath); err == nil { 99 return gofmtPath 100 } 101 102 gofmtPath = filepath.Join(cfg.GOROOT, "bin", gofmt) 103 if _, err := os.Stat(gofmtPath); err == nil { 104 return gofmtPath 105 } 106 107 // fallback to looking for gofmt in $PATH 108 return "gofmt" 109 }