check_files.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. #!/usr/bin/env python3
  2. # Copyright The Mbed TLS Contributors
  3. # SPDX-License-Identifier: Apache-2.0
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """
  17. This script checks the current state of the source code for minor issues,
  18. including incorrect file permissions, presence of tabs, non-Unix line endings,
  19. trailing whitespace, and presence of UTF-8 BOM.
  20. Note: requires python 3, must be run from Mbed TLS root.
  21. """
  22. import os
  23. import argparse
  24. import logging
  25. import codecs
  26. import re
  27. import subprocess
  28. import sys
  29. try:
  30. from typing import FrozenSet, Optional, Pattern # pylint: disable=unused-import
  31. except ImportError:
  32. pass
  33. import scripts_path # pylint: disable=unused-import
  34. from mbedtls_dev import build_tree
  35. class FileIssueTracker:
  36. """Base class for file-wide issue tracking.
  37. To implement a checker that processes a file as a whole, inherit from
  38. this class and implement `check_file_for_issue` and define ``heading``.
  39. ``suffix_exemptions``: files whose name ends with a string in this set
  40. will not be checked.
  41. ``path_exemptions``: files whose path (relative to the root of the source
  42. tree) matches this regular expression will not be checked. This can be
  43. ``None`` to match no path. Paths are normalized and converted to ``/``
  44. separators before matching.
  45. ``heading``: human-readable description of the issue
  46. """
  47. suffix_exemptions = frozenset() #type: FrozenSet[str]
  48. path_exemptions = None #type: Optional[Pattern[str]]
  49. # heading must be defined in derived classes.
  50. # pylint: disable=no-member
  51. def __init__(self):
  52. self.files_with_issues = {}
  53. @staticmethod
  54. def normalize_path(filepath):
  55. """Normalize ``filepath`` with / as the directory separator."""
  56. filepath = os.path.normpath(filepath)
  57. # On Windows, we may have backslashes to separate directories.
  58. # We need slashes to match exemption lists.
  59. seps = os.path.sep
  60. if os.path.altsep is not None:
  61. seps += os.path.altsep
  62. return '/'.join(filepath.split(seps))
  63. def should_check_file(self, filepath):
  64. """Whether the given file name should be checked.
  65. Files whose name ends with a string listed in ``self.suffix_exemptions``
  66. or whose path matches ``self.path_exemptions`` will not be checked.
  67. """
  68. for files_exemption in self.suffix_exemptions:
  69. if filepath.endswith(files_exemption):
  70. return False
  71. if self.path_exemptions and \
  72. re.match(self.path_exemptions, self.normalize_path(filepath)):
  73. return False
  74. return True
  75. def check_file_for_issue(self, filepath):
  76. """Check the specified file for the issue that this class is for.
  77. Subclasses must implement this method.
  78. """
  79. raise NotImplementedError
  80. def record_issue(self, filepath, line_number):
  81. """Record that an issue was found at the specified location."""
  82. if filepath not in self.files_with_issues.keys():
  83. self.files_with_issues[filepath] = []
  84. self.files_with_issues[filepath].append(line_number)
  85. def output_file_issues(self, logger):
  86. """Log all the locations where the issue was found."""
  87. if self.files_with_issues.values():
  88. logger.info(self.heading)
  89. for filename, lines in sorted(self.files_with_issues.items()):
  90. if lines:
  91. logger.info("{}: {}".format(
  92. filename, ", ".join(str(x) for x in lines)
  93. ))
  94. else:
  95. logger.info(filename)
  96. logger.info("")
  97. BINARY_FILE_PATH_RE_LIST = [
  98. r'docs/.*\.pdf\Z',
  99. r'programs/fuzz/corpuses/[^.]+\Z',
  100. r'tests/data_files/[^.]+\Z',
  101. r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
  102. r'tests/data_files/.*\.req\.[^/]+\Z',
  103. r'tests/data_files/.*malformed[^/]+\Z',
  104. r'tests/data_files/format_pkcs12\.fmt\Z',
  105. r'tests/data_files/.*\.bin\Z',
  106. ]
  107. BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
  108. class LineIssueTracker(FileIssueTracker):
  109. """Base class for line-by-line issue tracking.
  110. To implement a checker that processes files line by line, inherit from
  111. this class and implement `line_with_issue`.
  112. """
  113. # Exclude binary files.
  114. path_exemptions = BINARY_FILE_PATH_RE
  115. def issue_with_line(self, line, filepath, line_number):
  116. """Check the specified line for the issue that this class is for.
  117. Subclasses must implement this method.
  118. """
  119. raise NotImplementedError
  120. def check_file_line(self, filepath, line, line_number):
  121. if self.issue_with_line(line, filepath, line_number):
  122. self.record_issue(filepath, line_number)
  123. def check_file_for_issue(self, filepath):
  124. """Check the lines of the specified file.
  125. Subclasses must implement the ``issue_with_line`` method.
  126. """
  127. with open(filepath, "rb") as f:
  128. for i, line in enumerate(iter(f.readline, b"")):
  129. self.check_file_line(filepath, line, i + 1)
  130. def is_windows_file(filepath):
  131. _root, ext = os.path.splitext(filepath)
  132. return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
  133. class PermissionIssueTracker(FileIssueTracker):
  134. """Track files with bad permissions.
  135. Files that are not executable scripts must not be executable."""
  136. heading = "Incorrect permissions:"
  137. # .py files can be either full scripts or modules, so they may or may
  138. # not be executable.
  139. suffix_exemptions = frozenset({".py"})
  140. def check_file_for_issue(self, filepath):
  141. is_executable = os.access(filepath, os.X_OK)
  142. should_be_executable = filepath.endswith((".sh", ".pl"))
  143. if is_executable != should_be_executable:
  144. self.files_with_issues[filepath] = None
  145. class ShebangIssueTracker(FileIssueTracker):
  146. """Track files with a bad, missing or extraneous shebang line.
  147. Executable scripts must start with a valid shebang (#!) line.
  148. """
  149. heading = "Invalid shebang line:"
  150. # Allow either /bin/sh, /bin/bash, or /usr/bin/env.
  151. # Allow at most one argument (this is a Linux limitation).
  152. # For sh and bash, the argument if present must be options.
  153. # For env, the argument must be the base name of the interpreter.
  154. _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?'
  155. rb'|/usr/bin/env ([^\n /]+))$')
  156. _extensions = {
  157. b'bash': 'sh',
  158. b'perl': 'pl',
  159. b'python3': 'py',
  160. b'sh': 'sh',
  161. }
  162. def is_valid_shebang(self, first_line, filepath):
  163. m = re.match(self._shebang_re, first_line)
  164. if not m:
  165. return False
  166. interpreter = m.group(1) or m.group(2)
  167. if interpreter not in self._extensions:
  168. return False
  169. if not filepath.endswith('.' + self._extensions[interpreter]):
  170. return False
  171. return True
  172. def check_file_for_issue(self, filepath):
  173. is_executable = os.access(filepath, os.X_OK)
  174. with open(filepath, "rb") as f:
  175. first_line = f.readline()
  176. if first_line.startswith(b'#!'):
  177. if not is_executable:
  178. # Shebang on a non-executable file
  179. self.files_with_issues[filepath] = None
  180. elif not self.is_valid_shebang(first_line, filepath):
  181. self.files_with_issues[filepath] = [1]
  182. elif is_executable:
  183. # Executable without a shebang
  184. self.files_with_issues[filepath] = None
  185. class EndOfFileNewlineIssueTracker(FileIssueTracker):
  186. """Track files that end with an incomplete line
  187. (no newline character at the end of the last line)."""
  188. heading = "Missing newline at end of file:"
  189. path_exemptions = BINARY_FILE_PATH_RE
  190. def check_file_for_issue(self, filepath):
  191. with open(filepath, "rb") as f:
  192. try:
  193. f.seek(-1, 2)
  194. except OSError:
  195. # This script only works on regular files. If we can't seek
  196. # 1 before the end, it means that this position is before
  197. # the beginning of the file, i.e. that the file is empty.
  198. return
  199. if f.read(1) != b"\n":
  200. self.files_with_issues[filepath] = None
  201. class Utf8BomIssueTracker(FileIssueTracker):
  202. """Track files that start with a UTF-8 BOM.
  203. Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
  204. heading = "UTF-8 BOM present:"
  205. suffix_exemptions = frozenset([".vcxproj", ".sln"])
  206. path_exemptions = BINARY_FILE_PATH_RE
  207. def check_file_for_issue(self, filepath):
  208. with open(filepath, "rb") as f:
  209. if f.read().startswith(codecs.BOM_UTF8):
  210. self.files_with_issues[filepath] = None
  211. class UnicodeIssueTracker(LineIssueTracker):
  212. """Track lines with invalid characters or invalid text encoding."""
  213. heading = "Invalid UTF-8 or forbidden character:"
  214. # Only allow valid UTF-8, and only other explicitly allowed characters.
  215. # We deliberately exclude all characters that aren't a simple non-blank,
  216. # non-zero-width glyph, apart from a very small set (tab, ordinary space,
  217. # line breaks, "basic" no-break space and soft hyphen). In particular,
  218. # non-ASCII control characters, combinig characters, and Unicode state
  219. # changes (e.g. right-to-left text) are forbidden.
  220. # Note that we do allow some characters with a risk of visual confusion,
  221. # for example '-' (U+002D HYPHEN-MINUS) vs '­' (U+00AD SOFT HYPHEN) vs
  222. # '‐' (U+2010 HYPHEN), or 'A' (U+0041 LATIN CAPITAL LETTER A) vs
  223. # 'Α' (U+0391 GREEK CAPITAL LETTER ALPHA).
  224. GOOD_CHARACTERS = ''.join([
  225. '\t\n\r -~', # ASCII (tabs and line endings are checked separately)
  226. '\u00A0-\u00FF', # Latin-1 Supplement (for NO-BREAK SPACE and punctuation)
  227. '\u2010-\u2027\u2030-\u205E', # General Punctuation (printable)
  228. '\u2070\u2071\u2074-\u208E\u2090-\u209C', # Superscripts and Subscripts
  229. '\u2190-\u21FF', # Arrows
  230. '\u2200-\u22FF', # Mathematical Symbols
  231. '\u2500-\u257F' # Box Drawings characters used in markdown trees
  232. ])
  233. # Allow any of the characters and ranges above, and anything classified
  234. # as a word constituent.
  235. GOOD_CHARACTERS_RE = re.compile(r'[\w{}]+\Z'.format(GOOD_CHARACTERS))
  236. def issue_with_line(self, line, _filepath, line_number):
  237. try:
  238. text = line.decode('utf-8')
  239. except UnicodeDecodeError:
  240. return True
  241. if line_number == 1 and text.startswith('\uFEFF'):
  242. # Strip BOM (U+FEFF ZERO WIDTH NO-BREAK SPACE) at the beginning.
  243. # Which files are allowed to have a BOM is handled in
  244. # Utf8BomIssueTracker.
  245. text = text[1:]
  246. return not self.GOOD_CHARACTERS_RE.match(text)
  247. class UnixLineEndingIssueTracker(LineIssueTracker):
  248. """Track files with non-Unix line endings (i.e. files with CR)."""
  249. heading = "Non-Unix line endings:"
  250. def should_check_file(self, filepath):
  251. if not super().should_check_file(filepath):
  252. return False
  253. return not is_windows_file(filepath)
  254. def issue_with_line(self, line, _filepath, _line_number):
  255. return b"\r" in line
  256. class WindowsLineEndingIssueTracker(LineIssueTracker):
  257. """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
  258. heading = "Non-Windows line endings:"
  259. def should_check_file(self, filepath):
  260. if not super().should_check_file(filepath):
  261. return False
  262. return is_windows_file(filepath)
  263. def issue_with_line(self, line, _filepath, _line_number):
  264. return not line.endswith(b"\r\n") or b"\r" in line[:-2]
  265. class TrailingWhitespaceIssueTracker(LineIssueTracker):
  266. """Track lines with trailing whitespace."""
  267. heading = "Trailing whitespace:"
  268. suffix_exemptions = frozenset([".dsp", ".md"])
  269. def issue_with_line(self, line, _filepath, _line_number):
  270. return line.rstrip(b"\r\n") != line.rstrip()
  271. class TabIssueTracker(LineIssueTracker):
  272. """Track lines with tabs."""
  273. heading = "Tabs present:"
  274. suffix_exemptions = frozenset([
  275. ".pem", # some openssl dumps have tabs
  276. ".sln",
  277. "/Makefile",
  278. "/Makefile.inc",
  279. "/generate_visualc_files.pl",
  280. ])
  281. def issue_with_line(self, line, _filepath, _line_number):
  282. return b"\t" in line
  283. class MergeArtifactIssueTracker(LineIssueTracker):
  284. """Track lines with merge artifacts.
  285. These are leftovers from a ``git merge`` that wasn't fully edited."""
  286. heading = "Merge artifact:"
  287. def issue_with_line(self, line, _filepath, _line_number):
  288. # Detect leftover git conflict markers.
  289. if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
  290. return True
  291. if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
  292. return True
  293. if line.rstrip(b'\r\n') == b'=======' and \
  294. not _filepath.endswith('.md'):
  295. return True
  296. return False
  297. class IntegrityChecker:
  298. """Sanity-check files under the current directory."""
  299. def __init__(self, log_file):
  300. """Instantiate the sanity checker.
  301. Check files under the current directory.
  302. Write a report of issues to log_file."""
  303. build_tree.check_repo_path()
  304. self.logger = None
  305. self.setup_logger(log_file)
  306. self.issues_to_check = [
  307. PermissionIssueTracker(),
  308. ShebangIssueTracker(),
  309. EndOfFileNewlineIssueTracker(),
  310. Utf8BomIssueTracker(),
  311. UnicodeIssueTracker(),
  312. UnixLineEndingIssueTracker(),
  313. WindowsLineEndingIssueTracker(),
  314. TrailingWhitespaceIssueTracker(),
  315. TabIssueTracker(),
  316. MergeArtifactIssueTracker(),
  317. ]
  318. def setup_logger(self, log_file, level=logging.INFO):
  319. self.logger = logging.getLogger()
  320. self.logger.setLevel(level)
  321. if log_file:
  322. handler = logging.FileHandler(log_file)
  323. self.logger.addHandler(handler)
  324. else:
  325. console = logging.StreamHandler()
  326. self.logger.addHandler(console)
  327. @staticmethod
  328. def collect_files():
  329. bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
  330. bytes_filepaths = bytes_output.split(b'\0')[:-1]
  331. ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
  332. # Prepend './' to files in the top-level directory so that
  333. # something like `'/Makefile' in fp` matches in the top-level
  334. # directory as well as in subdirectories.
  335. return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
  336. for fp in ascii_filepaths]
  337. def check_files(self):
  338. for issue_to_check in self.issues_to_check:
  339. for filepath in self.collect_files():
  340. if issue_to_check.should_check_file(filepath):
  341. issue_to_check.check_file_for_issue(filepath)
  342. def output_issues(self):
  343. integrity_return_code = 0
  344. for issue_to_check in self.issues_to_check:
  345. if issue_to_check.files_with_issues:
  346. integrity_return_code = 1
  347. issue_to_check.output_file_issues(self.logger)
  348. return integrity_return_code
  349. def run_main():
  350. parser = argparse.ArgumentParser(description=__doc__)
  351. parser.add_argument(
  352. "-l", "--log_file", type=str, help="path to optional output log",
  353. )
  354. check_args = parser.parse_args()
  355. integrity_check = IntegrityChecker(check_args.log_file)
  356. integrity_check.check_files()
  357. return_code = integrity_check.output_issues()
  358. sys.exit(return_code)
  359. if __name__ == "__main__":
  360. run_main()