blob: f8d9261b4f6e6f63ff29e851f5a300821b2e0e92 [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 Peskine5d1dfd42020-03-24 18:25:17 +010020class 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
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 Peskineaf67f8d2020-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 Peskineaf67f8d2020-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 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):
Gilles Peskineaf67f8d2020-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 Peskineaf67f8d2020-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 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 """
82
83 def issue_with_line(self, line, filepath):
Gilles Peskineaf67f8d2020-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 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)
93
94 def check_file_for_issue(self, filepath):
Gilles Peskineaf67f8d2020-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 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
103class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100104 """Track files with bad permissions.
105
106 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000107
Gilles Peskine21e85f72019-02-25 21:10:04 +0100108 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000109
110 def check_file_for_issue(self, filepath):
Gilles Peskine6fc52152019-02-25 21:24:27 +0100111 is_executable = os.access(filepath, os.X_OK)
112 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
113 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000114 self.files_with_issues[filepath] = None
115
116
Gilles Peskined5240ec2019-02-25 20:59:05 +0100117class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100118 """Track files that end with an incomplete line
119 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000120
Gilles Peskine21e85f72019-02-25 21:10:04 +0100121 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000122
123 def check_file_for_issue(self, filepath):
124 with open(filepath, "rb") as f:
125 if not f.read().endswith(b"\n"):
126 self.files_with_issues[filepath] = None
127
128
Gilles Peskined5240ec2019-02-25 20:59:05 +0100129class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100130 """Track files that start with a UTF-8 BOM.
131 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000132
Gilles Peskine21e85f72019-02-25 21:10:04 +0100133 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000134
135 def check_file_for_issue(self, filepath):
136 with open(filepath, "rb") as f:
137 if f.read().startswith(codecs.BOM_UTF8):
138 self.files_with_issues[filepath] = None
139
140
Gilles Peskined5240ec2019-02-25 20:59:05 +0100141class LineEndingIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100142 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000143
Gilles Peskine21e85f72019-02-25 21:10:04 +0100144 heading = "Non Unix line endings:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000145
Gilles Peskined5240ec2019-02-25 20:59:05 +0100146 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000147 return b"\r" in line
148
149
Gilles Peskined5240ec2019-02-25 20:59:05 +0100150class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100151 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000152
Gilles Peskine21e85f72019-02-25 21:10:04 +0100153 heading = "Trailing whitespace:"
154 files_exemptions = frozenset(".md")
Darryl Green10d9ce32018-02-28 10:02:55 +0000155
Gilles Peskined5240ec2019-02-25 20:59:05 +0100156 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000157 return line.rstrip(b"\r\n") != line.rstrip()
158
159
Gilles Peskined5240ec2019-02-25 20:59:05 +0100160class TabIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100161 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000162
Gilles Peskine21e85f72019-02-25 21:10:04 +0100163 heading = "Tabs present:"
164 files_exemptions = frozenset([
165 "Makefile",
166 "generate_visualc_files.pl",
167 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000168
Gilles Peskined5240ec2019-02-25 20:59:05 +0100169 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000170 return b"\t" in line
171
172
Gilles Peskined5240ec2019-02-25 20:59:05 +0100173class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine76605492019-02-25 20:35:31 +0100174 """Track lines with merge artifacts.
175 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100176
Gilles Peskine21e85f72019-02-25 21:10:04 +0100177 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100178
Gilles Peskined5240ec2019-02-25 20:59:05 +0100179 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-11-23 21:11:52 +0100180 # Detect leftover git conflict markers.
181 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
182 return True
183 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
184 return True
185 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskined5240ec2019-02-25 20:59:05 +0100186 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100187 return True
188 return False
189
Darryl Green10d9ce32018-02-28 10:02:55 +0000190
Gilles Peskine5d1dfd42020-03-24 18:25:17 +0100191class IntegrityChecker:
Gilles Peskine76605492019-02-25 20:35:31 +0100192 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000193
194 def __init__(self, log_file):
Gilles Peskine76605492019-02-25 20:35:31 +0100195 """Instantiate the sanity checker.
196 Check files under the current directory.
197 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000198 self.check_repo_path()
199 self.logger = None
200 self.setup_logger(log_file)
201 self.files_to_check = (
202 ".c", ".h", ".sh", ".pl", ".py", ".md", ".function", ".data",
203 "Makefile", "CMakeLists.txt", "ChangeLog"
204 )
Gilles Peskine95c55752018-09-28 11:48:10 +0200205 self.excluded_directories = ['.git', 'mbed-os']
206 self.excluded_paths = list(map(os.path.normpath, [
207 'cov-int',
208 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200209 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000210 self.issues_to_check = [
211 PermissionIssueTracker(),
212 EndOfFileNewlineIssueTracker(),
213 Utf8BomIssueTracker(),
214 LineEndingIssueTracker(),
215 TrailingWhitespaceIssueTracker(),
216 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100217 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000218 ]
219
Gilles Peskine76605492019-02-25 20:35:31 +0100220 @staticmethod
221 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000222 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
223 raise Exception("Must be run from Mbed TLS root")
224
225 def setup_logger(self, log_file, level=logging.INFO):
226 self.logger = logging.getLogger()
227 self.logger.setLevel(level)
228 if log_file:
229 handler = logging.FileHandler(log_file)
230 self.logger.addHandler(handler)
231 else:
232 console = logging.StreamHandler()
233 self.logger.addHandler(console)
234
Gilles Peskine95c55752018-09-28 11:48:10 +0200235 def prune_branch(self, root, d):
236 if d in self.excluded_directories:
237 return True
238 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
239 return True
240 return False
241
Darryl Green10d9ce32018-02-28 10:02:55 +0000242 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200243 for root, dirs, files in os.walk("."):
244 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000245 for filename in sorted(files):
246 filepath = os.path.join(root, filename)
Gilles Peskine95c55752018-09-28 11:48:10 +0200247 if not filepath.endswith(self.files_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000248 continue
249 for issue_to_check in self.issues_to_check:
250 if issue_to_check.should_check_file(filepath):
251 issue_to_check.check_file_for_issue(filepath)
252
253 def output_issues(self):
254 integrity_return_code = 0
255 for issue_to_check in self.issues_to_check:
256 if issue_to_check.files_with_issues:
257 integrity_return_code = 1
258 issue_to_check.output_file_issues(self.logger)
259 return integrity_return_code
260
261
262def run_main():
Gilles Peskine79cfef02019-07-04 19:31:02 +0200263 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000264 parser.add_argument(
265 "-l", "--log_file", type=str, help="path to optional output log",
266 )
267 check_args = parser.parse_args()
268 integrity_check = IntegrityChecker(check_args.log_file)
269 integrity_check.check_files()
270 return_code = integrity_check.output_issues()
271 sys.exit(return_code)
272
273
274if __name__ == "__main__":
275 run_main()