coding_guidelines_check.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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. from pathlib import Path
  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 = 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: Path) -> bool:
  47. def check_aspell(root):
  48. return True
  49. def check_clang_format(root: Path) -> 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: Path, root: Path) -> 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: Path, 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: Path, root: Path) -> bool:
  131. return True
  132. def check_dir_name(path: Path, root: Path) -> 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: Path) -> bool:
  138. """
  139. file names should not contain any character '-'
  140. but some names are well known and use '-' as the separator, e.g.:
  141. - docker-compose
  142. - package-lock
  143. - vite-env.d
  144. """
  145. if path.stem in [
  146. "docker-compose",
  147. "package-lock",
  148. "vite-env.d",
  149. "osv-scanner",
  150. ]:
  151. return True
  152. m = re.search(INVALID_FILE_NAME_SEGMENT, path.stem)
  153. if m:
  154. print(f"--- found a character '-' in {m.groups()} in {path}")
  155. return not m
  156. def parse_commits_range(root: Path, commits: str) -> list:
  157. GIT_LOG_CMD = f"git log --pretty='%H' {commits}"
  158. try:
  159. ret = subprocess.check_output(
  160. shlex.split(GIT_LOG_CMD), cwd=root, universal_newlines=True
  161. )
  162. return [x for x in ret.split("\n") if x]
  163. except subprocess.CalledProcessError:
  164. print(f"can not parse any commit from the range {commits}")
  165. return []
  166. def analysis_new_item_name(root: Path, commit: str) -> bool:
  167. """
  168. For any file name in the repo, it is required to use '_' to replace '-'.
  169. For any directory name in the repo, it is required to use '-' to replace '_'.
  170. """
  171. GIT_SHOW_CMD = f"git show --oneline --name-status --diff-filter A {commit}"
  172. try:
  173. invalid_items = True
  174. output = subprocess.check_output(
  175. shlex.split(GIT_SHOW_CMD), cwd=root, universal_newlines=True
  176. )
  177. if not output:
  178. return True
  179. NEW_FILE_PATTERN = "^A\s+(\S+)"
  180. for line_no, line in enumerate(output.split("\n")):
  181. # bypass the first line, usually it is the commit description
  182. if line_no == 0:
  183. continue
  184. if not line:
  185. continue
  186. match = re.match(NEW_FILE_PATTERN, line)
  187. if not match:
  188. continue
  189. new_item = match.group(1)
  190. new_item = Path(new_item).resolve()
  191. if new_item.is_file():
  192. if not check_file_name(new_item):
  193. invalid_items = False
  194. continue
  195. new_item = new_item.parent
  196. if not check_dir_name(new_item, root):
  197. invalid_items = False
  198. continue
  199. else:
  200. return invalid_items
  201. except subprocess.CalledProcessError:
  202. return False
  203. def process_entire_pr(root: Path, commits: str) -> bool:
  204. if not commits:
  205. print("Please provide a commits range")
  206. return False
  207. commit_list = parse_commits_range(root, commits)
  208. if not commit_list:
  209. print(f"Quit since there is no commit to check with")
  210. return True
  211. print(f"there are {len(commit_list)} commits in the PR")
  212. found = False
  213. if not analysis_new_item_name(root, commits):
  214. print(f"{analysis_new_item_name.__doc__}")
  215. found = True
  216. if not run_clang_format_diff(root, commits):
  217. print(f"{run_clang_format_diff.__doc__}")
  218. found = True
  219. return not found
  220. def main() -> int:
  221. parser = argparse.ArgumentParser(
  222. description="Check if change meets all coding guideline requirements"
  223. )
  224. parser.add_argument(
  225. "-c", "--commits", default=None, help="Commit range in the form: a..b"
  226. )
  227. options = parser.parse_args()
  228. wamr_root = Path(__file__).parent.joinpath("..").resolve()
  229. if not pre_flight_check(wamr_root):
  230. return False
  231. return process_entire_pr(wamr_root, options.commits)
  232. # run with python3 -m unitest ci/coding_guidelines_check.py
  233. class TestCheck(unittest.TestCase):
  234. def test_check_dir_name_failed(self):
  235. root = Path("/root/Workspace/")
  236. new_file_path = root.joinpath("core/shared/platform/esp_idf/espid_memmap.c")
  237. self.assertFalse(check_dir_name(new_file_path, root))
  238. def test_check_dir_name_pass(self):
  239. root = Path("/root/Workspace/")
  240. new_file_path = root.joinpath("core/shared/platform/esp-idf/espid_memmap.c")
  241. self.assertTrue(check_dir_name(new_file_path, root))
  242. def test_check_file_name_failed(self):
  243. new_file_path = Path(
  244. "/root/Workspace/core/shared/platform/esp-idf/espid-memmap.c"
  245. )
  246. self.assertFalse(check_file_name(new_file_path))
  247. def test_check_file_name_pass(self):
  248. new_file_path = Path(
  249. "/root/Workspace/core/shared/platform/esp-idf/espid_memmap.c"
  250. )
  251. self.assertTrue(check_file_name(new_file_path))
  252. if __name__ == "__main__":
  253. sys.exit(0 if main() else 1)