blob: de4d24527e3ca8c8a317eeffb1925efe60f3bb55 [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:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200167 try:
168 f.seek(-1, 2)
169 except OSError:
170 # This script only works on regular files. If we can't seek
171 # 1 before the end, it means that this position is before
172 # the beginning of the file, i.e. that the file is empty.
173 return
174 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000175 self.files_with_issues[filepath] = None
176
177
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100178class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100179 """Track files that start with a UTF-8 BOM.
180 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000181
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100182 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000183
Gilles Peskine05a51a82020-05-10 16:52:44 +0200184 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200185 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100186
Darryl Green10d9ce32018-02-28 10:02:55 +0000187 def check_file_for_issue(self, filepath):
188 with open(filepath, "rb") as f:
189 if f.read().startswith(codecs.BOM_UTF8):
190 self.files_with_issues[filepath] = None
191
192
Gilles Peskine2c618732020-03-24 22:26:01 +0100193class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100194 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000195
Gilles Peskine2c618732020-03-24 22:26:01 +0100196 heading = "Non-Unix line endings:"
197
198 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200199 if not super().should_check_file(filepath):
200 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100201 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000202
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100203 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000204 return b"\r" in line
205
206
Gilles Peskine545e13f2020-03-24 22:29:11 +0100207class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200208 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100209
210 heading = "Non-Windows line endings:"
211
212 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200213 if not super().should_check_file(filepath):
214 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100215 return is_windows_file(filepath)
216
217 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200218 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100219
220
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100221class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100222 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000223
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100224 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200225 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000226
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100227 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000228 return line.rstrip(b"\r\n") != line.rstrip()
229
230
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100231class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100232 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000233
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100234 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200235 suffix_exemptions = frozenset([
Gilles Peskine2c618732020-03-24 22:26:01 +0100236 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100237 "/Makefile",
238 "/Makefile.inc",
239 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100240 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000241
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100242 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000243 return b"\t" in line
244
245
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100246class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100247 """Track lines with merge artifacts.
248 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100249
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100250 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100251
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100252 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100253 # Detect leftover git conflict markers.
254 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
255 return True
256 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
257 return True
258 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100259 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100260 return True
261 return False
262
Darryl Green10d9ce32018-02-28 10:02:55 +0000263
Gilles Peskine184c0962020-03-24 18:25:17 +0100264class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100265 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000266
267 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100268 """Instantiate the sanity checker.
269 Check files under the current directory.
270 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000271 self.check_repo_path()
272 self.logger = None
273 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000274 self.issues_to_check = [
275 PermissionIssueTracker(),
276 EndOfFileNewlineIssueTracker(),
277 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100278 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100279 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000280 TrailingWhitespaceIssueTracker(),
281 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100282 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000283 ]
284
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100285 @staticmethod
286 def check_repo_path():
Darryl Green10d9ce32018-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 Peskine3e2ee3c2020-05-10 17:18:06 +0200300 @staticmethod
301 def collect_files():
302 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
303 bytes_filepaths = bytes_output.split(b'\0')[:-1]
304 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
305 # Prepend './' to files in the top-level directory so that
306 # something like `'/Makefile' in fp` matches in the top-level
307 # directory as well as in subdirectories.
308 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
309 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200310
Darryl Green10d9ce32018-02-28 10:02:55 +0000311 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200312 for issue_to_check in self.issues_to_check:
313 for filepath in self.collect_files():
314 if issue_to_check.should_check_file(filepath):
315 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000316
317 def output_issues(self):
318 integrity_return_code = 0
319 for issue_to_check in self.issues_to_check:
320 if issue_to_check.files_with_issues:
321 integrity_return_code = 1
322 issue_to_check.output_file_issues(self.logger)
323 return integrity_return_code
324
325
326def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200327 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000328 parser.add_argument(
329 "-l", "--log_file", type=str, help="path to optional output log",
330 )
331 check_args = parser.parse_args()
332 integrity_check = IntegrityChecker(check_args.log_file)
333 integrity_check.check_files()
334 return_code = integrity_check.output_issues()
335 sys.exit(return_code)
336
337
338if __name__ == "__main__":
339 run_main()