blob: b48f62b75b6ab3888cd5be0e233298550a2fd1fb [file] [log] [blame]
Darryl Greenda02eb32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine081daf02019-07-04 19:31:02 +02002
3# This file is part of Mbed TLS (https://tls.mbed.org)
4# Copyright (c) 2018, Arm Limited, All Rights Reserved
5
Darryl Greenda02eb32018-02-28 10:02:55 +00006"""
Darryl Greenda02eb32018-02-28 10:02:55 +00007This script checks the current state of the source code for minor issues,
8including incorrect file permissions, presence of tabs, non-Unix line endings,
Gilles Peskine570f7a22019-07-04 19:31:33 +02009trailing whitespace, and presence of UTF-8 BOM.
Darryl Greenda02eb32018-02-28 10:02:55 +000010Note: requires python 3, must be run from Mbed TLS root.
11"""
12
13import os
14import argparse
15import logging
16import codecs
Gilles Peskineb4805ec2020-05-10 16:57:16 +020017import re
Darryl Greenda02eb32018-02-28 10:02:55 +000018import sys
19
20
Gilles Peskineb5847d22020-03-24 18:25:17 +010021class FileIssueTracker:
Gilles Peskine7194ecb2019-02-25 20:59:05 +010022 """Base class for file-wide issue tracking.
23
24 To implement a checker that processes a file as a whole, inherit from
Gilles Peskinefb8c3732019-02-25 21:10:04 +010025 this class and implement `check_file_for_issue` and define ``heading``.
26
Gilles Peskine45137612020-05-10 16:52:44 +020027 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskinefb8c3732019-02-25 21:10:04 +010028 will not be checked.
29
Gilles Peskineb4805ec2020-05-10 16:57:16 +020030 ``path_exemptions``: files whose path (relative to the root of the source
31 tree) matches this regular expression will not be checked. This can be
32 ``None`` to match no path. Paths are normalized and converted to ``/``
33 separators before matching.
34
Gilles Peskinefb8c3732019-02-25 21:10:04 +010035 ``heading``: human-readable description of the issue
Gilles Peskine7194ecb2019-02-25 20:59:05 +010036 """
Darryl Greenda02eb32018-02-28 10:02:55 +000037
Gilles Peskine45137612020-05-10 16:52:44 +020038 suffix_exemptions = frozenset()
Gilles Peskineb4805ec2020-05-10 16:57:16 +020039 path_exemptions = None
Gilles Peskinefb8c3732019-02-25 21:10:04 +010040 # heading must be defined in derived classes.
41 # pylint: disable=no-member
42
Darryl Greenda02eb32018-02-28 10:02:55 +000043 def __init__(self):
Darryl Greenda02eb32018-02-28 10:02:55 +000044 self.files_with_issues = {}
45
Gilles Peskineb4805ec2020-05-10 16:57:16 +020046 @staticmethod
47 def normalize_path(filepath):
48 """Normalize ``filepath`` """
49 filepath = os.path.normpath(filepath)
50 seps = os.path.sep
51 if os.path.altsep is not None:
52 seps += os.path.altsep
53 return '/'.join(filepath.split(seps))
54
Darryl Greenda02eb32018-02-28 10:02:55 +000055 def should_check_file(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010056 """Whether the given file name should be checked.
57
Gilles Peskine45137612020-05-10 16:52:44 +020058 Files whose name ends with a string listed in ``self.suffix_exemptions``
59 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskine558e26d2020-03-24 16:49:21 +010060 """
Gilles Peskine45137612020-05-10 16:52:44 +020061 for files_exemption in self.suffix_exemptions:
Darryl Greenda02eb32018-02-28 10:02:55 +000062 if filepath.endswith(files_exemption):
63 return False
Gilles Peskineb4805ec2020-05-10 16:57:16 +020064 if self.path_exemptions and \
65 re.match(self.path_exemptions, self.normalize_path(filepath)):
66 return False
Darryl Greenda02eb32018-02-28 10:02:55 +000067 return True
68
Darryl Greenda02eb32018-02-28 10:02:55 +000069 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010070 """Check the specified file for the issue that this class is for.
71
72 Subclasses must implement this method.
73 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +010074 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +000075
Gilles Peskine232fae32018-11-23 21:11:30 +010076 def record_issue(self, filepath, line_number):
Gilles Peskine558e26d2020-03-24 16:49:21 +010077 """Record that an issue was found at the specified location."""
Gilles Peskine232fae32018-11-23 21:11:30 +010078 if filepath not in self.files_with_issues.keys():
79 self.files_with_issues[filepath] = []
80 self.files_with_issues[filepath].append(line_number)
81
Darryl Greenda02eb32018-02-28 10:02:55 +000082 def output_file_issues(self, logger):
Gilles Peskine558e26d2020-03-24 16:49:21 +010083 """Log all the locations where the issue was found."""
Darryl Greenda02eb32018-02-28 10:02:55 +000084 if self.files_with_issues.values():
85 logger.info(self.heading)
86 for filename, lines in sorted(self.files_with_issues.items()):
87 if lines:
88 logger.info("{}: {}".format(
89 filename, ", ".join(str(x) for x in lines)
90 ))
91 else:
92 logger.info(filename)
93 logger.info("")
94
Gilles Peskine986a06d2020-05-10 16:57:59 +020095BINARY_FILE_PATH_RE_LIST = [
96 r'docs/.*\.pdf\Z',
97 r'programs/fuzz/corpuses/[^.]+\Z',
98 r'tests/data_files/[^.]+\Z',
99 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
100 r'tests/data_files/.*\.req\.[^/]+\Z',
101 r'tests/data_files/.*malformed[^/]+\Z',
102 r'tests/data_files/format_pkcs12\.fmt\Z',
103]
104BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
105
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100106class LineIssueTracker(FileIssueTracker):
107 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +0000108
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100109 To implement a checker that processes files line by line, inherit from
110 this class and implement `line_with_issue`.
111 """
112
Gilles Peskine986a06d2020-05-10 16:57:59 +0200113 # Exclude binary files.
114 path_exemptions = BINARY_FILE_PATH_RE
115
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100116 def issue_with_line(self, line, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100117 """Check the specified line for the issue that this class is for.
118
119 Subclasses must implement this method.
120 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100121 raise NotImplementedError
122
123 def check_file_line(self, filepath, line, line_number):
124 if self.issue_with_line(line, filepath):
125 self.record_issue(filepath, line_number)
126
127 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100128 """Check the lines of the specified file.
129
130 Subclasses must implement the ``issue_with_line`` method.
131 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100132 with open(filepath, "rb") as f:
133 for i, line in enumerate(iter(f.readline, b"")):
134 self.check_file_line(filepath, line, i + 1)
135
Gilles Peskine227dfd42020-03-24 22:26:01 +0100136
137def is_windows_file(filepath):
138 _root, ext = os.path.splitext(filepath)
Gilles Peskine86e58162020-04-26 00:33:13 +0200139 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100140
141
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100142class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100143 """Track files with bad permissions.
144
145 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000146
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100147 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000148
149 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +0100150 is_executable = os.access(filepath, os.X_OK)
151 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
152 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +0000153 self.files_with_issues[filepath] = None
154
155
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100156class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100157 """Track files that end with an incomplete line
158 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000159
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100160 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000161
Gilles Peskine986a06d2020-05-10 16:57:59 +0200162 path_exemptions = BINARY_FILE_PATH_RE
163
Darryl Greenda02eb32018-02-28 10:02:55 +0000164 def check_file_for_issue(self, filepath):
165 with open(filepath, "rb") as f:
166 if not f.read().endswith(b"\n"):
167 self.files_with_issues[filepath] = None
168
169
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100170class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100171 """Track files that start with a UTF-8 BOM.
172 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000173
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100174 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000175
Gilles Peskine45137612020-05-10 16:52:44 +0200176 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine986a06d2020-05-10 16:57:59 +0200177 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine227dfd42020-03-24 22:26:01 +0100178
Darryl Greenda02eb32018-02-28 10:02:55 +0000179 def check_file_for_issue(self, filepath):
180 with open(filepath, "rb") as f:
181 if f.read().startswith(codecs.BOM_UTF8):
182 self.files_with_issues[filepath] = None
183
184
Gilles Peskine227dfd42020-03-24 22:26:01 +0100185class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100186 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000187
Gilles Peskine227dfd42020-03-24 22:26:01 +0100188 heading = "Non-Unix line endings:"
189
190 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200191 if not super().should_check_file(filepath):
192 return False
Gilles Peskine227dfd42020-03-24 22:26:01 +0100193 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000194
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100195 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000196 return b"\r" in line
197
198
Gilles Peskine783da632020-03-24 22:29:11 +0100199class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200200 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100201
202 heading = "Non-Windows line endings:"
203
204 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200205 if not super().should_check_file(filepath):
206 return False
Gilles Peskine783da632020-03-24 22:29:11 +0100207 return is_windows_file(filepath)
208
209 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200210 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100211
212
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100213class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100214 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000215
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100216 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200217 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000218
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100219 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000220 return line.rstrip(b"\r\n") != line.rstrip()
221
222
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100223class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100224 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000225
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100226 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200227 suffix_exemptions = frozenset([
Gilles Peskine227dfd42020-03-24 22:26:01 +0100228 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100229 "/Makefile",
230 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100231 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000232
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100233 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000234 return b"\t" in line
235
236
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100237class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100238 """Track lines with merge artifacts.
239 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100240
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100241 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100242
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100243 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100244 # Detect leftover git conflict markers.
245 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
246 return True
247 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
248 return True
249 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100250 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100251 return True
252 return False
253
Darryl Greenda02eb32018-02-28 10:02:55 +0000254
Gilles Peskineb5847d22020-03-24 18:25:17 +0100255class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100256 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000257
258 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100259 """Instantiate the sanity checker.
260 Check files under the current directory.
261 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000262 self.check_repo_path()
263 self.logger = None
264 self.setup_logger(log_file)
Gilles Peskinec7153222020-03-24 22:05:02 +0100265 self.excluded_directories = [
266 '.git',
267 'mbed-os',
268 ]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200269 self.excluded_paths = list(map(os.path.normpath, [
270 'cov-int',
271 'examples',
272 'yotta/module'
273 ]))
Darryl Greenda02eb32018-02-28 10:02:55 +0000274 self.issues_to_check = [
275 PermissionIssueTracker(),
276 EndOfFileNewlineIssueTracker(),
277 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100278 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100279 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000280 TrailingWhitespaceIssueTracker(),
281 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100282 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000283 ]
284
Gilles Peskine4fb66782019-02-25 20:35:31 +0100285 @staticmethod
286 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000287 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
288 raise Exception("Must be run from Mbed TLS root")
289
290 def setup_logger(self, log_file, level=logging.INFO):
291 self.logger = logging.getLogger()
292 self.logger.setLevel(level)
293 if log_file:
294 handler = logging.FileHandler(log_file)
295 self.logger.addHandler(handler)
296 else:
297 console = logging.StreamHandler()
298 self.logger.addHandler(console)
299
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200300 def prune_branch(self, root, d):
301 if d in self.excluded_directories:
302 return True
303 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
304 return True
305 return False
306
Darryl Greenda02eb32018-02-28 10:02:55 +0000307 def check_files(self):
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200308 for root, dirs, files in os.walk("."):
309 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Greenda02eb32018-02-28 10:02:55 +0000310 for filename in sorted(files):
311 filepath = os.path.join(root, filename)
Darryl Greenda02eb32018-02-28 10:02:55 +0000312 for issue_to_check in self.issues_to_check:
313 if issue_to_check.should_check_file(filepath):
314 issue_to_check.check_file_for_issue(filepath)
315
316 def output_issues(self):
317 integrity_return_code = 0
318 for issue_to_check in self.issues_to_check:
319 if issue_to_check.files_with_issues:
320 integrity_return_code = 1
321 issue_to_check.output_file_issues(self.logger)
322 return integrity_return_code
323
324
325def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200326 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000327 parser.add_argument(
328 "-l", "--log_file", type=str, help="path to optional output log",
329 )
330 check_args = parser.parse_args()
331 integrity_check = IntegrityChecker(check_args.log_file)
332 integrity_check.check_files()
333 return_code = integrity_check.output_issues()
334 sys.exit(return_code)
335
336
337if __name__ == "__main__":
338 run_main()