blob: 50a817b9b90a80caa97ca2ca8a64629dd0c984ee [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine79cfef02019-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 Peskine47d7c2d2019-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
Andrzej Kurek825ebd42020-05-18 11:47:25 -040020class FileIssueTracker:
Gilles Peskined5240ec2019-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 Peskine21e85f72019-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 Peskined5240ec2019-02-25 20:59:05 +010030 """
Darryl Green10d9ce32018-02-28 10:02:55 +000031
Gilles Peskine21e85f72019-02-25 21:10:04 +010032 files_exemptions = frozenset()
33 # heading must be defined in derived classes.
34 # pylint: disable=no-member
Darryl Green10d9ce32018-02-28 10:02:55 +000035
36 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000037 self.files_with_issues = {}
38
39 def should_check_file(self, filepath):
Andrzej Kurek825ebd42020-05-18 11:47:25 -040040 """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):
Andrzej Kurek825ebd42020-05-18 11:47:25 -040051 """Check the specified file for the issue that this class is for.
52
53 Subclasses must implement this method.
54 """
Gilles Peskined5240ec2019-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):
Andrzej Kurek825ebd42020-05-18 11:47:25 -040058 """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):
Andrzej Kurek825ebd42020-05-18 11:47:25 -040064 """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 Peskined5240ec2019-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 Peskined5240ec2019-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 """
Darryl Green10d9ce32018-02-28 10:02:55 +000082
Gilles Peskined5240ec2019-02-25 20:59:05 +010083 def issue_with_line(self, line, filepath):
Andrzej Kurek825ebd42020-05-18 11:47:25 -040084 """Check the specified line for the issue that this class is for.
85
86 Subclasses must implement this method.
87 """
Gilles Peskined5240ec2019-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)
Darryl Green10d9ce32018-02-28 10:02:55 +000093
94 def check_file_for_issue(self, filepath):
Andrzej Kurek825ebd42020-05-18 11:47:25 -040095 """Check the lines of the specified file.
96
97 Subclasses must implement the ``issue_with_line`` method.
98 """
Gilles Peskined5240ec2019-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
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400103
104def is_windows_file(filepath):
105 _root, ext = os.path.splitext(filepath)
106 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
107
108
Gilles Peskined5240ec2019-02-25 20:59:05 +0100109class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-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 Peskine21e85f72019-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 Peskine6fc52152019-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 Peskined5240ec2019-02-25 20:59:05 +0100123class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-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 Peskine21e85f72019-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 Peskined5240ec2019-02-25 20:59:05 +0100135class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-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 Peskine21e85f72019-02-25 21:10:04 +0100139 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000140
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400141 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
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400149class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-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
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400152 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 Peskined5240ec2019-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
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400161class WindowsLineEndingIssueTracker(LineIssueTracker):
162 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
163
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):
170 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
171
172
Gilles Peskined5240ec2019-02-25 20:59:05 +0100173class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100174 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000175
Gilles Peskine21e85f72019-02-25 21:10:04 +0100176 heading = "Trailing whitespace:"
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400177 files_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000178
Gilles Peskined5240ec2019-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 Peskined5240ec2019-02-25 20:59:05 +0100183class TabIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100184 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000185
Gilles Peskine21e85f72019-02-25 21:10:04 +0100186 heading = "Tabs present:"
187 files_exemptions = frozenset([
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400188 ".sln",
189 "/Makefile",
190 "/generate_visualc_files.pl",
Gilles Peskine21e85f72019-02-25 21:10:04 +0100191 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000192
Gilles Peskined5240ec2019-02-25 20:59:05 +0100193 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000194 return b"\t" in line
195
196
Gilles Peskined5240ec2019-02-25 20:59:05 +0100197class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100198 """Track lines with merge artifacts.
199 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100200
Gilles Peskine21e85f72019-02-25 21:10:04 +0100201 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100202
Gilles Peskined5240ec2019-02-25 20:59:05 +0100203 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100204 # Detect leftover git conflict markers.
205 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
206 return True
207 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
208 return True
209 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskined5240ec2019-02-25 20:59:05 +0100210 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100211 return True
212 return False
213
Darryl Green10d9ce32018-02-28 10:02:55 +0000214
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400215class IntegrityChecker:
Gilles Peskine76605492019-02-25 20:35:31 +0100216 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000217
218 def __init__(self, log_file):
Gilles Peskine76605492019-02-25 20:35:31 +0100219 """Instantiate the sanity checker.
220 Check files under the current directory.
221 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000222 self.check_repo_path()
223 self.logger = None
224 self.setup_logger(log_file)
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400225 self.extensions_to_check = (
226 ".bat",
227 ".c",
228 ".data",
229 ".dsp",
230 ".function",
231 ".h",
232 ".md",
233 ".pl",
234 ".py",
235 ".sh",
236 ".sln",
237 ".vcxproj",
238 "/CMakeLists.txt",
239 "/ChangeLog",
240 "/Makefile",
Darryl Green10d9ce32018-02-28 10:02:55 +0000241 )
Jarno Lamsa02493af2019-04-25 14:56:17 +0300242 self.excluded_directories = ['.git', 'mbed-os', 'tinycrypt']
Gilles Peskine95c55752018-09-28 11:48:10 +0200243 self.excluded_paths = list(map(os.path.normpath, [
244 'cov-int',
245 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200246 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000247 self.issues_to_check = [
248 PermissionIssueTracker(),
249 EndOfFileNewlineIssueTracker(),
250 Utf8BomIssueTracker(),
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400251 UnixLineEndingIssueTracker(),
252 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000253 TrailingWhitespaceIssueTracker(),
254 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100255 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000256 ]
257
Gilles Peskine76605492019-02-25 20:35:31 +0100258 @staticmethod
259 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000260 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
261 raise Exception("Must be run from Mbed TLS root")
262
263 def setup_logger(self, log_file, level=logging.INFO):
264 self.logger = logging.getLogger()
265 self.logger.setLevel(level)
266 if log_file:
267 handler = logging.FileHandler(log_file)
268 self.logger.addHandler(handler)
269 else:
270 console = logging.StreamHandler()
271 self.logger.addHandler(console)
272
Gilles Peskine95c55752018-09-28 11:48:10 +0200273 def prune_branch(self, root, d):
274 if d in self.excluded_directories:
275 return True
276 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
277 return True
278 return False
279
Darryl Green10d9ce32018-02-28 10:02:55 +0000280 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200281 for root, dirs, files in os.walk("."):
282 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000283 for filename in sorted(files):
284 filepath = os.path.join(root, filename)
Andrzej Kurek825ebd42020-05-18 11:47:25 -0400285 if not filepath.endswith(self.extensions_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000286 continue
287 for issue_to_check in self.issues_to_check:
288 if issue_to_check.should_check_file(filepath):
289 issue_to_check.check_file_for_issue(filepath)
290
291 def output_issues(self):
292 integrity_return_code = 0
293 for issue_to_check in self.issues_to_check:
294 if issue_to_check.files_with_issues:
295 integrity_return_code = 1
296 issue_to_check.output_file_issues(self.logger)
297 return integrity_return_code
298
299
300def run_main():
Gilles Peskine79cfef02019-07-04 19:31:02 +0200301 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000302 parser.add_argument(
303 "-l", "--log_file", type=str, help="path to optional output log",
304 )
305 check_args = parser.parse_args()
306 integrity_check = IntegrityChecker(check_args.log_file)
307 integrity_check.check_files()
308 return_code = integrity_check.output_issues()
309 sys.exit(return_code)
310
311
312if __name__ == "__main__":
313 run_main()