blob: 6bb61e6cd37df788dad50a34a147aa6798f4f7c1 [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
17import sys
18
19
Gilles Peskine184c0962020-03-24 18:25:17 +010020class FileIssueTracker:
Gilles Peskine6ee576e2019-02-25 20:59:05 +010021 """Base class for file-wide issue tracking.
22
23 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine1e9698a2019-02-25 21:10:04 +010024 this class and implement `check_file_for_issue` and define ``heading``.
25
Gilles Peskine05a51a82020-05-10 16:52:44 +020026 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010027 will not be checked.
28
29 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010030 """
Darryl Green10d9ce32018-02-28 10:02:55 +000031
Gilles Peskine05a51a82020-05-10 16:52:44 +020032 suffix_exemptions = frozenset()
Gilles Peskine1e9698a2019-02-25 21:10:04 +010033 # heading must be defined in derived classes.
34 # pylint: disable=no-member
35
Darryl Green10d9ce32018-02-28 10:02:55 +000036 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000037 self.files_with_issues = {}
38
39 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010040 """Whether the given file name should be checked.
41
Gilles Peskine05a51a82020-05-10 16:52:44 +020042 Files whose name ends with a string listed in ``self.suffix_exemptions``
43 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaaee4442020-03-24 16:49:21 +010044 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020045 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000046 if filepath.endswith(files_exemption):
47 return False
48 return True
49
Darryl Green10d9ce32018-02-28 10:02:55 +000050 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010051 """Check the specified file for the issue that this class is for.
52
53 Subclasses must implement this method.
54 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010055 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000056
Gilles Peskine04398052018-11-23 21:11:30 +010057 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010058 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010059 if filepath not in self.files_with_issues.keys():
60 self.files_with_issues[filepath] = []
61 self.files_with_issues[filepath].append(line_number)
62
Darryl Green10d9ce32018-02-28 10:02:55 +000063 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +010064 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +000065 if self.files_with_issues.values():
66 logger.info(self.heading)
67 for filename, lines in sorted(self.files_with_issues.items()):
68 if lines:
69 logger.info("{}: {}".format(
70 filename, ", ".join(str(x) for x in lines)
71 ))
72 else:
73 logger.info(filename)
74 logger.info("")
75
Gilles Peskine6ee576e2019-02-25 20:59:05 +010076class LineIssueTracker(FileIssueTracker):
77 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +000078
Gilles Peskine6ee576e2019-02-25 20:59:05 +010079 To implement a checker that processes files line by line, inherit from
80 this class and implement `line_with_issue`.
81 """
82
83 def issue_with_line(self, line, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010084 """Check the specified line for the issue that this class is for.
85
86 Subclasses must implement this method.
87 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010088 raise NotImplementedError
89
90 def check_file_line(self, filepath, line, line_number):
91 if self.issue_with_line(line, filepath):
92 self.record_issue(filepath, line_number)
93
94 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010095 """Check the lines of the specified file.
96
97 Subclasses must implement the ``issue_with_line`` method.
98 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010099 with open(filepath, "rb") as f:
100 for i, line in enumerate(iter(f.readline, b"")):
101 self.check_file_line(filepath, line, i + 1)
102
Gilles Peskine2c618732020-03-24 22:26:01 +0100103
104def is_windows_file(filepath):
105 _root, ext = os.path.splitext(filepath)
Gilles Peskineaf387e02020-04-26 00:33:13 +0200106 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100107
108
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100109class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100110 """Track files with bad permissions.
111
112 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000113
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100114 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000115
116 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100117 is_executable = os.access(filepath, os.X_OK)
118 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
119 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000120 self.files_with_issues[filepath] = None
121
122
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100123class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100124 """Track files that end with an incomplete line
125 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000126
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100127 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000128
129 def check_file_for_issue(self, filepath):
130 with open(filepath, "rb") as f:
131 if not f.read().endswith(b"\n"):
132 self.files_with_issues[filepath] = None
133
134
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100135class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100136 """Track files that start with a UTF-8 BOM.
137 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000138
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100139 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000140
Gilles Peskine05a51a82020-05-10 16:52:44 +0200141 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine2c618732020-03-24 22:26:01 +0100142
Darryl Green10d9ce32018-02-28 10:02:55 +0000143 def check_file_for_issue(self, filepath):
144 with open(filepath, "rb") as f:
145 if f.read().startswith(codecs.BOM_UTF8):
146 self.files_with_issues[filepath] = None
147
148
Gilles Peskine2c618732020-03-24 22:26:01 +0100149class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100150 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000151
Gilles Peskine2c618732020-03-24 22:26:01 +0100152 heading = "Non-Unix line endings:"
153
154 def should_check_file(self, filepath):
155 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000156
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100157 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000158 return b"\r" in line
159
160
Gilles Peskine545e13f2020-03-24 22:29:11 +0100161class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200162 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100163
164 heading = "Non-Windows line endings:"
165
166 def should_check_file(self, filepath):
167 return is_windows_file(filepath)
168
169 def issue_with_line(self, line, _filepath):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200170 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100171
172
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100173class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100174 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000175
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100176 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200177 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000178
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100179 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000180 return line.rstrip(b"\r\n") != line.rstrip()
181
182
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100183class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100184 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000185
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100186 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200187 suffix_exemptions = frozenset([
Gilles Peskine2c618732020-03-24 22:26:01 +0100188 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100189 "/Makefile",
190 "/Makefile.inc",
191 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100192 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000193
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100194 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000195 return b"\t" in line
196
197
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100198class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100199 """Track lines with merge artifacts.
200 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100201
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100202 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100203
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100204 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100205 # Detect leftover git conflict markers.
206 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
207 return True
208 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
209 return True
210 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100211 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100212 return True
213 return False
214
Darryl Green10d9ce32018-02-28 10:02:55 +0000215
Gilles Peskine184c0962020-03-24 18:25:17 +0100216class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100217 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000218
219 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100220 """Instantiate the sanity checker.
221 Check files under the current directory.
222 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000223 self.check_repo_path()
224 self.logger = None
225 self.setup_logger(log_file)
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100226 self.excluded_directories = [
227 '.git',
228 'mbed-os',
229 ]
Gilles Peskine95c55752018-09-28 11:48:10 +0200230 self.excluded_paths = list(map(os.path.normpath, [
231 'cov-int',
232 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200233 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000234 self.issues_to_check = [
235 PermissionIssueTracker(),
236 EndOfFileNewlineIssueTracker(),
237 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100238 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100239 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000240 TrailingWhitespaceIssueTracker(),
241 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100242 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000243 ]
244
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100245 @staticmethod
246 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000247 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
248 raise Exception("Must be run from Mbed TLS root")
249
250 def setup_logger(self, log_file, level=logging.INFO):
251 self.logger = logging.getLogger()
252 self.logger.setLevel(level)
253 if log_file:
254 handler = logging.FileHandler(log_file)
255 self.logger.addHandler(handler)
256 else:
257 console = logging.StreamHandler()
258 self.logger.addHandler(console)
259
Gilles Peskine95c55752018-09-28 11:48:10 +0200260 def prune_branch(self, root, d):
261 if d in self.excluded_directories:
262 return True
263 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
264 return True
265 return False
266
Darryl Green10d9ce32018-02-28 10:02:55 +0000267 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200268 for root, dirs, files in os.walk("."):
269 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000270 for filename in sorted(files):
271 filepath = os.path.join(root, filename)
Darryl Green10d9ce32018-02-28 10:02:55 +0000272 for issue_to_check in self.issues_to_check:
273 if issue_to_check.should_check_file(filepath):
274 issue_to_check.check_file_for_issue(filepath)
275
276 def output_issues(self):
277 integrity_return_code = 0
278 for issue_to_check in self.issues_to_check:
279 if issue_to_check.files_with_issues:
280 integrity_return_code = 1
281 issue_to_check.output_file_issues(self.logger)
282 return integrity_return_code
283
284
285def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200286 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000287 parser.add_argument(
288 "-l", "--log_file", type=str, help="path to optional output log",
289 )
290 check_args = parser.parse_args()
291 integrity_check = IntegrityChecker(check_args.log_file)
292 integrity_check.check_files()
293 return_code = integrity_check.output_issues()
294 sys.exit(return_code)
295
296
297if __name__ == "__main__":
298 run_main()