blob: 11073f5e9225c2656d4c88f4244b1ce586e64a5c [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
17import sys
18
19
Gilles Peskineb5847d22020-03-24 18:25:17 +010020class FileIssueTracker:
Gilles Peskine7194ecb2019-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 Peskinefb8c3732019-02-25 21:10:04 +010024 this class and implement `check_file_for_issue` and define ``heading``.
25
Gilles Peskine45137612020-05-10 16:52:44 +020026 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskinefb8c3732019-02-25 21:10:04 +010027 will not be checked.
28
29 ``heading``: human-readable description of the issue
Gilles Peskine7194ecb2019-02-25 20:59:05 +010030 """
Darryl Greenda02eb32018-02-28 10:02:55 +000031
Gilles Peskine45137612020-05-10 16:52:44 +020032 suffix_exemptions = frozenset()
Gilles Peskinefb8c3732019-02-25 21:10:04 +010033 # heading must be defined in derived classes.
34 # pylint: disable=no-member
35
Darryl Greenda02eb32018-02-28 10:02:55 +000036 def __init__(self):
Darryl Greenda02eb32018-02-28 10:02:55 +000037 self.files_with_issues = {}
38
39 def should_check_file(self, filepath):
Gilles Peskine558e26d2020-03-24 16:49:21 +010040 """Whether the given file name should be checked.
41
Gilles Peskine45137612020-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 Peskine558e26d2020-03-24 16:49:21 +010044 """
Gilles Peskine45137612020-05-10 16:52:44 +020045 for files_exemption in self.suffix_exemptions:
Darryl Greenda02eb32018-02-28 10:02:55 +000046 if filepath.endswith(files_exemption):
47 return False
48 return True
49
Darryl Greenda02eb32018-02-28 10:02:55 +000050 def check_file_for_issue(self, filepath):
Gilles Peskine558e26d2020-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 Peskine7194ecb2019-02-25 20:59:05 +010055 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +000056
Gilles Peskine232fae32018-11-23 21:11:30 +010057 def record_issue(self, filepath, line_number):
Gilles Peskine558e26d2020-03-24 16:49:21 +010058 """Record that an issue was found at the specified location."""
Gilles Peskine232fae32018-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 Greenda02eb32018-02-28 10:02:55 +000063 def output_file_issues(self, logger):
Gilles Peskine558e26d2020-03-24 16:49:21 +010064 """Log all the locations where the issue was found."""
Darryl Greenda02eb32018-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 Peskine7194ecb2019-02-25 20:59:05 +010076class LineIssueTracker(FileIssueTracker):
77 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +000078
Gilles Peskine7194ecb2019-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 Peskine558e26d2020-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 Peskine7194ecb2019-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 Peskine558e26d2020-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 Peskine7194ecb2019-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 Peskine227dfd42020-03-24 22:26:01 +0100103
104def is_windows_file(filepath):
105 _root, ext = os.path.splitext(filepath)
Gilles Peskine86e58162020-04-26 00:33:13 +0200106 return ext in ('.bat', '.dsp', '.sln', '.vcxproj')
Gilles Peskine227dfd42020-03-24 22:26:01 +0100107
108
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100109class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100110 """Track files with bad permissions.
111
112 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000113
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100114 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000115
116 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-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 Greenda02eb32018-02-28 10:02:55 +0000120 self.files_with_issues[filepath] = None
121
122
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100123class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000126
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100127 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-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 Peskine7194ecb2019-02-25 20:59:05 +0100135class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000138
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100139 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000140
Gilles Peskine45137612020-05-10 16:52:44 +0200141 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskine227dfd42020-03-24 22:26:01 +0100142
Darryl Greenda02eb32018-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 Peskine227dfd42020-03-24 22:26:01 +0100149class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100150 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000151
Gilles Peskine227dfd42020-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 Greenda02eb32018-02-28 10:02:55 +0000156
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100157 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000158 return b"\r" in line
159
160
Gilles Peskine783da632020-03-24 22:29:11 +0100161class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200162 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-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 Peskine70ef5c62020-04-01 13:35:46 +0200170 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100171
172
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100173class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100174 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000175
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100176 heading = "Trailing whitespace:"
Gilles Peskine45137612020-05-10 16:52:44 +0200177 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000178
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100179 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000180 return line.rstrip(b"\r\n") != line.rstrip()
181
182
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100183class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100184 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000185
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100186 heading = "Tabs present:"
Gilles Peskine45137612020-05-10 16:52:44 +0200187 suffix_exemptions = frozenset([
Gilles Peskine227dfd42020-03-24 22:26:01 +0100188 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100189 "/Makefile",
190 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100191 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000192
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100193 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000194 return b"\t" in line
195
196
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100197class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-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 Peskineda6ccfc2018-11-23 21:11:52 +0100200
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100201 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100202
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100203 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-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 Peskine7194ecb2019-02-25 20:59:05 +0100210 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100211 return True
212 return False
213
Darryl Greenda02eb32018-02-28 10:02:55 +0000214
Gilles Peskineb5847d22020-03-24 18:25:17 +0100215class IntegrityChecker:
Gilles Peskine4fb66782019-02-25 20:35:31 +0100216 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000217
218 def __init__(self, log_file):
Gilles Peskine4fb66782019-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 Greenda02eb32018-02-28 10:02:55 +0000222 self.check_repo_path()
223 self.logger = None
224 self.setup_logger(log_file)
Gilles Peskinec7153222020-03-24 22:05:02 +0100225 self.excluded_directories = [
226 '.git',
227 'mbed-os',
228 ]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200229 self.excluded_paths = list(map(os.path.normpath, [
230 'cov-int',
231 'examples',
232 'yotta/module'
233 ]))
Darryl Greenda02eb32018-02-28 10:02:55 +0000234 self.issues_to_check = [
235 PermissionIssueTracker(),
236 EndOfFileNewlineIssueTracker(),
237 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100238 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100239 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000240 TrailingWhitespaceIssueTracker(),
241 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100242 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000243 ]
244
Gilles Peskine4fb66782019-02-25 20:35:31 +0100245 @staticmethod
246 def check_repo_path():
Darryl Greenda02eb32018-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 Peskine3400b4d2018-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 Greenda02eb32018-02-28 10:02:55 +0000267 def check_files(self):
Gilles Peskine3400b4d2018-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 Greenda02eb32018-02-28 10:02:55 +0000270 for filename in sorted(files):
271 filepath = os.path.join(root, filename)
Darryl Greenda02eb32018-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 Peskine081daf02019-07-04 19:31:02 +0200286 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-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()