blob: 4438cf18d6d92b1c63eb2db43ffe2e6884956a46 [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
Darryl Green10d9ce32018-02-28 10:02:55 +000018import sys
19
20
Gilles Peskine184c0962020-03-24 18:25:17 +010021class FileIssueTracker:
Gilles Peskine6ee576e2019-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 Peskine1e9698a2019-02-25 21:10:04 +010025 this class and implement `check_file_for_issue` and define ``heading``.
26
Gilles Peskine05a51a82020-05-10 16:52:44 +020027 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010028 will not be checked.
29
Gilles Peskine0598db82020-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 Peskine1e9698a2019-02-25 21:10:04 +010035 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010036 """
Darryl Green10d9ce32018-02-28 10:02:55 +000037
Gilles Peskine05a51a82020-05-10 16:52:44 +020038 suffix_exemptions = frozenset()
Gilles Peskine0598db82020-05-10 16:57:16 +020039 path_exemptions = None
Gilles Peskine1e9698a2019-02-25 21:10:04 +010040 # heading must be defined in derived classes.
41 # pylint: disable=no-member
42
Darryl Green10d9ce32018-02-28 10:02:55 +000043 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000044 self.files_with_issues = {}
45
Gilles Peskine0598db82020-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 Green10d9ce32018-02-28 10:02:55 +000055 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010056 """Whether the given file name should be checked.
57
Gilles Peskine05a51a82020-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 Peskineaaee4442020-03-24 16:49:21 +010060 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020061 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000062 if filepath.endswith(files_exemption):
63 return False
Gilles Peskine0598db82020-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 Green10d9ce32018-02-28 10:02:55 +000067 return True
68
Darryl Green10d9ce32018-02-28 10:02:55 +000069 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-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 Peskine6ee576e2019-02-25 20:59:05 +010074 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000075
Gilles Peskine04398052018-11-23 21:11:30 +010076 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010077 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-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 Green10d9ce32018-02-28 10:02:55 +000082 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +010083 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-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 Peskine6ee576e2019-02-25 20:59:05 +010095class LineIssueTracker(FileIssueTracker):
96 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +000097
Gilles Peskine6ee576e2019-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 Peskineaaee4442020-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 Peskine6ee576e2019-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 Peskineaaee4442020-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 Peskine6ee576e2019-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 Peskine2c618732020-03-24 22:26:01 +0100122
123def is_windows_file(filepath):
124 _root, ext = os.path.splitext(filepath)
Gilles Peskineaf387e02020-04-26 00:33:13 +0200125 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100126
127
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100128class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100129 """Track files with bad permissions.
130
131 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000132
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100133 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000134
135 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-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 Green10d9ce32018-02-28 10:02:55 +0000139 self.files_with_issues[filepath] = None
140
141
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100142class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-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 Green10d9ce32018-02-28 10:02:55 +0000145
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100146 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-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 Peskine6ee576e2019-02-25 20:59:05 +0100154class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-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 Green10d9ce32018-02-28 10:02:55 +0000157
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100158 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000159
Gilles Peskine05a51a82020-05-10 16:52:44 +0200160 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine2c618732020-03-24 22:26:01 +0100161
Darryl Green10d9ce32018-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 Peskine2c618732020-03-24 22:26:01 +0100168class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100169 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000170
Gilles Peskine2c618732020-03-24 22:26:01 +0100171 heading = "Non-Unix line endings:"
172
173 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200174 if not super().should_check_file(filepath):
175 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100176 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000177
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100178 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000179 return b"\r" in line
180
181
Gilles Peskine545e13f2020-03-24 22:29:11 +0100182class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200183 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100184
185 heading = "Non-Windows line endings:"
186
187 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200188 if not super().should_check_file(filepath):
189 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100190 return is_windows_file(filepath)
191
192 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200193 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100194
195
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100196class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100197 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000198
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100199 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200200 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000201
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100202 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000203 return line.rstrip(b"\r\n") != line.rstrip()
204
205
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100206class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100207 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000208
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100209 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200210 suffix_exemptions = frozenset([
Gilles Peskine2c618732020-03-24 22:26:01 +0100211 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100212 "/Makefile",
213 "/Makefile.inc",
214 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100215 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000216
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100217 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000218 return b"\t" in line
219
220
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100221class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100222 """Track lines with merge artifacts.
223 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100224
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100225 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100226
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100227 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100228 # Detect leftover git conflict markers.
229 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
230 return True
231 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
232 return True
233 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100234 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100235 return True
236 return False
237
Darryl Green10d9ce32018-02-28 10:02:55 +0000238
Gilles Peskine184c0962020-03-24 18:25:17 +0100239class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100240 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000241
242 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100243 """Instantiate the sanity checker.
244 Check files under the current directory.
245 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000246 self.check_repo_path()
247 self.logger = None
248 self.setup_logger(log_file)
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100249 self.excluded_directories = [
250 '.git',
251 'mbed-os',
252 ]
Gilles Peskine95c55752018-09-28 11:48:10 +0200253 self.excluded_paths = list(map(os.path.normpath, [
254 'cov-int',
255 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200256 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000257 self.issues_to_check = [
258 PermissionIssueTracker(),
259 EndOfFileNewlineIssueTracker(),
260 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100261 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100262 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000263 TrailingWhitespaceIssueTracker(),
264 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100265 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000266 ]
267
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100268 @staticmethod
269 def check_repo_path():
Darryl Green10d9ce32018-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 Peskine95c55752018-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 Green10d9ce32018-02-28 10:02:55 +0000290 def check_files(self):
Gilles Peskine95c55752018-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 Green10d9ce32018-02-28 10:02:55 +0000293 for filename in sorted(files):
294 filepath = os.path.join(root, filename)
Darryl Green10d9ce32018-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 Peskine7dfcfce2019-07-04 19:31:02 +0200309 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-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()