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 	"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, filename)
    143 			if err != nil {
    144 				return fmt.Errorf("computing diff: %s", err)
    145 			}
    146 			fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(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 writeTempFile(dir, prefix string, data []byte) (string, error) {
    229 	file, err := ioutil.TempFile(dir, prefix)
    230 	if err != nil {
    231 		return "", err
    232 	}
    233 	_, err = file.Write(data)
    234 	if err1 := file.Close(); err == nil {
    235 		err = err1
    236 	}
    237 	if err != nil {
    238 		os.Remove(file.Name())
    239 		return "", err
    240 	}
    241 	return file.Name(), nil
    242 }
    243 
    244 func diff(b1, b2 []byte, filename string) (data []byte, err error) {
    245 	f1, err := writeTempFile("", "gofmt", b1)
    246 	if err != nil {
    247 		return
    248 	}
    249 	defer os.Remove(f1)
    250 
    251 	f2, err := writeTempFile("", "gofmt", b2)
    252 	if err != nil {
    253 		return
    254 	}
    255 	defer os.Remove(f2)
    256 
    257 	cmd := "diff"
    258 	if runtime.GOOS == "plan9" {
    259 		cmd = "/bin/ape/diff"
    260 	}
    261 
    262 	data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
    263 	if len(data) > 0 {
    264 		// diff exits with a non-zero status when the files don't match.
    265 		// Ignore that failure as long as we get output.
    266 		return replaceTempFilename(data, filename)
    267 	}
    268 	return
    269 }
    270 
    271 // replaceTempFilename replaces temporary filenames in diff with actual one.
    272 //
    273 // --- /tmp/gofmt316145376	2017-02-03 19:13:00.280468375 -0500
    274 // +++ /tmp/gofmt617882815	2017-02-03 19:13:00.280468375 -0500
    275 // ...
    276 // ->
    277 // --- path/to/file.go.orig	2017-02-03 19:13:00.280468375 -0500
    278 // +++ path/to/file.go	2017-02-03 19:13:00.280468375 -0500
    279 // ...
    280 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
    281 	bs := bytes.SplitN(diff, []byte{'\n'}, 3)
    282 	if len(bs) < 3 {
    283 		return nil, fmt.Errorf("got unexpected diff for %s", filename)
    284 	}
    285 	// Preserve timestamps.
    286 	var t0, t1 []byte
    287 	if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
    288 		t0 = bs[0][i:]
    289 	}
    290 	if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
    291 		t1 = bs[1][i:]
    292 	}
    293 	// Always print filepath with slash separator.
    294 	f := filepath.ToSlash(filename)
    295 	bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
    296 	bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
    297 	return bytes.Join(bs, []byte{'\n'}), nil
    298 }
    299 
    300 const chmodSupported = runtime.GOOS != "windows"
    301 
    302 // backupFile writes data to a new file named filename<number> with permissions perm,
    303 // with <number randomly chosen such that the file name is unique. backupFile returns
    304 // the chosen file name.
    305 func backupFile(filename string, data []byte, perm os.FileMode) (string, error) {
    306 	// create backup file
    307 	f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
    308 	if err != nil {
    309 		return "", err
    310 	}
    311 	bakname := f.Name()
    312 	if chmodSupported {
    313 		err = f.Chmod(perm)
    314 		if err != nil {
    315 			f.Close()
    316 			os.Remove(bakname)
    317 			return bakname, err
    318 		}
    319 	}
    320 
    321 	// write data to backup file
    322 	n, err := f.Write(data)
    323 	if err == nil && n < len(data) {
    324 		err = io.ErrShortWrite
    325 	}
    326 	if err1 := f.Close(); err == nil {
    327 		err = err1
    328 	}
    329 
    330 	return bakname, err
    331 }
    332