github.com/MangoDowner/go-gm@v0.0.0-20180818020936-8baa2bd4408c/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  		files := base.FilterDotUnderscoreFiles(base.RelPaths(pkg.Internal.AllGoFiles))
    49  		base.Run(str.StringList(gofmt, "-l", "-w", files))
    50  	}
    51  }
    52  
    53  func gofmtPath() string {
    54  	gofmt := "gofmt"
    55  	if base.ToolIsWindows {
    56  		gofmt += base.ToolWindowsExtension
    57  	}
    58  
    59  	gofmtPath := filepath.Join(cfg.GOBIN, gofmt)
    60  	if _, err := os.Stat(gofmtPath); err == nil {
    61  		return gofmtPath
    62  	}
    63  
    64  	gofmtPath = filepath.Join(cfg.GOROOT, "bin", gofmt)
    65  	if _, err := os.Stat(gofmtPath); err == nil {
    66  		return gofmtPath
    67  	}
    68  
    69  	// fallback to looking for gofmt in $PATH
    70  	return "gofmt"
    71  }