1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
|
#!/usr/bin/env python3
# /*
# * FreeRTOS V202111.00
# * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# *
# * Permission is hereby granted, free of charge, to any person obtaining a copy of
# * this software and associated documentation files (the "Software"), to deal in
# * the Software without restriction, including without limitation the rights to
# * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# * the Software, and to permit persons to whom the Software is furnished to do so,
# * subject to the following conditions:
# *
# * The above copyright notice and this permission notice shall be included in all
# * copies or substantial portions of the Software.
# *
# * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# *
# * https://www.FreeRTOS.org
# * https://github.com/FreeRTOS
# *
# */
import os
import re
from argparse import ArgumentParser
from difflib import unified_diff
from json import load
import requests
from colorama import Fore, Style
def dprint(msg):
print("[DEBUG]: %s" % str(msg))
class HeaderChecker:
def separateHeaderIntoSections(self, header):
"""
Separate header into text, copyright, and spdx sections.
"""
cur_headers = dict()
cur_headers["text"] = []
cur_headers["copyright"] = []
cur_headers["spdx"] = []
for line in header:
if "Copyright" in line:
cur_headers["copyright"].append(line)
elif "SPDX-License-Identifier:" in line:
cur_headers["spdx"].append(line)
else:
cur_headers["text"].append(line)
return cur_headers
def __init__(
self,
header,
padding=1000,
ignored_files=None,
ignored_ext=None,
ignored_patterns=None,
py_ext=None,
asm_ext=None,
third_party_patterns=None,
):
self.padding = padding
self.header = header
# Construct mutated header for assembly files
self.asm_header = [";" + line for line in header]
# Construct mutated header for python files
self.py_header = ["#" + line for line in header]
self.headers = self.separateHeaderIntoSections(self.header)
self.headers_asm = self.separateHeaderIntoSections(self.asm_header)
self.headers_py = self.separateHeaderIntoSections(self.py_header)
self.ignorePatternList = []
if ignored_patterns:
for p in ignored_patterns:
self.ignorePatternList.append(re.compile(p))
self.ignoreFileList = ignored_files.copy() if ignored_files else []
self.ignoreExtList = ignored_ext.copy() if ignored_ext else []
self.pyExtList = py_ext.copy() if py_ext else []
self.asmExtList = asm_ext.copy() if asm_ext else []
self.thirdPartyPatternList = []
if third_party_patterns:
for p in third_party_patterns:
self.thirdPartyPatternList.append(re.compile(p))
self.spdx_data = None
self.sdpx_regex = None
def checkJSONList(self, path_json):
"""
This is particularly useful when ingesting output from other programs, like git actions
"""
assert os.path.exists(path_json), "No such file: " + path_json
# Get list of files to check from JSON file
with open(path_json) as file_json:
file_checklist = load(file_json)
assert isinstance(
file_checklist, list
), "Expected list for singular JSON List entry"
# Accrue how how files fail the check
n_failed = 0
for path_file in file_checklist:
assert isinstance(path_file, str), "Unexpected JSON format for " + path_json
if os.path.exists(path_file) and not self.isValidFile(path_file):
n_failed += 1
return n_failed
def isValidHeaderSection(self, file_ext, section_name, section):
"""Validate a given section based on file extentions and section name"""
valid = False
if file_ext in self.pyExtList:
valid = self.headers_py[section_name] == section
elif file_ext in self.asmExtList:
valid = self.headers[section_name] == section
valid |= self.headers_asm[section_name] == section
else:
valid = self.headers[section_name] == section
return valid
def getHeaderDiff(self, file_ext, header):
diff = []
if file_ext in self.pyExtList:
diff = list(unified_diff(header[: len(self.py_header)], self.py_header))
elif file_ext in self.asmExtList:
# For assembly files and headers, calculate diffs between both header types.
# Return the smallest diff.
diff_default = list(unified_diff(header[: len(self.header)], self.header))
diff_asm = list(
unified_diff(header[: len(self.asm_header)], self.asm_header)
)
if len(diff_asm) >= len(diff_default):
diff = diff_default
else:
diff = diff_asm
else:
diff = list(unified_diff(header[: len(self.header)], self.header))
return diff
def isValidFile(self, path):
assert os.path.exists(path), "No such file: " + path
print("-" * 85)
print("Checking file: %s..." % path, end="")
file_ext = os.path.splitext(path)[-1]
if self.isIgnoredFile(path) or os.path.isdir(path):
print("SKIP")
print("-" * 85)
return True
# Read sufficiently large chunk of the file which should contain the header
with open(path, encoding="utf-8", errors="ignore") as file:
chunk = file.read(len("".join(self.header)) + self.padding)
lines = [("%s\n" % line) for line in chunk.strip().splitlines()][
: len(self.header)
]
if (len(lines) > 0) and (lines[0].find("#!") == 0):
lines.remove(lines[0])
# Split lines in sections:
header_check = self.separateHeaderIntoSections(lines)
text_equal = self.isValidHeaderSection(
file_ext, "text", header_check["text"]
)
copyright_equal = self.isValidHeaderSection(
file_ext, "copyright", header_check["copyright"]
)
spdx_equal = self.isValidHeaderSection(
file_ext, "spdx", header_check["spdx"]
)
# Most files should have exactly the same sections
if text_equal and copyright_equal and spdx_equal:
print("PASS")
print("-" * 85)
return True
# Third party files may have a different copyright
elif self.isThirdPartyFile(path) and text_equal and spdx_equal:
print("PASS")
print("-" * 85)
return True
elif self.isThirdPartyFile(path) and self.validateSpdxLine(
header_check["spdx"]
):
print("PASS")
print("-" * 85)
return True
elif self.isThirdPartyFile(path):
print("FAIL")
print("-" * 85)
return False
else:
print("FAIL")
print("File Delta: %s" % path)
print(*self.getHeaderDiff(file_ext, lines))
print("-" * 85)
return False
def ignoreExtension(self, *args):
for ext in args:
self.ignoreExtList.append(ext)
def ignoreFile(self, *args):
for f in args:
self.ignoreFileList.append(f)
def ignorePattern(self, *args):
for p in args:
self.ignorePatternList.append(re.compile(p))
def addPyExtension(self, *args):
for p in args:
self.pyExtList.append(p)
def addAsmExtension(self, *args):
for p in args:
self.asmExtList.append(p)
def isIgnoredFile(self, path):
"""
There are multiple ways a file can be ignored. This is a catch all
"""
assert os.path.exists(path), "No such file: " + path
# Try simpler checks first
filename = os.path.split(path)[-1]
extension = os.path.splitext(filename)[-1]
if extension in self.ignoreExtList or filename in self.ignoreFileList:
return True
# Then iterate against regex patterns. In future consider Trie
for pattern in self.ignorePatternList:
# print(pattern)
if pattern.match(path):
return True
# print("DEBUG: did not match any regex")
return False
def isThirdPartyFile(self, path):
# Tterate against regex patterns
for pattern in self.thirdPartyPatternList:
if pattern.match(path):
return True
return False
def showHelp(self, path_config):
print(Fore.YELLOW)
print(
"\n\n \
*************************************************************************************************\n\
* FreeRTOS Header Check %s(FAILED)%s *\n\
*************************************************************************************************\n\
* *\n\
* %sWe do NOT require that all files contain the FreeRTOS File Header (copyright + license).%s *\n\
* While some files in this change-set don't adhere with the FreeRTOS File Header, *\n\
* they can be omitted from this check as needed. *\n\
* *\n\
* The Git PR check sources its scripts from your fork. *\n\
* For FreeRTOS/FreeRTOS, ignored files are listed in '.github/scripts/core_checker.py' *\n\
* For FreeRTOS/FreeRTOS-Kernel, ignored files are listed in '.github/scripts/kernel_checker.py' *\n\
* *\n\
* Please fix any offending files that should have the FreeRTOS header, *\n\
* or add new files to the ignore list as needed to make the check pass. *\n\
* *\n\
* %sInclude the required updates to the '*_checker.py' script in your PR to make the check pass.%s *\n\
*************************************************************************************************\n\
\n\n" # noqa: B950
% (Fore.RED, Fore.YELLOW, Fore.RED, Fore.YELLOW, Fore.RED, Fore.YELLOW)
)
print(Style.RESET_ALL)
@staticmethod
def configArgParser():
parser = ArgumentParser(
description="FreeRTOS file header checker. We expect a consistent header across all "
"first party files. The header includes current version number, copyright, "
"and FreeRTOS license."
)
parser.add_argument(
"files_checked",
nargs="+",
metavar="FILE_LIST",
help="Space separated list of files to check.",
)
parser.add_argument(
"-j",
"--json",
default=False,
action="store_true",
help="Treat arguments json files that store a list of files to check.",
)
return parser
def processArgs(self, args):
n_failed = 0
if args.json:
for path in args.files_checked:
n_failed += self.checkJSONList(path)
else:
for path in args.files_checked:
n_failed += not self.isValidFile(path)
return n_failed
def loadSpdxData(self):
"""Load spdx license and license exception information from github."""
spdx_data = dict()
spdx_url = "https://raw.githubusercontent.com/spdx/license-list-data/"
licenses_url = spdx_url + "master/json/licenses.json"
licenses = requests.get(licenses_url).json()
assert "licenses" in licenses
spdx_data["licenses"] = dict()
for license in licenses["licenses"]:
spdx_data["licenses"][license["licenseId"]] = True
exceptions_url = spdx_url + "master/json/exceptions.json"
exceptions = requests.get(exceptions_url).json()
assert "exceptions" in exceptions
spdx_data["exceptions"] = dict()
for exception in exceptions["exceptions"]:
spdx_data["exceptions"][exception["licenseExceptionId"]] = True
self.spdx_data = spdx_data
def validateSpdxTag(self, tag):
"""
Validate a given SPDX license tag against SPDX data from github
"""
error_count = 0
licenses = tag.split(" ")
license_exception_flag = False
paren_depth = 0
last_paren_depth = 0
for i in range(0, len(licenses)):
if licenses[i][0] == "(":
paren_depth += 1
# skip "and" "or" keywords
if licenses[i] in ["and", "AND", "or", "OR"]:
pass
# "with" keyword denotes a license exception
elif licenses[i] in ["with", "WITH"]:
# Set flag for next iteration
license_exception_flag = True
elif license_exception_flag:
if not licenses[i].strip("()") in self.spdx_data["exceptions"]:
dprint(
"Invalid license exception id {} in SPDX tag {}".format(
licenses[i], tag
)
)
error_count += 1
# No '(' character -> single license exception
if paren_depth <= last_paren_depth:
license_exception_flag = False
else:
if not licenses[i].strip("()") in self.spdx_data["licenses"]:
dprint(
'Invalid license id "{}" in SPDX tag "{}"'.format(
licenses[i], tag
)
)
error_count += 1
last_paren_depth = paren_depth
if licenses[i][-1] == ")":
paren_depth -= 1
return error_count
def validateSpdxLine(self, lines):
"""
Validate an SPDX license data line from a source file.
Like: /* SPDX-License-Identifier: MIT */
"""
if len(lines) == 0:
dprint("No SPDX identifier found.")
return False
if not self.spdx_data:
self.loadSpdxData()
if not self.sdpx_regex:
self.spdx_regex = re.compile(
r"^.*SPDX-License-Identifier:\s*(?P<tag>.*)\s*$"
)
error_count = 0
for line in lines:
matches = self.spdx_regex.match(line)
if "tag" in matches.groupdict():
error_count += self.validateSpdxTag(matches.group("tag"))
else:
error_count += 1
return error_count == 0
|