blob: a658415dc64ba8d0612b643be1413f2879b595ff [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine7dfcfce2019-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,
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 Peskine6ee576e2019-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 Peskine1e9698a2019-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 Peskine6ee576e2019-02-25 20:59:05 +010030 """
Darryl Green10d9ce32018-02-28 10:02:55 +000031
Gilles Peskine1e9698a2019-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 Peskine6ee576e2019-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 Peskine6ee576e2019-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 Peskine6ee576e2019-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 Peskine0d060ef2019-02-25 20:35:31 +010085 """Track files with bad permissions.
86
87 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +000088
Gilles Peskine1e9698a2019-02-25 21:10:04 +010089 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +000090
91 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-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 Green10d9ce32018-02-28 10:02:55 +000095 self.files_with_issues[filepath] = None
96
97
Gilles Peskine6ee576e2019-02-25 20:59:05 +010098class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-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 Green10d9ce32018-02-28 10:02:55 +0000101
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100102 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-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 Peskine6ee576e2019-02-25 20:59:05 +0100110class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-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 Green10d9ce32018-02-28 10:02:55 +0000113
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100114 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-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 Peskine6ee576e2019-02-25 20:59:05 +0100122class LineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100123 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000124
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100125 heading = "Non Unix line endings:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000126
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100127 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000128 return b"\r" in line
129
130
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100131class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100132 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000133
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100134 heading = "Trailing whitespace:"
135 files_exemptions = frozenset(".md")
Darryl Green10d9ce32018-02-28 10:02:55 +0000136
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100137 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000138 return line.rstrip(b"\r\n") != line.rstrip()
139
140
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100141class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100142 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000143
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100144 heading = "Tabs present:"
145 files_exemptions = frozenset([
146 "Makefile",
147 "generate_visualc_files.pl",
148 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000149
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100150 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000151 return b"\t" in line
152
153
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100154class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-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 Peskinec117d592018-11-23 21:11:52 +0100157
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100158 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100159
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100160 def issue_with_line(self, line, _filepath):
Gilles Peskinec117d592018-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 Peskine6ee576e2019-02-25 20:59:05 +0100167 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100168 return True
169 return False
170
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100171class TodoIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100172 """Track lines containing ``TODO``."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000173
Gilles Peskine1e9698a2019-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 Green10d9ce32018-02-28 10:02:55 +0000180
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100181 def issue_with_line(self, line, _filepath):
Darryl Green10d9ce32018-02-28 10:02:55 +0000182 return b"todo" in line.lower()
183
184
185class IntegrityChecker(object):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100186 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000187
188 def __init__(self, log_file):
Gilles Peskine0d060ef2019-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 Green10d9ce32018-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 Peskine95c55752018-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',
Gilles Peskine95c55752018-09-28 11:48:10 +0200203 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000204 self.issues_to_check = [
205 PermissionIssueTracker(),
206 EndOfFileNewlineIssueTracker(),
207 Utf8BomIssueTracker(),
208 LineEndingIssueTracker(),
209 TrailingWhitespaceIssueTracker(),
210 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100211 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000212 TodoIssueTracker(),
213 ]
214
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100215 @staticmethod
216 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000217 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
218 raise Exception("Must be run from Mbed TLS root")
219
220 def setup_logger(self, log_file, level=logging.INFO):
221 self.logger = logging.getLogger()
222 self.logger.setLevel(level)
223 if log_file:
224 handler = logging.FileHandler(log_file)
225 self.logger.addHandler(handler)
226 else:
227 console = logging.StreamHandler()
228 self.logger.addHandler(console)
229
Gilles Peskine95c55752018-09-28 11:48:10 +0200230 def prune_branch(self, root, d):
231 if d in self.excluded_directories:
232 return True
233 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
234 return True
235 return False
236
Darryl Green10d9ce32018-02-28 10:02:55 +0000237 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200238 for root, dirs, files in os.walk("."):
239 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000240 for filename in sorted(files):
241 filepath = os.path.join(root, filename)
Gilles Peskine95c55752018-09-28 11:48:10 +0200242 if not filepath.endswith(self.files_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000243 continue
244 for issue_to_check in self.issues_to_check:
245 if issue_to_check.should_check_file(filepath):
246 issue_to_check.check_file_for_issue(filepath)
247
248 def output_issues(self):
249 integrity_return_code = 0
250 for issue_to_check in self.issues_to_check:
251 if issue_to_check.files_with_issues:
252 integrity_return_code = 1
253 issue_to_check.output_file_issues(self.logger)
254 return integrity_return_code
255
256
257def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200258 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000259 parser.add_argument(
260 "-l", "--log_file", type=str, help="path to optional output log",
261 )
262 check_args = parser.parse_args()
263 integrity_check = IntegrityChecker(check_args.log_file)
264 integrity_check.check_files()
265 return_code = integrity_check.output_issues()
266 sys.exit(return_code)
267
268
269if __name__ == "__main__":
270 run_main()