blob: cb413c960c031ef3fc25b4efd1e40a875c59b23f [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
Gilles Peskined5240ec2019-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 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
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):
40 for files_exemption in self.files_exemptions:
41 if filepath.endswith(files_exemption):
42 return False
43 return True
44
Darryl Green10d9ce32018-02-28 10:02:55 +000045 def check_file_for_issue(self, filepath):
Gilles Peskined5240ec2019-02-25 20:59:05 +010046 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000047
Gilles Peskine04398052018-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 Green10d9ce32018-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 Peskined5240ec2019-02-25 20:59:05 +010065class LineIssueTracker(FileIssueTracker):
66 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +000067
Gilles Peskined5240ec2019-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 Peskinececc7262020-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 Peskined5240ec2019-02-25 20:59:05 +010090class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +010091 """Track files with bad permissions.
92
93 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +000094
Gilles Peskine21e85f72019-02-25 21:10:04 +010095 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +000096
97 def check_file_for_issue(self, filepath):
Gilles Peskine6fc52152019-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 Green10d9ce32018-02-28 10:02:55 +0000101 self.files_with_issues[filepath] = None
102
103
Gilles Peskined5240ec2019-02-25 20:59:05 +0100104class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-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 Green10d9ce32018-02-28 10:02:55 +0000107
Gilles Peskine21e85f72019-02-25 21:10:04 +0100108 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-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 Peskined5240ec2019-02-25 20:59:05 +0100116class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-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 Green10d9ce32018-02-28 10:02:55 +0000119
Gilles Peskine21e85f72019-02-25 21:10:04 +0100120 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000121
Gilles Peskinececc7262020-03-24 22:26:01 +0100122 files_exemptions = frozenset([".vcxproj", ".sln"])
123
Darryl Green10d9ce32018-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 Peskinececc7262020-03-24 22:26:01 +0100130class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100131 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000132
Gilles Peskinececc7262020-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 Green10d9ce32018-02-28 10:02:55 +0000137
Gilles Peskined5240ec2019-02-25 20:59:05 +0100138 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000139 return b"\r" in line
140
141
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100142class WindowsLineEndingIssueTracker(LineIssueTracker):
143 """Track files with non-Windows line endings (i.e. files without CR)."""
144
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):
151 return not line.endswith(b"\r\n")
152
153
Gilles Peskined5240ec2019-02-25 20:59:05 +0100154class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100155 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000156
Gilles Peskine21e85f72019-02-25 21:10:04 +0100157 heading = "Trailing whitespace:"
Gilles Peskinececc7262020-03-24 22:26:01 +0100158 files_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000159
Gilles Peskined5240ec2019-02-25 20:59:05 +0100160 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000161 return line.rstrip(b"\r\n") != line.rstrip()
162
163
Gilles Peskined5240ec2019-02-25 20:59:05 +0100164class TabIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100165 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000166
Gilles Peskine21e85f72019-02-25 21:10:04 +0100167 heading = "Tabs present:"
168 files_exemptions = frozenset([
Gilles Peskinececc7262020-03-24 22:26:01 +0100169 ".sln",
Gilles Peskined69f51b2020-03-24 22:01:28 +0100170 "/Makefile",
171 "/generate_visualc_files.pl",
Gilles Peskine21e85f72019-02-25 21:10:04 +0100172 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000173
Gilles Peskined5240ec2019-02-25 20:59:05 +0100174 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000175 return b"\t" in line
176
177
Gilles Peskined5240ec2019-02-25 20:59:05 +0100178class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-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 Peskinec117d592018-11-23 21:11:52 +0100181
Gilles Peskine21e85f72019-02-25 21:10:04 +0100182 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100183
Gilles Peskined5240ec2019-02-25 20:59:05 +0100184 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-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 Peskined5240ec2019-02-25 20:59:05 +0100191 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100192 return True
193 return False
194
Darryl Green10d9ce32018-02-28 10:02:55 +0000195
196class IntegrityChecker(object):
Gilles Peskine76605492019-02-25 20:35:31 +0100197 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000198
199 def __init__(self, log_file):
Gilles Peskine76605492019-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 Green10d9ce32018-02-28 10:02:55 +0000203 self.check_repo_path()
204 self.logger = None
205 self.setup_logger(log_file)
Gilles Peskined69f51b2020-03-24 22:01:28 +0100206 self.extensions_to_check = (
Gilles Peskineeb9929e2020-03-24 22:05:02 +0100207 ".c",
Gilles Peskine1978b682020-03-24 22:05:41 +0100208 ".data",
Gilles Peskinececc7262020-03-24 22:26:01 +0100209 ".dsp",
Gilles Peskine1978b682020-03-24 22:05:41 +0100210 ".function",
Gilles Peskineeb9929e2020-03-24 22:05:02 +0100211 ".h",
Gilles Peskine1978b682020-03-24 22:05:41 +0100212 ".md",
Gilles Peskineeb9929e2020-03-24 22:05:02 +0100213 ".pl",
214 ".py",
Gilles Peskine1978b682020-03-24 22:05:41 +0100215 ".sh",
Gilles Peskinececc7262020-03-24 22:26:01 +0100216 ".sln",
217 ".vcxproj",
Gilles Peskineeb9929e2020-03-24 22:05:02 +0100218 "/CMakeLists.txt",
219 "/ChangeLog",
Gilles Peskine1978b682020-03-24 22:05:41 +0100220 "/Makefile",
Darryl Green10d9ce32018-02-28 10:02:55 +0000221 )
Gilles Peskineeb9929e2020-03-24 22:05:02 +0100222 self.excluded_directories = [
223 '.git',
224 'mbed-os',
225 ]
Gilles Peskine95c55752018-09-28 11:48:10 +0200226 self.excluded_paths = list(map(os.path.normpath, [
227 'cov-int',
228 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200229 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000230 self.issues_to_check = [
231 PermissionIssueTracker(),
232 EndOfFileNewlineIssueTracker(),
233 Utf8BomIssueTracker(),
Gilles Peskinececc7262020-03-24 22:26:01 +0100234 UnixLineEndingIssueTracker(),
Gilles Peskine0d5b0162020-03-24 22:29:11 +0100235 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000236 TrailingWhitespaceIssueTracker(),
237 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100238 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000239 ]
240
Gilles Peskine76605492019-02-25 20:35:31 +0100241 @staticmethod
242 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000243 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
244 raise Exception("Must be run from Mbed TLS root")
245
246 def setup_logger(self, log_file, level=logging.INFO):
247 self.logger = logging.getLogger()
248 self.logger.setLevel(level)
249 if log_file:
250 handler = logging.FileHandler(log_file)
251 self.logger.addHandler(handler)
252 else:
253 console = logging.StreamHandler()
254 self.logger.addHandler(console)
255
Gilles Peskine95c55752018-09-28 11:48:10 +0200256 def prune_branch(self, root, d):
257 if d in self.excluded_directories:
258 return True
259 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
260 return True
261 return False
262
Darryl Green10d9ce32018-02-28 10:02:55 +0000263 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200264 for root, dirs, files in os.walk("."):
265 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000266 for filename in sorted(files):
267 filepath = os.path.join(root, filename)
Gilles Peskined69f51b2020-03-24 22:01:28 +0100268 if not filepath.endswith(self.extensions_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000269 continue
270 for issue_to_check in self.issues_to_check:
271 if issue_to_check.should_check_file(filepath):
272 issue_to_check.check_file_for_issue(filepath)
273
274 def output_issues(self):
275 integrity_return_code = 0
276 for issue_to_check in self.issues_to_check:
277 if issue_to_check.files_with_issues:
278 integrity_return_code = 1
279 issue_to_check.output_file_issues(self.logger)
280 return integrity_return_code
281
282
283def run_main():
Gilles Peskine79cfef02019-07-04 19:31:02 +0200284 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000285 parser.add_argument(
286 "-l", "--log_file", type=str, help="path to optional output log",
287 )
288 check_args = parser.parse_args()
289 integrity_check = IntegrityChecker(check_args.log_file)
290 integrity_check.check_files()
291 return_code = integrity_check.output_issues()
292 sys.exit(return_code)
293
294
295if __name__ == "__main__":
296 run_main()