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 "golang.org/x/tools/internal/gocommand"
25 "golang.org/x/tools/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{
47 GocmdRunner: &gocommand.Runner{},
54 flag.BoolVar(&options.AllErrors, "e", false, "report all errors (not just the first 10 on different lines)")
55 flag.StringVar(&options.LocalPrefix, "local", "", "put imports beginning with this string after 3rd-party packages; comma-separated list")
56 flag.BoolVar(&options.FormatOnly, "format-only", false, "if true, don't fix imports and only format. In this mode, goimports is effectively gofmt, with the addition that imports are grouped into sections.")
59 func report(err error) {
60 scanner.PrintError(os.Stderr, err)
65 fmt.Fprintf(os.Stderr, "usage: goimports [flags] [path ...]\n")
70 func isGoFile(f os.FileInfo) bool {
71 // ignore non-Go files
73 return !f.IsDir() && !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go")
76 // argumentType is which mode goimports was invoked as.
80 // fromStdin means the user is piping their source into goimports.
81 fromStdin argumentType = iota
83 // singleArg is the common case from editors, when goimports is run on
87 // multipleArg is when the user ran "goimports file1.go file2.go"
88 // or ran goimports on a directory tree.
92 func processFile(filename string, in io.Reader, out io.Writer, argType argumentType) error {
94 if argType == fromStdin {
101 f, err := os.Open(filename)
109 src, err := ioutil.ReadAll(in)
116 // Determine whether the provided -srcdirc is a directory or file
117 // and then use it to override the target.
119 // See https://github.com/dominikh/go-mode.el/issues/146
121 if argType == multipleArg {
122 return errors.New("-srcdir value can't be a file when passing multiple arguments or when walking directories")
125 } else if argType == singleArg && strings.HasSuffix(*srcdir, ".go") && !isDir(*srcdir) {
126 // For a file which doesn't exist on disk yet, but might shortly.
127 // e.g. user in editor opens $DIR/newfile.go and newfile.go doesn't yet exist on disk.
128 // The goimports on-save hook writes the buffer to a temp file
129 // first and runs goimports before the actual save to newfile.go.
130 // The editor's buffer is named "newfile.go" so that is passed to goimports as:
131 // goimports -srcdir=/gopath/src/pkg/newfile.go /tmp/gofmtXXXXXXXX.go
132 // and then the editor reloads the result from the tmp file and writes
136 // Pretend that file is from *srcdir in order to decide
137 // visible imports correctly.
138 target = filepath.Join(*srcdir, filepath.Base(filename))
142 res, err := imports.Process(target, src, opt)
147 if !bytes.Equal(src, res) {
148 // formatting has changed
150 fmt.Fprintln(out, filename)
153 if argType == fromStdin {
154 // filename is "<standard input>"
155 return errors.New("can't use -w on stdin")
157 // On Windows, we need to re-set the permissions from the file. See golang/go#38225.
158 var perms os.FileMode
159 if fi, err := os.Stat(filename); err == nil {
160 perms = fi.Mode() & os.ModePerm
162 err = ioutil.WriteFile(filename, res, perms)
168 if argType == fromStdin {
169 filename = "stdin.go" // because <standard input>.orig looks silly
171 data, err := diff(src, res, filename)
173 return fmt.Errorf("computing diff: %s", err)
175 fmt.Printf("diff -u %s %s\n", filepath.ToSlash(filename+".orig"), filepath.ToSlash(filename))
180 if !*list && !*write && !*doDiff {
181 _, err = out.Write(res)
187 func visitFile(path string, f os.FileInfo, err error) error {
188 if err == nil && isGoFile(f) {
189 err = processFile(path, nil, os.Stdout, multipleArg)
197 func walkDir(path string) {
198 filepath.Walk(path, visitFile)
202 runtime.GOMAXPROCS(runtime.NumCPU())
204 // call gofmtMain in a separate function
205 // so that it can use defer and have them
206 // run before the exit.
211 // parseFlags parses command line flags and returns the paths to process.
212 // It's a var so that custom implementations can replace it in other files.
213 var parseFlags = func() []string {
214 flag.BoolVar(&verbose, "v", false, "verbose logging")
220 func bufferedFileWriter(dest string) (w io.Writer, close func()) {
221 f, err := os.Create(dest)
225 bw := bufio.NewWriter(f)
227 if err := bw.Flush(); err != nil {
228 log.Fatalf("error flushing %v: %v", dest, err)
230 if err := f.Close(); err != nil {
238 paths := parseFlags()
240 if *cpuProfile != "" {
241 bw, flush := bufferedFileWriter(*cpuProfile)
242 pprof.StartCPUProfile(bw)
244 defer pprof.StopCPUProfile()
246 // doTrace is a conditionally compiled wrapper around runtime/trace. It is
247 // used to allow goimports to compile under gccgo, which does not support
248 // runtime/trace. See https://golang.org/issue/15544.
250 if *memProfileRate > 0 {
251 runtime.MemProfileRate = *memProfileRate
252 bw, flush := bufferedFileWriter(*memProfile)
254 runtime.GC() // materialize all statistics
255 if err := pprof.WriteHeapProfile(bw); err != nil {
263 log.SetFlags(log.LstdFlags | log.Lmicroseconds)
264 options.Env.Logf = log.Printf
266 if options.TabWidth < 0 {
267 fmt.Fprintf(os.Stderr, "negative tabwidth %d\n", options.TabWidth)
273 if err := processFile("<standard input>", os.Stdin, os.Stdout, fromStdin); err != nil {
281 argType = multipleArg
284 for _, path := range paths {
285 switch dir, err := os.Stat(path); {
291 if err := processFile(path, nil, os.Stdout, argType); err != nil {
298 func writeTempFile(dir, prefix string, data []byte) (string, error) {
299 file, err := ioutil.TempFile(dir, prefix)
303 _, err = file.Write(data)
304 if err1 := file.Close(); err == nil {
308 os.Remove(file.Name())
311 return file.Name(), nil
314 func diff(b1, b2 []byte, filename string) (data []byte, err error) {
315 f1, err := writeTempFile("", "gofmt", b1)
321 f2, err := writeTempFile("", "gofmt", b2)
328 if runtime.GOOS == "plan9" {
329 cmd = "/bin/ape/diff"
332 data, err = exec.Command(cmd, "-u", f1, f2).CombinedOutput()
334 // diff exits with a non-zero status when the files don't match.
335 // Ignore that failure as long as we get output.
336 return replaceTempFilename(data, filename)
341 // replaceTempFilename replaces temporary filenames in diff with actual one.
343 // --- /tmp/gofmt316145376 2017-02-03 19:13:00.280468375 -0500
344 // +++ /tmp/gofmt617882815 2017-02-03 19:13:00.280468375 -0500
347 // --- path/to/file.go.orig 2017-02-03 19:13:00.280468375 -0500
348 // +++ path/to/file.go 2017-02-03 19:13:00.280468375 -0500
350 func replaceTempFilename(diff []byte, filename string) ([]byte, error) {
351 bs := bytes.SplitN(diff, []byte{'\n'}, 3)
353 return nil, fmt.Errorf("got unexpected diff for %s", filename)
355 // Preserve timestamps.
357 if i := bytes.LastIndexByte(bs[0], '\t'); i != -1 {
360 if i := bytes.LastIndexByte(bs[1], '\t'); i != -1 {
363 // Always print filepath with slash separator.
364 f := filepath.ToSlash(filename)
365 bs[0] = []byte(fmt.Sprintf("--- %s%s", f+".orig", t0))
366 bs[1] = []byte(fmt.Sprintf("+++ %s%s", f, t1))
367 return bytes.Join(bs, []byte{'\n'}), nil
370 // isFile reports whether name is a file.
371 func isFile(name string) bool {
372 fi, err := os.Stat(name)
373 return err == nil && fi.Mode().IsRegular()
376 // isDir reports whether name is a directory.
377 func isDir(name string) bool {
378 fi, err := os.Stat(name)
379 return err == nil && fi.IsDir()