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