Debian Codegraph @

gofmt.go

raw symbols SCIP
1 // Copyright 2009 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 "bytes"
9 "context"
10 "encoding/json"
11 "flag"
12 "fmt"
13 "go/ast"
14 "go/parser"
15 "go/scanner"
16 "go/token"
17 "io"
18 "io/fs"
19 "os"
20 "os/exec"
21 "path/filepath"
22 "regexp"
23 "runtime"
24 "runtime/pprof"
25 "strings"
26 "sync"
27
28 "golang.org/x/sync/semaphore"
29
30 gformat "mvdan.cc/gofumpt/format"
31 "mvdan.cc/gofumpt/internal/govendor/diff"
32 "mvdan.cc/gofumpt/internal/govendor/go/printer"
33 gversion "mvdan.cc/gofumpt/internal/version"
34 )
35
36 //go:generate go run gen_govendor.go
37 //go:generate go run . -w internal/govendor
38
39 var (
40 // main operation modes
41 list = flag.Bool("l", false, "")
42 write = flag.Bool("w", false, "")
43 doDiff = flag.Bool("d", false, "")
44 allErrors = flag.Bool("e", false, "")
45
46 // debugging
47 cpuprofile = flag.String("cpuprofile", "", "")
48
49 // gofumpt's own flags
50 langVersion = flag.String("lang", "", "")
51 modulePath = flag.String("modpath", "", "")
52 extraRules = flag.Bool("extra", false, "")
53 showVersion = flag.Bool("version", false, "")
54
55 // DEPRECATED
56 rewriteRule = flag.String("r", "", "")
57 simplifyAST = flag.Bool("s", false, "")
58 )
59
60 var version = ""
61
62 // Keep these in sync with go/format/format.go.
63 const (
64 tabWidth = 8
65 printerMode = printer.UseSpaces | printer.TabIndent | printerNormalizeNumbers
66
67 // printerNormalizeNumbers means to canonicalize number literal prefixes
68 // and exponents while printing. See https://golang.org/doc/go1.13#gofmt.
69 //
70 // This value is defined in go/printer specifically for go/format and cmd/gofmt.
71 printerNormalizeNumbers = 1 << 30
72 )
73
74 // fdSem guards the number of concurrently-open file descriptors.
75 //
76 // For now, this is arbitrarily set to 200, based on the observation that many
77 // platforms default to a kernel limit of 256. Ideally, perhaps we should derive
78 // it from rlimit on platforms that support that system call.
79 //
80 // File descriptors opened from outside of this package are not tracked,
81 // so this limit may be approximate.
82 var fdSem = make(chan bool, 200)
83
84 var (
85 fileSet = token.NewFileSet() // per process FileSet
86 parserMode parser.Mode
87 )
88
89 func usage() {
90 fmt.Fprintf(os.Stderr, `usage: gofumpt [flags] [path ...]
91 -version show version and exit
92
93 -d display diffs instead of rewriting files
94 -e report all errors (not just the first 10 on different lines)
95 -l list files whose formatting differs from gofumpt's
96 -w write result to (source) file instead of stdout
97 -extra enable extra rules which should be vetted by a human
98
99 -lang str target Go version in the form "1.X" (default from go.mod)
100 -modpath str Go module path containing the source file (default from go.mod)
101 `)
102 }
103
104 func initParserMode() {
105 parserMode = parser.ParseComments | parser.SkipObjectResolution
106 if *allErrors {
107 parserMode |= parser.AllErrors
108 }
109 }
110
111 func isGoFile(f fs.DirEntry) bool {
112 // ignore non-Go files
113 name := f.Name()
114 return !strings.HasPrefix(name, ".") && strings.HasSuffix(name, ".go") && !f.IsDir()
115 }
116
117 var rxCodeGenerated = regexp.MustCompile(`^// Code generated .* DO NOT EDIT\.$`)
118
119 func isGenerated(file *ast.File) bool {
120 for _, cg := range file.Comments {
121 if cg.Pos() > file.Package {
122 return false
123 }
124 for _, line := range cg.List {
125 if rxCodeGenerated.MatchString(line.Text) {
126 return true
127 }
128 }
129 }
130 return false
131 }
132
133 // A sequencer performs concurrent tasks that may write output, but emits that
134 // output in a deterministic order.
135 type sequencer struct {
136 maxWeight int64
137 sem *semaphore.Weighted // weighted by input bytes (an approximate proxy for memory overhead)
138 prev <-chan *reporterState // 1-buffered
139 }
140
141 // newSequencer returns a sequencer that allows concurrent tasks up to maxWeight
142 // and writes tasks' output to out and err.
143 func newSequencer(maxWeight int64, out, err io.Writer) *sequencer {
144 sem := semaphore.NewWeighted(maxWeight)
145 prev := make(chan *reporterState, 1)
146 prev <- &reporterState{out: out, err: err}
147 return &sequencer{
148 maxWeight: maxWeight,
149 sem: sem,
150 prev: prev,
151 }
152 }
153
154 // exclusive is a weight that can be passed to a sequencer to cause
155 // a task to be executed without any other concurrent tasks.
156 const exclusive = -1
157
158 // Add blocks until the sequencer has enough weight to spare, then adds f as a
159 // task to be executed concurrently.
160 //
161 // If the weight is either negative or larger than the sequencer's maximum
162 // weight, Add blocks until all other tasks have completed, then the task
163 // executes exclusively (blocking all other calls to Add until it completes).
164 //
165 // f may run concurrently in a goroutine, but its output to the passed-in
166 // reporter will be sequential relative to the other tasks in the sequencer.
167 //
168 // If f invokes a method on the reporter, execution of that method may block
169 // until the previous task has finished. (To maximize concurrency, f should
170 // avoid invoking the reporter until it has finished any parallelizable work.)
171 //
172 // If f returns a non-nil error, that error will be reported after f's output
173 // (if any) and will cause a nonzero final exit code.
174 func (s *sequencer) Add(weight int64, f func(*reporter) error) {
175 if weight < 0 || weight > s.maxWeight {
176 weight = s.maxWeight
177 }
178 if err := s.sem.Acquire(context.TODO(), weight); err != nil {
179 // Change the task from "execute f" to "report err".
180 weight = 0
181 f = func(*reporter) error { return err }
182 }
183
184 r := &reporter{prev: s.prev}
185 next := make(chan *reporterState, 1)
186 s.prev = next
187
188 // Start f in parallel: it can run until it invokes a method on r, at which
189 // point it will block until the previous task releases the output state.
190 go func() {
191 if err := f(r); err != nil {
192 r.Report(err)
193 }
194 next <- r.getState() // Release the next task.
195 s.sem.Release(weight)
196 }()
197 }
198
199 // AddReport prints an error to s after the output of any previously-added
200 // tasks, causing the final exit code to be nonzero.
201 func (s *sequencer) AddReport(err error) {
202 s.Add(0, func(*reporter) error { return err })
203 }
204
205 // GetExitCode waits for all previously-added tasks to complete, then returns an
206 // exit code for the sequence suitable for passing to os.Exit.
207 func (s *sequencer) GetExitCode() int {
208 c := make(chan int, 1)
209 s.Add(0, func(r *reporter) error {
210 c <- r.ExitCode()
211 return nil
212 })
213 return <-c
214 }
215
216 // A reporter reports output, warnings, and errors.
217 type reporter struct {
218 prev <-chan *reporterState
219 state *reporterState
220 }
221
222 // reporterState carries the state of a reporter instance.
223 //
224 // Only one reporter at a time may have access to a reporterState.
225 type reporterState struct {
226 out, err io.Writer
227 exitCode int
228 }
229
230 // getState blocks until any prior reporters are finished with the reporter
231 // state, then returns the state for manipulation.
232 func (r *reporter) getState() *reporterState {
233 if r.state == nil {
234 r.state = <-r.prev
235 }
236 return r.state
237 }
238
239 // Warnf emits a warning message to the reporter's error stream,
240 // without changing its exit code.
241 func (r *reporter) Warnf(format string, args ...any) {
242 fmt.Fprintf(r.getState().err, format, args...)
243 }
244
245 // Write emits a slice to the reporter's output stream.
246 //
247 // Any error is returned to the caller, and does not otherwise affect the
248 // reporter's exit code.
249 func (r *reporter) Write(p []byte) (int, error) {
250 return r.getState().out.Write(p)
251 }
252
253 // Report emits a non-nil error to the reporter's error stream,
254 // changing its exit code to a nonzero value.
255 func (r *reporter) Report(err error) {
256 if err == nil {
257 panic("Report with nil error")
258 }
259 st := r.getState()
260 scanner.PrintError(st.err, err)
261 st.exitCode = 2
262 }
263
264 func (r *reporter) ExitCode() int {
265 return r.getState().exitCode
266 }
267
268 // If info == nil, we are formatting stdin instead of a file.
269 // If in == nil, the source is the contents of the file with the given filename.
270 func processFile(filename string, info fs.FileInfo, in io.Reader, r *reporter, explicit bool) error {
271 src, err := readFile(filename, info, in)
272 if err != nil {
273 return err
274 }
275
276 fileSet := token.NewFileSet()
277 fragmentOk := false
278 if info == nil {
279 // If we are formatting stdin, we accept a program fragment in lieu of a
280 // complete source file.
281 fragmentOk = true
282 }
283 file, sourceAdj, indentAdj, err := parse(fileSet, filename, src, fragmentOk)
284 if err != nil {
285 return err
286 }
287
288 ast.SortImports(fileSet, file)
289
290 // Apply gofumpt's changes before we print the code in gofumpt's format.
291
292 // If either -lang or -modpath aren't set, fetch them from go.mod.
293 lang := *langVersion
294 modpath := *modulePath
295 if lang == "" || modpath == "" {
296 dir := filepath.Dir(filename)
297 mod, ok := moduleCacheByDir.Load(dir)
298 if ok && mod != nil {
299 mod := mod.(*module)
300 if lang == "" {
301 lang = mod.Go
302 }
303 if modpath == "" {
304 modpath = mod.Module.Path
305 }
306 }
307 }
308
309 // We always apply the gofumpt formatting rules to explicit files, including stdin.
310 // Otherwise, we don't apply them on generated files.
311 // We also skip walking vendor directories entirely, but that happens elsewhere.
312 if explicit || !isGenerated(file) {
313 gformat.File(fileSet, file, gformat.Options{
314 LangVersion: lang,
315 ModulePath: modpath,
316 ExtraRules: *extraRules,
317 })
318 }
319
320 res, err := format(fileSet, file, sourceAdj, indentAdj, src, printer.Config{Mode: printerMode, Tabwidth: tabWidth})
321 if err != nil {
322 return err
323 }
324
325 if !bytes.Equal(src, res) {
326 // formatting has changed
327 if *list {
328 fmt.Fprintln(r, filename)
329 }
330 if *write {
331 if info == nil {
332 panic("-w should not have been allowed with stdin")
333 }
334 // make a temporary backup before overwriting original
335 perm := info.Mode().Perm()
336 bakname, err := backupFile(filename+".", src, perm)
337 if err != nil {
338 return err
339 }
340 fdSem <- true
341 err = os.WriteFile(filename, res, perm)
342 <-fdSem
343 if err != nil {
344 os.Rename(bakname, filename)
345 return err
346 }
347 err = os.Remove(bakname)
348 if err != nil {
349 return err
350 }
351 }
352 if *doDiff {
353 newName := filepath.ToSlash(filename)
354 oldName := newName + ".orig"
355 r.Write(diff.Diff(oldName, src, newName, res))
356 }
357 }
358
359 if !*list && !*write && !*doDiff {
360 _, err = r.Write(res)
361 }
362
363 return err
364 }
365
366 // readFile reads the contents of filename, described by info.
367 // If in is non-nil, readFile reads directly from it.
368 // Otherwise, readFile opens and reads the file itself,
369 // with the number of concurrently-open files limited by fdSem.
370 func readFile(filename string, info fs.FileInfo, in io.Reader) ([]byte, error) {
371 if in == nil {
372 fdSem <- true
373 var err error
374 f, err := os.Open(filename)
375 if err != nil {
376 return nil, err
377 }
378 in = f
379 defer func() {
380 f.Close()
381 <-fdSem
382 }()
383 }
384
385 // Compute the file's size and read its contents with minimal allocations.
386 //
387 // If we have the FileInfo from filepath.WalkDir, use it to make
388 // a buffer of the right size and avoid ReadAll's reallocations.
389 //
390 // If the size is unknown (or bogus, or overflows an int), fall back to
391 // a size-independent ReadAll.
392 size := -1
393 if info != nil && info.Mode().IsRegular() && int64(int(info.Size())) == info.Size() {
394 size = int(info.Size())
395 }
396 if size+1 <= 0 {
397 // The file is not known to be regular, so we don't have a reliable size for it.
398 var err error
399 src, err := io.ReadAll(in)
400 if err != nil {
401 return nil, err
402 }
403 return src, nil
404 }
405
406 // We try to read size+1 bytes so that we can detect modifications: if we
407 // read more than size bytes, then the file was modified concurrently.
408 // (If that happens, we could, say, append to src to finish the read, or
409 // proceed with a truncated buffer — but the fact that it changed at all
410 // indicates a possible race with someone editing the file, so we prefer to
411 // stop to avoid corrupting it.)
412 src := make([]byte, size+1)
413 n, err := io.ReadFull(in, src)
414 switch err {
415 case nil, io.EOF, io.ErrUnexpectedEOF:
416 // io.ReadFull returns io.EOF (for an empty file) or io.ErrUnexpectedEOF
417 // (for a non-empty file) if the file was changed unexpectedly. Continue
418 // with comparing file sizes in those cases.
419 default:
420 return nil, err
421 }
422 if n < size {
423 return nil, fmt.Errorf("error: size of %s changed during reading (from %d to %d bytes)", filename, size, n)
424 } else if n > size {
425 return nil, fmt.Errorf("error: size of %s changed during reading (from %d to >=%d bytes)", filename, size, len(src))
426 }
427 return src[:n], nil
428 }
429
430 func main() { os.Exit(main1()) }
431
432 func main1() int {
433 // Arbitrarily limit in-flight work to 2MiB times the number of threads.
434 //
435 // The actual overhead for the parse tree and output will depend on the
436 // specifics of the file, but this at least keeps the footprint of the process
437 // roughly proportional to GOMAXPROCS.
438 maxWeight := (2 << 20) * int64(runtime.GOMAXPROCS(0))
439 s := newSequencer(maxWeight, os.Stdout, os.Stderr)
440
441 // call gofmtMain in a separate function
442 // so that it can use defer and have them
443 // run before the exit.
444 gofmtMain(s)
445 return s.GetExitCode()
446 }
447
448 func gofmtMain(s *sequencer) {
449 // Ensure our parsed files never start with base 1,
450 // to ensure that using token.NoPos+1 will panic.
451 fileSet.AddFile("gofumpt_base.go", 1, 10)
452
453 flag.Usage = usage
454 flag.Parse()
455
456 if *simplifyAST {
457 fmt.Fprintf(os.Stderr, "warning: -s is deprecated as it is always enabled\n")
458 }
459 if *rewriteRule != "" {
460 fmt.Fprintf(os.Stderr, `the rewrite flag is no longer available; use "gofmt -r" instead`+"\n")
461 os.Exit(2)
462 }
463
464 // Print the gofumpt version if the user asks for it.
465 if *showVersion {
466 fmt.Println(gversion.String(version))
467 return
468 }
469
470 if *cpuprofile != "" {
471 fdSem <- true
472 f, err := os.Create(*cpuprofile)
473 if err != nil {
474 s.AddReport(fmt.Errorf("creating cpu profile: %s", err))
475 return
476 }
477 defer func() {
478 f.Close()
479 <-fdSem
480 }()
481 pprof.StartCPUProfile(f)
482 defer pprof.StopCPUProfile()
483 }
484
485 initParserMode()
486
487 args := flag.Args()
488 if len(args) == 0 {
489 if *write {
490 s.AddReport(fmt.Errorf("error: cannot use -w with standard input"))
491 return
492 }
493 s.Add(0, func(r *reporter) error {
494 // TODO: test explicit==true
495 return processFile("<standard input>", nil, os.Stdin, r, true)
496 })
497 return
498 }
499
500 for _, arg := range args {
501 switch info, err := os.Stat(arg); {
502 case err != nil:
503 s.AddReport(err)
504 case !info.IsDir():
505 // Non-directory arguments are always formatted.
506 arg := arg
507 s.Add(fileWeight(arg, info), func(r *reporter) error {
508 return processFile(arg, info, nil, r, true)
509 })
510 default:
511 // Directories are walked, ignoring non-Go files.
512 err := filepath.WalkDir(arg, func(path string, f fs.DirEntry, err error) error {
513 // vendor and testdata directories are skipped,
514 // unless they are explicitly passed as an argument.
515 base := filepath.Base(path)
516 if path != arg && (base == "vendor" || base == "testdata") {
517 return filepath.SkipDir
518 }
519
520 if err != nil || !isGoFile(f) {
521 return err
522 }
523 info, err := f.Info()
524 if err != nil {
525 s.AddReport(err)
526 return nil
527 }
528 s.Add(fileWeight(path, info), func(r *reporter) error {
529 return processFile(path, info, nil, r, false)
530 })
531 return nil
532 })
533 if err != nil {
534 s.AddReport(err)
535 }
536 }
537 }
538 }
539
540 type module struct {
541 Go string
542 Module struct {
543 Path string
544 }
545 }
546
547 func loadModuleInfo(dir string) any {
548 cmd := exec.Command("go", "mod", "edit", "-json")
549 cmd.Dir = dir
550
551 // Spawning "go mod edit" will open files by design,
552 // such as the named pipe to obtain stdout.
553 // TODO(mvdan): if we run into "too many open files" errors again in the
554 // future, we probably need to turn fdSem into a weighted semaphore so this
555 // operation can acquire a weight larger than 1.
556 fdSem <- true
557 out, err := cmd.Output()
558 defer func() { <-fdSem }()
559
560 if err != nil || len(out) == 0 {
561 return nil
562 }
563 mod := new(module)
564 if err := json.Unmarshal(out, mod); err != nil {
565 return nil
566 }
567 return mod
568 }
569
570 // Written to by fileWeight, read from fileWeight and processFile.
571 // A present but nil value means that loading the module info failed.
572 // Note that we don't require the keys to be absolute directories,
573 // so duplicates are possible. The same can happen with symlinks.
574 var moduleCacheByDir sync.Map // map[dirString]*module
575
576 func fileWeight(path string, info fs.FileInfo) int64 {
577 dir := filepath.Dir(path)
578 if _, ok := moduleCacheByDir.Load(dir); !ok {
579 moduleCacheByDir.Store(dir, loadModuleInfo(dir))
580 }
581 if info == nil {
582 return exclusive
583 }
584 if info.Mode().Type() == fs.ModeSymlink {
585 var err error
586 info, err = os.Stat(path)
587 if err != nil {
588 return exclusive
589 }
590 }
591 if !info.Mode().IsRegular() {
592 // For non-regular files, FileInfo.Size is system-dependent and thus not a
593 // reliable indicator of weight.
594 return exclusive
595 }
596 return info.Size()
597 }
598
599 const chmodSupported = runtime.GOOS != "windows"
600
601 // backupFile writes data to a new file named filename<number> with permissions perm,
602 // with <number randomly chosen such that the file name is unique. backupFile returns
603 // the chosen file name.
604 func backupFile(filename string, data []byte, perm fs.FileMode) (string, error) {
605 fdSem <- true
606 defer func() { <-fdSem }()
607
608 // create backup file
609 f, err := os.CreateTemp(filepath.Dir(filename), filepath.Base(filename))
610 if err != nil {
611 return "", err
612 }
613 bakname := f.Name()
614 if chmodSupported {
615 err = f.Chmod(perm)
616 if err != nil {
617 f.Close()
618 os.Remove(bakname)
619 return bakname, err
620 }
621 }
622
623 // write data to backup file
624 _, err = f.Write(data)
625 if err1 := f.Close(); err == nil {
626 err = err1
627 }
628
629 return bakname, err
630 }