blob: b42a43988d8c23011f5d57200855e0d309f53cf2 [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 Peskine7194ecb2019-02-25 20:59:05 +010020class FileIssueTracker(object):
21 """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
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 Peskine7194ecb2019-02-25 20:59:05 +010030 """
Darryl Greenda02eb32018-02-28 10:02:55 +000031
Gilles Peskinefb8c3732019-02-25 21:10:04 +010032 files_exemptions = frozenset()
33 # 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):
40 for files_exemption in self.files_exemptions:
41 if filepath.endswith(files_exemption):
42 return False
43 return True
44
Darryl Greenda02eb32018-02-28 10:02:55 +000045 def check_file_for_issue(self, filepath):
Gilles Peskine7194ecb2019-02-25 20:59:05 +010046 raise NotImplementedError
Darryl Greenda02eb32018-02-28 10:02:55 +000047
Gilles Peskine232fae32018-11-23 21:11:30 +010048 def record_issue(self, filepath, line_number):
49 if filepath not in self.files_with_issues.keys():
50 self.files_with_issues[filepath] = []
51 self.files_with_issues[filepath].append(line_number)
52
Darryl Greenda02eb32018-02-28 10:02:55 +000053 def output_file_issues(self, logger):
54 if self.files_with_issues.values():
55 logger.info(self.heading)
56 for filename, lines in sorted(self.files_with_issues.items()):
57 if lines:
58 logger.info("{}: {}".format(
59 filename, ", ".join(str(x) for x in lines)
60 ))
61 else:
62 logger.info(filename)
63 logger.info("")
64
Gilles Peskine7194ecb2019-02-25 20:59:05 +010065class LineIssueTracker(FileIssueTracker):
66 """Base class for line-by-line issue tracking.
Darryl Greenda02eb32018-02-28 10:02:55 +000067
Gilles Peskine7194ecb2019-02-25 20:59:05 +010068 To implement a checker that processes files line by line, inherit from
69 this class and implement `line_with_issue`.
70 """
71
72 def issue_with_line(self, line, filepath):
73 raise NotImplementedError
74
75 def check_file_line(self, filepath, line, line_number):
76 if self.issue_with_line(line, filepath):
77 self.record_issue(filepath, line_number)
78
79 def check_file_for_issue(self, filepath):
80 with open(filepath, "rb") as f:
81 for i, line in enumerate(iter(f.readline, b"")):
82 self.check_file_line(filepath, line, i + 1)
83
Gilles Peskine227dfd42020-03-24 22:26:01 +010084
85def is_windows_file(filepath):
86 _root, ext = os.path.splitext(filepath)
87 return ext in ('.dsp', '.sln', '.vcxproj')
88
89
Gilles Peskine7194ecb2019-02-25 20:59:05 +010090class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010091 """Track files with bad permissions.
92
93 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +000094
Gilles Peskinefb8c3732019-02-25 21:10:04 +010095 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +000096
97 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +010098 is_executable = os.access(filepath, os.X_OK)
99 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
100 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +0000101 self.files_with_issues[filepath] = None
102
103
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100104class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100105 """Track files that end with an incomplete line
106 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000107
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100108 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000109
110 def check_file_for_issue(self, filepath):
111 with open(filepath, "rb") as f:
112 if not f.read().endswith(b"\n"):
113 self.files_with_issues[filepath] = None
114
115
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100116class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100117 """Track files that start with a UTF-8 BOM.
118 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000119
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100120 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000121
Gilles Peskine227dfd42020-03-24 22:26:01 +0100122 files_exemptions = frozenset([".vcxproj", ".sln"])
123
Darryl Greenda02eb32018-02-28 10:02:55 +0000124 def check_file_for_issue(self, filepath):
125 with open(filepath, "rb") as f:
126 if f.read().startswith(codecs.BOM_UTF8):
127 self.files_with_issues[filepath] = None
128
129
Gilles Peskine227dfd42020-03-24 22:26:01 +0100130class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100131 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000132
Gilles Peskine227dfd42020-03-24 22:26:01 +0100133 heading = "Non-Unix line endings:"
134
135 def should_check_file(self, filepath):
136 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000137
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100138 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000139 return b"\r" in line
140
141
Gilles Peskine783da632020-03-24 22:29:11 +0100142class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200143 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine783da632020-03-24 22:29:11 +0100144
145 heading = "Non-Windows line endings:"
146
147 def should_check_file(self, filepath):
148 return is_windows_file(filepath)
149
150 def issue_with_line(self, line, _filepath):
Gilles Peskine70ef5c62020-04-01 13:35:46 +0200151 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine783da632020-03-24 22:29:11 +0100152
153
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100154class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100155 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000156
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100157 heading = "Trailing whitespace:"
Gilles Peskine227dfd42020-03-24 22:26:01 +0100158 files_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000159
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100160 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000161 return line.rstrip(b"\r\n") != line.rstrip()
162
163
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100164class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100165 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000166
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100167 heading = "Tabs present:"
168 files_exemptions = frozenset([
Gilles Peskine227dfd42020-03-24 22:26:01 +0100169 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100170 "/Makefile",
171 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100172 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000173
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100174 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000175 return b"\t" in line
176
177
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100178class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100179 """Track lines with merge artifacts.
180 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100181
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100182 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100183
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100184 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100185 # Detect leftover git conflict markers.
186 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
187 return True
188 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
189 return True
190 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100191 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100192 return True
193 return False
194
Darryl Greenda02eb32018-02-28 10:02:55 +0000195
196class IntegrityChecker(object):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100197 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000198
199 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100200 """Instantiate the sanity checker.
201 Check files under the current directory.
202 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000203 self.check_repo_path()
204 self.logger = None
205 self.setup_logger(log_file)
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100206 self.extensions_to_check = (
Gilles Peskinec7153222020-03-24 22:05:02 +0100207 ".c",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100208 ".data",
Gilles Peskine227dfd42020-03-24 22:26:01 +0100209 ".dsp",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100210 ".function",
Gilles Peskinec7153222020-03-24 22:05:02 +0100211 ".h",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100212 ".md",
Gilles Peskinec7153222020-03-24 22:05:02 +0100213 ".pl",
214 ".py",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100215 ".sh",
Gilles Peskine227dfd42020-03-24 22:26:01 +0100216 ".sln",
217 ".vcxproj",
Gilles Peskinec7153222020-03-24 22:05:02 +0100218 "/CMakeLists.txt",
219 "/ChangeLog",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100220 "/Makefile",
Darryl Greenda02eb32018-02-28 10:02:55 +0000221 )
Gilles Peskinec7153222020-03-24 22:05:02 +0100222 self.excluded_directories = [
223 '.git',
224 'mbed-os',
225 ]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200226 self.excluded_paths = list(map(os.path.normpath, [
227 'cov-int',
228 'examples',
229 'yotta/module'
230 ]))
Darryl Greenda02eb32018-02-28 10:02:55 +0000231 self.issues_to_check = [
232 PermissionIssueTracker(),
233 EndOfFileNewlineIssueTracker(),
234 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100235 UnixLineEndingIssueTracker(),
Gilles Peskine783da632020-03-24 22:29:11 +0100236 WindowsLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000237 TrailingWhitespaceIssueTracker(),
238 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100239 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000240 ]
241
Gilles Peskine4fb66782019-02-25 20:35:31 +0100242 @staticmethod
243 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000244 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
245 raise Exception("Must be run from Mbed TLS root")
246
247 def setup_logger(self, log_file, level=logging.INFO):
248 self.logger = logging.getLogger()
249 self.logger.setLevel(level)
250 if log_file:
251 handler = logging.FileHandler(log_file)
252 self.logger.addHandler(handler)
253 else:
254 console = logging.StreamHandler()
255 self.logger.addHandler(console)
256
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200257 def prune_branch(self, root, d):
258 if d in self.excluded_directories:
259 return True
260 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
261 return True
262 return False
263
Darryl Greenda02eb32018-02-28 10:02:55 +0000264 def check_files(self):
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200265 for root, dirs, files in os.walk("."):
266 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Greenda02eb32018-02-28 10:02:55 +0000267 for filename in sorted(files):
268 filepath = os.path.join(root, filename)
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100269 if not filepath.endswith(self.extensions_to_check):
Darryl Greenda02eb32018-02-28 10:02:55 +0000270 continue
271 for issue_to_check in self.issues_to_check:
272 if issue_to_check.should_check_file(filepath):
273 issue_to_check.check_file_for_issue(filepath)
274
275 def output_issues(self):
276 integrity_return_code = 0
277 for issue_to_check in self.issues_to_check:
278 if issue_to_check.files_with_issues:
279 integrity_return_code = 1
280 issue_to_check.output_file_issues(self.logger)
281 return integrity_return_code
282
283
284def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200285 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000286 parser.add_argument(
287 "-l", "--log_file", type=str, help="path to optional output log",
288 )
289 check_args = parser.parse_args()
290 integrity_check = IntegrityChecker(check_args.log_file)
291 integrity_check.check_files()
292 return_code = integrity_check.output_issues()
293 sys.exit(return_code)
294
295
296if __name__ == "__main__":
297 run_main()