Black Lives Matter. Support the Equal Justice Initiative.

Source file src/cmd/gofmt/gofmt.go

Documentation: cmd/gofmt

     1  // Copyright 2009 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  	"bytes"
     9  	"flag"
    10  	"fmt"
    11  	"go/ast"
    12  	"go/parser"
    13  	"go/printer"
    14  	"go/scanner"
    15  	"go/token"
    16  	"io"
    17  	"io/ioutil"
    18  	"os"
    19  	"path/filepath"
    20  	"runtime"
    21  	"runtime/pprof"
    22  	"strings"
    23  
    24  	"cmd/internal/diff"
    25  )
    26  
    27  var (
    28  	// main operation modes
    29  	list        = flag.Bool("l", false, "list files whose formatting differs from gofmt's")
    30  	write       = flag.Bool("w", false, "write result to (source) file instead of stdout")
    31  	rewriteRule = flag.String("r", "", "rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')")
    32  	simplifyAST = flag.Bool("s", false, "simplify code")
    33  	doDiff      = flag.Bool("d", false, "display diffs instead of rewriting files")
    34  	allErrors   = flag.Bool("e", false, "report all errors (not just the first 10 on different lines)")
    35  
    36  	// debugging
    37  	cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file")
    38  )
    39  
    40  // Keep these in sync with go/format/format.go.
    41  const (
    42  	tabWidth    = 8
    43  	printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
    44  
    45  	// printerNormalizeNumbers means to canonicalize number literal prefixes
    46  	// and exponents while printing. See https://golang.org/doc/go1.13#gofmt.
    47  	//
    48  	// This value is defined in go/printer specifically for go/format and cmd/gofmt.
    49  	printerNormalizeNumbers = 1 << 30
    50  )
    51  
    52  var (
    53  	fileSet    = token.NewFileSet() // per process FileSet
    54  	exitCode   = 0
    55  	rewrite    func(*ast.File) *ast.File
    56  	parserMode parser.Mode
    57  )
    58  
    59  func report(err error) {
    60  	scanner.PrintError(os.Stderr, err)
    61  	exitCode = 2
    62  }
    63  
    64  func usage() {
    65  	fmt.Fprintf(os.Stderr, "usage: gofmt [flags] [path ...]\n")
    66  	flag.PrintDefaults()
    67  }
    68  
    69  func initParserMode() {
    70  	parserMode = parser.ParseComments
    71  	if *allErrors {
    72  		parserMode |= parser.AllErrors
    73  	}
    74  }
    75  
    76  func isGoFile(f os.FileInfo) bool {
    77  	// ignore non-Go files
    78  	name := f.Name()
    79  	return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
    80  }
    81  
    82  // If in == nil, the source is the contents of the file with the given filename.
    83  func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error {
    84  	var perm os.FileMode = 0644
    85  	if in == nil {
    86  		f, err := os.Open(filename)
    87  		if err != nil {
    88  			return err
    89  		}
    90  		defer f.Close()
    91  		fi, err := f.Stat()
    92  		if err != nil {
    93  			return err
    94  		}
    95  		in = f
    96  		perm = fi.Mode().Perm()
    97  	}
    98  
    99  	src, err := ioutil.ReadAll(in)
   100  	if err != nil {
   101  		return err
   102  	}
   103  
   104  	file, sourceAdj, indentAdj, err := parse(fileSet, filename, src, stdin)
   105  	if err != nil {
   106  		return err
   107  	}
   108  
   109  	if rewrite != nil {
   110  		if sourceAdj == nil {
   111  			file = rewrite(file)
   112  		} else {
   113  			fmt.Fprintf(os.Stderr, "warning: rewrite ignored for incomplete programs\n")
   114  		}
   115  	}
   116  
   117  	ast.SortImports(fileSet, file)
   118  
   119  	if *simplifyAST {
   120  		simplify(file)
   121  	}
   122  
   123  	res, err := format(fileSet, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth})
   124  	if err != nil {
   125  		return err
   126  	}
   127  
   128  	if !bytes.Equal(src, res) {
   129  		// formatting has changed
   130  		if *list {
   131  			fmt.Fprintln(out, filename)
   132  		}
   133  		if *write {
   134  			// make a temporary backup before overwriting original
   135  			bakname, err := backupFile(filename+".", src, perm)
   136  			if err != nil {
   137  				return err
   138  			}
   139  			err = ioutil.WriteFile(filename, res, perm)
   140  			if err != nil {
   141  				os.Rename(bakname, filename)
   142  				return err
   143  			}
   144  			err = os.Remove(bakname)
   145  			if err != nil {
   146  				return err
   147  			}
   148  		}
   149  		if *doDiff {
   150  			data, err := diffWithReplaceTempFile(src, res, filename)
   151  			if err != nil {
   152  				return fmt.Errorf("computing diff: %s", err)
   153  			}
   154  			fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
   155  			out.Write(data)
   156  		}
   157  	}
   158  
   159  	if !*list && !*write && !*doDiff {
   160  		_, err = out.Write(res)
   161  	}
   162  
   163  	return err
   164  }
   165  
   166  func visitFile(path string, f os.FileInfo, err error) error {
   167  	if err == nil && isGoFile(f) {
   168  		err = processFile(path, nil, os.Stdout, false)
   169  	}
   170  	// Don't complain if a file was deleted in the meantime (i.e.
   171  	// the directory changed concurrently while running gofmt).
   172  	if err != nil && !os.IsNotExist(err) {
   173  		report(err)
   174  	}
   175  	return nil
   176  }
   177  
   178  func walkDir(path string) {
   179  	filepath.Walk(path, visitFile)
   180  }
   181  
   182  func main() {
   183  	// call gofmtMain in a separate function
   184  	// so that it can use defer and have them
   185  	// run before the exit.
   186  	gofmtMain()
   187  	os.Exit(exitCode)
   188  }
   189  
   190  func gofmtMain() {
   191  	flag.Usage = usage
   192  	flag.Parse()
   193  
   194  	if *cpuprofile != "" {
   195  		f, err := os.Create(*cpuprofile)
   196  		if err != nil {
   197  			fmt.Fprintf(os.Stderr, "creating cpu profile: %s\n", err)
   198  			exitCode = 2
   199  			return
   200  		}
   201  		defer f.Close()
   202  		pprof.StartCPUProfile(f)
   203  		defer pprof.StopCPUProfile()
   204  	}
   205  
   206  	initParserMode()
   207  	initRewrite()
   208  
   209  	if flag.NArg() == 0 {
   210  		if *write {
   211  			fmt.Fprintln(os.Stderr, "error: cannot use -w with standard input")
   212  			exitCode = 2
   213  			return
   214  		}
   215  		if err := processFile("<standard input>", os.Stdin, os.Stdout, true); err != nil {
   216  			report(err)
   217  		}
   218  		return
   219  	}
   220  
   221  	for i := 0; i < flag.NArg(); i++ {
   222  		path := flag.Arg(i)
   223  		switch dir, err := os.Stat(path); {
   224  		case err != nil:
   225  			report(err)
   226  		case dir.IsDir():
   227  			walkDir(path)
   228  		default:
   229  			if err := processFile(path, nil, os.Stdout, false); err != nil {
   230  				report(err)
   231  			}
   232  		}
   233  	}
   234  }
   235  
   236  func diffWithReplaceTempFile(b1, b2 []byte, filename string) ([]byte, error) {
   237  	data, err := diff.Diff("gofmt", b1, b2)
   238  	if len(data) > 0 {
   239  		return replaceTempFilename(data, filename)
   240  	}
   241  	return data, err
   242  }
   243  
   244  // replaceTempFilename replaces temporary filenames in diff with actual one.
   245  //
   246  // --- /tmp/gofmt316145376	2017-02-03 19:13:00.280468375 -0500
   247  // +++ /tmp/gofmt617882815	2017-02-03 19:13:00.280468375 -0500
   248  // ...
   249  // ->
   250  // --- path/to/file.go.orig	2017-02-03 19:13:00.280468375 -0500
   251  // +++ path/to/file.go	2017-02-03 19:13:00.280468375 -0500
   252  // ...
   253  func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
   254  	bs := bytes.SplitN(diff, []byte{'\n'}, 3)
   255  	if len(bs) < 3 {
   256  		return nil, fmt.Errorf("got unexpected diff for %s", filename)
   257  	}
   258  	// Preserve timestamps.
   259  	var t0, t1 []byte
   260  	if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
   261  		t0 = bs[0][i:]
   262  	}
   263  	if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
   264  		t1 = bs[1][i:]
   265  	}
   266  	// Always print filepath with slash separator.
   267  	f := filepath.ToSlash(filename)
   268  	bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
   269  	bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
   270  	return bytes.Join(bs, []byte{'\n'}), nil
   271  }
   272  
   273  const chmodSupported = runtime.GOOS != "windows"
   274  
   275  // backupFile writes data to a new file named filename<number> with permissions perm,
   276  // with <number randomly chosen such that the file name is unique. backupFile returns
   277  // the chosen file name.
   278  func backupFile(filename string, data []byte, perm os.FileMode) (string, error) {
   279  	// create backup file
   280  	f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
   281  	if err != nil {
   282  		return "", err
   283  	}
   284  	bakname := f.Name()
   285  	if chmodSupported {
   286  		err = f.Chmod(perm)
   287  		if err != nil {
   288  			f.Close()
   289  			os.Remove(bakname)
   290  			return bakname, err
   291  		}
   292  	}
   293  
   294  	// write data to backup file
   295  	_, err = f.Write(data)
   296  	if err1 := f.Close(); err == nil {
   297  		err = err1
   298  	}
   299  
   300  	return bakname, err
   301  }
   302  

View as plain text