check_files.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. #!/usr/bin/env python3
  2. # Copyright The Mbed TLS Contributors
  3. # SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
  4. #
  5. # This file is provided under the Apache License 2.0, or the
  6. # GNU General Public License v2.0 or later.
  7. #
  8. # **********
  9. # Apache License 2.0:
  10. #
  11. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  12. # not use this file except in compliance with the License.
  13. # You may obtain a copy of the License at
  14. #
  15. # http://www.apache.org/licenses/LICENSE-2.0
  16. #
  17. # Unless required by applicable law or agreed to in writing, software
  18. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  19. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20. # See the License for the specific language governing permissions and
  21. # limitations under the License.
  22. #
  23. # **********
  24. #
  25. # **********
  26. # GNU General Public License v2.0 or later:
  27. #
  28. # This program is free software; you can redistribute it and/or modify
  29. # it under the terms of the GNU General Public License as published by
  30. # the Free Software Foundation; either version 2 of the License, or
  31. # (at your option) any later version.
  32. #
  33. # This program is distributed in the hope that it will be useful,
  34. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  35. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  36. # GNU General Public License for more details.
  37. #
  38. # You should have received a copy of the GNU General Public License along
  39. # with this program; if not, write to the Free Software Foundation, Inc.,
  40. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  41. #
  42. # **********
  43. """
  44. This script checks the current state of the source code for minor issues,
  45. including incorrect file permissions, presence of tabs, non-Unix line endings,
  46. trailing whitespace, and presence of UTF-8 BOM.
  47. Note: requires python 3, must be run from Mbed TLS root.
  48. """
  49. import os
  50. import argparse
  51. import logging
  52. import codecs
  53. import re
  54. import subprocess
  55. import sys
  56. class FileIssueTracker:
  57. """Base class for file-wide issue tracking.
  58. To implement a checker that processes a file as a whole, inherit from
  59. this class and implement `check_file_for_issue` and define ``heading``.
  60. ``suffix_exemptions``: files whose name ends with a string in this set
  61. will not be checked.
  62. ``path_exemptions``: files whose path (relative to the root of the source
  63. tree) matches this regular expression will not be checked. This can be
  64. ``None`` to match no path. Paths are normalized and converted to ``/``
  65. separators before matching.
  66. ``heading``: human-readable description of the issue
  67. """
  68. suffix_exemptions = frozenset()
  69. path_exemptions = None
  70. # heading must be defined in derived classes.
  71. # pylint: disable=no-member
  72. def __init__(self):
  73. self.files_with_issues = {}
  74. @staticmethod
  75. def normalize_path(filepath):
  76. """Normalize ``filepath`` with / as the directory separator."""
  77. filepath = os.path.normpath(filepath)
  78. # On Windows, we may have backslashes to separate directories.
  79. # We need slashes to match exemption lists.
  80. seps = os.path.sep
  81. if os.path.altsep is not None:
  82. seps += os.path.altsep
  83. return '/'.join(filepath.split(seps))
  84. def should_check_file(self, filepath):
  85. """Whether the given file name should be checked.
  86. Files whose name ends with a string listed in ``self.suffix_exemptions``
  87. or whose path matches ``self.path_exemptions`` will not be checked.
  88. """
  89. for files_exemption in self.suffix_exemptions:
  90. if filepath.endswith(files_exemption):
  91. return False
  92. if self.path_exemptions and \
  93. re.match(self.path_exemptions, self.normalize_path(filepath)):
  94. return False
  95. return True
  96. def check_file_for_issue(self, filepath):
  97. """Check the specified file for the issue that this class is for.
  98. Subclasses must implement this method.
  99. """
  100. raise NotImplementedError
  101. def record_issue(self, filepath, line_number):
  102. """Record that an issue was found at the specified location."""
  103. if filepath not in self.files_with_issues.keys():
  104. self.files_with_issues[filepath] = []
  105. self.files_with_issues[filepath].append(line_number)
  106. def output_file_issues(self, logger):
  107. """Log all the locations where the issue was found."""
  108. if self.files_with_issues.values():
  109. logger.info(self.heading)
  110. for filename, lines in sorted(self.files_with_issues.items()):
  111. if lines:
  112. logger.info("{}: {}".format(
  113. filename, ", ".join(str(x) for x in lines)
  114. ))
  115. else:
  116. logger.info(filename)
  117. logger.info("")
  118. BINARY_FILE_PATH_RE_LIST = [
  119. r'docs/.*\.pdf\Z',
  120. r'programs/fuzz/corpuses/[^.]+\Z',
  121. r'tests/data_files/[^.]+\Z',
  122. r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z',
  123. r'tests/data_files/.*\.req\.[^/]+\Z',
  124. r'tests/data_files/.*malformed[^/]+\Z',
  125. r'tests/data_files/format_pkcs12\.fmt\Z',
  126. ]
  127. BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST))
  128. class LineIssueTracker(FileIssueTracker):
  129. """Base class for line-by-line issue tracking.
  130. To implement a checker that processes files line by line, inherit from
  131. this class and implement `line_with_issue`.
  132. """
  133. # Exclude binary files.
  134. path_exemptions = BINARY_FILE_PATH_RE
  135. def issue_with_line(self, line, filepath):
  136. """Check the specified line for the issue that this class is for.
  137. Subclasses must implement this method.
  138. """
  139. raise NotImplementedError
  140. def check_file_line(self, filepath, line, line_number):
  141. if self.issue_with_line(line, filepath):
  142. self.record_issue(filepath, line_number)
  143. def check_file_for_issue(self, filepath):
  144. """Check the lines of the specified file.
  145. Subclasses must implement the ``issue_with_line`` method.
  146. """
  147. with open(filepath, "rb") as f:
  148. for i, line in enumerate(iter(f.readline, b"")):
  149. self.check_file_line(filepath, line, i + 1)
  150. def is_windows_file(filepath):
  151. _root, ext = os.path.splitext(filepath)
  152. return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj')
  153. class PermissionIssueTracker(FileIssueTracker):
  154. """Track files with bad permissions.
  155. Files that are not executable scripts must not be executable."""
  156. heading = "Incorrect permissions:"
  157. def check_file_for_issue(self, filepath):
  158. is_executable = os.access(filepath, os.X_OK)
  159. should_be_executable = filepath.endswith((".sh", ".pl", ".py"))
  160. if is_executable != should_be_executable:
  161. self.files_with_issues[filepath] = None
  162. class EndOfFileNewlineIssueTracker(FileIssueTracker):
  163. """Track files that end with an incomplete line
  164. (no newline character at the end of the last line)."""
  165. heading = "Missing newline at end of file:"
  166. path_exemptions = BINARY_FILE_PATH_RE
  167. def check_file_for_issue(self, filepath):
  168. with open(filepath, "rb") as f:
  169. try:
  170. f.seek(-1, 2)
  171. except OSError:
  172. # This script only works on regular files. If we can't seek
  173. # 1 before the end, it means that this position is before
  174. # the beginning of the file, i.e. that the file is empty.
  175. return
  176. if f.read(1) != b"\n":
  177. self.files_with_issues[filepath] = None
  178. class Utf8BomIssueTracker(FileIssueTracker):
  179. """Track files that start with a UTF-8 BOM.
  180. Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM."""
  181. heading = "UTF-8 BOM present:"
  182. suffix_exemptions = frozenset([".vcxproj", ".sln"])
  183. path_exemptions = BINARY_FILE_PATH_RE
  184. def check_file_for_issue(self, filepath):
  185. with open(filepath, "rb") as f:
  186. if f.read().startswith(codecs.BOM_UTF8):
  187. self.files_with_issues[filepath] = None
  188. class UnixLineEndingIssueTracker(LineIssueTracker):
  189. """Track files with non-Unix line endings (i.e. files with CR)."""
  190. heading = "Non-Unix line endings:"
  191. def should_check_file(self, filepath):
  192. if not super().should_check_file(filepath):
  193. return False
  194. return not is_windows_file(filepath)
  195. def issue_with_line(self, line, _filepath):
  196. return b"\r" in line
  197. class WindowsLineEndingIssueTracker(LineIssueTracker):
  198. """Track files with non-Windows line endings (i.e. CR or LF not in CRLF)."""
  199. heading = "Non-Windows line endings:"
  200. def should_check_file(self, filepath):
  201. if not super().should_check_file(filepath):
  202. return False
  203. return is_windows_file(filepath)
  204. def issue_with_line(self, line, _filepath):
  205. return not line.endswith(b"\r\n") or b"\r" in line[:-2]
  206. class TrailingWhitespaceIssueTracker(LineIssueTracker):
  207. """Track lines with trailing whitespace."""
  208. heading = "Trailing whitespace:"
  209. suffix_exemptions = frozenset([".dsp", ".md"])
  210. def issue_with_line(self, line, _filepath):
  211. return line.rstrip(b"\r\n") != line.rstrip()
  212. class TabIssueTracker(LineIssueTracker):
  213. """Track lines with tabs."""
  214. heading = "Tabs present:"
  215. suffix_exemptions = frozenset([
  216. ".pem", # some openssl dumps have tabs
  217. ".sln",
  218. "/Makefile",
  219. "/generate_visualc_files.pl",
  220. ])
  221. def issue_with_line(self, line, _filepath):
  222. return b"\t" in line
  223. class MergeArtifactIssueTracker(LineIssueTracker):
  224. """Track lines with merge artifacts.
  225. These are leftovers from a ``git merge`` that wasn't fully edited."""
  226. heading = "Merge artifact:"
  227. def issue_with_line(self, line, _filepath):
  228. # Detect leftover git conflict markers.
  229. if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '):
  230. return True
  231. if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3
  232. return True
  233. if line.rstrip(b'\r\n') == b'=======' and \
  234. not _filepath.endswith('.md'):
  235. return True
  236. return False
  237. class IntegrityChecker:
  238. """Sanity-check files under the current directory."""
  239. def __init__(self, log_file):
  240. """Instantiate the sanity checker.
  241. Check files under the current directory.
  242. Write a report of issues to log_file."""
  243. self.check_repo_path()
  244. self.logger = None
  245. self.setup_logger(log_file)
  246. self.issues_to_check = [
  247. PermissionIssueTracker(),
  248. EndOfFileNewlineIssueTracker(),
  249. Utf8BomIssueTracker(),
  250. UnixLineEndingIssueTracker(),
  251. WindowsLineEndingIssueTracker(),
  252. TrailingWhitespaceIssueTracker(),
  253. TabIssueTracker(),
  254. MergeArtifactIssueTracker(),
  255. ]
  256. @staticmethod
  257. def check_repo_path():
  258. if not all(os.path.isdir(d) for d in ["include", "library", "tests"]):
  259. raise Exception("Must be run from Mbed TLS root")
  260. def setup_logger(self, log_file, level=logging.INFO):
  261. self.logger = logging.getLogger()
  262. self.logger.setLevel(level)
  263. if log_file:
  264. handler = logging.FileHandler(log_file)
  265. self.logger.addHandler(handler)
  266. else:
  267. console = logging.StreamHandler()
  268. self.logger.addHandler(console)
  269. @staticmethod
  270. def collect_files():
  271. bytes_output = subprocess.check_output(['git', 'ls-files', '-z'])
  272. bytes_filepaths = bytes_output.split(b'\0')[:-1]
  273. ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths)
  274. # Prepend './' to files in the top-level directory so that
  275. # something like `'/Makefile' in fp` matches in the top-level
  276. # directory as well as in subdirectories.
  277. return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp)
  278. for fp in ascii_filepaths]
  279. def check_files(self):
  280. for issue_to_check in self.issues_to_check:
  281. for filepath in self.collect_files():
  282. if issue_to_check.should_check_file(filepath):
  283. issue_to_check.check_file_for_issue(filepath)
  284. def output_issues(self):
  285. integrity_return_code = 0
  286. for issue_to_check in self.issues_to_check:
  287. if issue_to_check.files_with_issues:
  288. integrity_return_code = 1
  289. issue_to_check.output_file_issues(self.logger)
  290. return integrity_return_code
  291. def run_main():
  292. parser = argparse.ArgumentParser(description=__doc__)
  293. parser.add_argument(
  294. "-l", "--log_file", type=str, help="path to optional output log",
  295. )
  296. check_args = parser.parse_args()
  297. integrity_check = IntegrityChecker(check_args.log_file)
  298. integrity_check.check_files()
  299. return_code = integrity_check.output_issues()
  300. sys.exit(return_code)
  301. if __name__ == "__main__":
  302. run_main()