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