| Tim Windelschmidt | 7c0bd0b | 2025-01-10 04:15:37 +0100 | [diff] [blame^] | 1 | package gofmt |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "os" |
| 6 | |
| 7 | "github.com/golangci/gofmt/gofmt" |
| 8 | "golang.org/x/tools/go/analysis" |
| 9 | |
| 10 | alib "source.monogon.dev/build/analysis/lib" |
| 11 | ) |
| 12 | |
| 13 | var Analyzer = &analysis.Analyzer{ |
| 14 | Name: "gofmt", |
| 15 | Doc: "checks if files have been run through `gofmt -s`", |
| 16 | Run: func(pass *analysis.Pass) (any, error) { |
| 17 | for _, f := range pass.Files { |
| 18 | if alib.IsGeneratedFile(f) { |
| 19 | continue |
| 20 | } |
| 21 | |
| 22 | fileName := pass.Fset.PositionFor(f.Pos(), true).Filename |
| 23 | src, err := os.ReadFile(fileName) |
| 24 | if err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | |
| 28 | res, err := gofmt.Source(fileName, src, gofmt.Options{NeedSimplify: true}) |
| 29 | if err != nil { |
| 30 | return nil, err |
| 31 | } |
| 32 | |
| 33 | if bytes.Equal(src, res) { |
| 34 | continue |
| 35 | } |
| 36 | |
| 37 | pass.Report(analysis.Diagnostic{ |
| 38 | Pos: f.Pos(), |
| 39 | Message: "not formatted with gofmt -s", |
| 40 | SuggestedFixes: []analysis.SuggestedFix{ |
| 41 | { |
| 42 | TextEdits: []analysis.TextEdit{ |
| 43 | { |
| 44 | Pos: f.FileStart, |
| 45 | End: f.FileEnd, |
| 46 | NewText: res, |
| 47 | }, |
| 48 | }, |
| 49 | }, |
| 50 | }, |
| 51 | }) |
| 52 | } |
| 53 | return nil, nil |
| 54 | }, |
| 55 | } |