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