coding_guidelines_check.py 7.6 KB

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