| Tim Windelschmidt | e6cc227 | 2024-09-19 16:32:55 +0200 | [diff] [blame] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| 4 | package haslicense |
| 5 | |
| 6 | import ( |
| 7 | "fmt" |
| 8 | "strings" |
| 9 | |
| 10 | "golang.org/x/tools/go/analysis" |
| 11 | |
| 12 | alib "source.monogon.dev/build/analysis/lib" |
| 13 | ) |
| 14 | |
| 15 | const header = `// Copyright The Monogon Project Authors. |
| 16 | // SPDX-License-Identifier: Apache-2.0 |
| 17 | |
| 18 | ` |
| 19 | |
| 20 | var Analyzer = &analysis.Analyzer{ |
| 21 | Name: "haslicense", |
| 22 | Doc: "haslicense checks for an existing license header in monogon source code.", |
| 23 | Run: func(p *analysis.Pass) (any, error) { |
| 24 | for _, file := range p.Files { |
| 25 | if alib.IsGeneratedFile(file) { |
| 26 | continue |
| 27 | } |
| 28 | |
| 29 | if len(file.Comments) > 0 { |
| Tim Windelschmidt | 30553e8 | 2025-02-10 16:48:47 +0100 | [diff] [blame^] | 30 | var hasCopyright, hasSPDX bool |
| 31 | lines := strings.Split(file.Comments[0].Text(), "\n") |
| 32 | for _, line := range lines { |
| 33 | switch { |
| 34 | case strings.HasPrefix(line, "Copyright "): |
| 35 | hasCopyright = true |
| 36 | case strings.HasPrefix(line, "SPDX-License-Identifier"): |
| 37 | hasSPDX = true |
| 38 | } |
| Tim Windelschmidt | e6cc227 | 2024-09-19 16:32:55 +0200 | [diff] [blame] | 39 | } |
| Tim Windelschmidt | e6cc227 | 2024-09-19 16:32:55 +0200 | [diff] [blame] | 40 | |
| Tim Windelschmidt | 30553e8 | 2025-02-10 16:48:47 +0100 | [diff] [blame^] | 41 | if hasCopyright && hasSPDX { |
| Tim Windelschmidt | e6cc227 | 2024-09-19 16:32:55 +0200 | [diff] [blame] | 42 | continue |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | p.Report(analysis.Diagnostic{ |
| 47 | Pos: file.FileStart, |
| 48 | End: file.FileStart, |
| 49 | Message: "File is missing license header. Please add it.", |
| 50 | SuggestedFixes: []analysis.SuggestedFix{ |
| 51 | { |
| 52 | Message: fmt.Sprintf("should prepend file with `%s`", header), |
| 53 | TextEdits: []analysis.TextEdit{ |
| 54 | { |
| 55 | Pos: file.FileStart, |
| 56 | End: file.FileStart, |
| 57 | NewText: []byte(header), |
| 58 | }, |
| 59 | }, |
| 60 | }, |
| 61 | }, |
| 62 | }) |
| 63 | } |
| 64 | |
| 65 | return nil, nil |
| 66 | }, |
| 67 | } |