blob: c11188c0b83301506d7c0765cc4f34cead530f3b [file] [log] [blame]
Darryl Greenda02eb32018-02-28 10:02:55 +00001#!/usr/bin/env python3
2"""
3This file is part of Mbed TLS (https://tls.mbed.org)
4
5Copyright (c) 2018, Arm Limited, All Rights Reserved
6
7Purpose
8
9This script checks the current state of the source code for minor issues,
10including incorrect file permissions, presence of tabs, non-Unix line endings,
11trailing whitespace, presence of UTF-8 BOM, and TODO comments.
12Note: requires python 3, must be run from Mbed TLS root.
13"""
14
15import os
16import argparse
17import logging
18import codecs
19import sys
20
21
22class IssueTracker(object):
23 """Base class for issue tracking. Issues should inherit from this and
24 overwrite either issue_with_line if they check the file line by line, or
25 overwrite check_file_for_issue if they check the file as a whole."""
26
27 def __init__(self):
28 self.heading = ""
29 self.files_exemptions = []
30 self.files_with_issues = {}
31
32 def should_check_file(self, filepath):
33 for files_exemption in self.files_exemptions:
34 if filepath.endswith(files_exemption):
35 return False
36 return True
37
38 def issue_with_line(self, line):
39 raise NotImplementedError
40
41 def check_file_for_issue(self, filepath):
42 with open(filepath, "rb") as f:
43 for i, line in enumerate(iter(f.readline, b"")):
44 self.check_file_line(filepath, line, i + 1)
45
Gilles Peskine232fae32018-11-23 21:11:30 +010046 def record_issue(self, filepath, line_number):
47 if filepath not in self.files_with_issues.keys():
48 self.files_with_issues[filepath] = []
49 self.files_with_issues[filepath].append(line_number)
50
Darryl Greenda02eb32018-02-28 10:02:55 +000051 def check_file_line(self, filepath, line, line_number):
52 if self.issue_with_line(line):
Gilles Peskine232fae32018-11-23 21:11:30 +010053 self.record_issue(filepath, line_number)
Darryl Greenda02eb32018-02-28 10:02:55 +000054
55 def output_file_issues(self, logger):
56 if self.files_with_issues.values():
57 logger.info(self.heading)
58 for filename, lines in sorted(self.files_with_issues.items()):
59 if lines:
60 logger.info("{}: {}".format(
61 filename, ", ".join(str(x) for x in lines)
62 ))
63 else:
64 logger.info(filename)
65 logger.info("")
66
67
68class PermissionIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010069 """Track files with bad permissions.
70
71 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +000072
73 def __init__(self):
74 super().__init__()
75 self.heading = "Incorrect permissions:"
76
77 def check_file_for_issue(self, filepath):
78 if not (os.access(filepath, os.X_OK) ==
79 filepath.endswith((".sh", ".pl", ".py"))):
80 self.files_with_issues[filepath] = None
81
82
83class EndOfFileNewlineIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010084 """Track files that end with an incomplete line
85 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +000086
87 def __init__(self):
88 super().__init__()
89 self.heading = "Missing newline at end of file:"
90
91 def check_file_for_issue(self, filepath):
92 with open(filepath, "rb") as f:
93 if not f.read().endswith(b"\n"):
94 self.files_with_issues[filepath] = None
95
96
97class Utf8BomIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010098 """Track files that start with a UTF-8 BOM.
99 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000100
101 def __init__(self):
102 super().__init__()
103 self.heading = "UTF-8 BOM present:"
104
105 def check_file_for_issue(self, filepath):
106 with open(filepath, "rb") as f:
107 if f.read().startswith(codecs.BOM_UTF8):
108 self.files_with_issues[filepath] = None
109
110
111class LineEndingIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100112 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000113
114 def __init__(self):
115 super().__init__()
116 self.heading = "Non Unix line endings:"
117
118 def issue_with_line(self, line):
119 return b"\r" in line
120
121
122class TrailingWhitespaceIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100123 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000124
125 def __init__(self):
126 super().__init__()
127 self.heading = "Trailing whitespace:"
128 self.files_exemptions = [".md"]
129
130 def issue_with_line(self, line):
131 return line.rstrip(b"\r\n") != line.rstrip()
132
133
134class TabIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100135 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000136
137 def __init__(self):
138 super().__init__()
139 self.heading = "Tabs present:"
140 self.files_exemptions = [
141 "Makefile", "generate_visualc_files.pl"
142 ]
143
144 def issue_with_line(self, line):
145 return b"\t" in line
146
147
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100148class MergeArtifactIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100149 """Track lines with merge artifacts.
150 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100151
152 def __init__(self):
153 super().__init__()
154 self.heading = "Merge artifact:"
155
156 def issue_with_line(self, filepath, line):
157 # Detect leftover git conflict markers.
158 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
159 return True
160 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
161 return True
162 if line.rstrip(b'\r\n') == b'=======' and \
163 not filepath.endswith('.md'):
164 return True
165 return False
166
167 def check_file_line(self, filepath, line, line_number):
168 if self.issue_with_line(filepath, line):
169 self.record_issue(filepath, line_number)
170
Darryl Greenda02eb32018-02-28 10:02:55 +0000171class TodoIssueTracker(IssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100172 """Track lines containing ``TODO``."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000173
174 def __init__(self):
175 super().__init__()
176 self.heading = "TODO present:"
177 self.files_exemptions = [
178 __file__, "benchmark.c", "pull_request_template.md"
179 ]
180
181 def issue_with_line(self, line):
182 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():
259 parser = argparse.ArgumentParser(
260 description=(
261 "This script checks the current state of the source code for "
262 "minor issues, including incorrect file permissions, "
263 "presence of tabs, non-Unix line endings, trailing whitespace, "
264 "presence of UTF-8 BOM, and TODO comments. "
265 "Note: requires python 3, must be run from Mbed TLS root."
266 )
267 )
268 parser.add_argument(
269 "-l", "--log_file", type=str, help="path to optional output log",
270 )
271 check_args = parser.parse_args()
272 integrity_check = IntegrityChecker(check_args.log_file)
273 integrity_check.check_files()
274 return_code = integrity_check.output_issues()
275 sys.exit(return_code)
276
277
278if __name__ == "__main__":
279 run_main()