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.
25 gformat "mvdan.cc/gofumpt/format"
26 "mvdan.cc/gofumpt/internal/diff"
30 // main operation modes
31 list = flag.Bool("l", false, "list files whose formatting differs from gofumpt's")
32 write = flag.Bool("w", false, "write result to (source) file instead of stdout")
33 rewriteRule = flag.String("r", "", "rewrite rule (e.g., 'a[b:len(a)] -> a[b:]')")
34 simplifyAST = flag.Bool("s", false, "simplify code")
35 doDiff = flag.Bool("d", false, "display diffs instead of rewriting files")
36 allErrors = flag.Bool("e", false, "report all errors (not just the first 10 on different lines)")
39 cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file")
42 // Keep these in sync with go/format/format.go.
45 printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
47 // printerNormalizeNumbers means to canonicalize number literal prefixes
48 // and exponents while printing. See https://golang.org/doc/go1.13#gofumpt.
50 // This value is defined in go/printer specifically for go/format and cmd/gofumpt.
51 printerNormalizeNumbers = 1 << 30
55 fileSet = token.NewFileSet() // per process FileSet
57 rewrite func(*ast.File) *ast.File
58 parserMode parser.Mode
61 func report(err error) {
62 scanner.PrintError(os.Stderr, err)
67 fmt.Fprintf(os.Stderr, "usage: gofumpt [flags] [path ...]\n")
71 func initParserMode() {
72 parserMode = parser.ParseComments
74 parserMode |= parser.AllErrors
78 func isGoFile(f os.FileInfo) bool {
79 // ignore non-Go files
81 return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
84 // If in == nil, the source is the contents of the file with the given filename.
85 func processFile(filename string, in io.Reader, out io.Writer, stdin bool) error {
86 var perm os.FileMode = 0o644
88 f, err := os.Open(filename)
98 perm = fi.Mode().Perm()
101 src, err := ioutil.ReadAll(in)
106 file, sourceAdj, indentAdj, err := parse(fileSet, filename, src, stdin)
112 if sourceAdj == nil {
115 fmt.Fprintf(os.Stderr, "warning: rewrite ignored for incomplete programs\n")
119 ast.SortImports(fileSet, file)
125 // Apply gofumpt's changes before we print the code in gofumpt's
127 if *langVersion == "" {
128 out, err := exec.Command("go", "list", "-m", "-f", "{{.GoVersion}}").Output()
129 out = bytes.TrimSpace(out)
130 if err == nil && len(out) > 0 {
131 *langVersion = string(out)
134 gformat.File(fileSet, file, gformat.Options{
135 LangVersion: *langVersion,
136 ExtraRules: *extraRules,
139 res, err := format(fileSet, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth})
144 if !bytes.Equal(src, res) {
145 // formatting has changed
147 fmt.Fprintln(out, filename)
150 // make a temporary backup before overwriting original
151 bakname, err := backupFile(filename+".", src, perm)
155 err = ioutil.WriteFile(filename, res, perm)
157 os.Rename(bakname, filename)
160 err = os.Remove(bakname)
166 data, err := diffWithReplaceTempFile(src, res, filename)
168 return fmt.Errorf("computing diff: %s", err)
170 fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
175 if !*list && !*write && !*doDiff {
176 _, err = out.Write(res)
182 func visitFile(path string, f os.FileInfo, err error) error {
183 if err == nil && isGoFile(f) {
184 err = processFile(path, nil, os.Stdout, false)
186 // Don't complain if a file was deleted in the meantime (i.e.
187 // the directory changed concurrently while running gofumpt).
188 if err != nil && !os.IsNotExist(err) {
194 func walkDir(path string) {
195 filepath.Walk(path, visitFile)
199 // call gofumptMain in a separate function
200 // so that it can use defer and have them
201 // run before the exit.
210 // Print the gofumpt version if the user asks for it.
216 if *cpuprofile != "" {
217 f, err := os.Create(*cpuprofile)
219 fmt.Fprintf(os.Stderr, "creating cpu profile: %s\n", err)
224 pprof.StartCPUProfile(f)
225 defer pprof.StopCPUProfile()
231 if flag.NArg() == 0 {
233 fmt.Fprintln(os.Stderr, "error: cannot use -w with standard input")
237 if err := processFile("<standard input>", os.Stdin, os.Stdout, true); err != nil {
243 for i := 0; i < flag.NArg(); i++ {
245 switch dir, err := os.Stat(path); {
251 if err := processFile(path, nil, os.Stdout, false); err != nil {
258 func diffWithReplaceTempFile(b1, b2 []byte, filename string) ([]byte, error) {
259 data, err := diff.Diff("gofumpt", b1, b2)
261 return replaceTempFilename(data, filename)
266 // replaceTempFilename replaces temporary filenames in diff with actual one.
268 // --- /tmp/gofumpt316145376 2017-02-03 19:13:00.280468375 -0500
269 // +++ /tmp/gofumpt617882815 2017-02-03 19:13:00.280468375 -0500
272 // --- path/to/file.go.orig 2017-02-03 19:13:00.280468375 -0500
273 // +++ path/to/file.go 2017-02-03 19:13:00.280468375 -0500
275 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
276 bs := bytes.SplitN(diff, []byte{'\n'}, 3)
278 return nil, fmt.Errorf("got unexpected diff for %s", filename)
280 // Preserve timestamps.
282 if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
285 if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
288 // Always print filepath with slash separator.
289 f := filepath.ToSlash(filename)
290 bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
291 bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
292 return bytes.Join(bs, []byte{'\n'}), nil
295 const chmodSupported = runtime.GOOS != "windows"
297 // backupFile writes data to a new file named filename<number> with permissions perm,
298 // with <number randomly chosen such that the file name is unique. backupFile returns
299 // the chosen file name.
300 func backupFile(filename string, data []byte, perm os.FileMode) (string, error) {
301 // create backup file
302 f, err := ioutil.TempFile(filepath.Dir(filename), filepath.Base(filename))
316 // write data to backup file
317 _, err = f.Write(data)
318 if err1 := f.Close(); err == nil {