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.
24 gformat "mvdan.cc/gofumpt/format"
25 "mvdan.cc/gofumpt/gofumports/internal/imports"
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.")
35 verbose bool // verbose logging
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")
41 options = &imports.Options{
46 Env: &imports.ProcessEnv{},
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.")
57 func report(err error) {
58 scanner.PrintError(os.Stderr, err)
63 fmt.Fprintf(os.Stderr, "usage: gofumports [flags] [path ...]\n")
68 func isGoFile(f os.FileInfo) bool {
69 // ignore non-Go files
71 return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
74 // argumentType is which mode gofumports was invoked as.
78 // fromStdin means the user is piping their source into gofumports.
79 fromStdin argumentType = iota
81 // singleArg is the common case from editors, when gofumports is run on
85 // multipleArg is when the user ran "gofumports file1.go file2.go"
86 // or ran gofumports on a directory tree.
90 func processFile(filename string, in io.Reader, out io.Writer, argType argumentType) error {
92 if argType == fromStdin {
99 f, err := os.Open(filename)
107 src, err := ioutil.ReadAll(in)
114 // Determine whether the provided -srcdirc is a directory or file
115 // and then use it to override the target.
117 // See https://github.com/dominikh/go-mode.el/issues/146
119 if argType == multipleArg {
120 return errors.New("-srcdir value can't be a file when passing multiple arguments or when walking directories")
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
134 // Pretend that file is from *srcdir in order to decide
135 // visible imports correctly.
136 target = filepath.Join(*srcdir, filepath.Base(filename))
140 res, err := imports.Process(target, src, opt)
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)
154 res, err = gformat.Source(res, gformat.Options{LangVersion: *langVersion})
159 if !bytes.Equal(src, res) {
160 // formatting has changed
162 fmt.Fprintln(out, filename)
165 if argType == fromStdin {
166 // filename is "<standard input>"
167 return errors.New("can't use -w on stdin")
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
174 err = ioutil.WriteFile(filename, res, perms)
180 if argType == fromStdin {
181 filename = "stdin.go" // because <standard input>.orig looks silly
183 data, err := diff(src, res, filename)
185 return fmt.Errorf("computing diff: %s", err)
187 fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
192 if !*list && !*write && !*doDiff {
193 _, err = out.Write(res)
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)
209 func walkDir(path string) {
210 filepath.Walk(path, visitFile)
214 runtime.GOMAXPROCS(runtime.NumCPU())
216 // call gofmtMain in a separate function
217 // so that it can use defer and have them
218 // run before the exit.
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")
232 func bufferedFileWriter(dest string) (w io.Writer, close func()) {
233 f, err := os.Create(dest)
237 bw := bufio.NewWriter(f)
239 if err := bw.Flush(); err != nil {
240 log.Fatalf("error flushing %v: %v", dest, err)
242 if err := f.Close(); err != nil {
250 paths := parseFlags()
252 if *cpuProfile != "" {
253 bw, flush := bufferedFileWriter(*cpuProfile)
254 pprof.StartCPUProfile(bw)
256 defer pprof.StopCPUProfile()
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.
262 if *memProfileRate > 0 {
263 runtime.MemProfileRate = *memProfileRate
264 bw, flush := bufferedFileWriter(*memProfile)
266 runtime.GC() // materialize all statistics
267 if err := pprof.WriteHeapProfile(bw); err != nil {
275 log.SetFlags(log.LstdFlags | log.Lmicroseconds)
276 options.Env.Logf = log.Printf
278 if options.TabWidth < 0 {
279 fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth)
285 if err := processFile("<standard input>", os.Stdin, os.Stdout, fromStdin); err != nil {
293 argType = multipleArg
296 for _, path := range paths {
297 switch dir, err := os.Stat(path); {
303 if err := processFile(path, nil, os.Stdout, argType); err != nil {
310 func writeTempFile(dir, prefix string, data []byte) (string, error) {
311 file, err := ioutil.TempFile(dir, prefix)
315 _, err = file.Write(data)
316 if err1 := file.Close(); err == nil {
320 os.Remove(file.Name())
323 return file.Name(), nil
326 func diff(b1, b2 []byte, filename string) (data []byte, err error) {
327 f1, err := writeTempFile("", "gofmt", b1)
333 f2, err := writeTempFile("", "gofmt", b2)
340 if runtime.GOOS == "plan9" {
341 cmd = "/bin/ape/diff"
344 data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
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)
353 // replaceTempFilename replaces temporary filenames in diff with actual one.
355 // --- /tmp/gofmt316145376 2017-02-03 19:13:00.280468375 -0500
356 // +++ /tmp/gofmt617882815 2017-02-03 19:13:00.280468375 -0500
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
362 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
363 bs := bytes.SplitN(diff, []byte{'\n'}, 3)
365 return nil, fmt.Errorf("got unexpected diff for %s", filename)
367 // Preserve timestamps.
369 if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
372 if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
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
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()
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()