blob: 255bed8b93a4ae3d05a176fa4049d20df322c4b6 [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,
Gilles Peskine55b49ee2019-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 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
Darryl Green10d9ce32018-02-28 10:02:55 +0000171
172class IntegrityChecker(object):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100173 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000174
175 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100176 """Instantiate the sanity checker.
177 Check files under the current directory.
178 Write a report of issues to log_file."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000179 self.check_repo_path()
180 self.logger = None
181 self.setup_logger(log_file)
182 self.files_to_check = (
183 ".c", ".h", ".sh", ".pl", ".py", ".md", ".function", ".data",
184 "Makefile", "CMakeLists.txt", "ChangeLog"
185 )
Gilles Peskine95c55752018-09-28 11:48:10 +0200186 self.excluded_directories = ['.git', 'mbed-os']
187 self.excluded_paths = list(map(os.path.normpath, [
188 'cov-int',
189 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200190 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000191 self.issues_to_check = [
192 PermissionIssueTracker(),
193 EndOfFileNewlineIssueTracker(),
194 Utf8BomIssueTracker(),
195 LineEndingIssueTracker(),
196 TrailingWhitespaceIssueTracker(),
197 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100198 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000199 ]
200
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100201 @staticmethod
202 def check_repo_path():
Darryl Green10d9ce32018-02-28 10:02:55 +0000203 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
204 raise Exception("Must be run from Mbed TLS root")
205
206 def setup_logger(self, log_file, level=logging.INFO):
207 self.logger = logging.getLogger()
208 self.logger.setLevel(level)
209 if log_file:
210 handler = logging.FileHandler(log_file)
211 self.logger.addHandler(handler)
212 else:
213 console = logging.StreamHandler()
214 self.logger.addHandler(console)
215
Gilles Peskine95c55752018-09-28 11:48:10 +0200216 def prune_branch(self, root, d):
217 if d in self.excluded_directories:
218 return True
219 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
220 return True
221 return False
222
Darryl Green10d9ce32018-02-28 10:02:55 +0000223 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200224 for root, dirs, files in os.walk("."):
225 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000226 for filename in sorted(files):
227 filepath = os.path.join(root, filename)
Gilles Peskine95c55752018-09-28 11:48:10 +0200228 if not filepath.endswith(self.files_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000229 continue
230 for issue_to_check in self.issues_to_check:
231 if issue_to_check.should_check_file(filepath):
232 issue_to_check.check_file_for_issue(filepath)
233
234 def output_issues(self):
235 integrity_return_code = 0
236 for issue_to_check in self.issues_to_check:
237 if issue_to_check.files_with_issues:
238 integrity_return_code = 1
239 issue_to_check.output_file_issues(self.logger)
240 return integrity_return_code
241
242
243def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200244 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000245 parser.add_argument(
246 "-l", "--log_file", type=str, help="path to optional output log",
247 )
248 check_args = parser.parse_args()
249 integrity_check = IntegrityChecker(check_args.log_file)
250 integrity_check.check_files()
251 return_code = integrity_check.output_issues()
252 sys.exit(return_code)
253
254
255if __name__ == "__main__":
256 run_main()