blob: 46a8d660d00d574b123e2b466b6370e8f397ba28 [file] [log] [blame]
Tim Windelschmidte6cc2272024-09-19 16:32:55 +02001// Copyright The Monogon Project Authors.
2// SPDX-License-Identifier: Apache-2.0
3
4package haslicense
5
6import (
7 "fmt"
8 "strings"
9
10 "golang.org/x/tools/go/analysis"
11
12 alib "source.monogon.dev/build/analysis/lib"
13)
14
15const header = `// Copyright The Monogon Project Authors.
16// SPDX-License-Identifier: Apache-2.0
17
18`
19
20var 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 Windelschmidt30553e82025-02-10 16:48:47 +010030 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 Windelschmidte6cc2272024-09-19 16:32:55 +020039 }
Tim Windelschmidte6cc2272024-09-19 16:32:55 +020040
Tim Windelschmidt30553e82025-02-10 16:48:47 +010041 if hasCopyright && hasSPDX {
Tim Windelschmidte6cc2272024-09-19 16:32:55 +020042 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}