github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/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 os.Exit(2) 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 if in == nil { 77 f, err := os.Open(filename) 78 if err != nil { 79 return err 80 } 81 defer f.Close() 82 in = f 83 } 84 85 src, err := ioutil.ReadAll(in) 86 if err != nil { 87 return err 88 } 89 90 file, sourceAdj, indentAdj, err := parse(fileSet, filename, src, stdin) 91 if err != nil { 92 return err 93 } 94 95 if rewrite != nil { 96 if sourceAdj == nil { 97 file = rewrite(file) 98 } else { 99 fmt.Fprintf(os.Stderr, "warning: rewrite ignored for incomplete programs\n") 100 } 101 } 102 103 ast.SortImports(fileSet, file) 104 105 if *simplifyAST { 106 simplify(file) 107 } 108 109 res, err := format(fileSet, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth}) 110 if err != nil { 111 return err 112 } 113 114 if !bytes.Equal(src, res) { 115 // formatting has changed 116 if *list { 117 fmt.Fprintln(out, filename) 118 } 119 if *write { 120 err = ioutil.WriteFile(filename, res, 0644) 121 if err != nil { 122 return err 123 } 124 } 125 if *doDiff { 126 data, err := diff(src, res) 127 if err != nil { 128 return fmt.Errorf("computing diff: %s", err) 129 } 130 fmt.Printf("diff %s gofmt/%s\n", filename, filename) 131 out.Write(data) 132 } 133 } 134 135 if !*list && !*write && !*doDiff { 136 _, err = out.Write(res) 137 } 138 139 return err 140 } 141 142 func visitFile(path string, f os.FileInfo, err error) error { 143 if err == nil && isGoFile(f) { 144 err = processFile(path, nil, os.Stdout, false) 145 } 146 // Don't complain if a file was deleted in the meantime (i.e. 147 // the directory changed concurrently while running gofmt). 148 if err != nil && !os.IsNotExist(err) { 149 report(err) 150 } 151 return nil 152 } 153 154 func walkDir(path string) { 155 filepath.Walk(path, visitFile) 156 } 157 158 func main() { 159 // call gofmtMain in a separate function 160 // so that it can use defer and have them 161 // run before the exit. 162 gofmtMain() 163 os.Exit(exitCode) 164 } 165 166 func gofmtMain() { 167 flag.Usage = usage 168 flag.Parse() 169 170 if *cpuprofile != "" { 171 f, err := os.Create(*cpuprofile) 172 if err != nil { 173 fmt.Fprintf(os.Stderr, "creating cpu profile: %s\n", err) 174 exitCode = 2 175 return 176 } 177 defer f.Close() 178 pprof.StartCPUProfile(f) 179 defer pprof.StopCPUProfile() 180 } 181 182 initParserMode() 183 initRewrite() 184 185 if flag.NArg() == 0 { 186 if *write { 187 fmt.Fprintln(os.Stderr, "error: cannot use -w with standard input") 188 exitCode = 2 189 return 190 } 191 if err := processFile("<standard input>", os.Stdin, os.Stdout, true); err != nil { 192 report(err) 193 } 194 return 195 } 196 197 for i := 0; i < flag.NArg(); i++ { 198 path := flag.Arg(i) 199 switch dir, err := os.Stat(path); { 200 case err != nil: 201 report(err) 202 case dir.IsDir(): 203 walkDir(path) 204 default: 205 if err := processFile(path, nil, os.Stdout, false); err != nil { 206 report(err) 207 } 208 } 209 } 210 } 211 212 func diff(b1, b2 []byte) (data []byte, err error) { 213 f1, err := ioutil.TempFile("", "gofmt") 214 if err != nil { 215 return 216 } 217 defer os.Remove(f1.Name()) 218 defer f1.Close() 219 220 f2, err := ioutil.TempFile("", "gofmt") 221 if err != nil { 222 return 223 } 224 defer os.Remove(f2.Name()) 225 defer f2.Close() 226 227 f1.Write(b1) 228 f2.Write(b2) 229 230 data, err = exec.Command("diff", "-u", f1.Name(), f2.Name()).CombinedOutput() 231 if len(data) > 0 { 232 // diff exits with a non-zero status when the files don't match. 233 // Ignore that failure as long as we get output. 234 err = nil 235 } 236 return 237 238 }