blob: 96911c8eb1935fe8d9d6a26f5a7d438fdce595de [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):
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 Greenda02eb32018-02-28 10:02:55 +000056 def should_check_file(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010057 """Whether the given file name should be checked.
58
Gilles Peskine45137612020-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 Peskine558e26d2020-03-24 16:49:21 +010061 """
Gilles Peskine45137612020-05-10 16:52:44 +020062 for files_exemption in self.suffix_exemptions:
Darryl Greenda02eb32018-02-28 10:02:55 +000063 if filepath.endswith(files_exemption):
64 return False
Gilles Peskineb4805ec2020-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 Greenda02eb32018-02-28 10:02:55 +000068 return True
69
Darryl Greenda02eb32018-02-28 10:02:55 +000070 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-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 Peskine7194ecb2019-02-25 20:59:05 +010075 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +000076
Gilles Peskine232fae32018-11-23 21:11:30 +010077 def record_issue(self, filepath, line_number):
Gilles Peskine558e26d2020-03-24 16:49:21 +010078 """Record that an issue was found at the specified location."""
Gilles Peskine232fae32018-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 Greenda02eb32018-02-28 10:02:55 +000083 def output_file_issues(self, logger):
Gilles Peskine558e26d2020-03-24 16:49:21 +010084 """Log all the locations where the issue was found."""
Darryl Greenda02eb32018-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 Peskine986a06d2020-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 Peskine7194ecb2019-02-25 20:59:05 +0100107class LineIssueTracker(FileIssueTracker):
108 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +0000109
Gilles Peskine7194ecb2019-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 Peskine986a06d2020-05-10 16:57:59 +0200114 # Exclude binary files.
115 path_exemptions = BINARY_FILE_PATH_RE
116
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100117 def issue_with_line(self, line, filepath):
Gilles Peskine558e26d2020-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 Peskine7194ecb2019-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 Peskine558e26d2020-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 Peskine7194ecb2019-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 Peskine227dfd42020-03-24 22:26:01 +0100137
138def is_windows_file(filepath):
139 _root, ext = os.path.splitext(filepath)
Gilles Peskine86e58162020-04-26 00:33:13 +0200140 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100141
142
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100143class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100144 """Track files with bad permissions.
145
146 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000147
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100148 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000149
150 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-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 Greenda02eb32018-02-28 10:02:55 +0000154 self.files_with_issues[filepath] = None
155
156
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100157class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000160
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100161 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000162
Gilles Peskine986a06d2020-05-10 16:57:59 +0200163 path_exemptions = BINARY_FILE_PATH_RE
164
Darryl Greenda02eb32018-02-28 10:02:55 +0000165 def check_file_for_issue(self, filepath):
166 with open(filepath, "rb") as f:
Gilles Peskinebe76c192020-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 Greenda02eb32018-02-28 10:02:55 +0000175 self.files_with_issues[filepath] = None
176
177
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100178class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000181
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100182 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000183
Gilles Peskine45137612020-05-10 16:52:44 +0200184 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine986a06d2020-05-10 16:57:59 +0200185 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine227dfd42020-03-24 22:26:01 +0100186
Darryl Greenda02eb32018-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 Peskine227dfd42020-03-24 22:26:01 +0100193class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100194 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000195
Gilles Peskine227dfd42020-03-24 22:26:01 +0100196 heading = "Non-Unix line endings:"
197
198 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200199 if not super().should_check_file(filepath):
200 return False
Gilles Peskine227dfd42020-03-24 22:26:01 +0100201 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000202
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100203 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000204 return b"\r" in line
205
206
Gilles Peskine783da632020-03-24 22:29:11 +0100207class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200208 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100209
210 heading = "Non-Windows line endings:"
211
212 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200213 if not super().should_check_file(filepath):
214 return False
Gilles Peskine783da632020-03-24 22:29:11 +0100215 return is_windows_file(filepath)
216
217 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200218 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100219
220
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100221class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100222 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000223
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100224 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200225 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000226
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100227 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000228 return line.rstrip(b"\r\n") != line.rstrip()
229
230
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100231class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100232 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000233
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100234 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200235 suffix_exemptions = frozenset([
Gilles Peskine227dfd42020-03-24 22:26:01 +0100236 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100237 "/Makefile",
238 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100239 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000240
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100241 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000242 return b"\t" in line
243
244
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100245class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100246 """Track lines with merge artifacts.
247 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100248
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100249 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100250
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100251 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100252 # Detect leftover git conflict markers.
253 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
254 return True
255 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
256 return True
257 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100258 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100259 return True
260 return False
261
Darryl Greenda02eb32018-02-28 10:02:55 +0000262
Gilles Peskineb5847d22020-03-24 18:25:17 +0100263class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100264 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000265
266 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100267 """Instantiate the sanity checker.
268 Check files under the current directory.
269 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000270 self.check_repo_path()
271 self.logger = None
272 self.setup_logger(log_file)
Darryl Greenda02eb32018-02-28 10:02:55 +0000273 self.issues_to_check = [
274 PermissionIssueTracker(),
275 EndOfFileNewlineIssueTracker(),
276 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100277 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100278 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000279 TrailingWhitespaceIssueTracker(),
280 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100281 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000282 ]
283
Gilles Peskine4fb66782019-02-25 20:35:31 +0100284 @staticmethod
285 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000286 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
287 raise Exception("Must be run from Mbed TLS root")
288
289 def setup_logger(self, log_file, level=logging.INFO):
290 self.logger = logging.getLogger()
291 self.logger.setLevel(level)
292 if log_file:
293 handler = logging.FileHandler(log_file)
294 self.logger.addHandler(handler)
295 else:
296 console = logging.StreamHandler()
297 self.logger.addHandler(console)
298
Gilles Peskine4bda3252020-05-10 17:18:06 +0200299 @staticmethod
300 def collect_files():
301 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
302 bytes_filepaths = bytes_output.split(b'\0')[:-1]
303 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
304 # Prepend './' to files in the top-level directory so that
305 # something like `'/Makefile' in fp` matches in the top-level
306 # directory as well as in subdirectories.
307 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
308 for fp in ascii_filepaths]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200309
Darryl Greenda02eb32018-02-28 10:02:55 +0000310 def check_files(self):
Gilles Peskine4bda3252020-05-10 17:18:06 +0200311 for issue_to_check in self.issues_to_check:
312 for filepath in self.collect_files():
313 if issue_to_check.should_check_file(filepath):
314 issue_to_check.check_file_for_issue(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000315
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()