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/gocommand"
26 "mvdan.cc/gofumpt/gofumports/internal/imports"
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.")
36 verbose bool // verbose logging
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")
42 options = &imports.Options{
47 Env: &imports.ProcessEnv{
48 GocmdRunner: &gocommand.Runner{},
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.")
60 func report(err error) {
61 scanner.PrintError(os.Stderr, err)
66 fmt.Fprintf(os.Stderr, "usage: gofumports [flags] [path ...]\n")
71 func isGoFile(f os.FileInfo) bool {
72 // ignore non-Go files
74 return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
77 // argumentType is which mode gofumports was invoked as.
81 // fromStdin means the user is piping their source into gofumports.
82 fromStdin argumentType = iota
84 // singleArg is the common case from editors, when gofumports is run on
88 // multipleArg is when the user ran "gofumports file1.go file2.go"
89 // or ran gofumports on a directory tree.
93 func processFile(filename string, in io.Reader, out io.Writer, argType argumentType) error {
95 if argType == fromStdin {
102 f, err := os.Open(filename)
110 src, err := ioutil.ReadAll(in)
117 // Determine whether the provided -srcdirc is a directory or file
118 // and then use it to override the target.
120 // See https://github.com/dominikh/go-mode.el/issues/146
122 if argType == multipleArg {
123 return errors.New("-srcdir value can't be a file when passing multiple arguments or when walking directories")
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
137 // Pretend that file is from *srcdir in order to decide
138 // visible imports correctly.
139 target = filepath.Join(*srcdir, filepath.Base(filename))
143 res, err := imports.Process(target, src, opt)
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)
157 res, err = gformat.Source(res, gformat.Options{LangVersion: *langVersion})
162 if !bytes.Equal(src, res) {
163 // formatting has changed
165 fmt.Fprintln(out, filename)
168 if argType == fromStdin {
169 // filename is "<standard input>"
170 return errors.New("can't use -w on stdin")
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
177 err = ioutil.WriteFile(filename, res, perms)
183 if argType == fromStdin {
184 filename = "stdin.go" // because <standard input>.orig looks silly
186 data, err := diff(src, res, filename)
188 return fmt.Errorf("computing diff: %s", err)
190 fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
195 if !*list && !*write && !*doDiff {
196 _, err = out.Write(res)
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)
212 func walkDir(path string) {
213 filepath.Walk(path, visitFile)
217 runtime.GOMAXPROCS(runtime.NumCPU())
219 // call gofmtMain in a separate function
220 // so that it can use defer and have them
221 // run before the exit.
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")
235 func bufferedFileWriter(dest string) (w io.Writer, close func()) {
236 f, err := os.Create(dest)
240 bw := bufio.NewWriter(f)
242 if err := bw.Flush(); err != nil {
243 log.Fatalf("error flushing %v: %v", dest, err)
245 if err := f.Close(); err != nil {
253 paths := parseFlags()
255 if *cpuProfile != "" {
256 bw, flush := bufferedFileWriter(*cpuProfile)
257 pprof.StartCPUProfile(bw)
259 defer pprof.StopCPUProfile()
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.
265 if *memProfileRate > 0 {
266 runtime.MemProfileRate = *memProfileRate
267 bw, flush := bufferedFileWriter(*memProfile)
269 runtime.GC() // materialize all statistics
270 if err := pprof.WriteHeapProfile(bw); err != nil {
278 log.SetFlags(log.LstdFlags | log.Lmicroseconds)
279 options.Env.Logf = log.Printf
281 if options.TabWidth < 0 {
282 fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth)
288 if err := processFile("<standard input>", os.Stdin, os.Stdout, fromStdin); err != nil {
296 argType = multipleArg
299 for _, path := range paths {
300 switch dir, err := os.Stat(path); {
306 if err := processFile(path, nil, os.Stdout, argType); err != nil {
313 func writeTempFile(dir, prefix string, data []byte) (string, error) {
314 file, err := ioutil.TempFile(dir, prefix)
318 _, err = file.Write(data)
319 if err1 := file.Close(); err == nil {
323 os.Remove(file.Name())
326 return file.Name(), nil
329 func diff(b1, b2 []byte, filename string) (data []byte, err error) {
330 f1, err := writeTempFile("", "gofmt", b1)
336 f2, err := writeTempFile("", "gofmt", b2)
343 if runtime.GOOS == "plan9" {
344 cmd = "/bin/ape/diff"
347 data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
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)
356 // replaceTempFilename replaces temporary filenames in diff with actual one.
358 // --- /tmp/gofmt316145376 2017-02-03 19:13:00.280468375 -0500
359 // +++ /tmp/gofmt617882815 2017-02-03 19:13:00.280468375 -0500
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
365 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
366 bs := bytes.SplitN(diff, []byte{'\n'}, 3)
368 return nil, fmt.Errorf("got unexpected diff for %s", filename)
370 // Preserve timestamps.
372 if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
375 if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
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
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()
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()