.gitignore added
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / mvdan.cc / gofumpt@v0.1.0 / gofmt.go
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         gformat "mvdan.cc/gofumpt/format"
26         "mvdan.cc/gofumpt/internal/diff"
27 )
28
29 var (
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)")
37
38         // debugging
39         cpuprofile = flag.String("cpuprofile", "", "write cpu profile to this file")
40 )
41
42 // Keep these in sync with go/format/format.go.
43 const (
44         tabWidth    = 8
45         printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
46
47         // printerNormalizeNumbers means to canonicalize number literal prefixes
48         // and exponents while printing. See https://golang.org/doc/go1.13#gofumpt.
49         //
50         // This value is defined in go/printer specifically for go/format and cmd/gofumpt.
51         printerNormalizeNumbers = 1 << 30
52 )
53
54 var (
55         fileSet    = token.NewFileSet() // per process FileSet
56         exitCode   = 0
57         rewrite    func(*ast.File) *ast.File
58         parserMode parser.Mode
59 )
60
61 func report(err error) {
62         scanner.PrintError(os.Stderr, err)
63         exitCode = 2
64 }
65
66 func usage() {
67         fmt.Fprintf(os.Stderr, "usage: gofumpt [flags] [path ...]\n")
68         flag.PrintDefaults()
69 }
70
71 func initParserMode() {
72         parserMode = parser.ParseComments
73         if *allErrors {
74                 parserMode |= parser.AllErrors
75         }
76 }
77
78 func isGoFile(f os.FileInfo) bool {
79         // ignore non-Go files
80         name := f.Name()
81         return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
82 }
83
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
87         if in == nil {
88                 f, err := os.Open(filename)
89                 if err != nil {
90                         return err
91                 }
92                 defer f.Close()
93                 fi, err := f.Stat()
94                 if err != nil {
95                         return err
96                 }
97                 in = f
98                 perm = fi.Mode().Perm()
99         }
100
101         src, err := ioutil.ReadAll(in)
102         if err != nil {
103                 return err
104         }
105
106         file, sourceAdj, indentAdj, err := parse(fileSet, filename, src, stdin)
107         if err != nil {
108                 return err
109         }
110
111         if rewrite != nil {
112                 if sourceAdj == nil {
113                         file = rewrite(file)
114                 } else {
115                         fmt.Fprintf(os.Stderr, "warning: rewrite ignored for incomplete programs\n")
116                 }
117         }
118
119         ast.SortImports(fileSet, file)
120
121         if *simplifyAST {
122                 simplify(file)
123         }
124
125         // Apply gofumpt's changes before we print the code in gofumpt's
126         // format.
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)
132                 }
133         }
134         gformat.File(fileSet, file, gformat.Options{
135                 LangVersion: *langVersion,
136                 ExtraRules:  *extraRules,
137         })
138
139         res, err := format(fileSet, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth})
140         if err != nil {
141                 return err
142         }
143
144         if !bytes.Equal(src, res) {
145                 // formatting has changed
146                 if *list {
147                         fmt.Fprintln(out, filename)
148                 }
149                 if *write {
150                         // make a temporary backup before overwriting original
151                         bakname, err := backupFile(filename+".", src, perm)
152                         if err != nil {
153                                 return err
154                         }
155                         err = ioutil.WriteFile(filename, res, perm)
156                         if err != nil {
157                                 os.Rename(bakname, filename)
158                                 return err
159                         }
160                         err = os.Remove(bakname)
161                         if err != nil {
162                                 return err
163                         }
164                 }
165                 if *doDiff {
166                         data, err := diffWithReplaceTempFile(src, res, filename)
167                         if err != nil {
168                                 return fmt.Errorf("computing diff: %s", err)
169                         }
170                         fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
171                         out.Write(data)
172                 }
173         }
174
175         if !*list && !*write && !*doDiff {
176                 _, err = out.Write(res)
177         }
178
179         return err
180 }
181
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)
185         }
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) {
189                 report(err)
190         }
191         return nil
192 }
193
194 func walkDir(path string) {
195         filepath.Walk(path, visitFile)
196 }
197
198 func main() {
199         // call gofumptMain in a separate function
200         // so that it can use defer and have them
201         // run before the exit.
202         gofumptMain()
203         os.Exit(exitCode)
204 }
205
206 func gofumptMain() {
207         flag.Usage = usage
208         flag.Parse()
209
210         // Print the gofumpt version if the user asks for it.
211         if *showVersion {
212                 printVersion()
213                 return
214         }
215
216         if *cpuprofile != "" {
217                 f, err := os.Create(*cpuprofile)
218                 if err != nil {
219                         fmt.Fprintf(os.Stderr, "creating cpu profile: %s\n", err)
220                         exitCode = 2
221                         return
222                 }
223                 defer f.Close()
224                 pprof.StartCPUProfile(f)
225                 defer pprof.StopCPUProfile()
226         }
227
228         initParserMode()
229         initRewrite()
230
231         if flag.NArg() == 0 {
232                 if *write {
233                         fmt.Fprintln(os.Stderr, "error: cannot use -w with standard input")
234                         exitCode = 2
235                         return
236                 }
237                 if err := processFile("<standard input>", os.Stdin, os.Stdout, true); err != nil {
238                         report(err)
239                 }
240                 return
241         }
242
243         for i := 0; i < flag.NArg(); i++ {
244                 path := flag.Arg(i)
245                 switch dir, err := os.Stat(path); {
246                 case err != nil:
247                         report(err)
248                 case dir.IsDir():
249                         walkDir(path)
250                 default:
251                         if err := processFile(path, nil, os.Stdout, false); err != nil {
252                                 report(err)
253                         }
254                 }
255         }
256 }
257
258 func diffWithReplaceTempFile(b1, b2 []byte, filename string) ([]byte, error) {
259         data, err := diff.Diff("gofumpt", b1, b2)
260         if len(data) > 0 {
261                 return replaceTempFilename(data, filename)
262         }
263         return data, err
264 }
265
266 // replaceTempFilename replaces temporary filenames in diff with actual one.
267 //
268 // --- /tmp/gofumpt316145376    2017-02-03 19:13:00.280468375 -0500
269 // +++ /tmp/gofumpt617882815    2017-02-03 19:13:00.280468375 -0500
270 // ...
271 // ->
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
274 // ...
275 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
276         bs := bytes.SplitN(diff, []byte{'\n'}, 3)
277         if len(bs) < 3 {
278                 return nil, fmt.Errorf("got unexpected diff for %s", filename)
279         }
280         // Preserve timestamps.
281         var t0, t1 []byte
282         if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
283                 t0 = bs[0][i:]
284         }
285         if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
286                 t1 = bs[1][i:]
287         }
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
293 }
294
295 const chmodSupported = runtime.GOOS != "windows"
296
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))
303         if err != nil {
304                 return "", err
305         }
306         bakname := f.Name()
307         if chmodSupported {
308                 err = f.Chmod(perm)
309                 if err != nil {
310                         f.Close()
311                         os.Remove(bakname)
312                         return bakname, err
313                 }
314         }
315
316         // write data to backup file
317         _, err = f.Write(data)
318         if err1 := f.Close(); err == nil {
319                 err = err1
320         }
321
322         return bakname, err
323 }