blob: c1fb61df2847c9e828881ce8ad320affe805a895 [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 'bl2/ext',
37 'docs',
Antonio de Angelis2e526ca2024-04-11 15:44:46 +010038 'interface/include/mbedtls',
Xinyu Zhang235d5ae2021-02-07 10:42:38 +080039 'lib',
Antonio de Angelis2e526ca2024-04-11 15:44:46 +010040 'platform/ext',
Xinyu Zhang235d5ae2021-02-07 10:42:38 +080041 'tools'
Leonardo Sandoval314eed82020-08-05 13:32:04 -050042)
43
44# List of ignored files in folders that aren't ignored
Antonio de Angelis2e526ca2024-04-11 15:44:46 +010045IGNORED_FILES = (
46 'interface/include/psa/build_info.h',
47 'interface/include/psa/crypto.h',
48 'interface/include/psa/crypto_adjust_auto_enabled.h',
Antonio de Angelis423eb5f2024-09-19 14:31:03 +010049 'interface/include/psa/crypto_adjust_config_dependencies.h',
Antonio de Angelis2e526ca2024-04-11 15:44:46 +010050 'interface/include/psa/crypto_adjust_config_key_pair_types.h',
51 'interface/include/psa/crypto_adjust_config_synonyms.h',
52 'interface/include/psa/crypto_builtin_composites.h',
53 'interface/include/psa/crypto_builtin_key_derivation.h',
54 'interface/include/psa/crypto_builtin_primitives.h',
55 'interface/include/psa/crypto_compat.h',
56 'interface/include/psa/crypto_driver_common.h',
57 'interface/include/psa/crypto_driver_contexts_composites.h',
58 'interface/include/psa/crypto_driver_contexts_key_derivation.h',
59 'interface/include/psa/crypto_driver_contexts_primitives.h',
60 'interface/include/psa/crypto_extra.h',
61 'interface/include/psa/crypto_legacy.h',
62 'interface/include/psa/crypto_platform.h',
63 'interface/include/psa/crypto_se_driver.h',
64 'interface/include/psa/crypto_sizes.h',
65 'interface/include/psa/crypto_struct.h',
66 'interface/include/psa/crypto_types.h',
67 'interface/include/psa/crypto_values.h'
68)
Leonardo Sandoval314eed82020-08-05 13:32:04 -050069
70# Supported comment styles (Python regex)
71COMMENT_PATTERN = '(\*|/\*|\#|//)'
72
73# Any combination of spaces and/or tabs
74SPACING = '[ \t]*'
75
76# Line must start with a comment and optional spacing
77LINE_START = '^' + SPACING + COMMENT_PATTERN + SPACING
78
79# Line end with optional spacing
80EOL = SPACING + '$'
81
Antonio de Angelis2e526ca2024-04-11 15:44:46 +010082# Year or period as YYYY or YYYY-YYYY, or nothing as per the
83# Linux Foundation copyright notice recommendation
84TIME_PERIOD = '([0-9]{4}(-[0-9]{4})?)?'
Leonardo Sandoval314eed82020-08-05 13:32:04 -050085
86# Any string with valid license ID, don't allow adding postfix
87LICENSE_ID = '.*(BSD-3-Clause|BSD-2-Clause-FreeBSD)([ ,.\);].*)?'
88
89# File must contain both lines to pass the check
90COPYRIGHT_LINE = LINE_START + 'Copyright' + '.*' + TIME_PERIOD + '.*' + EOL
91LICENSE_ID_LINE = LINE_START + 'SPDX-License-Identifier:' + LICENSE_ID + EOL
92
93# Compiled license patterns
94COPYRIGHT_PATTERN = re.compile(COPYRIGHT_LINE, re.MULTILINE)
95LICENSE_ID_PATTERN = re.compile(LICENSE_ID_LINE, re.MULTILINE)
96
97CURRENT_YEAR = str(datetime.datetime.now().year)
98
99COPYRIGHT_OK = 0
100COPYRIGHT_ERROR = 1
101
102def check_copyright(path, args, encoding='utf-8'):
103 '''Checks a file for a correct copyright header.'''
104
105 result = COPYRIGHT_OK
106
107 with open(path, encoding=encoding) as file_:
108 file_content = file_.read()
109
110 copyright_line = COPYRIGHT_PATTERN.search(file_content)
111 if not copyright_line:
112 print("ERROR: Missing copyright in " + file_.name)
113 result = COPYRIGHT_ERROR
Leonardo Sandoval314eed82020-08-05 13:32:04 -0500114
115 if not LICENSE_ID_PATTERN.search(file_content):
116 print("ERROR: License ID error in " + file_.name)
117 result = COPYRIGHT_ERROR
118
119 return result
120
121def main(args):
122 print("Checking the copyrights in the code...")
123
124 if args.verbose:
125 print ("Copyright regexp: " + COPYRIGHT_LINE)
126 print ("License regexp: " + LICENSE_ID_LINE)
127
128 if args.patch:
129 print("Checking files modified between patches " + args.from_ref
130 + " and " + args.to_ref + "...")
131
132 (rc, stdout, stderr) = utils.shell_command(['git', 'diff',
133 '--diff-filter=ACMRT', '--name-only', args.from_ref, args.to_ref ])
134 if rc:
135 return COPYRIGHT_ERROR
136
137 files = stdout.splitlines()
138
139 else:
140 print("Checking all files tracked by git...")
141
142 (rc, stdout, stderr) = utils.shell_command([ 'git', 'ls-files' ])
143 if rc:
144 return COPYRIGHT_ERROR
145
146 files = stdout.splitlines()
147
148 count_ok = 0
149 count_warning = 0
150 count_error = 0
151
152 for f in files:
153
154 if utils.file_is_ignored(f, VALID_FILE_EXTENSIONS, IGNORED_FILES, IGNORED_FOLDERS):
155 if args.verbose:
156 print("Ignoring file " + f)
157 continue
158
159 if args.verbose:
160 print("Checking file " + f)
161
162 rc = check_copyright(f, args)
163
164 if rc == COPYRIGHT_OK:
165 count_ok += 1
166 elif rc == COPYRIGHT_ERROR:
167 count_error += 1
168
169 print("\nSummary:")
170 print("\t{} files analyzed".format(count_ok + count_error))
171
172 if count_error == 0:
173 print("\tNo errors found")
174 return COPYRIGHT_OK
175 else:
176 print("\t{} errors found".format(count_error))
177 return COPYRIGHT_ERROR
178
179def parse_cmd_line(argv, prog_name):
180 parser = argparse.ArgumentParser(
181 prog=prog_name,
182 formatter_class=argparse.RawTextHelpFormatter,
183 description="Check copyright of all files of codebase",
184 epilog="""
185For each source file in the tree, checks that the copyright header
186has the correct format.
187""")
188
189 parser.add_argument("--tree", "-t",
190 help="Path to the source tree to check (default: %(default)s)",
191 default=os.curdir)
192
193 parser.add_argument("--verbose", "-v",
194 help="Increase verbosity to the source tree to check (default: %(default)s)",
195 action='store_true', default=False)
196
197 parser.add_argument("--patch", "-p",
198 help="""
199Patch mode.
200Instead of checking all files in the source tree, the script will consider
201only files that are modified by the latest patch(es).""",
202 action="store_true")
203
Leonardo Sandoval900de582020-09-07 18:34:57 -0500204 (rc, stdout, stderr) = utils.shell_command(['git', 'merge-base', 'HEAD', 'origin/master'])
Leonardo Sandoval314eed82020-08-05 13:32:04 -0500205 if rc:
206 print("Git merge-base command failed. Cannot determine base commit.")
207 sys.exit(rc)
208 merge_bases = stdout.splitlines()
209
210 # This should not happen, but it's better to be safe.
211 if len(merge_bases) > 1:
212 print("WARNING: Multiple merge bases found. Using the first one as base commit.")
213
214 parser.add_argument("--from-ref",
215 help="Base commit in patch mode (default: %(default)s)",
216 default=merge_bases[0])
217 parser.add_argument("--to-ref",
218 help="Final commit in patch mode (default: %(default)s)",
219 default="HEAD")
220
221 args = parser.parse_args(argv)
222 return args
223
224
225if __name__ == "__main__":
226 args = parse_cmd_line(sys.argv[1:], sys.argv[0])
227
228 os.chdir(args.tree)
229
230 rc = main(args)
231
232 sys.exit(rc)