blob: 3992c46680768f369bc3f5de92235d00faeab5e2 [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 Peskine7194ecb2019-02-25 20:59:05 +010095class LineIssueTracker(FileIssueTracker):
96 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +000097
Gilles Peskine7194ecb2019-02-25 20:59:05 +010098 To implement a checker that processes files line by line, inherit from
99 this class and implement `line_with_issue`.
100 """
101
102 def issue_with_line(self, line, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100103 """Check the specified line for the issue that this class is for.
104
105 Subclasses must implement this method.
106 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100107 raise NotImplementedError
108
109 def check_file_line(self, filepath, line, line_number):
110 if self.issue_with_line(line, filepath):
111 self.record_issue(filepath, line_number)
112
113 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +0100114 """Check the lines of the specified file.
115
116 Subclasses must implement the ``issue_with_line`` method.
117 """
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100118 with open(filepath, "rb") as f:
119 for i, line in enumerate(iter(f.readline, b"")):
120 self.check_file_line(filepath, line, i + 1)
121
Gilles Peskine227dfd42020-03-24 22:26:01 +0100122
123def is_windows_file(filepath):
124 _root, ext = os.path.splitext(filepath)
Gilles Peskine86e58162020-04-26 00:33:13 +0200125 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100126
127
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100128class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100129 """Track files with bad permissions.
130
131 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000132
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100133 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000134
135 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +0100136 is_executable = os.access(filepath, os.X_OK)
137 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
138 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +0000139 self.files_with_issues[filepath] = None
140
141
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100142class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100143 """Track files that end with an incomplete line
144 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000145
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100146 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000147
148 def check_file_for_issue(self, filepath):
149 with open(filepath, "rb") as f:
150 if not f.read().endswith(b"\n"):
151 self.files_with_issues[filepath] = None
152
153
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100154class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100155 """Track files that start with a UTF-8 BOM.
156 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000157
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100158 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000159
Gilles Peskine45137612020-05-10 16:52:44 +0200160 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine227dfd42020-03-24 22:26:01 +0100161
Darryl Greenda02eb32018-02-28 10:02:55 +0000162 def check_file_for_issue(self, filepath):
163 with open(filepath, "rb") as f:
164 if f.read().startswith(codecs.BOM_UTF8):
165 self.files_with_issues[filepath] = None
166
167
Gilles Peskine227dfd42020-03-24 22:26:01 +0100168class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100169 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000170
Gilles Peskine227dfd42020-03-24 22:26:01 +0100171 heading = "Non-Unix line endings:"
172
173 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200174 if not super().should_check_file(filepath):
175 return False
Gilles Peskine227dfd42020-03-24 22:26:01 +0100176 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000177
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100178 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000179 return b"\r" in line
180
181
Gilles Peskine783da632020-03-24 22:29:11 +0100182class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200183 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100184
185 heading = "Non-Windows line endings:"
186
187 def should_check_file(self, filepath):
Gilles Peskineb4805ec2020-05-10 16:57:16 +0200188 if not super().should_check_file(filepath):
189 return False
Gilles Peskine783da632020-03-24 22:29:11 +0100190 return is_windows_file(filepath)
191
192 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200193 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100194
195
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100196class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100197 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000198
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100199 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200200 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000201
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100202 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000203 return line.rstrip(b"\r\n") != line.rstrip()
204
205
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100206class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100207 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000208
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100209 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200210 suffix_exemptions = frozenset([
Gilles Peskine227dfd42020-03-24 22:26:01 +0100211 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100212 "/Makefile",
213 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100214 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000215
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100216 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000217 return b"\t" in line
218
219
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100220class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100221 """Track lines with merge artifacts.
222 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100223
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100224 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100225
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100226 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100227 # Detect leftover git conflict markers.
228 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
229 return True
230 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
231 return True
232 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100233 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100234 return True
235 return False
236
Darryl Greenda02eb32018-02-28 10:02:55 +0000237
Gilles Peskineb5847d22020-03-24 18:25:17 +0100238class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100239 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000240
241 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100242 """Instantiate the sanity checker.
243 Check files under the current directory.
244 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000245 self.check_repo_path()
246 self.logger = None
247 self.setup_logger(log_file)
Gilles Peskinec7153222020-03-24 22:05:02 +0100248 self.excluded_directories = [
249 '.git',
250 'mbed-os',
251 ]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200252 self.excluded_paths = list(map(os.path.normpath, [
253 'cov-int',
254 'examples',
255 'yotta/module'
256 ]))
Darryl Greenda02eb32018-02-28 10:02:55 +0000257 self.issues_to_check = [
258 PermissionIssueTracker(),
259 EndOfFileNewlineIssueTracker(),
260 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100261 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100262 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000263 TrailingWhitespaceIssueTracker(),
264 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100265 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000266 ]
267
Gilles Peskine4fb66782019-02-25 20:35:31 +0100268 @staticmethod
269 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000270 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
271 raise Exception("Must be run from Mbed TLS root")
272
273 def setup_logger(self, log_file, level=logging.INFO):
274 self.logger = logging.getLogger()
275 self.logger.setLevel(level)
276 if log_file:
277 handler = logging.FileHandler(log_file)
278 self.logger.addHandler(handler)
279 else:
280 console = logging.StreamHandler()
281 self.logger.addHandler(console)
282
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200283 def prune_branch(self, root, d):
284 if d in self.excluded_directories:
285 return True
286 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
287 return True
288 return False
289
Darryl Greenda02eb32018-02-28 10:02:55 +0000290 def check_files(self):
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200291 for root, dirs, files in os.walk("."):
292 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Greenda02eb32018-02-28 10:02:55 +0000293 for filename in sorted(files):
294 filepath = os.path.join(root, filename)
Darryl Greenda02eb32018-02-28 10:02:55 +0000295 for issue_to_check in self.issues_to_check:
296 if issue_to_check.should_check_file(filepath):
297 issue_to_check.check_file_for_issue(filepath)
298
299 def output_issues(self):
300 integrity_return_code = 0
301 for issue_to_check in self.issues_to_check:
302 if issue_to_check.files_with_issues:
303 integrity_return_code = 1
304 issue_to_check.output_file_issues(self.logger)
305 return integrity_return_code
306
307
308def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200309 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000310 parser.add_argument(
311 "-l", "--log_file", type=str, help="path to optional output log",
312 )
313 check_args = parser.parse_args()
314 integrity_check = IntegrityChecker(check_args.log_file)
315 integrity_check.check_files()
316 return_code = integrity_check.output_issues()
317 sys.exit(return_code)
318
319
320if __name__ == "__main__":
321 run_main()