Debian Codegraph @

copyright/copyright.go

raw symbols SCIP
1 // Copyright 2020 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package copyright checks that files have the correct copyright notices.
6 package copyright
7
8 import (
9 "go/ast"
10 "go/parser"
11 "go/token"
12 "io/fs"
13 "os"
14 "path/filepath"
15 "regexp"
16 "strings"
17 )
18
19 // (used only by tests)
20 func checkCopyright(dir string) ([]string, error) {
21 var files []string
22 err := filepath.WalkDir(dir, func(path string, d fs.DirEntry, err error) error {
23 if err != nil {
24 return err
25 }
26 if d.IsDir() {
27 // Skip directories like ".git".
28 if strings.HasPrefix(d.Name(), ".") && d.Name() != "." && d.Name() != ".." {
29 return filepath.SkipDir
30 }
31 // Skip any directory that starts with an underscore, as the go
32 // command would.
33 if strings.HasPrefix(d.Name(), "_") {
34 return filepath.SkipDir
35 }
36 return nil
37 }
38 needsCopyright, err := checkFile(dir, path)
39 if err != nil {
40 return err
41 }
42 if needsCopyright {
43 files = append(files, path)
44 }
45 return nil
46 })
47 return files, err
48 }
49
50 var copyrightRe = regexp.MustCompile(`Copyright \d{4} The Go Authors. All rights reserved.
51 Use of this source code is governed by a BSD-style
52 license that can be found in the LICENSE file.`)
53
54 func checkFile(toolsDir, filename string) (bool, error) {
55 // Only check Go files.
56 if !strings.HasSuffix(filename, ".go") {
57 return false, nil
58 }
59 // Don't check testdata files.
60 normalized := strings.TrimPrefix(filepath.ToSlash(filename), filepath.ToSlash(toolsDir))
61 if strings.Contains(normalized, "/testdata/") {
62 return false, nil
63 }
64 // goyacc is the only file with a different copyright header.
65 if strings.HasSuffix(normalized, "cmd/goyacc/yacc.go") {
66 return false, nil
67 }
68 content, err := os.ReadFile(filename)
69 if err != nil {
70 return false, err
71 }
72 fset := token.NewFileSet()
73 parsed, err := parser.ParseFile(fset, filename, content, parser.ParseComments)
74 if err != nil {
75 return false, err
76 }
77 // Don't require headers on generated files.
78 if ast.IsGenerated(parsed) {
79 return false, nil
80 }
81 shouldAddCopyright := true
82 for _, c := range parsed.Comments {
83 // The copyright should appear before the package declaration.
84 if c.Pos() > parsed.Package {
85 break
86 }
87 if copyrightRe.MatchString(c.Text()) {
88 shouldAddCopyright = false
89 break
90 }
91 }
92 return shouldAddCopyright, nil
93 }