Giant blob of minor changes
[dotfiles/.git] / .config / coc / extensions / coc-go-data / tools / pkg / mod / mvdan.cc / gofumpt@v0.0.0-20200802201014-ab5a8192947d / gofumports / goimports.go
1 // Copyright 2013 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         "bufio"
9         "bytes"
10         "errors"
11         "flag"
12         "fmt"
13         "go/scanner"
14         "io"
15         "io/ioutil"
16         "log"
17         "os"
18         "os/exec"
19         "path/filepath"
20         "runtime"
21         "runtime/pprof"
22         "strings"
23
24         gformat "mvdan.cc/gofumpt/format"
25         "mvdan.cc/gofumpt/gofumports/internal/imports"
26 )
27
28 var (
29         // main operation modes
30         list   = flag.Bool("l", false, "list files whose formatting differs from goimport's")
31         write  = flag.Bool("w", false, "write result to (source) file instead of stdout")
32         doDiff = flag.Bool("d", false, "display diffs instead of rewriting files")
33         srcdir = flag.String("srcdir", "", "choose imports as if source code is from `dir`. When operating on a single file, dir may instead be the complete file name.")
34
35         verbose bool // verbose logging
36
37         cpuProfile     = flag.String("cpuprofile", "", "CPU profile output")
38         memProfile     = flag.String("memprofile", "", "memory profile output")
39         memProfileRate = flag.Int("memrate", 0, "if > 0, sets runtime.MemProfileRate")
40
41         options = &imports.Options{
42                 TabWidth:  8,
43                 TabIndent: true,
44                 Comments:  true,
45                 Fragment:  true,
46                 Env:       &imports.ProcessEnv{},
47         }
48         exitCode = 0
49 )
50
51 func init() {
52         flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)")
53         flag.StringVar(&options.Env.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
54         flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, gofumports is effectively gofmt, with the addition that imports are grouped into sections.")
55 }
56
57 func report(err error) {
58         scanner.PrintError(os.Stderr, err)
59         exitCode = 2
60 }
61
62 func usage() {
63         fmt.Fprintf(os.Stderr, "usage: gofumports [flags] [path ...]\n")
64         flag.PrintDefaults()
65         os.Exit(2)
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 // argumentType is which mode gofumports was invoked as.
75 type argumentType int
76
77 const (
78         // fromStdin means the user is piping their source into gofumports.
79         fromStdin argumentType = iota
80
81         // singleArg is the common case from editors, when gofumports is run on
82         // a single file.
83         singleArg
84
85         // multipleArg is when the user ran "gofumports file1.go file2.go"
86         // or ran gofumports on a directory tree.
87         multipleArg
88 )
89
90 func processFile(filename string, in io.Reader, out io.Writer, argType argumentType) error {
91         opt := options
92         if argType == fromStdin {
93                 nopt := *options
94                 nopt.Fragment = true
95                 opt = &nopt
96         }
97
98         if in == nil {
99                 f, err := os.Open(filename)
100                 if err != nil {
101                         return err
102                 }
103                 defer f.Close()
104                 in = f
105         }
106
107         src, err := ioutil.ReadAll(in)
108         if err != nil {
109                 return err
110         }
111
112         target := filename
113         if *srcdir != "" {
114                 // Determine whether the provided -srcdirc is a directory or file
115                 // and then use it to override the target.
116                 //
117                 // See https://github.com/dominikh/go-mode.el/issues/146
118                 if isFile(*srcdir) {
119                         if argType == multipleArg {
120                                 return errors.New("-srcdir value can't be a file when passing multiple arguments or when walking directories")
121                         }
122                         target = *srcdir
123                 } else if argType == singleArg && strings.HasSuffix(*srcdir, ".go") && !isDir(*srcdir) {
124                         // For a file which doesn't exist on disk yet, but might shortly.
125                         // e.g. user in editor opens $DIR/newfile.go and newfile.go doesn't yet exist on disk.
126                         // The gofumports on-save hook writes the buffer to a temp file
127                         // first and runs gofumports before the actual save to newfile.go.
128                         // The editor's buffer is named "newfile.go" so that is passed to gofumports as:
129                         //      gofumports -srcdir=/gopath/src/pkg/newfile.go /tmp/gofmtXXXXXXXX.go
130                         // and then the editor reloads the result from the tmp file and writes
131                         // it to newfile.go.
132                         target = *srcdir
133                 } else {
134                         // Pretend that file is from *srcdir in order to decide
135                         // visible imports correctly.
136                         target = filepath.Join(*srcdir, filepath.Base(filename))
137                 }
138         }
139
140         res, err := imports.Process(target, src, opt)
141         if err != nil {
142                 return err
143         }
144
145         // This is the only gofumpt change on gofumports's codebase, besides changing
146         // the name in the usage text.
147         if *langVersion == "" {
148                 out, err := exec.Command("go", "list", "-m", "-f", "{{.GoVersion}}").Output()
149                 out = bytes.TrimSpace(out)
150                 if err == nil && len(out) > 0 {
151                         *langVersion = string(out)
152                 }
153         }
154         res, err = gformat.Source(res, gformat.Options{LangVersion: *langVersion})
155         if err != nil {
156                 return err
157         }
158
159         if !bytes.Equal(src, res) {
160                 // formatting has changed
161                 if *list {
162                         fmt.Fprintln(out, filename)
163                 }
164                 if *write {
165                         if argType == fromStdin {
166                                 // filename is "<standard input>"
167                                 return errors.New("can't use -w on stdin")
168                         }
169                         // On Windows, we need to re-set the permissions from the file. See golang/go#38225.
170                         var perms os.FileMode
171                         if fi, err := os.Stat(filename); err == nil {
172                                 perms = fi.Mode() & os.ModePerm
173                         }
174                         err = ioutil.WriteFile(filename, res, perms)
175                         if err != nil {
176                                 return err
177                         }
178                 }
179                 if *doDiff {
180                         if argType == fromStdin {
181                                 filename = "stdin.go" // because <standard input>.orig looks silly
182                         }
183                         data, err := diff(src, res, filename)
184                         if err != nil {
185                                 return fmt.Errorf("computing diff: %s", err)
186                         }
187                         fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
188                         out.Write(data)
189                 }
190         }
191
192         if !*list && !*write && !*doDiff {
193                 _, err = out.Write(res)
194         }
195
196         return err
197 }
198
199 func visitFile(path string, f os.FileInfo, err error) error {
200         if err == nil && isGoFile(f) {
201                 err = processFile(path, nil, os.Stdout, multipleArg)
202         }
203         if err != nil {
204                 report(err)
205         }
206         return nil
207 }
208
209 func walkDir(path string) {
210         filepath.Walk(path, visitFile)
211 }
212
213 func main() {
214         runtime.GOMAXPROCS(runtime.NumCPU())
215
216         // call gofmtMain in a separate function
217         // so that it can use defer and have them
218         // run before the exit.
219         gofmtMain()
220         os.Exit(exitCode)
221 }
222
223 // parseFlags parses command line flags and returns the paths to process.
224 // It's a var so that custom implementations can replace it in other files.
225 var parseFlags = func() []string {
226         flag.BoolVar(&verbose, "v", false, "verbose logging")
227
228         flag.Parse()
229         return flag.Args()
230 }
231
232 func bufferedFileWriter(dest string) (w io.Writer, close func()) {
233         f, err := os.Create(dest)
234         if err != nil {
235                 log.Fatal(err)
236         }
237         bw := bufio.NewWriter(f)
238         return bw, func() {
239                 if err := bw.Flush(); err != nil {
240                         log.Fatalf("error flushing %v: %v", dest, err)
241                 }
242                 if err := f.Close(); err != nil {
243                         log.Fatal(err)
244                 }
245         }
246 }
247
248 func gofmtMain() {
249         flag.Usage = usage
250         paths := parseFlags()
251
252         if *cpuProfile != "" {
253                 bw, flush := bufferedFileWriter(*cpuProfile)
254                 pprof.StartCPUProfile(bw)
255                 defer flush()
256                 defer pprof.StopCPUProfile()
257         }
258         // doTrace is a conditionally compiled wrapper around runtime/trace. It is
259         // used to allow gofumports to compile under gccgo, which does not support
260         // runtime/trace. See https://golang.org/issue/15544.
261         defer doTrace()()
262         if *memProfileRate > 0 {
263                 runtime.MemProfileRate = *memProfileRate
264                 bw, flush := bufferedFileWriter(*memProfile)
265                 defer func() {
266                         runtime.GC() // materialize all statistics
267                         if err := pprof.WriteHeapProfile(bw); err != nil {
268                                 log.Fatal(err)
269                         }
270                         flush()
271                 }()
272         }
273
274         if verbose {
275                 log.SetFlags(log.LstdFlags | log.Lmicroseconds)
276                 options.Env.Logf = log.Printf
277         }
278         if options.TabWidth < 0 {
279                 fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth)
280                 exitCode = 2
281                 return
282         }
283
284         if len(paths) == 0 {
285                 if err := processFile("<standard input>", os.Stdin, os.Stdout, fromStdin); err != nil {
286                         report(err)
287                 }
288                 return
289         }
290
291         argType := singleArg
292         if len(paths) > 1 {
293                 argType = multipleArg
294         }
295
296         for _, path := range paths {
297                 switch dir, err := os.Stat(path); {
298                 case err != nil:
299                         report(err)
300                 case dir.IsDir():
301                         walkDir(path)
302                 default:
303                         if err := processFile(path, nil, os.Stdout, argType); err != nil {
304                                 report(err)
305                         }
306                 }
307         }
308 }
309
310 func writeTempFile(dir, prefix string, data []byte) (string, error) {
311         file, err := ioutil.TempFile(dir, prefix)
312         if err != nil {
313                 return "", err
314         }
315         _, err = file.Write(data)
316         if err1 := file.Close(); err == nil {
317                 err = err1
318         }
319         if err != nil {
320                 os.Remove(file.Name())
321                 return "", err
322         }
323         return file.Name(), nil
324 }
325
326 func diff(b1, b2 []byte, filename string) (data []byte, err error) {
327         f1, err := writeTempFile("", "gofmt", b1)
328         if err != nil {
329                 return
330         }
331         defer os.Remove(f1)
332
333         f2, err := writeTempFile("", "gofmt", b2)
334         if err != nil {
335                 return
336         }
337         defer os.Remove(f2)
338
339         cmd := "diff"
340         if runtime.GOOS == "plan9" {
341                 cmd = "/bin/ape/diff"
342         }
343
344         data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
345         if len(data) > 0 {
346                 // diff exits with a non-zero status when the files don't match.
347                 // Ignore that failure as long as we get output.
348                 return replaceTempFilename(data, filename)
349         }
350         return
351 }
352
353 // replaceTempFilename replaces temporary filenames in diff with actual one.
354 //
355 // --- /tmp/gofmt316145376      2017-02-03 19:13:00.280468375 -0500
356 // +++ /tmp/gofmt617882815      2017-02-03 19:13:00.280468375 -0500
357 // ...
358 // ->
359 // --- path/to/file.go.orig     2017-02-03 19:13:00.280468375 -0500
360 // +++ path/to/file.go  2017-02-03 19:13:00.280468375 -0500
361 // ...
362 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
363         bs := bytes.SplitN(diff, []byte{'\n'}, 3)
364         if len(bs) < 3 {
365                 return nil, fmt.Errorf("got unexpected diff for %s", filename)
366         }
367         // Preserve timestamps.
368         var t0, t1 []byte
369         if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
370                 t0 = bs[0][i:]
371         }
372         if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
373                 t1 = bs[1][i:]
374         }
375         // Always print filepath with slash separator.
376         f := filepath.ToSlash(filename)
377         bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
378         bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
379         return bytes.Join(bs, []byte{'\n'}), nil
380 }
381
382 // isFile reports whether name is a file.
383 func isFile(name string) bool {
384         fi, err := os.Stat(name)
385         return err == nil && fi.Mode().IsRegular()
386 }
387
388 // isDir reports whether name is a directory.
389 func isDir(name string) bool {
390         fi, err := os.Stat(name)
391         return err == nil && fi.IsDir()
392 }