blob: 4ba1d8dbb579356c71ceba3fd0f05f5d39eb6917 [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,
Gilles Peskine570f7a22019-07-04 19:31:33 +02009trailing whitespace, and presence of UTF-8 BOM.
Darryl Greenda02eb32018-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 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
Gilles Peskine227dfd42020-03-24 22:26:01 +010084
85def is_windows_file(filepath):
86 _root, ext = os.path.splitext(filepath)
87 return ext in ('.dsp', '.sln', '.vcxproj')
88
89
Gilles Peskine7194ecb2019-02-25 20:59:05 +010090class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +010091 """Track files with bad permissions.
92
93 Files that are not executable scripts must not be executable."""
Darryl Greenda02eb32018-02-28 10:02:55 +000094
Gilles Peskinefb8c3732019-02-25 21:10:04 +010095 heading = "Incorrect permissions:"
Darryl Greenda02eb32018-02-28 10:02:55 +000096
97 def check_file_for_issue(self, filepath):
Gilles Peskinede128232019-02-25 21:24:27 +010098 is_executable = os.access(filepath, os.X_OK)
99 should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
100 if is_executable != should_be_executable:
Darryl Greenda02eb32018-02-28 10:02:55 +0000101 self.files_with_issues[filepath] = None
102
103
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100104class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100105 """Track files that end with an incomplete line
106 (no newline character at the end of the last line)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000107
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100108 heading = "Missing newline at end of file:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000109
110 def check_file_for_issue(self, filepath):
111 with open(filepath, "rb") as f:
112 if not f.read().endswith(b"\n"):
113 self.files_with_issues[filepath] = None
114
115
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100116class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100117 """Track files that start with a UTF-8 BOM.
118 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000119
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100120 heading = "UTF-8 BOM present:"
Darryl Greenda02eb32018-02-28 10:02:55 +0000121
Gilles Peskine227dfd42020-03-24 22:26:01 +0100122 files_exemptions = frozenset([".vcxproj", ".sln"])
123
Darryl Greenda02eb32018-02-28 10:02:55 +0000124 def check_file_for_issue(self, filepath):
125 with open(filepath, "rb") as f:
126 if f.read().startswith(codecs.BOM_UTF8):
127 self.files_with_issues[filepath] = None
128
129
Gilles Peskine227dfd42020-03-24 22:26:01 +0100130class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100131 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000132
Gilles Peskine227dfd42020-03-24 22:26:01 +0100133 heading = "Non-Unix line endings:"
134
135 def should_check_file(self, filepath):
136 return not is_windows_file(filepath)
Darryl Greenda02eb32018-02-28 10:02:55 +0000137
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100138 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000139 return b"\r" in line
140
141
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100142class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100143 """Track lines with trailing whitespace."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000144
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100145 heading = "Trailing whitespace:"
Gilles Peskine227dfd42020-03-24 22:26:01 +0100146 files_exemptions = frozenset([".dsp", ".md"])
Darryl Greenda02eb32018-02-28 10:02:55 +0000147
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100148 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000149 return line.rstrip(b"\r\n") != line.rstrip()
150
151
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100152class TabIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100153 """Track lines with tabs."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000154
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100155 heading = "Tabs present:"
156 files_exemptions = frozenset([
Gilles Peskine227dfd42020-03-24 22:26:01 +0100157 ".sln",
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100158 "/Makefile",
159 "/generate_visualc_files.pl",
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100160 ])
Darryl Greenda02eb32018-02-28 10:02:55 +0000161
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100162 def issue_with_line(self, line, _filepath):
Darryl Greenda02eb32018-02-28 10:02:55 +0000163 return b"\t" in line
164
165
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100166class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100167 """Track lines with merge artifacts.
168 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100169
Gilles Peskinefb8c3732019-02-25 21:10:04 +0100170 heading = "Merge artifact:"
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100171
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100172 def issue_with_line(self, line, _filepath):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100173 # Detect leftover git conflict markers.
174 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
175 return True
176 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
177 return True
178 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine7194ecb2019-02-25 20:59:05 +0100179 not _filepath.endswith('.md'):
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100180 return True
181 return False
182
Darryl Greenda02eb32018-02-28 10:02:55 +0000183
184class IntegrityChecker(object):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100185 """Sanity-check files under the current directory."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000186
187 def __init__(self, log_file):
Gilles Peskine4fb66782019-02-25 20:35:31 +0100188 """Instantiate the sanity checker.
189 Check files under the current directory.
190 Write a report of issues to log_file."""
Darryl Greenda02eb32018-02-28 10:02:55 +0000191 self.check_repo_path()
192 self.logger = None
193 self.setup_logger(log_file)
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100194 self.extensions_to_check = (
Gilles Peskinec7153222020-03-24 22:05:02 +0100195 ".c",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100196 ".data",
Gilles Peskine227dfd42020-03-24 22:26:01 +0100197 ".dsp",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100198 ".function",
Gilles Peskinec7153222020-03-24 22:05:02 +0100199 ".h",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100200 ".md",
Gilles Peskinec7153222020-03-24 22:05:02 +0100201 ".pl",
202 ".py",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100203 ".sh",
Gilles Peskine227dfd42020-03-24 22:26:01 +0100204 ".sln",
205 ".vcxproj",
Gilles Peskinec7153222020-03-24 22:05:02 +0100206 "/CMakeLists.txt",
207 "/ChangeLog",
Gilles Peskine318f15e2020-03-24 22:05:41 +0100208 "/Makefile",
Darryl Greenda02eb32018-02-28 10:02:55 +0000209 )
Gilles Peskinec7153222020-03-24 22:05:02 +0100210 self.excluded_directories = [
211 '.git',
212 'mbed-os',
213 ]
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200214 self.excluded_paths = list(map(os.path.normpath, [
215 'cov-int',
216 'examples',
217 'yotta/module'
218 ]))
Darryl Greenda02eb32018-02-28 10:02:55 +0000219 self.issues_to_check = [
220 PermissionIssueTracker(),
221 EndOfFileNewlineIssueTracker(),
222 Utf8BomIssueTracker(),
Gilles Peskine227dfd42020-03-24 22:26:01 +0100223 UnixLineEndingIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000224 TrailingWhitespaceIssueTracker(),
225 TabIssueTracker(),
Gilles Peskineda6ccfc2018-11-23 21:11:52 +0100226 MergeArtifactIssueTracker(),
Darryl Greenda02eb32018-02-28 10:02:55 +0000227 ]
228
Gilles Peskine4fb66782019-02-25 20:35:31 +0100229 @staticmethod
230 def check_repo_path():
Darryl Greenda02eb32018-02-28 10:02:55 +0000231 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
232 raise Exception("Must be run from Mbed TLS root")
233
234 def setup_logger(self, log_file, level=logging.INFO):
235 self.logger = logging.getLogger()
236 self.logger.setLevel(level)
237 if log_file:
238 handler = logging.FileHandler(log_file)
239 self.logger.addHandler(handler)
240 else:
241 console = logging.StreamHandler()
242 self.logger.addHandler(console)
243
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200244 def prune_branch(self, root, d):
245 if d in self.excluded_directories:
246 return True
247 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
248 return True
249 return False
250
Darryl Greenda02eb32018-02-28 10:02:55 +0000251 def check_files(self):
Gilles Peskine3400b4d2018-09-28 11:48:10 +0200252 for root, dirs, files in os.walk("."):
253 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Greenda02eb32018-02-28 10:02:55 +0000254 for filename in sorted(files):
255 filepath = os.path.join(root, filename)
Gilles Peskinec251e0d2020-03-24 22:01:28 +0100256 if not filepath.endswith(self.extensions_to_check):
Darryl Greenda02eb32018-02-28 10:02:55 +0000257 continue
258 for issue_to_check in self.issues_to_check:
259 if issue_to_check.should_check_file(filepath):
260 issue_to_check.check_file_for_issue(filepath)
261
262 def output_issues(self):
263 integrity_return_code = 0
264 for issue_to_check in self.issues_to_check:
265 if issue_to_check.files_with_issues:
266 integrity_return_code = 1
267 issue_to_check.output_file_issues(self.logger)
268 return integrity_return_code
269
270
271def run_main():
Gilles Peskine081daf02019-07-04 19:31:02 +0200272 parser = argparse.ArgumentParser(description=__doc__)
Darryl Greenda02eb32018-02-28 10:02:55 +0000273 parser.add_argument(
274 "-l", "--log_file", type=str, help="path to optional output log",
275 )
276 check_args = parser.parse_args()
277 integrity_check = IntegrityChecker(check_args.log_file)
278 integrity_check.check_files()
279 return_code = integrity_check.output_issues()
280 sys.exit(return_code)
281
282
283if __name__ == "__main__":
284 run_main()