coding_guidelines_check.py 8.9 KB

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