Skip to content

Commit 0d967ef

Browse files
committed
go/analysis/internal/checker: format files modified by -fix
When running a checker in -fix mode, try to format the file before writing it. Change-Id: I760f851f0ccd4a68c97949b21dabae39cb4ffaeb Reviewed-on: https://go-review.googlesource.com/c/tools/+/209861 Run-TryBot: Michael Matloob <[email protected]> TryBot-Result: Gobot Gobot <[email protected]> Reviewed-by: Rebecca Stambler <[email protected]>
1 parent 660eba4 commit 0d967ef

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

go/analysis/internal/checker/checker.go

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@ import (
1313
"encoding/gob"
1414
"flag"
1515
"fmt"
16+
"go/format"
17+
"go/parser"
1618
"go/token"
1719
"go/types"
1820
"io/ioutil"
@@ -341,6 +343,7 @@ func applyFixes(roots []*action) {
341343

342344
visitAll(roots)
343345

346+
fset := token.NewFileSet() // Shared by parse calls below
344347
// Now we've got a set of valid edits for each file. Get the new file contents.
345348
for f, tree := range editsForFile {
346349
contents, err := ioutil.ReadFile(f.Name())
@@ -375,6 +378,15 @@ func applyFixes(roots []*action) {
375378
out.Write(contents[cur:])
376379
}
377380

381+
// Try to format the file.
382+
ff, err := parser.ParseFile(fset, f.Name(), out.Bytes(), parser.ParseComments)
383+
if err == nil {
384+
var buf bytes.Buffer
385+
if err = format.Node(&buf, fset, ff); err == nil {
386+
out = buf
387+
}
388+
}
389+
378390
ioutil.WriteFile(f.Name(), out.Bytes(), 0644)
379391
}
380392
}

0 commit comments

Comments
 (0)