blob: a5b5950234e673f5a0e26a3936768d8adf2d632e [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,
9trailing whitespace, presence of UTF-8 BOM, and TODO comments.
10Note: 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
84class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010085 """Track files with bad permissions.
86
87 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +000088
Gilles Peskinefb8c3732019-02-25 21:10:04 +010089 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +000090
91 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +010092 is_executable = os.access(filepath, os.X_OK)
93 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
94 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +000095 self.files_with_issues[filepath] = None
96
97
Gilles Peskine7194ecb2019-02-25 20:59:05 +010098class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010099 """Track files that end with an incomplete line
100 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000101
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100102 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000103
104 def check_file_for_issue(self, filepath):
105 with open(filepath, "rb") as f:
106 if not f.read().endswith(b"\n"):
107 self.files_with_issues[filepath] = None
108
109
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100110class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100111 """Track files that start with a UTF-8 BOM.
112 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000113
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100114 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000115
116 def check_file_for_issue(self, filepath):
117 with open(filepath, "rb") as f:
118 if f.read().startswith(codecs.BOM_UTF8):
119 self.files_with_issues[filepath] = None
120
121
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100122class LineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100123 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000124
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100125 heading = "Non Unix line endings:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000126
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100127 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000128 return b"\r" in line
129
130
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100131class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100132 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000133
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100134 heading = "Trailing whitespace:"
135 files_exemptions = frozenset(".md")
Darryl Greenda02eb32018-02-28 10:02:55 +0000136
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100137 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000138 return line.rstrip(b"\r\n") != line.rstrip()
139
140
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100141class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100142 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000143
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100144 heading = "Tabs present:"
145 files_exemptions = frozenset([
146 "Makefile",
147 "generate_visualc_files.pl",
148 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000149
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100150 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000151 return b"\t" in line
152
153
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100154class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100155 """Track lines with merge artifacts.
156 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100157
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100158 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100159
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100160 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100161 # Detect leftover git conflict markers.
162 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
163 return True
164 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
165 return True
166 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100167 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100168 return True
169 return False
170
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100171class TodoIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100172 """Track lines containing ``TODO``."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000173
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100174 heading = "TODO present:"
175 files_exemptions = frozenset([
176 os.path.basename(__file__),
177 "benchmark.c",
178 "pull_request_template.md",
179 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000180
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100181 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000182 return b"todo" in line.lower()
183
184
185class IntegrityChecker(object):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100186 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000187
188 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100189 """Instantiate the sanity checker.
190 Check files under the current directory.
191 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000192 self.check_repo_path()
193 self.logger = None
194 self.setup_logger(log_file)
195 self.files_to_check = (
196 ".c", ".h", ".sh", ".pl", ".py", ".md", ".function", ".data",
197 "Makefile", "CMakeLists.txt", "ChangeLog"
198 )
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200199 self.excluded_directories = ['.git', 'mbed-os']
200 self.excluded_paths = list(map(os.path.normpath, [
201 'cov-int',
202 'examples',
203 'yotta/module'
204 ]))
Darryl Greenda02eb32018-02-28 10:02:55 +0000205 self.issues_to_check = [
206 PermissionIssueTracker(),
207 EndOfFileNewlineIssueTracker(),
208 Utf8BomIssueTracker(),
209 LineEndingIssueTracker(),
210 TrailingWhitespaceIssueTracker(),
211 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100212 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000213 TodoIssueTracker(),
214 ]
215
Gilles Peskine4fb66782019-02-25 20:35:31 +0100216 @staticmethod
217 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000218 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
219 raise Exception("Must be run from Mbed TLS root")
220
221 def setup_logger(self, log_file, level=logging.INFO):
222 self.logger = logging.getLogger()
223 self.logger.setLevel(level)
224 if log_file:
225 handler = logging.FileHandler(log_file)
226 self.logger.addHandler(handler)
227 else:
228 console = logging.StreamHandler()
229 self.logger.addHandler(console)
230
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200231 def prune_branch(self, root, d):
232 if d in self.excluded_directories:
233 return True
234 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
235 return True
236 return False
237
Darryl Greenda02eb32018-02-28 10:02:55 +0000238 def check_files(self):
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200239 for root, dirs, files in os.walk("."):
240 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Greenda02eb32018-02-28 10:02:55 +0000241 for filename in sorted(files):
242 filepath = os.path.join(root, filename)
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200243 if not filepath.endswith(self.files_to_check):
Darryl Greenda02eb32018-02-28 10:02:55 +0000244 continue
245 for issue_to_check in self.issues_to_check:
246 if issue_to_check.should_check_file(filepath):
247 issue_to_check.check_file_for_issue(filepath)
248
249 def output_issues(self):
250 integrity_return_code = 0
251 for issue_to_check in self.issues_to_check:
252 if issue_to_check.files_with_issues:
253 integrity_return_code = 1
254 issue_to_check.output_file_issues(self.logger)
255 return integrity_return_code
256
257
258def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200259 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000260 parser.add_argument(
261 "-l", "--log_file", type=str, help="path to optional output log",
262 )
263 check_args = parser.parse_args()
264 integrity_check = IntegrityChecker(check_args.log_file)
265 integrity_check.check_files()
266 return_code = integrity_check.output_issues()
267 sys.exit(return_code)
268
269
270if __name__ == "__main__":
271 run_main()