blob: e3593662b386f2fb1c65a3c81ee621919f124507 [file] [log] [blame]
Darryl Green10d9ce32018-02-28 10:02:55 +00001#!/usr/bin/env python3
Gilles Peskine7dfcfce2019-07-04 19:31:02 +02002
Bence Szépkúti1e148272020-08-07 13:07:28 +02003# Copyright The Mbed TLS Contributors
Dave Rodgman0f2971a2023-11-03 12:04:52 +00004# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskine7dfcfce2019-07-04 19:31:02 +02005
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
Gilles Peskine0598db82020-05-10 16:57:16 +020017import re
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +020018import subprocess
Darryl Green10d9ce32018-02-28 10:02:55 +000019import sys
Gilles Peskineac9e7c02020-08-11 15:11:50 +020020try:
21 from typing import FrozenSet, Optional, Pattern # pylint: disable=unused-import
22except ImportError:
23 pass
Darryl Green10d9ce32018-02-28 10:02:55 +000024
Gilles Peskine7ff47662022-09-18 21:17:09 +020025import scripts_path # pylint: disable=unused-import
26from mbedtls_dev import build_tree
27
Darryl Green10d9ce32018-02-28 10:02:55 +000028
Gilles Peskine184c0962020-03-24 18:25:17 +010029class FileIssueTracker:
Gilles Peskine6ee576e2019-02-25 20:59:05 +010030 """Base class for file-wide issue tracking.
31
32 To implement a checker that processes a file as a whole, inherit from
Gilles Peskine1e9698a2019-02-25 21:10:04 +010033 this class and implement `check_file_for_issue` and define ``heading``.
34
Gilles Peskine05a51a82020-05-10 16:52:44 +020035 ``suffix_exemptions``: files whose name ends with a string in this set
Gilles Peskine1e9698a2019-02-25 21:10:04 +010036 will not be checked.
37
Gilles Peskine0598db82020-05-10 16:57:16 +020038 ``path_exemptions``: files whose path (relative to the root of the source
39 tree) matches this regular expression will not be checked. This can be
40 ``None`` to match no path. Paths are normalized and converted to ``/``
41 separators before matching.
42
Gilles Peskine1e9698a2019-02-25 21:10:04 +010043 ``heading``: human-readable description of the issue
Gilles Peskine6ee576e2019-02-25 20:59:05 +010044 """
Darryl Green10d9ce32018-02-28 10:02:55 +000045
Gilles Peskineac9e7c02020-08-11 15:11:50 +020046 suffix_exemptions = frozenset() #type: FrozenSet[str]
47 path_exemptions = None #type: Optional[Pattern[str]]
Gilles Peskine1e9698a2019-02-25 21:10:04 +010048 # heading must be defined in derived classes.
49 # pylint: disable=no-member
50
Darryl Green10d9ce32018-02-28 10:02:55 +000051 def __init__(self):
Darryl Green10d9ce32018-02-28 10:02:55 +000052 self.files_with_issues = {}
53
Gilles Peskine0598db82020-05-10 16:57:16 +020054 @staticmethod
55 def normalize_path(filepath):
Gilles Peskineeca95db2020-05-28 18:19:20 +020056 """Normalize ``filepath`` with / as the directory separator."""
Gilles Peskine0598db82020-05-10 16:57:16 +020057 filepath = os.path.normpath(filepath)
Gilles Peskineeca95db2020-05-28 18:19:20 +020058 # On Windows, we may have backslashes to separate directories.
59 # We need slashes to match exemption lists.
Gilles Peskine0598db82020-05-10 16:57:16 +020060 seps = os.path.sep
61 if os.path.altsep is not None:
62 seps += os.path.altsep
63 return '/'.join(filepath.split(seps))
64
Darryl Green10d9ce32018-02-28 10:02:55 +000065 def should_check_file(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010066 """Whether the given file name should be checked.
67
Gilles Peskine05a51a82020-05-10 16:52:44 +020068 Files whose name ends with a string listed in ``self.suffix_exemptions``
69 or whose path matches ``self.path_exemptions`` will not be checked.
Gilles Peskineaaee4442020-03-24 16:49:21 +010070 """
Gilles Peskine05a51a82020-05-10 16:52:44 +020071 for files_exemption in self.suffix_exemptions:
Darryl Green10d9ce32018-02-28 10:02:55 +000072 if filepath.endswith(files_exemption):
73 return False
Gilles Peskine0598db82020-05-10 16:57:16 +020074 if self.path_exemptions and \
75 re.match(self.path_exemptions, self.normalize_path(filepath)):
76 return False
Darryl Green10d9ce32018-02-28 10:02:55 +000077 return True
78
Darryl Green10d9ce32018-02-28 10:02:55 +000079 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +010080 """Check the specified file for the issue that this class is for.
81
82 Subclasses must implement this method.
83 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +010084 raise NotImplementedError
Darryl Green10d9ce32018-02-28 10:02:55 +000085
Gilles Peskine04398052018-11-23 21:11:30 +010086 def record_issue(self, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +010087 """Record that an issue was found at the specified location."""
Gilles Peskine04398052018-11-23 21:11:30 +010088 if filepath not in self.files_with_issues.keys():
89 self.files_with_issues[filepath] = []
90 self.files_with_issues[filepath].append(line_number)
91
Darryl Green10d9ce32018-02-28 10:02:55 +000092 def output_file_issues(self, logger):
Gilles Peskineaaee4442020-03-24 16:49:21 +010093 """Log all the locations where the issue was found."""
Darryl Green10d9ce32018-02-28 10:02:55 +000094 if self.files_with_issues.values():
95 logger.info(self.heading)
96 for filename, lines in sorted(self.files_with_issues.items()):
97 if lines:
98 logger.info("{}: {}".format(
99 filename, ", ".join(str(x) for x in lines)
100 ))
101 else:
102 logger.info(filename)
103 logger.info("")
104
Gilles Peskined4a853d2020-05-10 16:57:59 +0200105BINARY_FILE_PATH_RE_LIST = [
106 r'docs/.*\.pdf\Z',
107 r'programs/fuzz/corpuses/[^.]+\Z',
108 r'tests/data_files/[^.]+\Z',
109 r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
110 r'tests/data_files/.*\.req\.[^/]+\Z',
111 r'tests/data_files/.*malformed[^/]+\Z',
112 r'tests/data_files/format_pkcs12\.fmt\Z',
Gilles Peskine66548d12023-01-05 20:27:18 +0100113 r'tests/data_files/.*\.bin\Z',
Gilles Peskined4a853d2020-05-10 16:57:59 +0200114]
115BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
116
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100117class LineIssueTracker(FileIssueTracker):
118 """Base class for line-by-line issue tracking.
Darryl Green10d9ce32018-02-28 10:02:55 +0000119
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100120 To implement a checker that processes files line by line, inherit from
121 this class and implement `line_with_issue`.
122 """
123
Gilles Peskined4a853d2020-05-10 16:57:59 +0200124 # Exclude binary files.
125 path_exemptions = BINARY_FILE_PATH_RE
126
Gilles Peskineff723d82023-01-05 20:28:30 +0100127 def issue_with_line(self, line, filepath, line_number):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100128 """Check the specified line for the issue that this class is for.
129
130 Subclasses must implement this method.
131 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100132 raise NotImplementedError
133
134 def check_file_line(self, filepath, line, line_number):
Gilles Peskineff723d82023-01-05 20:28:30 +0100135 if self.issue_with_line(line, filepath, line_number):
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100136 self.record_issue(filepath, line_number)
137
138 def check_file_for_issue(self, filepath):
Gilles Peskineaaee4442020-03-24 16:49:21 +0100139 """Check the lines of the specified file.
140
141 Subclasses must implement the ``issue_with_line`` method.
142 """
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100143 with open(filepath, "rb") as f:
144 for i, line in enumerate(iter(f.readline, b"")):
145 self.check_file_line(filepath, line, i + 1)
146
Gilles Peskine2c618732020-03-24 22:26:01 +0100147
148def is_windows_file(filepath):
149 _root, ext = os.path.splitext(filepath)
Gilles Peskined2df86f2020-05-10 17:36:51 +0200150 return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
Gilles Peskine2c618732020-03-24 22:26:01 +0100151
152
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100153class PermissionIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100154 """Track files with bad permissions.
155
156 Files that are not executable scripts must not be executable."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000157
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100158 heading = "Incorrect permissions:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000159
Gilles Peskine15898ee2020-08-08 23:14:27 +0200160 # .py files can be either full scripts or modules, so they may or may
161 # not be executable.
162 suffix_exemptions = frozenset({".py"})
163
Darryl Green10d9ce32018-02-28 10:02:55 +0000164 def check_file_for_issue(self, filepath):
Gilles Peskine23e64f22019-02-25 21:24:27 +0100165 is_executable = os.access(filepath, os.X_OK)
Gilles Peskine15898ee2020-08-08 23:14:27 +0200166 should_be_executable = filepath.endswith((".sh", ".pl"))
Gilles Peskine23e64f22019-02-25 21:24:27 +0100167 if is_executable != should_be_executable:
Darryl Green10d9ce32018-02-28 10:02:55 +0000168 self.files_with_issues[filepath] = None
169
170
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200171class ShebangIssueTracker(FileIssueTracker):
172 """Track files with a bad, missing or extraneous shebang line.
173
174 Executable scripts must start with a valid shebang (#!) line.
175 """
176
177 heading = "Invalid shebang line:"
178
179 # Allow either /bin/sh, /bin/bash, or /usr/bin/env.
180 # Allow at most one argument (this is a Linux limitation).
181 # For sh and bash, the argument if present must be options.
Shaun Case0e7791f2021-12-20 21:14:10 -0800182 # For env, the argument must be the base name of the interpreter.
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200183 _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?'
184 rb'|/usr/bin/env ([^\n /]+))$')
185 _extensions = {
186 b'bash': 'sh',
187 b'perl': 'pl',
188 b'python3': 'py',
189 b'sh': 'sh',
190 }
191
192 def is_valid_shebang(self, first_line, filepath):
193 m = re.match(self._shebang_re, first_line)
194 if not m:
195 return False
196 interpreter = m.group(1) or m.group(2)
197 if interpreter not in self._extensions:
198 return False
199 if not filepath.endswith('.' + self._extensions[interpreter]):
200 return False
201 return True
202
203 def check_file_for_issue(self, filepath):
204 is_executable = os.access(filepath, os.X_OK)
205 with open(filepath, "rb") as f:
206 first_line = f.readline()
207 if first_line.startswith(b'#!'):
208 if not is_executable:
209 # Shebang on a non-executable file
210 self.files_with_issues[filepath] = None
211 elif not self.is_valid_shebang(first_line, filepath):
212 self.files_with_issues[filepath] = [1]
213 elif is_executable:
214 # Executable without a shebang
215 self.files_with_issues[filepath] = None
216
217
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100218class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100219 """Track files that end with an incomplete line
220 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000221
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100222 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000223
Gilles Peskined4a853d2020-05-10 16:57:59 +0200224 path_exemptions = BINARY_FILE_PATH_RE
225
Darryl Green10d9ce32018-02-28 10:02:55 +0000226 def check_file_for_issue(self, filepath):
227 with open(filepath, "rb") as f:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200228 try:
229 f.seek(-1, 2)
230 except OSError:
231 # This script only works on regular files. If we can't seek
232 # 1 before the end, it means that this position is before
233 # the beginning of the file, i.e. that the file is empty.
234 return
235 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000236 self.files_with_issues[filepath] = None
237
238
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100239class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100240 """Track files that start with a UTF-8 BOM.
241 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000242
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100243 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000244
Gilles Peskine05a51a82020-05-10 16:52:44 +0200245 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200246 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100247
Darryl Green10d9ce32018-02-28 10:02:55 +0000248 def check_file_for_issue(self, filepath):
249 with open(filepath, "rb") as f:
250 if f.read().startswith(codecs.BOM_UTF8):
251 self.files_with_issues[filepath] = None
252
253
Gilles Peskineb60b7a32023-01-05 20:28:57 +0100254class UnicodeIssueTracker(LineIssueTracker):
255 """Track lines with invalid characters or invalid text encoding."""
256
257 heading = "Invalid UTF-8 or forbidden character:"
258
Aditya Deshpandee76dc392023-01-30 13:46:58 +0000259 # Only allow valid UTF-8, and only other explicitly allowed characters.
Gilles Peskineb60b7a32023-01-05 20:28:57 +0100260 # We deliberately exclude all characters that aren't a simple non-blank,
261 # non-zero-width glyph, apart from a very small set (tab, ordinary space,
262 # line breaks, "basic" no-break space and soft hyphen). In particular,
263 # non-ASCII control characters, combinig characters, and Unicode state
264 # changes (e.g. right-to-left text) are forbidden.
265 # Note that we do allow some characters with a risk of visual confusion,
266 # for example '-' (U+002D HYPHEN-MINUS) vs '­' (U+00AD SOFT HYPHEN) vs
267 # '‐' (U+2010 HYPHEN), or 'A' (U+0041 LATIN CAPITAL LETTER A) vs
268 # 'Α' (U+0391 GREEK CAPITAL LETTER ALPHA).
269 GOOD_CHARACTERS = ''.join([
270 '\t\n\r -~', # ASCII (tabs and line endings are checked separately)
271 '\u00A0-\u00FF', # Latin-1 Supplement (for NO-BREAK SPACE and punctuation)
272 '\u2010-\u2027\u2030-\u205E', # General Punctuation (printable)
273 '\u2070\u2071\u2074-\u208E\u2090-\u209C', # Superscripts and Subscripts
274 '\u2190-\u21FF', # Arrows
275 '\u2200-\u22FF', # Mathematical Symbols
Aditya Deshpandea9186f32023-02-01 13:30:26 +0000276 '\u2500-\u257F' # Box Drawings characters used in markdown trees
Gilles Peskineb60b7a32023-01-05 20:28:57 +0100277 ])
278 # Allow any of the characters and ranges above, and anything classified
279 # as a word constituent.
280 GOOD_CHARACTERS_RE = re.compile(r'[\w{}]+\Z'.format(GOOD_CHARACTERS))
281
282 def issue_with_line(self, line, _filepath, line_number):
283 try:
284 text = line.decode('utf-8')
285 except UnicodeDecodeError:
286 return True
287 if line_number == 1 and text.startswith('\uFEFF'):
288 # Strip BOM (U+FEFF ZERO WIDTH NO-BREAK SPACE) at the beginning.
289 # Which files are allowed to have a BOM is handled in
290 # Utf8BomIssueTracker.
291 text = text[1:]
292 return not self.GOOD_CHARACTERS_RE.match(text)
293
Gilles Peskine2c618732020-03-24 22:26:01 +0100294class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100295 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000296
Gilles Peskine2c618732020-03-24 22:26:01 +0100297 heading = "Non-Unix line endings:"
298
299 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200300 if not super().should_check_file(filepath):
301 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100302 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000303
Gilles Peskineff723d82023-01-05 20:28:30 +0100304 def issue_with_line(self, line, _filepath, _line_number):
Darryl Green10d9ce32018-02-28 10:02:55 +0000305 return b"\r" in line
306
307
Gilles Peskine545e13f2020-03-24 22:29:11 +0100308class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200309 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100310
311 heading = "Non-Windows line endings:"
312
313 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200314 if not super().should_check_file(filepath):
315 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100316 return is_windows_file(filepath)
317
Gilles Peskineff723d82023-01-05 20:28:30 +0100318 def issue_with_line(self, line, _filepath, _line_number):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200319 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100320
321
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100322class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100323 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000324
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100325 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200326 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000327
Gilles Peskineff723d82023-01-05 20:28:30 +0100328 def issue_with_line(self, line, _filepath, _line_number):
Darryl Green10d9ce32018-02-28 10:02:55 +0000329 return line.rstrip(b"\r\n") != line.rstrip()
330
331
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100332class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100333 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000334
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100335 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200336 suffix_exemptions = frozenset([
Gilles Peskine344da1c2020-05-10 17:37:02 +0200337 ".pem", # some openssl dumps have tabs
Gilles Peskine2c618732020-03-24 22:26:01 +0100338 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100339 "/Makefile",
340 "/Makefile.inc",
341 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100342 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000343
Gilles Peskineff723d82023-01-05 20:28:30 +0100344 def issue_with_line(self, line, _filepath, _line_number):
Darryl Green10d9ce32018-02-28 10:02:55 +0000345 return b"\t" in line
346
347
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100348class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100349 """Track lines with merge artifacts.
350 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100351
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100352 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100353
Gilles Peskineff723d82023-01-05 20:28:30 +0100354 def issue_with_line(self, line, _filepath, _line_number):
Gilles Peskinec117d592018-11-23 21:11:52 +0100355 # Detect leftover git conflict markers.
356 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
357 return True
358 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
359 return True
360 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100361 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100362 return True
363 return False
364
Darryl Green10d9ce32018-02-28 10:02:55 +0000365
Gilles Peskine184c0962020-03-24 18:25:17 +0100366class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100367 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000368
369 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100370 """Instantiate the sanity checker.
371 Check files under the current directory.
372 Write a report of issues to log_file."""
Gilles Peskine7ff47662022-09-18 21:17:09 +0200373 build_tree.check_repo_path()
Darryl Green10d9ce32018-02-28 10:02:55 +0000374 self.logger = None
375 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000376 self.issues_to_check = [
377 PermissionIssueTracker(),
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200378 ShebangIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000379 EndOfFileNewlineIssueTracker(),
380 Utf8BomIssueTracker(),
Gilles Peskineb60b7a32023-01-05 20:28:57 +0100381 UnicodeIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100382 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100383 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000384 TrailingWhitespaceIssueTracker(),
385 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100386 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000387 ]
388
Darryl Green10d9ce32018-02-28 10:02:55 +0000389 def setup_logger(self, log_file, level=logging.INFO):
390 self.logger = logging.getLogger()
391 self.logger.setLevel(level)
392 if log_file:
393 handler = logging.FileHandler(log_file)
394 self.logger.addHandler(handler)
395 else:
396 console = logging.StreamHandler()
397 self.logger.addHandler(console)
398
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200399 @staticmethod
400 def collect_files():
401 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
402 bytes_filepaths = bytes_output.split(b'\0')[:-1]
403 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
404 # Prepend './' to files in the top-level directory so that
405 # something like `'/Makefile' in fp` matches in the top-level
406 # directory as well as in subdirectories.
407 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
408 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200409
Darryl Green10d9ce32018-02-28 10:02:55 +0000410 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200411 for issue_to_check in self.issues_to_check:
412 for filepath in self.collect_files():
413 if issue_to_check.should_check_file(filepath):
414 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000415
416 def output_issues(self):
417 integrity_return_code = 0
418 for issue_to_check in self.issues_to_check:
419 if issue_to_check.files_with_issues:
420 integrity_return_code = 1
421 issue_to_check.output_file_issues(self.logger)
422 return integrity_return_code
423
424
425def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200426 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000427 parser.add_argument(
428 "-l", "--log_file", type=str, help="path to optional output log",
429 )
430 check_args = parser.parse_args()
431 integrity_check = IntegrityChecker(check_args.log_file)
432 integrity_check.check_files()
433 return_code = integrity_check.output_issues()
434 sys.exit(return_code)
435
436
437if __name__ == "__main__":
438 run_main()