|
| 1 | +import argparse |
| 2 | +import subprocess |
| 3 | +import os |
| 4 | +from pathlib import Path |
| 5 | +from colorama import Fore, Style |
| 6 | + |
| 7 | +# 支持的文件类型 |
| 8 | +SUPPORTED_FILES = { |
| 9 | + ".h": "c", |
| 10 | + ".hh": "c", |
| 11 | + ".hpp": "c", |
| 12 | + ".c": "c", |
| 13 | + ".cc": "c", |
| 14 | + ".cpp": "c", |
| 15 | + ".cxx": "c", |
| 16 | + ".cu": "c", |
| 17 | + ".mlu": "c", |
| 18 | + ".cl": "c", |
| 19 | + ".py": "py", |
| 20 | +} |
| 21 | + |
| 22 | +def format_file(file: Path, check: bool, formatter) -> bool: |
| 23 | + formatter = formatter.get(SUPPORTED_FILES.get(file.suffix, None), None) |
| 24 | + if not formatter: |
| 25 | + return True # 文件类型不支持,跳过 |
| 26 | + |
| 27 | + try: |
| 28 | + cmd = [] |
| 29 | + if formatter.startswith("clang-format"): |
| 30 | + cmd = [formatter, "-style=file", "-i", file] |
| 31 | + if check: |
| 32 | + cmd.insert(2, "-dry-run") |
| 33 | + process = subprocess.run( |
| 34 | + cmd, |
| 35 | + capture_output=True, |
| 36 | + text=True, |
| 37 | + check=True, |
| 38 | + ) |
| 39 | + if process.stderr: |
| 40 | + print(f"{Fore.YELLOW}{file} is not formatted.{Style.RESET_ALL}") |
| 41 | + print(f"Use {Fore.CYAN}{formatter} -style=file -i {file}{Style.RESET_ALL} to format it.") |
| 42 | + return False |
| 43 | + else: |
| 44 | + subprocess.run( |
| 45 | + cmd, |
| 46 | + capture_output=True, |
| 47 | + text=True, |
| 48 | + check=True, |
| 49 | + ) |
| 50 | + print(f"{Fore.CYAN}Formatted: {file}{Style.RESET_ALL}") |
| 51 | + elif formatter == "black": |
| 52 | + cmd = [formatter, file] |
| 53 | + if check: |
| 54 | + cmd.insert(1, "--check") |
| 55 | + process = subprocess.run( |
| 56 | + cmd, |
| 57 | + capture_output=True, |
| 58 | + text=True, |
| 59 | + check=True, |
| 60 | + ) |
| 61 | + if process.stderr: |
| 62 | + print(f"{Fore.YELLOW}{file} is not formatted.{Style.RESET_ALL}") |
| 63 | + print(f"Use {Fore.CYAN}{formatter} {file}{Style.RESET_ALL} to format it.") |
| 64 | + return False |
| 65 | + else: |
| 66 | + subprocess.run( |
| 67 | + cmd, |
| 68 | + capture_output=True, |
| 69 | + text=True, |
| 70 | + check=True, |
| 71 | + ) |
| 72 | + print(f"{Fore.CYAN}Formatted: {file}{Style.RESET_ALL}") |
| 73 | + except FileNotFoundError: |
| 74 | + print(f"{Fore.RED}Formatter {formatter} not found, {file} skipped.{Style.RESET_ALL}") |
| 75 | + except subprocess.CalledProcessError as e: |
| 76 | + print(f"{Fore.RED}Formatter {formatter} failed: {e}{Style.RESET_ALL}") |
| 77 | + |
| 78 | + return True |
| 79 | + |
| 80 | +def git_added_files(): |
| 81 | + """获取所有已暂存更改的文件""" |
| 82 | + try: |
| 83 | + # 使用 git diff --cached --name-only 获取所有已添加到暂存区的文件 |
| 84 | + result = subprocess.run( |
| 85 | + ["git", "diff", "--cached", "--name-only"], |
| 86 | + capture_output=True, |
| 87 | + text=True, |
| 88 | + check=True, |
| 89 | + ) |
| 90 | + for file in result.stdout.splitlines(): |
| 91 | + yield Path(file.strip()) |
| 92 | + except subprocess.CalledProcessError as e: |
| 93 | + print(f"{Fore.RED}Git diff failed: {e}{Style.RESET_ALL}") |
| 94 | + |
| 95 | +def git_modified_since_ref(ref): |
| 96 | + """获取从指定的 Git 引用到当前状态的修改文件列表""" |
| 97 | + try: |
| 98 | + result = subprocess.run( |
| 99 | + ["git", "diff", f"{ref}..", "--diff-filter=AMR", "--name-only"], |
| 100 | + capture_output=True, |
| 101 | + text=True, |
| 102 | + check=True, |
| 103 | + ) |
| 104 | + for file in result.stdout.splitlines(): |
| 105 | + yield Path(file.strip()) |
| 106 | + except subprocess.CalledProcessError as e: |
| 107 | + print(f"{Fore.RED}Git diff failed: {e}{Style.RESET_ALL}") |
| 108 | + |
| 109 | +def list_files(paths): |
| 110 | + """递归获取指定路径下的所有文件""" |
| 111 | + files = [] |
| 112 | + for path in paths: |
| 113 | + if path.is_file(): |
| 114 | + yield path |
| 115 | + elif path.is_dir(): |
| 116 | + for dirpath, _, filenames in os.walk(path): |
| 117 | + for name in filenames: |
| 118 | + yield Path(dirpath) / name |
| 119 | + else: |
| 120 | + print(f"{Fore.RED}Error: {path} is not a file or directory.{Style.RESET_ALL}") |
| 121 | + |
| 122 | +def filter_in_path(file: Path, path) -> bool: |
| 123 | + """判断文件是否在指定路径下""" |
| 124 | + for p in path: |
| 125 | + if file.is_relative_to(p): |
| 126 | + return True |
| 127 | + return False |
| 128 | + |
| 129 | +def main(): |
| 130 | + parser = argparse.ArgumentParser() |
| 131 | + parser.add_argument("--ref", type=str, help="Git reference (commit hash) to compare against.") |
| 132 | + parser.add_argument("--path", nargs="*", type=Path, help="Files to format or check.") |
| 133 | + parser.add_argument("--check", action="store_true", help="Check files without modifying them.") |
| 134 | + parser.add_argument("--c", default="clang-format-16", help="C formatter (default: clang-format-16)") |
| 135 | + parser.add_argument("--py", default="black", help="Python formatter (default: black)") |
| 136 | + args = parser.parse_args() |
| 137 | + |
| 138 | + if args.ref is None and args.path is None: |
| 139 | + # Last commit. |
| 140 | + print("{Fore.GREEN}Formating git added files.{Style.RESET_ALL}") |
| 141 | + files = git_added_files() |
| 142 | + |
| 143 | + else: |
| 144 | + if args.ref is None: |
| 145 | + print(f"{Fore.GREEN}Formating files in {args.path}.{Style.RESET_ALL}") |
| 146 | + files = list_files(args.path) |
| 147 | + elif args.path is None: |
| 148 | + print(f"{Fore.GREEN}Formating git modified files from {args.ref}.{Style.RESET_ALL}") |
| 149 | + files = git_modified_since_ref(args.ref) |
| 150 | + else: |
| 151 | + print(f"{Fore.GREEN}Formating git modified files from {args.ref} in {args.path}.{Style.RESET_ALL}") |
| 152 | + files = (file for file in git_modified_since_ref(args.ref) if filter_in_path(file, args.path)) |
| 153 | + |
| 154 | + formatted = True |
| 155 | + for file in files: |
| 156 | + if not format_file(file, args.check,{ |
| 157 | + "c": args.c, |
| 158 | + "py": args.py, |
| 159 | + }): |
| 160 | + formatted = False |
| 161 | + |
| 162 | + if not formatted: |
| 163 | + exit(1) |
| 164 | + |
| 165 | +if __name__ == "__main__": |
| 166 | + main() |
0 commit comments