github.com/riscv/riscv-go@v0.0.0-20200123204226-124ebd6fcc8e/src/cmd/gofmt/gofmt.go (about)

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