Home | History | Annotate | Download | only in 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 	"internal/format"
     17 	"io"
     18 	"io/ioutil"
     19 	"os"
     20 	"os/exec"
     21 	"path/filepath"
     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 	os.Exit(2)
     60 }
     61 
     62 func initParserMode() {
     63 	parserMode = parser.ParseComments
     64 	if *allErrors {
     65 		parserMode |= parser.AllErrors
     66 	}
     67 }
     68 
     69 func isGoFile(f os.FileInfo) bool {
     70 	// ignore non-Go files
     71 	name := f.Name()
     72 	return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
     73 }
     74 
     75 // If in == nil, the source is the contents of the file with the given filename.
     76 func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error {
     77 	if in == nil {
     78 		f, err := os.Open(filename)
     79 		if err != nil {
     80 			return err
     81 		}
     82 		defer f.Close()
     83 		in = f
     84 	}
     85 
     86 	src, err := ioutil.ReadAll(in)
     87 	if err != nil {
     88 		return err
     89 	}
     90 
     91 	file, sourceAdj, indentAdj, err := format.Parse(fileSet, filename, src, stdin)
     92 	if err != nil {
     93 		return err
     94 	}
     95 
     96 	if rewrite != nil {
     97 		if sourceAdj == nil {
     98 			file = rewrite(file)
     99 		} else {
    100 			fmt.Fprintf(os.Stderr, "warning: rewrite ignored for incomplete programs\n")
    101 		}
    102 	}
    103 
    104 	ast.SortImports(fileSet, file)
    105 
    106 	if *simplifyAST {
    107 		simplify(file)
    108 	}
    109 
    110 	res, err := format.Format(fileSet, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth})
    111 	if err != nil {
    112 		return err
    113 	}
    114 
    115 	if !bytes.Equal(src, res) {
    116 		// formatting has changed
    117 		if *list {
    118 			fmt.Fprintln(out, filename)
    119 		}
    120 		if *write {
    121 			err = ioutil.WriteFile(filename, res, 0644)
    122 			if err != nil {
    123 				return err
    124 			}
    125 		}
    126 		if *doDiff {
    127 			data, err := diff(src, res)
    128 			if err != nil {
    129 				return fmt.Errorf("computing diff: %s", err)
    130 			}
    131 			fmt.Printf("diff %s gofmt/%s\n", filename, filename)
    132 			out.Write(data)
    133 		}
    134 	}
    135 
    136 	if !*list && !*write && !*doDiff {
    137 		_, err = out.Write(res)
    138 	}
    139 
    140 	return err
    141 }
    142 
    143 func visitFile(path string, f os.FileInfo, err error) error {
    144 	if err == nil && isGoFile(f) {
    145 		err = processFile(path, nil, os.Stdout, false)
    146 	}
    147 	if err != nil {
    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 }
    238