blob: d00113577f9e67ebb4bd7a0626dd68fa13801c1e [file] [log] [blame]
Leonardo Sandoval314eed82020-08-05 13:32:04 -05001#!/usr/bin/env python3
2#
Xinyu Zhang235d5ae2021-02-07 10:42:38 +08003# Copyright (c) 2019-2021, Arm Limited. All rights reserved.
Leonardo Sandoval314eed82020-08-05 13:32:04 -05004#
5# SPDX-License-Identifier: BSD-3-Clause
6#
7
8"""
9Check if a given file includes the copyright boiler plate.
10This checker supports the following comment styles:
11 /*
12 *
13 //
14 #
15"""
16
17import argparse
18import datetime
19import collections
20import fnmatch
21import shlex
22import os
23import re
24import sys
25import utils
26from itertools import islice
27
28# File extensions to check
29VALID_FILE_EXTENSIONS = ('.c', '.conf', '.dts', '.dtsi', '.editorconfig',
30 '.h', '.i', '.ld', 'Makefile', '.mk', '.msvc',
31 '.py', '.S', '.scat', '.sh')
32
33# Paths inside the tree to ignore. Hidden folders and files are always ignored.
34# They mustn't end in '/'.
35IGNORED_FOLDERS = (
Xinyu Zhang235d5ae2021-02-07 10:42:38 +080036 'platform/ext',
37 'bl2/ext',
38 'docs',
39 'lib',
40 'tools'
Leonardo Sandoval314eed82020-08-05 13:32:04 -050041)
42
43# List of ignored files in folders that aren't ignored
Xinyu Zhang235d5ae2021-02-07 10:42:38 +080044IGNORED_FILES = ()
Leonardo Sandoval314eed82020-08-05 13:32:04 -050045
46# Supported comment styles (Python regex)
47COMMENT_PATTERN = '(\*|/\*|\#|//)'
48
49# Any combination of spaces and/or tabs
50SPACING = '[ \t]*'
51
52# Line must start with a comment and optional spacing
53LINE_START = '^' + SPACING + COMMENT_PATTERN + SPACING
54
55# Line end with optional spacing
56EOL = SPACING + '$'
57
58# Year or period as YYYY or YYYY-YYYY
59TIME_PERIOD = '[0-9]{4}(-[0-9]{4})?'
60
61# Any string with valid license ID, don't allow adding postfix
62LICENSE_ID = '.*(BSD-3-Clause|BSD-2-Clause-FreeBSD)([ ,.\);].*)?'
63
64# File must contain both lines to pass the check
65COPYRIGHT_LINE = LINE_START + 'Copyright' + '.*' + TIME_PERIOD + '.*' + EOL
66LICENSE_ID_LINE = LINE_START + 'SPDX-License-Identifier:' + LICENSE_ID + EOL
67
68# Compiled license patterns
69COPYRIGHT_PATTERN = re.compile(COPYRIGHT_LINE, re.MULTILINE)
70LICENSE_ID_PATTERN = re.compile(LICENSE_ID_LINE, re.MULTILINE)
71
72CURRENT_YEAR = str(datetime.datetime.now().year)
73
74COPYRIGHT_OK = 0
75COPYRIGHT_ERROR = 1
76
77def check_copyright(path, args, encoding='utf-8'):
78 '''Checks a file for a correct copyright header.'''
79
80 result = COPYRIGHT_OK
81
82 with open(path, encoding=encoding) as file_:
83 file_content = file_.read()
84
85 copyright_line = COPYRIGHT_PATTERN.search(file_content)
86 if not copyright_line:
87 print("ERROR: Missing copyright in " + file_.name)
88 result = COPYRIGHT_ERROR
Leonardo Sandoval314eed82020-08-05 13:32:04 -050089
90 if not LICENSE_ID_PATTERN.search(file_content):
91 print("ERROR: License ID error in " + file_.name)
92 result = COPYRIGHT_ERROR
93
94 return result
95
96def main(args):
97 print("Checking the copyrights in the code...")
98
99 if args.verbose:
100 print ("Copyright regexp: " + COPYRIGHT_LINE)
101 print ("License regexp: " + LICENSE_ID_LINE)
102
103 if args.patch:
104 print("Checking files modified between patches " + args.from_ref
105 + " and " + args.to_ref + "...")
106
107 (rc, stdout, stderr) = utils.shell_command(['git', 'diff',
108 '--diff-filter=ACMRT', '--name-only', args.from_ref, args.to_ref ])
109 if rc:
110 return COPYRIGHT_ERROR
111
112 files = stdout.splitlines()
113
114 else:
115 print("Checking all files tracked by git...")
116
117 (rc, stdout, stderr) = utils.shell_command([ 'git', 'ls-files' ])
118 if rc:
119 return COPYRIGHT_ERROR
120
121 files = stdout.splitlines()
122
123 count_ok = 0
124 count_warning = 0
125 count_error = 0
126
127 for f in files:
128
129 if utils.file_is_ignored(f, VALID_FILE_EXTENSIONS, IGNORED_FILES, IGNORED_FOLDERS):
130 if args.verbose:
131 print("Ignoring file " + f)
132 continue
133
134 if args.verbose:
135 print("Checking file " + f)
136
137 rc = check_copyright(f, args)
138
139 if rc == COPYRIGHT_OK:
140 count_ok += 1
141 elif rc == COPYRIGHT_ERROR:
142 count_error += 1
143
144 print("\nSummary:")
145 print("\t{} files analyzed".format(count_ok + count_error))
146
147 if count_error == 0:
148 print("\tNo errors found")
149 return COPYRIGHT_OK
150 else:
151 print("\t{} errors found".format(count_error))
152 return COPYRIGHT_ERROR
153
154def parse_cmd_line(argv, prog_name):
155 parser = argparse.ArgumentParser(
156 prog=prog_name,
157 formatter_class=argparse.RawTextHelpFormatter,
158 description="Check copyright of all files of codebase",
159 epilog="""
160For each source file in the tree, checks that the copyright header
161has the correct format.
162""")
163
164 parser.add_argument("--tree", "-t",
165 help="Path to the source tree to check (default: %(default)s)",
166 default=os.curdir)
167
168 parser.add_argument("--verbose", "-v",
169 help="Increase verbosity to the source tree to check (default: %(default)s)",
170 action='store_true', default=False)
171
172 parser.add_argument("--patch", "-p",
173 help="""
174Patch mode.
175Instead of checking all files in the source tree, the script will consider
176only files that are modified by the latest patch(es).""",
177 action="store_true")
178
Leonardo Sandoval900de582020-09-07 18:34:57 -0500179 (rc, stdout, stderr) = utils.shell_command(['git', 'merge-base', 'HEAD', 'origin/master'])
Leonardo Sandoval314eed82020-08-05 13:32:04 -0500180 if rc:
181 print("Git merge-base command failed. Cannot determine base commit.")
182 sys.exit(rc)
183 merge_bases = stdout.splitlines()
184
185 # This should not happen, but it's better to be safe.
186 if len(merge_bases) > 1:
187 print("WARNING: Multiple merge bases found. Using the first one as base commit.")
188
189 parser.add_argument("--from-ref",
190 help="Base commit in patch mode (default: %(default)s)",
191 default=merge_bases[0])
192 parser.add_argument("--to-ref",
193 help="Final commit in patch mode (default: %(default)s)",
194 default="HEAD")
195
196 args = parser.parse_args(argv)
197 return args
198
199
200if __name__ == "__main__":
201 args = parse_cmd_line(sys.argv[1:], sys.argv[0])
202
203 os.chdir(args.tree)
204
205 rc = main(args)
206
207 sys.exit(rc)