blob: e8abd751e736bd285bc70083f7d24009b5238f8e [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
26 ``files_exemptions``: files whose name ends with a string in this set
27 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 Peskine1e9698a2019-02-25 21:10:04 +010032 files_exemptions = frozenset()
33 # 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
42 Files whose name ends with a string listed in ``self.files_exemptions``
43 will not be checked.
44 """
Darryl Green10d9ce32018-02-28 10:02:55 +000045 for files_exemption in self.files_exemptions:
46 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 Peskine2c618732020-03-24 22:26:01 +0100141 files_exemptions = frozenset([".vcxproj", ".sln"])
142
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 Peskine2c618732020-03-24 22:26:01 +0100177 files_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:"
187 files_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 Peskine6e8d5a02020-03-24 22:01:28 +0100226 self.extensions_to_check = (
Gilles Peskineaf387e02020-04-26 00:33:13 +0200227 ".bat",
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100228 ".c",
Gilles Peskine5308f122020-03-24 22:05:41 +0100229 ".data",
Gilles Peskine2c618732020-03-24 22:26:01 +0100230 ".dsp",
Gilles Peskine5308f122020-03-24 22:05:41 +0100231 ".function",
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100232 ".h",
Gilles Peskine5308f122020-03-24 22:05:41 +0100233 ".md",
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100234 ".pl",
235 ".py",
Gilles Peskine5308f122020-03-24 22:05:41 +0100236 ".sh",
Gilles Peskine2c618732020-03-24 22:26:01 +0100237 ".sln",
238 ".vcxproj",
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100239 "/CMakeLists.txt",
240 "/ChangeLog",
Gilles Peskine5308f122020-03-24 22:05:41 +0100241 "/Makefile",
242 "/Makefile.inc",
Darryl Green10d9ce32018-02-28 10:02:55 +0000243 )
Gilles Peskine6a45d1e2020-03-24 22:05:02 +0100244 self.excluded_directories = [
245 '.git',
246 'mbed-os',
247 ]
Gilles Peskine95c55752018-09-28 11:48:10 +0200248 self.excluded_paths = list(map(os.path.normpath, [
249 'cov-int',
250 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200251 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000252 self.issues_to_check = [
253 PermissionIssueTracker(),
254 EndOfFileNewlineIssueTracker(),
255 Utf8BomIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100256 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100257 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000258 TrailingWhitespaceIssueTracker(),
259 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100260 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000261 ]
262
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100263 @staticmethod
264 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000265 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
266 raise Exception("Must be run from Mbed TLS root")
267
268 def setup_logger(self, log_file, level=logging.INFO):
269 self.logger = logging.getLogger()
270 self.logger.setLevel(level)
271 if log_file:
272 handler = logging.FileHandler(log_file)
273 self.logger.addHandler(handler)
274 else:
275 console = logging.StreamHandler()
276 self.logger.addHandler(console)
277
Gilles Peskine95c55752018-09-28 11:48:10 +0200278 def prune_branch(self, root, d):
279 if d in self.excluded_directories:
280 return True
281 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
282 return True
283 return False
284
Darryl Green10d9ce32018-02-28 10:02:55 +0000285 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200286 for root, dirs, files in os.walk("."):
287 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000288 for filename in sorted(files):
289 filepath = os.path.join(root, filename)
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100290 if not filepath.endswith(self.extensions_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000291 continue
292 for issue_to_check in self.issues_to_check:
293 if issue_to_check.should_check_file(filepath):
294 issue_to_check.check_file_for_issue(filepath)
295
296 def output_issues(self):
297 integrity_return_code = 0
298 for issue_to_check in self.issues_to_check:
299 if issue_to_check.files_with_issues:
300 integrity_return_code = 1
301 issue_to_check.output_file_issues(self.logger)
302 return integrity_return_code
303
304
305def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200306 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000307 parser.add_argument(
308 "-l", "--log_file", type=str, help="path to optional output log",
309 )
310 check_args = parser.parse_args()
311 integrity_check = IntegrityChecker(check_args.log_file)
312 integrity_check.check_files()
313 return_code = integrity_check.output_issues()
314 sys.exit(return_code)
315
316
317if __name__ == "__main__":
318 run_main()