blob: 751b32bdd664b97edd084ed20ab5df5e1ca7fae2 [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine7dfcfce2019-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 Green10d9ce32018-02-28 10:02:55 +00006"""
Darryl Green10d9ce32018-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 Peskine55b49ee2019-07-04 19:31:33 +02009trailing whitespace, and presence of UTF-8 BOM.
Darryl Green10d9ce32018-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 Peskine0598db82020-05-10 16:57:16 +020017import re
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +020018import subprocess
Darryl Green10d9ce32018-02-28 10:02:55 +000019import sys
20
21
Gilles Peskine184c0962020-03-24 18:25:17 +010022class FileIssueTracker:
Gilles Peskine6ee576e2019-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 Peskine1e9698a2019-02-25 21:10:04 +010026 this class and implement `check_file_for_issue` and define ``heading``.
27
Gilles Peskine05a51a82020-05-10 16:52:44 +020028 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010029 will not be checked.
30
Gilles Peskine0598db82020-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 Peskine1e9698a2019-02-25 21:10:04 +010036 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010037 """
Darryl Green10d9ce32018-02-28 10:02:55 +000038
Gilles Peskine05a51a82020-05-10 16:52:44 +020039 suffix_exemptions = frozenset()
Gilles Peskine0598db82020-05-10 16:57:16 +020040 path_exemptions = None
Gilles Peskine1e9698a2019-02-25 21:10:04 +010041 # heading must be defined in derived classes.
42 # pylint: disable=no-member
43
Darryl Green10d9ce32018-02-28 10:02:55 +000044 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000045 self.files_with_issues = {}
46
Gilles Peskine0598db82020-05-10 16:57:16 +020047 @staticmethod
48 def normalize_path(filepath):
49 """Normalize ``filepath`` """
50 filepath = os.path.normpath(filepath)
51 seps = os.path.sep
52 if os.path.altsep is not None:
53 seps += os.path.altsep
54 return '/'.join(filepath.split(seps))
55
Darryl Green10d9ce32018-02-28 10:02:55 +000056 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010057 """Whether the given file name should be checked.
58
Gilles Peskine05a51a82020-05-10 16:52:44 +020059 Files whose name ends with a string listed in ``self.suffix_exemptions``
60 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaaee4442020-03-24 16:49:21 +010061 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020062 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000063 if filepath.endswith(files_exemption):
64 return False
Gilles Peskine0598db82020-05-10 16:57:16 +020065 if self.path_exemptions and \
66 re.match(self.path_exemptions, self.normalize_path(filepath)):
67 return False
Darryl Green10d9ce32018-02-28 10:02:55 +000068 return True
69
Darryl Green10d9ce32018-02-28 10:02:55 +000070 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010071 """Check the specified file for the issue that this class is for.
72
73 Subclasses must implement this method.
74 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010075 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000076
Gilles Peskine04398052018-11-23 21:11:30 +010077 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010078 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010079 if filepath not in self.files_with_issues.keys():
80 self.files_with_issues[filepath] = []
81 self.files_with_issues[filepath].append(line_number)
82
Darryl Green10d9ce32018-02-28 10:02:55 +000083 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +010084 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +000085 if self.files_with_issues.values():
86 logger.info(self.heading)
87 for filename, lines in sorted(self.files_with_issues.items()):
88 if lines:
89 logger.info("{}: {}".format(
90 filename, ", ".join(str(x) for x in lines)
91 ))
92 else:
93 logger.info(filename)
94 logger.info("")
95
Gilles Peskined4a853d2020-05-10 16:57:59 +020096BINARY_FILE_PATH_RE_LIST = [
97 r'docs/.*\.pdf\Z',
98 r'programs/fuzz/corpuses/[^.]+\Z',
99 r'tests/data_files/[^.]+\Z',
100 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
101 r'tests/data_files/.*\.req\.[^/]+\Z',
102 r'tests/data_files/.*malformed[^/]+\Z',
103 r'tests/data_files/format_pkcs12\.fmt\Z',
104]
105BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
106
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100107class LineIssueTracker(FileIssueTracker):
108 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000109
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100110 To implement a checker that processes files line by line, inherit from
111 this class and implement `line_with_issue`.
112 """
113
Gilles Peskined4a853d2020-05-10 16:57:59 +0200114 # Exclude binary files.
115 path_exemptions = BINARY_FILE_PATH_RE
116
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100117 def issue_with_line(self, line, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100118 """Check the specified line for the issue that this class is for.
119
120 Subclasses must implement this method.
121 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100122 raise NotImplementedError
123
124 def check_file_line(self, filepath, line, line_number):
125 if self.issue_with_line(line, filepath):
126 self.record_issue(filepath, line_number)
127
128 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100129 """Check the lines of the specified file.
130
131 Subclasses must implement the ``issue_with_line`` method.
132 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100133 with open(filepath, "rb") as f:
134 for i, line in enumerate(iter(f.readline, b"")):
135 self.check_file_line(filepath, line, i + 1)
136
Gilles Peskine2c618732020-03-24 22:26:01 +0100137
138def is_windows_file(filepath):
139 _root, ext = os.path.splitext(filepath)
Gilles Peskineaf387e02020-04-26 00:33:13 +0200140 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100141
142
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100143class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100144 """Track files with bad permissions.
145
146 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000147
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100148 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000149
150 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100151 is_executable = os.access(filepath, os.X_OK)
152 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
153 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000154 self.files_with_issues[filepath] = None
155
156
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100157class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100158 """Track files that end with an incomplete line
159 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000160
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100161 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000162
Gilles Peskined4a853d2020-05-10 16:57:59 +0200163 path_exemptions = BINARY_FILE_PATH_RE
164
Darryl Green10d9ce32018-02-28 10:02:55 +0000165 def check_file_for_issue(self, filepath):
166 with open(filepath, "rb") as f:
167 if not f.read().endswith(b"\n"):
168 self.files_with_issues[filepath] = None
169
170
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100171class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100172 """Track files that start with a UTF-8 BOM.
173 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000174
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100175 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000176
Gilles Peskine05a51a82020-05-10 16:52:44 +0200177 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200178 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100179
Darryl Green10d9ce32018-02-28 10:02:55 +0000180 def check_file_for_issue(self, filepath):
181 with open(filepath, "rb") as f:
182 if f.read().startswith(codecs.BOM_UTF8):
183 self.files_with_issues[filepath] = None
184
185
Gilles Peskine2c618732020-03-24 22:26:01 +0100186class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100187 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000188
Gilles Peskine2c618732020-03-24 22:26:01 +0100189 heading = "Non-Unix line endings:"
190
191 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200192 if not super().should_check_file(filepath):
193 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100194 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000195
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100196 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000197 return b"\r" in line
198
199
Gilles Peskine545e13f2020-03-24 22:29:11 +0100200class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200201 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100202
203 heading = "Non-Windows line endings:"
204
205 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200206 if not super().should_check_file(filepath):
207 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100208 return is_windows_file(filepath)
209
210 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200211 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100212
213
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100214class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100215 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000216
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100217 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200218 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000219
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100220 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000221 return line.rstrip(b"\r\n") != line.rstrip()
222
223
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100224class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100225 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000226
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100227 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200228 suffix_exemptions = frozenset([
Gilles Peskine2c618732020-03-24 22:26:01 +0100229 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100230 "/Makefile",
231 "/Makefile.inc",
232 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100233 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000234
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100235 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000236 return b"\t" in line
237
238
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100239class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100240 """Track lines with merge artifacts.
241 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100242
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100243 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100244
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100245 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100246 # Detect leftover git conflict markers.
247 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
248 return True
249 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
250 return True
251 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100252 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100253 return True
254 return False
255
Darryl Green10d9ce32018-02-28 10:02:55 +0000256
Gilles Peskine184c0962020-03-24 18:25:17 +0100257class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100258 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000259
260 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100261 """Instantiate the sanity checker.
262 Check files under the current directory.
263 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000264 self.check_repo_path()
265 self.logger = None
266 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000267 self.issues_to_check = [
268 PermissionIssueTracker(),
269 EndOfFileNewlineIssueTracker(),
270 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100271 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100272 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000273 TrailingWhitespaceIssueTracker(),
274 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100275 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000276 ]
277
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100278 @staticmethod
279 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000280 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
281 raise Exception("Must be run from Mbed TLS root")
282
283 def setup_logger(self, log_file, level=logging.INFO):
284 self.logger = logging.getLogger()
285 self.logger.setLevel(level)
286 if log_file:
287 handler = logging.FileHandler(log_file)
288 self.logger.addHandler(handler)
289 else:
290 console = logging.StreamHandler()
291 self.logger.addHandler(console)
292
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200293 @staticmethod
294 def collect_files():
295 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
296 bytes_filepaths = bytes_output.split(b'\0')[:-1]
297 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
298 # Prepend './' to files in the top-level directory so that
299 # something like `'/Makefile' in fp` matches in the top-level
300 # directory as well as in subdirectories.
301 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
302 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200303
Darryl Green10d9ce32018-02-28 10:02:55 +0000304 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200305 for issue_to_check in self.issues_to_check:
306 for filepath in self.collect_files():
307 if issue_to_check.should_check_file(filepath):
308 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000309
310 def output_issues(self):
311 integrity_return_code = 0
312 for issue_to_check in self.issues_to_check:
313 if issue_to_check.files_with_issues:
314 integrity_return_code = 1
315 issue_to_check.output_file_issues(self.logger)
316 return integrity_return_code
317
318
319def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200320 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000321 parser.add_argument(
322 "-l", "--log_file", type=str, help="path to optional output log",
323 )
324 check_args = parser.parse_args()
325 integrity_check = IntegrityChecker(check_args.log_file)
326 integrity_check.check_files()
327 return_code = integrity_check.output_issues()
328 sys.exit(return_code)
329
330
331if __name__ == "__main__":
332 run_main()