blob: 31edf8b61c51198d3462752d65b3674ce4ab0998 [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 Rodgman16799db2023-11-02 19:47:20 +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
Darryl Green10d9ce32018-02-28 10:02:55 +000013import argparse
Darryl Green10d9ce32018-02-28 10:02:55 +000014import codecs
Gilles Peskine990030b2023-11-03 13:55:00 +010015import logging
16import os
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 Peskined9071e72022-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 Peskine0ed9e782023-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 Peskineb3897432023-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 Peskineb3897432023-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 Peskine4aebb8d2020-08-08 23:15:18 +0200153class ShebangIssueTracker(FileIssueTracker):
154 """Track files with a bad, missing or extraneous shebang line.
155
156 Executable scripts must start with a valid shebang (#!) line.
157 """
158
159 heading = "Invalid shebang line:"
160
161 # Allow either /bin/sh, /bin/bash, or /usr/bin/env.
162 # Allow at most one argument (this is a Linux limitation).
163 # For sh and bash, the argument if present must be options.
Shaun Case8b0ecbc2021-12-20 21:14:10 -0800164 # For env, the argument must be the base name of the interpreter.
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200165 _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?'
166 rb'|/usr/bin/env ([^\n /]+))$')
167 _extensions = {
168 b'bash': 'sh',
169 b'perl': 'pl',
170 b'python3': 'py',
171 b'sh': 'sh',
172 }
173
174 def is_valid_shebang(self, first_line, filepath):
175 m = re.match(self._shebang_re, first_line)
176 if not m:
177 return False
178 interpreter = m.group(1) or m.group(2)
179 if interpreter not in self._extensions:
180 return False
181 if not filepath.endswith('.' + self._extensions[interpreter]):
182 return False
183 return True
184
185 def check_file_for_issue(self, filepath):
186 is_executable = os.access(filepath, os.X_OK)
187 with open(filepath, "rb") as f:
188 first_line = f.readline()
189 if first_line.startswith(b'#!'):
190 if not is_executable:
191 # Shebang on a non-executable file
192 self.files_with_issues[filepath] = None
193 elif not self.is_valid_shebang(first_line, filepath):
194 self.files_with_issues[filepath] = [1]
195 elif is_executable:
196 # Executable without a shebang
197 self.files_with_issues[filepath] = None
198
199
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100200class EndOfFileNewlineIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100201 """Track files that end with an incomplete line
202 (no newline character at the end of the last line)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000203
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100204 heading = "Missing newline at end of file:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000205
Gilles Peskined4a853d2020-05-10 16:57:59 +0200206 path_exemptions = BINARY_FILE_PATH_RE
207
Darryl Green10d9ce32018-02-28 10:02:55 +0000208 def check_file_for_issue(self, filepath):
209 with open(filepath, "rb") as f:
Gilles Peskine12b180a2020-05-10 17:36:42 +0200210 try:
211 f.seek(-1, 2)
212 except OSError:
213 # This script only works on regular files. If we can't seek
214 # 1 before the end, it means that this position is before
215 # the beginning of the file, i.e. that the file is empty.
216 return
217 if f.read(1) != b"\n":
Darryl Green10d9ce32018-02-28 10:02:55 +0000218 self.files_with_issues[filepath] = None
219
220
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100221class Utf8BomIssueTracker(FileIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100222 """Track files that start with a UTF-8 BOM.
223 Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000224
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100225 heading = "UTF-8 BOM present:"
Darryl Green10d9ce32018-02-28 10:02:55 +0000226
Gilles Peskine05a51a82020-05-10 16:52:44 +0200227 suffix_exemptions = frozenset([".vcxproj", ".sln"])
Gilles Peskined4a853d2020-05-10 16:57:59 +0200228 path_exemptions = BINARY_FILE_PATH_RE
Gilles Peskine2c618732020-03-24 22:26:01 +0100229
Darryl Green10d9ce32018-02-28 10:02:55 +0000230 def check_file_for_issue(self, filepath):
231 with open(filepath, "rb") as f:
232 if f.read().startswith(codecs.BOM_UTF8):
233 self.files_with_issues[filepath] = None
234
235
Gilles Peskined11bb472023-01-05 20:28:57 +0100236class UnicodeIssueTracker(LineIssueTracker):
237 """Track lines with invalid characters or invalid text encoding."""
238
239 heading = "Invalid UTF-8 or forbidden character:"
240
Aditya Deshpande15b6dd02023-01-30 13:46:58 +0000241 # Only allow valid UTF-8, and only other explicitly allowed characters.
Gilles Peskined11bb472023-01-05 20:28:57 +0100242 # We deliberately exclude all characters that aren't a simple non-blank,
243 # non-zero-width glyph, apart from a very small set (tab, ordinary space,
244 # line breaks, "basic" no-break space and soft hyphen). In particular,
245 # non-ASCII control characters, combinig characters, and Unicode state
246 # changes (e.g. right-to-left text) are forbidden.
247 # Note that we do allow some characters with a risk of visual confusion,
248 # for example '-' (U+002D HYPHEN-MINUS) vs '­' (U+00AD SOFT HYPHEN) vs
249 # '‐' (U+2010 HYPHEN), or 'A' (U+0041 LATIN CAPITAL LETTER A) vs
250 # 'Α' (U+0391 GREEK CAPITAL LETTER ALPHA).
251 GOOD_CHARACTERS = ''.join([
252 '\t\n\r -~', # ASCII (tabs and line endings are checked separately)
253 '\u00A0-\u00FF', # Latin-1 Supplement (for NO-BREAK SPACE and punctuation)
254 '\u2010-\u2027\u2030-\u205E', # General Punctuation (printable)
255 '\u2070\u2071\u2074-\u208E\u2090-\u209C', # Superscripts and Subscripts
256 '\u2190-\u21FF', # Arrows
257 '\u2200-\u22FF', # Mathematical Symbols
Aditya Deshpandeebb22692023-02-01 13:30:26 +0000258 '\u2500-\u257F' # Box Drawings characters used in markdown trees
Gilles Peskined11bb472023-01-05 20:28:57 +0100259 ])
260 # Allow any of the characters and ranges above, and anything classified
261 # as a word constituent.
262 GOOD_CHARACTERS_RE = re.compile(r'[\w{}]+\Z'.format(GOOD_CHARACTERS))
263
264 def issue_with_line(self, line, _filepath, line_number):
265 try:
266 text = line.decode('utf-8')
267 except UnicodeDecodeError:
268 return True
269 if line_number == 1 and text.startswith('\uFEFF'):
270 # Strip BOM (U+FEFF ZERO WIDTH NO-BREAK SPACE) at the beginning.
271 # Which files are allowed to have a BOM is handled in
272 # Utf8BomIssueTracker.
273 text = text[1:]
274 return not self.GOOD_CHARACTERS_RE.match(text)
275
Gilles Peskine2c618732020-03-24 22:26:01 +0100276class UnixLineEndingIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100277 """Track files with non-Unix line endings (i.e. files with CR)."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000278
Gilles Peskine2c618732020-03-24 22:26:01 +0100279 heading = "Non-Unix line endings:"
280
281 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200282 if not super().should_check_file(filepath):
283 return False
Gilles Peskine2c618732020-03-24 22:26:01 +0100284 return not is_windows_file(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000285
Gilles Peskineb3897432023-01-05 20:28:30 +0100286 def issue_with_line(self, line, _filepath, _line_number):
Darryl Green10d9ce32018-02-28 10:02:55 +0000287 return b"\r" in line
288
289
Gilles Peskine545e13f2020-03-24 22:29:11 +0100290class WindowsLineEndingIssueTracker(LineIssueTracker):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200291 """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
Gilles Peskine545e13f2020-03-24 22:29:11 +0100292
293 heading = "Non-Windows line endings:"
294
295 def should_check_file(self, filepath):
Gilles Peskine0598db82020-05-10 16:57:16 +0200296 if not super().should_check_file(filepath):
297 return False
Gilles Peskine545e13f2020-03-24 22:29:11 +0100298 return is_windows_file(filepath)
299
Gilles Peskineb3897432023-01-05 20:28:30 +0100300 def issue_with_line(self, line, _filepath, _line_number):
Gilles Peskined703a2e2020-04-01 13:35:46 +0200301 return not line.endswith(b"\r\n") or b"\r" in line[:-2]
Gilles Peskine545e13f2020-03-24 22:29:11 +0100302
303
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100304class TrailingWhitespaceIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100305 """Track lines with trailing whitespace."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000306
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100307 heading = "Trailing whitespace:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200308 suffix_exemptions = frozenset([".dsp", ".md"])
Darryl Green10d9ce32018-02-28 10:02:55 +0000309
Gilles Peskineb3897432023-01-05 20:28:30 +0100310 def issue_with_line(self, line, _filepath, _line_number):
Darryl Green10d9ce32018-02-28 10:02:55 +0000311 return line.rstrip(b"\r\n") != line.rstrip()
312
313
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100314class TabIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100315 """Track lines with tabs."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000316
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100317 heading = "Tabs present:"
Gilles Peskine05a51a82020-05-10 16:52:44 +0200318 suffix_exemptions = frozenset([
Gilles Peskine344da1c2020-05-10 17:37:02 +0200319 ".pem", # some openssl dumps have tabs
Gilles Peskine2c618732020-03-24 22:26:01 +0100320 ".sln",
Gilles Peskine6e8d5a02020-03-24 22:01:28 +0100321 "/Makefile",
322 "/Makefile.inc",
323 "/generate_visualc_files.pl",
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100324 ])
Darryl Green10d9ce32018-02-28 10:02:55 +0000325
Gilles Peskineb3897432023-01-05 20:28:30 +0100326 def issue_with_line(self, line, _filepath, _line_number):
Darryl Green10d9ce32018-02-28 10:02:55 +0000327 return b"\t" in line
328
329
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100330class MergeArtifactIssueTracker(LineIssueTracker):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100331 """Track lines with merge artifacts.
332 These are leftovers from a ``git merge`` that wasn't fully edited."""
Gilles Peskinec117d592018-11-23 21:11:52 +0100333
Gilles Peskine1e9698a2019-02-25 21:10:04 +0100334 heading = "Merge artifact:"
Gilles Peskinec117d592018-11-23 21:11:52 +0100335
Gilles Peskineb3897432023-01-05 20:28:30 +0100336 def issue_with_line(self, line, _filepath, _line_number):
Gilles Peskinec117d592018-11-23 21:11:52 +0100337 # Detect leftover git conflict markers.
338 if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
339 return True
340 if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
341 return True
342 if line.rstrip(b'\r\n') == b'=======' and \
Gilles Peskine6ee576e2019-02-25 20:59:05 +0100343 not _filepath.endswith('.md'):
Gilles Peskinec117d592018-11-23 21:11:52 +0100344 return True
345 return False
346
Darryl Green10d9ce32018-02-28 10:02:55 +0000347
Gilles Peskine184c0962020-03-24 18:25:17 +0100348class IntegrityChecker:
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100349 """Sanity-check files under the current directory."""
Darryl Green10d9ce32018-02-28 10:02:55 +0000350
351 def __init__(self, log_file):
Gilles Peskine0d060ef2019-02-25 20:35:31 +0100352 """Instantiate the sanity checker.
353 Check files under the current directory.
354 Write a report of issues to log_file."""
Gilles Peskined9071e72022-09-18 21:17:09 +0200355 build_tree.check_repo_path()
Darryl Green10d9ce32018-02-28 10:02:55 +0000356 self.logger = None
357 self.setup_logger(log_file)
Darryl Green10d9ce32018-02-28 10:02:55 +0000358 self.issues_to_check = [
Gilles Peskine4aebb8d2020-08-08 23:15:18 +0200359 ShebangIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000360 EndOfFileNewlineIssueTracker(),
361 Utf8BomIssueTracker(),
Gilles Peskined11bb472023-01-05 20:28:57 +0100362 UnicodeIssueTracker(),
Gilles Peskine2c618732020-03-24 22:26:01 +0100363 UnixLineEndingIssueTracker(),
Gilles Peskine545e13f2020-03-24 22:29:11 +0100364 WindowsLineEndingIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000365 TrailingWhitespaceIssueTracker(),
366 TabIssueTracker(),
Gilles Peskinec117d592018-11-23 21:11:52 +0100367 MergeArtifactIssueTracker(),
Darryl Green10d9ce32018-02-28 10:02:55 +0000368 ]
369
Darryl Green10d9ce32018-02-28 10:02:55 +0000370 def setup_logger(self, log_file, level=logging.INFO):
371 self.logger = logging.getLogger()
372 self.logger.setLevel(level)
373 if log_file:
374 handler = logging.FileHandler(log_file)
375 self.logger.addHandler(handler)
376 else:
377 console = logging.StreamHandler()
378 self.logger.addHandler(console)
379
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200380 @staticmethod
381 def collect_files():
382 bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
383 bytes_filepaths = bytes_output.split(b'\0')[:-1]
384 ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
385 # Prepend './' to files in the top-level directory so that
386 # something like `'/Makefile' in fp` matches in the top-level
387 # directory as well as in subdirectories.
388 return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
389 for fp in ascii_filepaths]
Gilles Peskine95c55752018-09-28 11:48:10 +0200390
Darryl Green10d9ce32018-02-28 10:02:55 +0000391 def check_files(self):
Gilles Peskine3e2ee3c2020-05-10 17:18:06 +0200392 for issue_to_check in self.issues_to_check:
393 for filepath in self.collect_files():
394 if issue_to_check.should_check_file(filepath):
395 issue_to_check.check_file_for_issue(filepath)
Darryl Green10d9ce32018-02-28 10:02:55 +0000396
397 def output_issues(self):
398 integrity_return_code = 0
399 for issue_to_check in self.issues_to_check:
400 if issue_to_check.files_with_issues:
401 integrity_return_code = 1
402 issue_to_check.output_file_issues(self.logger)
403 return integrity_return_code
404
405
406def run_main():
Gilles Peskine7dfcfce2019-07-04 19:31:02 +0200407 parser = argparse.ArgumentParser(description=__doc__)
Darryl Green10d9ce32018-02-28 10:02:55 +0000408 parser.add_argument(
409 "-l", "--log_file", type=str, help="path to optional output log",
410 )
411 check_args = parser.parse_args()
412 integrity_check = IntegrityChecker(check_args.log_file)
413 integrity_check.check_files()
414 return_code = integrity_check.output_issues()
415 sys.exit(return_code)
416
417
418if __name__ == "__main__":
419 run_main()