coding_guidelines_check.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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-14"
  16. GIT_CLANG_FORMAT_CMD = "git-clang-format-14"
  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", ".cc", ".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-14` or `git-clang-format-14` 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-14.0.0
  82. You can download the package from
  83. https://github.com/llvm/llvm-project/releases
  84. and install it.
  85. For Debian/Ubuntu, we can probably use
  86. `sudo apt-get install clang-format-14`.
  87. Homebrew has it as a part of llvm@14.
  88. ```shell
  89. brew install llvm@14
  90. /usr/local/opt/llvm@14/bin/clang-format
  91. ```
  92. 2. Format the C/C++ source file
  93. ``` shell
  94. cd path/to/wamr/root
  95. clang-format-14 --style file -i path/to/file
  96. ```
  97. The code wrapped by `/* clang-format off */` and `/* clang-format on */`
  98. will not be formatted, you shall use them when the formatted code is not
  99. readable or friendly:
  100. ``` cc
  101. /* clang-format off */
  102. code snippets
  103. /* clang-format on */
  104. ```
  105. """
  106. try:
  107. before, after = commits.split("..")
  108. after = after if after else "HEAD"
  109. COMMAND = (
  110. f"{GIT_CLANG_FORMAT_CMD} -v --binary "
  111. f"{shutil.which(CLANG_FORMAT_CMD)} --style file "
  112. f"--extensions c,cpp,h --diff {before} {after}"
  113. )
  114. p = subprocess.Popen(
  115. shlex.split(COMMAND),
  116. stdout=subprocess.PIPE,
  117. stderr=None,
  118. stdin=None,
  119. universal_newlines=True,
  120. )
  121. stdout, _ = p.communicate()
  122. if not stdout.startswith("diff --git"):
  123. return True
  124. diff_content = stdout.split("\n")
  125. found = False
  126. for summary in [x for x in diff_content if x.startswith("diff --git")]:
  127. # b/path/to/file -> path/to/file
  128. with_invalid_format = re.split(r"\s+", summary)[-1][2:]
  129. if not is_excluded(with_invalid_format):
  130. print(f"--- {with_invalid_format} failed on code style checking.")
  131. found = True
  132. else:
  133. return not found
  134. except subprocess.subprocess.CalledProcessError:
  135. return False
  136. def run_aspell(file_path: Path, root: Path) -> bool:
  137. return True
  138. def check_dir_name(path: Path, root: Path) -> bool:
  139. m = re.search(INVALID_DIR_NAME_SEGMENT, str(path.relative_to(root).parent))
  140. if m:
  141. print(f"--- found a character '_' in {m.groups()} in {path}")
  142. return not m
  143. def check_file_name(path: Path) -> bool:
  144. """
  145. file names should not contain any character '-'
  146. but some names are well known and use '-' as the separator, e.g.:
  147. - docker-compose
  148. - package-lock
  149. - vite-env.d
  150. """
  151. if path.stem in [
  152. "docker-compose",
  153. "package-lock",
  154. "vite-env.d",
  155. "osv-scanner",
  156. ]:
  157. return True
  158. m = re.search(INVALID_FILE_NAME_SEGMENT, path.stem)
  159. if m:
  160. print(f"--- found a character '-' in {m.groups()} in {path}")
  161. return not m
  162. def parse_commits_range(root: Path, commits: str) -> list:
  163. GIT_LOG_CMD = f"git log --pretty='%H' {commits}"
  164. try:
  165. ret = subprocess.check_output(
  166. shlex.split(GIT_LOG_CMD), cwd=root, universal_newlines=True
  167. )
  168. return [x for x in ret.split("\n") if x]
  169. except subprocess.CalledProcessError:
  170. print(f"can not parse any commit from the range {commits}")
  171. return []
  172. def analysis_new_item_name(root: Path, commit: str) -> bool:
  173. """
  174. For any file name in the repo, it is required to use '_' to replace '-'.
  175. For any directory name in the repo, it is required to use '-' to replace '_'.
  176. """
  177. GIT_SHOW_CMD = f"git show --oneline --name-status --diff-filter A {commit}"
  178. try:
  179. invalid_items = True
  180. output = subprocess.check_output(
  181. shlex.split(GIT_SHOW_CMD), cwd=root, universal_newlines=True
  182. )
  183. if not output:
  184. return True
  185. NEW_FILE_PATTERN = "^A\s+(\S+)"
  186. for line_no, line in enumerate(output.split("\n")):
  187. # bypass the first line, usually it is the commit description
  188. if line_no == 0:
  189. continue
  190. if not line:
  191. continue
  192. match = re.match(NEW_FILE_PATTERN, line)
  193. if not match:
  194. continue
  195. new_item = match.group(1)
  196. new_item = Path(new_item).resolve()
  197. if new_item.is_file():
  198. if not check_file_name(new_item):
  199. invalid_items = False
  200. continue
  201. new_item = new_item.parent
  202. if not check_dir_name(new_item, root):
  203. invalid_items = False
  204. continue
  205. else:
  206. return invalid_items
  207. except subprocess.CalledProcessError:
  208. return False
  209. def process_entire_pr(root: Path, commits: str) -> bool:
  210. if not commits:
  211. print("Please provide a commits range")
  212. return False
  213. commit_list = parse_commits_range(root, commits)
  214. if not commit_list:
  215. print(f"Quit since there is no commit to check with")
  216. return True
  217. print(f"there are {len(commit_list)} commits in the PR")
  218. found = False
  219. if not analysis_new_item_name(root, commits):
  220. print(f"{analysis_new_item_name.__doc__}")
  221. found = True
  222. if not run_clang_format_diff(root, commits):
  223. print(f"{run_clang_format_diff.__doc__}")
  224. found = True
  225. return not found
  226. def main() -> int:
  227. parser = argparse.ArgumentParser(
  228. description="Check if change meets all coding guideline requirements"
  229. )
  230. parser.add_argument(
  231. "-c", "--commits", default=None, help="Commit range in the form: a..b"
  232. )
  233. options = parser.parse_args()
  234. wamr_root = Path(__file__).parent.joinpath("..").resolve()
  235. if not pre_flight_check(wamr_root):
  236. return False
  237. return process_entire_pr(wamr_root, options.commits)
  238. # run with python3 -m unitest ci/coding_guidelines_check.py
  239. class TestCheck(unittest.TestCase):
  240. def test_check_dir_name_failed(self):
  241. root = Path("/root/Workspace/")
  242. new_file_path = root.joinpath("core/shared/platform/esp_idf/espid_memmap.c")
  243. self.assertFalse(check_dir_name(new_file_path, root))
  244. def test_check_dir_name_pass(self):
  245. root = Path("/root/Workspace/")
  246. new_file_path = root.joinpath("core/shared/platform/esp-idf/espid_memmap.c")
  247. self.assertTrue(check_dir_name(new_file_path, root))
  248. def test_check_file_name_failed(self):
  249. new_file_path = Path(
  250. "/root/Workspace/core/shared/platform/esp-idf/espid-memmap.c"
  251. )
  252. self.assertFalse(check_file_name(new_file_path))
  253. def test_check_file_name_pass(self):
  254. new_file_path = Path(
  255. "/root/Workspace/core/shared/platform/esp-idf/espid_memmap.c"
  256. )
  257. self.assertTrue(check_file_name(new_file_path))
  258. if __name__ == "__main__":
  259. sys.exit(0 if main() else 1)