blob: a5436fc6426a138e913817dfcc1b91032da8cb0e [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
Gilles Peskine4bda3252020-05-10 17:18:06 +020018import subprocess
Darryl Greenda02eb32018-02-28 10:02:55 +000019import sys
20
21
Gilles Peskineb5847d22020-03-24 18:25:17 +010022class FileIssueTracker:
Gilles Peskine7194ecb2019-02-25 20:59:05 +010023 """Base class for file-wide issue tracking.
24
25 To implement a checker that processes a file as a whole, inherit from
Gilles Peskinefb8c3732019-02-25 21:10:04 +010026 this class and implement `check_file_for_issue` and define ``heading``.
27
Gilles Peskine45137612020-05-10 16:52:44 +020028 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskinefb8c3732019-02-25 21:10:04 +010029 will not be checked.
30
Gilles Peskineb4805ec2020-05-10 16:57:16 +020031 ``path_exemptions``: files whose path (relative to the root of the source
32 tree) matches this regular expression will not be checked. This can be
33 ``None`` to match no path. Paths are normalized and converted to ``/``
34 separators before matching.
35
Gilles Peskinefb8c3732019-02-25 21:10:04 +010036 ``heading``: human-readable description of the issue
Gilles Peskine7194ecb2019-02-25 20:59:05 +010037 """
Darryl Greenda02eb32018-02-28 10:02:55 +000038
Gilles Peskine45137612020-05-10 16:52:44 +020039 suffix_exemptions = frozenset()
Gilles Peskineb4805ec2020-05-10 16:57:16 +020040 path_exemptions = None
Gilles Peskinefb8c3732019-02-25 21:10:04 +010041 # heading must be defined in derived classes.
42 # pylint: disable=no-member
43
Darryl Greenda02eb32018-02-28 10:02:55 +000044 def __init__(self):
Darryl Greenda02eb32018-02-28 10:02:55 +000045 self.files_with_issues = {}
46
Gilles Peskineb4805ec2020-05-10 16:57:16 +020047 @staticmethod
48 def normalize_path(filepath):
Gilles Peskine14b559a2020-05-28 18:19:20 +020049 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskineb4805ec2020-05-10 16:57:16 +020050 filepath = os.path.normpath(filepath)
Gilles Peskine14b559a2020-05-28 18:19:20 +020051 # On Windows, we may have backslashes to separate directories.
52 # We need slashes to match exemption lists.
Gilles Peskineb4805ec2020-05-10 16:57:16 +020053 seps = os.path.sep
54 if os.path.altsep is not None:
55 seps += os.path.altsep
56 return '/'.join(filepath.split(seps))
57
Darryl Greenda02eb32018-02-28 10:02:55 +000058 def should_check_file(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010059 """Whether the given file name should be checked.
60
Gilles Peskine45137612020-05-10 16:52:44 +020061 Files whose name ends with a string listed in ``self.suffix_exemptions``
62 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskine558e26d2020-03-24 16:49:21 +010063 """
Gilles Peskine45137612020-05-10 16:52:44 +020064 for files_exemption in self.suffix_exemptions:
Darryl Greenda02eb32018-02-28 10:02:55 +000065 if filepath.endswith(files_exemption):
66 return False
Gilles Peskineb4805ec2020-05-10 16:57:16 +020067 if self.path_exemptions and \
68 re.match(self.path_exemptions, self.normalize_path(filepath)):
69 return False
Darryl Greenda02eb32018-02-28 10:02:55 +000070 return True
71
Darryl Greenda02eb32018-02-28 10:02:55 +000072 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010073 """Check the specified file for the issue that this class is for.
74
75 Subclasses must implement this method.
76 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +010077 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +000078
Gilles Peskine232fae32018-11-23 21:11:30 +010079 def record_issue(self, filepath, line_number):
Gilles Peskine558e26d2020-03-24 16:49:21 +010080 """Record that an issue was found at the specified location."""
Gilles Peskine232fae32018-11-23 21:11:30 +010081 if filepath not in self.files_with_issues.keys():
82 self.files_with_issues[filepath] = []
83 self.files_with_issues[filepath].append(line_number)
84
Darryl Greenda02eb32018-02-28 10:02:55 +000085 def output_file_issues(self, logger):
Gilles Peskine558e26d2020-03-24 16:49:21 +010086 """Log all the locations where the issue was found."""
Darryl Greenda02eb32018-02-28 10:02:55 +000087 if self.files_with_issues.values():
88 logger.info(self.heading)
89 for filename, lines in sorted(self.files_with_issues.items()):
90 if lines:
91 logger.info("{}: {}".format(
92 filename, ", ".join(str(x) for x in lines)
93 ))
94 else:
95 logger.info(filename)
96 logger.info("")
97
Gilles Peskine986a06d2020-05-10 16:57:59 +020098BINARY_FILE_PATH_RE_LIST = [
99 r'docs/.*\.pdf\Z',
100 r'programs/fuzz/corpuses/[^.]+\Z',
101 r'tests/data_files/[^.]+\Z',
102 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
103 r'tests/data_files/.*\.req\.[^/]+\Z',
104 r'tests/data_files/.*malformed[^/]+\Z',
105 r'tests/data_files/format_pkcs12\.fmt\Z',
106]
107BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
108
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100109class LineIssueTracker(FileIssueTracker):
110 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +0000111
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100112 To implement a checker that processes files line by line, inherit from
113 this class and implement `line_with_issue`.
114 """
115
Gilles Peskine986a06d2020-05-10 16:57:59 +0200116 # Exclude binary files.
117 path_exemptions = BINARY_FILE_PATH_RE
118
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100119 def issue_with_line(self, line, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100120 """Check the specified line for the issue that this class is for.
121
122 Subclasses must implement this method.
123 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100124 raise NotImplementedError
125
126 def check_file_line(self, filepath, line, line_number):
127 if self.issue_with_line(line, filepath):
128 self.record_issue(filepath, line_number)
129
130 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100131 """Check the lines of the specified file.
132
133 Subclasses must implement the ``issue_with_line`` method.
134 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100135 with open(filepath, "rb") as f:
136 for i, line in enumerate(iter(f.readline, b"")):
137 self.check_file_line(filepath, line, i + 1)
138
Gilles Peskine227dfd42020-03-24 22:26:01 +0100139
140def is_windows_file(filepath):
141 _root, ext = os.path.splitext(filepath)
Gilles Peskinee7e149f2020-05-10 17:36:51 +0200142 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100143
144
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100145class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100146 """Track files with bad permissions.
147
148 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000149
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100150 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000151
152 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +0100153 is_executable = os.access(filepath, os.X_OK)
154 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
155 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +0000156 self.files_with_issues[filepath] = None
157
158
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100159class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100160 """Track files that end with an incomplete line
161 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000162
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100163 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000164
Gilles Peskine986a06d2020-05-10 16:57:59 +0200165 path_exemptions = BINARY_FILE_PATH_RE
166
Darryl Greenda02eb32018-02-28 10:02:55 +0000167 def check_file_for_issue(self, filepath):
168 with open(filepath, "rb") as f:
Gilles Peskinebe76c192020-05-10 17:36:42 +0200169 try:
170 f.seek(-1, 2)
171 except OSError:
172 # This script only works on regular files. If we can't seek
173 # 1 before the end, it means that this position is before
174 # the beginning of the file, i.e. that the file is empty.
175 return
176 if f.read(1) != b"\n":
Darryl Greenda02eb32018-02-28 10:02:55 +0000177 self.files_with_issues[filepath] = None
178
179
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100180class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100181 """Track files that start with a UTF-8 BOM.
182 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000183
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100184 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000185
Gilles Peskine45137612020-05-10 16:52:44 +0200186 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine986a06d2020-05-10 16:57:59 +0200187 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine227dfd42020-03-24 22:26:01 +0100188
Darryl Greenda02eb32018-02-28 10:02:55 +0000189 def check_file_for_issue(self, filepath):
190 with open(filepath, "rb") as f:
191 if f.read().startswith(codecs.BOM_UTF8):
192 self.files_with_issues[filepath] = None
193
194
Gilles Peskine227dfd42020-03-24 22:26:01 +0100195class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100196 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000197
Gilles Peskine227dfd42020-03-24 22:26:01 +0100198 heading = "Non-Unix line endings:"
199
200 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200201 if not super().should_check_file(filepath):
202 return False
Gilles Peskine227dfd42020-03-24 22:26:01 +0100203 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000204
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100205 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000206 return b"\r" in line
207
208
Gilles Peskine783da632020-03-24 22:29:11 +0100209class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200210 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100211
212 heading = "Non-Windows line endings:"
213
214 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200215 if not super().should_check_file(filepath):
216 return False
Gilles Peskine783da632020-03-24 22:29:11 +0100217 return is_windows_file(filepath)
218
219 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200220 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100221
222
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100223class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100224 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000225
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100226 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200227 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000228
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100229 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000230 return line.rstrip(b"\r\n") != line.rstrip()
231
232
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100233class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100234 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000235
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100236 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200237 suffix_exemptions = frozenset([
Gilles Peskine8fa5be52020-05-10 17:37:02 +0200238 ".pem", # some openssl dumps have tabs
Gilles Peskine227dfd42020-03-24 22:26:01 +0100239 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100240 "/Makefile",
241 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100242 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000243
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100244 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000245 return b"\t" in line
246
247
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100248class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100249 """Track lines with merge artifacts.
250 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100251
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100252 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100253
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100254 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100255 # Detect leftover git conflict markers.
256 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
257 return True
258 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
259 return True
260 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100261 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100262 return True
263 return False
264
Darryl Greenda02eb32018-02-28 10:02:55 +0000265
Gilles Peskineb5847d22020-03-24 18:25:17 +0100266class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100267 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000268
269 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100270 """Instantiate the sanity checker.
271 Check files under the current directory.
272 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000273 self.check_repo_path()
274 self.logger = None
275 self.setup_logger(log_file)
Darryl Greenda02eb32018-02-28 10:02:55 +0000276 self.issues_to_check = [
277 PermissionIssueTracker(),
278 EndOfFileNewlineIssueTracker(),
279 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100280 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100281 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000282 TrailingWhitespaceIssueTracker(),
283 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100284 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000285 ]
286
Gilles Peskine4fb66782019-02-25 20:35:31 +0100287 @staticmethod
288 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000289 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
290 raise Exception("Must be run from Mbed TLS root")
291
292 def setup_logger(self, log_file, level=logging.INFO):
293 self.logger = logging.getLogger()
294 self.logger.setLevel(level)
295 if log_file:
296 handler = logging.FileHandler(log_file)
297 self.logger.addHandler(handler)
298 else:
299 console = logging.StreamHandler()
300 self.logger.addHandler(console)
301
Gilles Peskine4bda3252020-05-10 17:18:06 +0200302 @staticmethod
303 def collect_files():
304 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
305 bytes_filepaths = bytes_output.split(b'\0')[:-1]
306 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
307 # Prepend './' to files in the top-level directory so that
308 # something like `'/Makefile' in fp` matches in the top-level
309 # directory as well as in subdirectories.
310 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
311 for fp in ascii_filepaths]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200312
Darryl Greenda02eb32018-02-28 10:02:55 +0000313 def check_files(self):
Gilles Peskine4bda3252020-05-10 17:18:06 +0200314 for issue_to_check in self.issues_to_check:
315 for filepath in self.collect_files():
316 if issue_to_check.should_check_file(filepath):
317 issue_to_check.check_file_for_issue(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000318
319 def output_issues(self):
320 integrity_return_code = 0
321 for issue_to_check in self.issues_to_check:
322 if issue_to_check.files_with_issues:
323 integrity_return_code = 1
324 issue_to_check.output_file_issues(self.logger)
325 return integrity_return_code
326
327
328def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200329 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000330 parser.add_argument(
331 "-l", "--log_file", type=str, help="path to optional output log",
332 )
333 check_args = parser.parse_args()
334 integrity_check = IntegrityChecker(check_args.log_file)
335 integrity_check.check_files()
336 return_code = integrity_check.output_issues()
337 sys.exit(return_code)
338
339
340if __name__ == "__main__":
341 run_main()