check_files.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. class FileIssueTracker:
  34. """Base class for file-wide issue tracking.
  35. To implement a checker that processes a file as a whole, inherit from
  36. this class and implement `check_file_for_issue` and define ``heading``.
  37. ``suffix_exemptions``: files whose name ends with a string in this set
  38. will not be checked.
  39. ``path_exemptions``: files whose path (relative to the root of the source
  40. tree) matches this regular expression will not be checked. This can be
  41. ``None`` to match no path. Paths are normalized and converted to ``/``
  42. separators before matching.
  43. ``heading``: human-readable description of the issue
  44. """
  45. suffix_exemptions = frozenset() #type: FrozenSet[str]
  46. path_exemptions = None #type: Optional[Pattern[str]]
  47. # heading must be defined in derived classes.
  48. # pylint: disable=no-member
  49. def __init__(self):
  50. self.files_with_issues = {}
  51. @staticmethod
  52. def normalize_path(filepath):
  53. """Normalize ``filepath`` with / as the directory separator."""
  54. filepath = os.path.normpath(filepath)
  55. # On Windows, we may have backslashes to separate directories.
  56. # We need slashes to match exemption lists.
  57. seps = os.path.sep
  58. if os.path.altsep is not None:
  59. seps += os.path.altsep
  60. return '/'.join(filepath.split(seps))
  61. def should_check_file(self, filepath):
  62. """Whether the given file name should be checked.
  63. Files whose name ends with a string listed in ``self.suffix_exemptions``
  64. or whose path matches ``self.path_exemptions`` will not be checked.
  65. """
  66. for files_exemption in self.suffix_exemptions:
  67. if filepath.endswith(files_exemption):
  68. return False
  69. if self.path_exemptions and \
  70. re.match(self.path_exemptions, self.normalize_path(filepath)):
  71. return False
  72. return True
  73. def check_file_for_issue(self, filepath):
  74. """Check the specified file for the issue that this class is for.
  75. Subclasses must implement this method.
  76. """
  77. raise NotImplementedError
  78. def record_issue(self, filepath, line_number):
  79. """Record that an issue was found at the specified location."""
  80. if filepath not in self.files_with_issues.keys():
  81. self.files_with_issues[filepath] = []
  82. self.files_with_issues[filepath].append(line_number)
  83. def output_file_issues(self, logger):
  84. """Log all the locations where the issue was found."""
  85. if self.files_with_issues.values():
  86. logger.info(self.heading)
  87. for filename, lines in sorted(self.files_with_issues.items()):
  88. if lines:
  89. logger.info("{}: {}".format(
  90. filename, ", ".join(str(x) for x in lines)
  91. ))
  92. else:
  93. logger.info(filename)
  94. logger.info("")
  95. BINARY_FILE_PATH_RE_LIST = [
  96. r'docs/.*\.pdf\Z',
  97. r'programs/fuzz/corpuses/[^.]+\Z',
  98. r'tests/data_files/[^.]+\Z',
  99. r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
  100. r'tests/data_files/.*\.req\.[^/]+\Z',
  101. r'tests/data_files/.*malformed[^/]+\Z',
  102. r'tests/data_files/format_pkcs12\.fmt\Z',
  103. ]
  104. BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
  105. class LineIssueTracker(FileIssueTracker):
  106. """Base class for line-by-line issue tracking.
  107. To implement a checker that processes files line by line, inherit from
  108. this class and implement `line_with_issue`.
  109. """
  110. # Exclude binary files.
  111. path_exemptions = BINARY_FILE_PATH_RE
  112. def issue_with_line(self, line, filepath):
  113. """Check the specified line for the issue that this class is for.
  114. Subclasses must implement this method.
  115. """
  116. raise NotImplementedError
  117. def check_file_line(self, filepath, line, line_number):
  118. if self.issue_with_line(line, filepath):
  119. self.record_issue(filepath, line_number)
  120. def check_file_for_issue(self, filepath):
  121. """Check the lines of the specified file.
  122. Subclasses must implement the ``issue_with_line`` method.
  123. """
  124. with open(filepath, "rb") as f:
  125. for i, line in enumerate(iter(f.readline, b"")):
  126. self.check_file_line(filepath, line, i + 1)
  127. def is_windows_file(filepath):
  128. _root, ext = os.path.splitext(filepath)
  129. return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
  130. class PermissionIssueTracker(FileIssueTracker):
  131. """Track files with bad permissions.
  132. Files that are not executable scripts must not be executable."""
  133. heading = "Incorrect permissions:"
  134. # .py files can be either full scripts or modules, so they may or may
  135. # not be executable.
  136. suffix_exemptions = frozenset({".py"})
  137. def check_file_for_issue(self, filepath):
  138. is_executable = os.access(filepath, os.X_OK)
  139. should_be_executable = filepath.endswith((".sh", ".pl"))
  140. if is_executable != should_be_executable:
  141. self.files_with_issues[filepath] = None
  142. class ShebangIssueTracker(FileIssueTracker):
  143. """Track files with a bad, missing or extraneous shebang line.
  144. Executable scripts must start with a valid shebang (#!) line.
  145. """
  146. heading = "Invalid shebang line:"
  147. # Allow either /bin/sh, /bin/bash, or /usr/bin/env.
  148. # Allow at most one argument (this is a Linux limitation).
  149. # For sh and bash, the argument if present must be options.
  150. # For env, the argument must be the base name of the interpeter.
  151. _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?'
  152. rb'|/usr/bin/env ([^\n /]+))$')
  153. _extensions = {
  154. b'bash': 'sh',
  155. b'perl': 'pl',
  156. b'python3': 'py',
  157. b'sh': 'sh',
  158. }
  159. def is_valid_shebang(self, first_line, filepath):
  160. m = re.match(self._shebang_re, first_line)
  161. if not m:
  162. return False
  163. interpreter = m.group(1) or m.group(2)
  164. if interpreter not in self._extensions:
  165. return False
  166. if not filepath.endswith('.' + self._extensions[interpreter]):
  167. return False
  168. return True
  169. def check_file_for_issue(self, filepath):
  170. is_executable = os.access(filepath, os.X_OK)
  171. with open(filepath, "rb") as f:
  172. first_line = f.readline()
  173. if first_line.startswith(b'#!'):
  174. if not is_executable:
  175. # Shebang on a non-executable file
  176. self.files_with_issues[filepath] = None
  177. elif not self.is_valid_shebang(first_line, filepath):
  178. self.files_with_issues[filepath] = [1]
  179. elif is_executable:
  180. # Executable without a shebang
  181. self.files_with_issues[filepath] = None
  182. class EndOfFileNewlineIssueTracker(FileIssueTracker):
  183. """Track files that end with an incomplete line
  184. (no newline character at the end of the last line)."""
  185. heading = "Missing newline at end of file:"
  186. path_exemptions = BINARY_FILE_PATH_RE
  187. def check_file_for_issue(self, filepath):
  188. with open(filepath, "rb") as f:
  189. try:
  190. f.seek(-1, 2)
  191. except OSError:
  192. # This script only works on regular files. If we can't seek
  193. # 1 before the end, it means that this position is before
  194. # the beginning of the file, i.e. that the file is empty.
  195. return
  196. if f.read(1) != b"\n":
  197. self.files_with_issues[filepath] = None
  198. class Utf8BomIssueTracker(FileIssueTracker):
  199. """Track files that start with a UTF-8 BOM.
  200. Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
  201. heading = "UTF-8 BOM present:"
  202. suffix_exemptions = frozenset([".vcxproj", ".sln"])
  203. path_exemptions = BINARY_FILE_PATH_RE
  204. def check_file_for_issue(self, filepath):
  205. with open(filepath, "rb") as f:
  206. if f.read().startswith(codecs.BOM_UTF8):
  207. self.files_with_issues[filepath] = None
  208. class UnixLineEndingIssueTracker(LineIssueTracker):
  209. """Track files with non-Unix line endings (i.e. files with CR)."""
  210. heading = "Non-Unix line endings:"
  211. def should_check_file(self, filepath):
  212. if not super().should_check_file(filepath):
  213. return False
  214. return not is_windows_file(filepath)
  215. def issue_with_line(self, line, _filepath):
  216. return b"\r" in line
  217. class WindowsLineEndingIssueTracker(LineIssueTracker):
  218. """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
  219. heading = "Non-Windows line endings:"
  220. def should_check_file(self, filepath):
  221. if not super().should_check_file(filepath):
  222. return False
  223. return is_windows_file(filepath)
  224. def issue_with_line(self, line, _filepath):
  225. return not line.endswith(b"\r\n") or b"\r" in line[:-2]
  226. class TrailingWhitespaceIssueTracker(LineIssueTracker):
  227. """Track lines with trailing whitespace."""
  228. heading = "Trailing whitespace:"
  229. suffix_exemptions = frozenset([".dsp", ".md"])
  230. def issue_with_line(self, line, _filepath):
  231. return line.rstrip(b"\r\n") != line.rstrip()
  232. class TabIssueTracker(LineIssueTracker):
  233. """Track lines with tabs."""
  234. heading = "Tabs present:"
  235. suffix_exemptions = frozenset([
  236. ".pem", # some openssl dumps have tabs
  237. ".sln",
  238. "/Makefile",
  239. "/Makefile.inc",
  240. "/generate_visualc_files.pl",
  241. ])
  242. def issue_with_line(self, line, _filepath):
  243. return b"\t" in line
  244. class MergeArtifactIssueTracker(LineIssueTracker):
  245. """Track lines with merge artifacts.
  246. These are leftovers from a ``git merge`` that wasn't fully edited."""
  247. heading = "Merge artifact:"
  248. def issue_with_line(self, line, _filepath):
  249. # Detect leftover git conflict markers.
  250. if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
  251. return True
  252. if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
  253. return True
  254. if line.rstrip(b'\r\n') == b'=======' and \
  255. not _filepath.endswith('.md'):
  256. return True
  257. return False
  258. class IntegrityChecker:
  259. """Sanity-check files under the current directory."""
  260. def __init__(self, log_file):
  261. """Instantiate the sanity checker.
  262. Check files under the current directory.
  263. Write a report of issues to log_file."""
  264. self.check_repo_path()
  265. self.logger = None
  266. self.setup_logger(log_file)
  267. self.issues_to_check = [
  268. PermissionIssueTracker(),
  269. ShebangIssueTracker(),
  270. EndOfFileNewlineIssueTracker(),
  271. Utf8BomIssueTracker(),
  272. UnixLineEndingIssueTracker(),
  273. WindowsLineEndingIssueTracker(),
  274. TrailingWhitespaceIssueTracker(),
  275. TabIssueTracker(),
  276. MergeArtifactIssueTracker(),
  277. ]
  278. @staticmethod
  279. def check_repo_path():
  280. if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
  281. raise Exception("Must be run from Mbed TLS root")
  282. def setup_logger(self, log_file, level=logging.INFO):
  283. self.logger = logging.getLogger()
  284. self.logger.setLevel(level)
  285. if log_file:
  286. handler = logging.FileHandler(log_file)
  287. self.logger.addHandler(handler)
  288. else:
  289. console = logging.StreamHandler()
  290. self.logger.addHandler(console)
  291. @staticmethod
  292. def collect_files():
  293. bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
  294. bytes_filepaths = bytes_output.split(b'\0')[:-1]
  295. ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
  296. # Prepend './' to files in the top-level directory so that
  297. # something like `'/Makefile' in fp` matches in the top-level
  298. # directory as well as in subdirectories.
  299. return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
  300. for fp in ascii_filepaths]
  301. def check_files(self):
  302. for issue_to_check in self.issues_to_check:
  303. for filepath in self.collect_files():
  304. if issue_to_check.should_check_file(filepath):
  305. issue_to_check.check_file_for_issue(filepath)
  306. def output_issues(self):
  307. integrity_return_code = 0
  308. for issue_to_check in self.issues_to_check:
  309. if issue_to_check.files_with_issues:
  310. integrity_return_code = 1
  311. issue_to_check.output_file_issues(self.logger)
  312. return integrity_return_code
  313. def run_main():
  314. parser = argparse.ArgumentParser(description=__doc__)
  315. parser.add_argument(
  316. "-l", "--log_file", type=str, help="path to optional output log",
  317. )
  318. check_args = parser.parse_args()
  319. integrity_check = IntegrityChecker(check_args.log_file)
  320. integrity_check.check_files()
  321. return_code = integrity_check.output_issues()
  322. sys.exit(return_code)
  323. if __name__ == "__main__":
  324. run_main()