coding_guidelines_check.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. #!/usr/bin/env python3
  2. #
  3. # Copyright (C) 2019 Intel Corporation. All rights reserved.
  4. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  5. #
  6. import argparse
  7. import re
  8. import pathlib
  9. import re
  10. import shlex
  11. import shutil
  12. import subprocess
  13. import sys
  14. import unittest
  15. CLANG_FORMAT_CMD = "clang-format-12"
  16. GIT_CLANG_FORMAT_CMD = "git-clang-format-12"
  17. # glob style patterns
  18. EXCLUDE_PATHS = [
  19. "**/.git/*",
  20. "**/.github/*",
  21. "**/.vscode/*",
  22. "**/assembly-script/*",
  23. "**/build/*",
  24. "**/build-scripts/*",
  25. "**/ci/*",
  26. "**/core/deps/*",
  27. "**/doc/*",
  28. "**/samples/wasm-c-api/src/*.*",
  29. "**/samples/workload/*",
  30. "**/test-tools/wasi-sdk/*",
  31. "**/test-tools/IoT-APP-Store-Demo/*",
  32. "**/tests/wamr-test-suites/workspace/*",
  33. "**/wamr-sdk/*",
  34. ]
  35. C_SUFFIXES = [".c", ".cpp", ".h"]
  36. INVALID_DIR_NAME_SEGMENT = r"([a-zA-Z0-9]+\_[a-zA-Z0-9]+)"
  37. INVALID_FILE_NAME_SEGMENT = r"([a-zA-Z0-9]+\-[a-zA-Z0-9]+)"
  38. def locate_command(command: str) -> bool:
  39. if not shutil.which(command):
  40. print(f"Command '{command}'' not found")
  41. return False
  42. return True
  43. def is_excluded(path: str) -> bool:
  44. path = pathlib.Path(path).resolve()
  45. for exclude_path in EXCLUDE_PATHS:
  46. if path.match(exclude_path):
  47. return True
  48. return False
  49. def pre_flight_check(root: pathlib) -> bool:
  50. def check_aspell(root):
  51. return True
  52. def check_clang_foramt(root: pathlib) -> bool:
  53. if not locate_command(CLANG_FORMAT_CMD):
  54. return False
  55. # Quick syntax check for .clang-format
  56. try:
  57. subprocess.check_output(
  58. shlex.split(f"{CLANG_FORMAT_CMD} --dump-config"), cwd=root
  59. )
  60. except subprocess.CalledProcessError:
  61. print(f"Might have a typo in .clang-format")
  62. return False
  63. return True
  64. def check_git_clang_format() -> bool:
  65. return locate_command(GIT_CLANG_FORMAT_CMD)
  66. return check_aspell(root) and check_clang_foramt(root) and check_git_clang_format()
  67. def run_clang_format(file_path: pathlib, root: pathlib) -> bool:
  68. try:
  69. subprocess.check_call(
  70. shlex.split(
  71. f"{CLANG_FORMAT_CMD} --style=file --Werror --dry-run {file_path}"
  72. ),
  73. cwd=root,
  74. )
  75. return True
  76. except subprocess.CalledProcessError:
  77. print(f"{file_path} failed the check of {CLANG_FORMAT_CMD}")
  78. return False
  79. def run_clang_format_diff(root: pathlib, commits: str) -> bool:
  80. """
  81. Use `clang-format-12` and `git-clang-format-12` to check code
  82. format of the PR, which specificed a commit range. It is required to
  83. format code before `git commit` or when failed the PR check:
  84. ``` shell
  85. cd path/to/wamr/root
  86. clang-format-12 --style file -i path/to/file
  87. ```
  88. The code wrapped by `/* clang-format off */` and `/* clang-format on */`
  89. will not be formatted, you shall use them when the formatted code is not
  90. readable or friendly:
  91. ``` cc
  92. /* clang-format off */
  93. code snippets
  94. /* clang-format on */
  95. ```
  96. """
  97. try:
  98. before, after = commits.split("..")
  99. after = after if after else "HEAD"
  100. COMMAND = (
  101. f"{GIT_CLANG_FORMAT_CMD} -v --binary "
  102. f"{shutil.which(CLANG_FORMAT_CMD)} --style file "
  103. f"--extensions c,cpp,h --diff {before} {after}"
  104. )
  105. p = subprocess.Popen(
  106. shlex.split(COMMAND),
  107. stdout=subprocess.PIPE,
  108. stderr=None,
  109. stdin=None,
  110. universal_newlines=True,
  111. )
  112. stdout, _ = p.communicate()
  113. if not stdout.startswith("diff --git"):
  114. return True
  115. diff_content = stdout.split("\n")
  116. found = False
  117. for summary in [x for x in diff_content if x.startswith("diff --git")]:
  118. # b/path/to/file -> path/to/file
  119. with_invalid_format = re.split("\s+", summary)[-1][2:]
  120. if not is_excluded(with_invalid_format):
  121. print(f"--- {with_invalid_format} failed on code style checking.")
  122. found = True
  123. else:
  124. return not found
  125. except subprocess.subprocess.CalledProcessError:
  126. return False
  127. def run_aspell(file_path: pathlib, root: pathlib) -> bool:
  128. return True
  129. def check_dir_name(path: pathlib, root: pathlib) -> bool:
  130. m = re.search(INVALID_DIR_NAME_SEGMENT, str(path.relative_to(root).parent))
  131. if m:
  132. print(f"--- found a character '_' in {m.groups()} in {path}")
  133. return not m
  134. def check_file_name(path: pathlib) -> bool:
  135. m = re.search(INVALID_FILE_NAME_SEGMENT, path.stem)
  136. if m:
  137. print(f"--- found a character '-' in {m.groups()} in {path}")
  138. return not m
  139. def parse_commits_range(root: pathlib, commits: str) -> list:
  140. GIT_LOG_CMD = f"git log --pretty='%H' {commits}"
  141. try:
  142. ret = subprocess.check_output(
  143. shlex.split(GIT_LOG_CMD), cwd=root, universal_newlines=True
  144. )
  145. return [x for x in ret.split("\n") if x]
  146. except subprocess.CalledProcessError:
  147. print(f"can not parse any commit from the range {commits}")
  148. return []
  149. def analysis_new_item_name(root: pathlib, commit: str) -> bool:
  150. """
  151. For any file name in the repo, it is required to use '_' to replace '-'.
  152. For any directory name in the repo, it is required to use '-' to replace '_'.
  153. """
  154. GIT_SHOW_CMD = f"git show --oneline --name-status --diff-filter A {commit}"
  155. try:
  156. invalid_items = True
  157. output = subprocess.check_output(
  158. shlex.split(GIT_SHOW_CMD), cwd=root, universal_newlines=True
  159. )
  160. if not output:
  161. return True
  162. NEW_FILE_PATTERN = "^A\s+(\S+)"
  163. for line_no, line in enumerate(output.split("\n")):
  164. # bypass the first line, usually it is the commit description
  165. if line_no == 0:
  166. continue
  167. if not line:
  168. continue
  169. match = re.match(NEW_FILE_PATTERN, line)
  170. if not match:
  171. continue
  172. new_item = match.group(1)
  173. new_item = pathlib.Path(new_item).resolve()
  174. if new_item.is_file():
  175. if not check_file_name(new_item):
  176. invalid_items = False
  177. continue
  178. new_item = new_item.parent
  179. if not check_dir_name(new_item, root):
  180. invalid_items = False
  181. continue
  182. else:
  183. return invalid_items
  184. except subprocess.CalledProcessError:
  185. return False
  186. def process_entire_pr(root: pathlib, commits: str) -> bool:
  187. if not commits:
  188. print("Please provide a commits range")
  189. return False
  190. commit_list = parse_commits_range(root, commits)
  191. if not commit_list:
  192. print(f"Quit since there is no commit to check with")
  193. return True
  194. print(f"there are {len(commit_list)} commits in the PR")
  195. found = False
  196. if not analysis_new_item_name(root, commits):
  197. print(f"{analysis_new_item_name.__doc__}")
  198. found = True
  199. if not run_clang_format_diff(root, commits):
  200. print(f"{run_clang_format_diff.__doc__}")
  201. found = True
  202. return not found
  203. def main() -> int:
  204. parser = argparse.ArgumentParser(
  205. description="Check if change meets all coding guideline requirements"
  206. )
  207. parser.add_argument(
  208. "-c", "--commits", default=None, help="Commit range in the form: a..b"
  209. )
  210. options = parser.parse_args()
  211. wamr_root = pathlib.Path(__file__).parent.joinpath("..").resolve()
  212. if not pre_flight_check(wamr_root):
  213. return False
  214. return process_entire_pr(wamr_root, options.commits)
  215. # run with python3 -m unitest ci/coding_guidelines_check.py
  216. class TestCheck(unittest.TestCase):
  217. def test_check_dir_name_failed(self):
  218. root = pathlib.Path("/root/Workspace/")
  219. new_file_path = root.joinpath("core/shared/platform/esp_idf/espid_memmap.c")
  220. self.assertFalse(check_dir_name(new_file_path, root))
  221. def test_check_dir_name_pass(self):
  222. root = pathlib.Path("/root/Workspace/")
  223. new_file_path = root.joinpath("core/shared/platform/esp-idf/espid_memmap.c")
  224. self.assertTrue(check_dir_name(new_file_path, root))
  225. def test_check_file_name_failed(self):
  226. new_file_path = pathlib.Path(
  227. "/root/Workspace/core/shared/platform/esp-idf/espid-memmap.c"
  228. )
  229. self.assertFalse(check_file_name(new_file_path))
  230. def test_check_file_name_pass(self):
  231. new_file_path = pathlib.Path(
  232. "/root/Workspace/core/shared/platform/esp-idf/espid_memmap.c"
  233. )
  234. self.assertTrue(check_file_name(new_file_path))
  235. if __name__ == "__main__":
  236. sys.exit(0 if main() else 1)