blob: ed6787289a88513728a328bd452b9d3f4e6de425 [file] [log] [blame]
Darryl Green10d9ce32018-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
46 def check_file_line(self, filepath, line, line_number):
47 if self.issue_with_line(line):
48 if filepath not in self.files_with_issues.keys():
49 self.files_with_issues[filepath] = []
50 self.files_with_issues[filepath].append(line_number)
51
52 def output_file_issues(self, logger):
53 if self.files_with_issues.values():
54 logger.info(self.heading)
55 for filename, lines in sorted(self.files_with_issues.items()):
56 if lines:
57 logger.info("{}: {}".format(
58 filename, ", ".join(str(x) for x in lines)
59 ))
60 else:
61 logger.info(filename)
62 logger.info("")
63
64
65class PermissionIssueTracker(IssueTracker):
66
67 def __init__(self):
68 super().__init__()
69 self.heading = "Incorrect permissions:"
70
71 def check_file_for_issue(self, filepath):
72 if not (os.access(filepath, os.X_OK) ==
73 filepath.endswith((".sh", ".pl", ".py"))):
74 self.files_with_issues[filepath] = None
75
76
77class EndOfFileNewlineIssueTracker(IssueTracker):
78
79 def __init__(self):
80 super().__init__()
81 self.heading = "Missing newline at end of file:"
82
83 def check_file_for_issue(self, filepath):
84 with open(filepath, "rb") as f:
85 if not f.read().endswith(b"\n"):
86 self.files_with_issues[filepath] = None
87
88
89class Utf8BomIssueTracker(IssueTracker):
90
91 def __init__(self):
92 super().__init__()
93 self.heading = "UTF-8 BOM present:"
94
95 def check_file_for_issue(self, filepath):
96 with open(filepath, "rb") as f:
97 if f.read().startswith(codecs.BOM_UTF8):
98 self.files_with_issues[filepath] = None
99
100
101class LineEndingIssueTracker(IssueTracker):
102
103 def __init__(self):
104 super().__init__()
105 self.heading = "Non Unix line endings:"
106
107 def issue_with_line(self, line):
108 return b"\r" in line
109
110
111class TrailingWhitespaceIssueTracker(IssueTracker):
112
113 def __init__(self):
114 super().__init__()
115 self.heading = "Trailing whitespace:"
116 self.files_exemptions = [".md"]
117
118 def issue_with_line(self, line):
119 return line.rstrip(b"\r\n") != line.rstrip()
120
121
122class TabIssueTracker(IssueTracker):
123
124 def __init__(self):
125 super().__init__()
126 self.heading = "Tabs present:"
127 self.files_exemptions = [
128 "Makefile", "generate_visualc_files.pl"
129 ]
130
131 def issue_with_line(self, line):
132 return b"\t" in line
133
134
135class TodoIssueTracker(IssueTracker):
136
137 def __init__(self):
138 super().__init__()
139 self.heading = "TODO present:"
140 self.files_exemptions = [
141 __file__, "benchmark.c", "pull_request_template.md"
142 ]
143
144 def issue_with_line(self, line):
145 return b"todo" in line.lower()
146
147
148class IntegrityChecker(object):
149
150 def __init__(self, log_file):
151 self.check_repo_path()
152 self.logger = None
153 self.setup_logger(log_file)
154 self.files_to_check = (
155 ".c", ".h", ".sh", ".pl", ".py", ".md", ".function", ".data",
156 "Makefile", "CMakeLists.txt", "ChangeLog"
157 )
Gilles Peskine95c55752018-09-28 11:48:10 +0200158 self.excluded_directories = ['.git', 'mbed-os']
159 self.excluded_paths = list(map(os.path.normpath, [
160 'cov-int',
161 'examples',
Gilles Peskine95c55752018-09-28 11:48:10 +0200162 ]))
Darryl Green10d9ce32018-02-28 10:02:55 +0000163 self.issues_to_check = [
164 PermissionIssueTracker(),
165 EndOfFileNewlineIssueTracker(),
166 Utf8BomIssueTracker(),
167 LineEndingIssueTracker(),
168 TrailingWhitespaceIssueTracker(),
169 TabIssueTracker(),
170 TodoIssueTracker(),
171 ]
172
173 def check_repo_path(self):
174 if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
175 raise Exception("Must be run from Mbed TLS root")
176
177 def setup_logger(self, log_file, level=logging.INFO):
178 self.logger = logging.getLogger()
179 self.logger.setLevel(level)
180 if log_file:
181 handler = logging.FileHandler(log_file)
182 self.logger.addHandler(handler)
183 else:
184 console = logging.StreamHandler()
185 self.logger.addHandler(console)
186
Gilles Peskine95c55752018-09-28 11:48:10 +0200187 def prune_branch(self, root, d):
188 if d in self.excluded_directories:
189 return True
190 if os.path.normpath(os.path.join(root, d)) in self.excluded_paths:
191 return True
192 return False
193
Darryl Green10d9ce32018-02-28 10:02:55 +0000194 def check_files(self):
Gilles Peskine95c55752018-09-28 11:48:10 +0200195 for root, dirs, files in os.walk("."):
196 dirs[:] = sorted(d for d in dirs if not self.prune_branch(root, d))
Darryl Green10d9ce32018-02-28 10:02:55 +0000197 for filename in sorted(files):
198 filepath = os.path.join(root, filename)
Gilles Peskine95c55752018-09-28 11:48:10 +0200199 if not filepath.endswith(self.files_to_check):
Darryl Green10d9ce32018-02-28 10:02:55 +0000200 continue
201 for issue_to_check in self.issues_to_check:
202 if issue_to_check.should_check_file(filepath):
203 issue_to_check.check_file_for_issue(filepath)
204
205 def output_issues(self):
206 integrity_return_code = 0
207 for issue_to_check in self.issues_to_check:
208 if issue_to_check.files_with_issues:
209 integrity_return_code = 1
210 issue_to_check.output_file_issues(self.logger)
211 return integrity_return_code
212
213
214def run_main():
215 parser = argparse.ArgumentParser(
216 description=(
217 "This script checks the current state of the source code for "
218 "minor issues, including incorrect file permissions, "
219 "presence of tabs, non-Unix line endings, trailing whitespace, "
220 "presence of UTF-8 BOM, and TODO comments. "
221 "Note: requires python 3, must be run from Mbed TLS root."
222 )
223 )
224 parser.add_argument(
225 "-l", "--log_file", type=str, help="path to optional output log",
226 )
227 check_args = parser.parse_args()
228 integrity_check = IntegrityChecker(check_args.log_file)
229 integrity_check.check_files()
230 return_code = integrity_check.output_issues()
231 sys.exit(return_code)
232
233
234if __name__ == "__main__":
235 run_main()