使用 clang-format 格式化单个文件 Args: file_path: 要格式化的文件路径 clang_format_cmd: clang-format 命令 dry_run: 如果为 True,只检查格式而不修改文件 Returns: (success, message) 元组
(file_path, clang_format_cmd="clang-format", dry_run=False)
| 62 | |
| 63 | |
| 64 | def format_file(file_path, clang_format_cmd="clang-format", dry_run=False): |
| 65 | """ |
| 66 | 使用 clang-format 格式化单个文件 |
| 67 | |
| 68 | Args: |
| 69 | file_path: 要格式化的文件路径 |
| 70 | clang_format_cmd: clang-format 命令 |
| 71 | dry_run: 如果为 True,只检查格式而不修改文件 |
| 72 | |
| 73 | Returns: |
| 74 | (success, message) 元组 |
| 75 | """ |
| 76 | try: |
| 77 | if dry_run: |
| 78 | # 检查格式,不修改文件 |
| 79 | result = subprocess.run( |
| 80 | [clang_format_cmd, "--dry-run", "--Werror", str(file_path)], |
| 81 | capture_output=True, |
| 82 | text=True, |
| 83 | check=False, |
| 84 | ) |
| 85 | if result.returncode == 0: |
| 86 | return True, "格式正确" |
| 87 | else: |
| 88 | return False, result.stderr.strip() or "格式需要调整" |
| 89 | else: |
| 90 | # 格式化文件 |
| 91 | result = subprocess.run( |
| 92 | [clang_format_cmd, "-i", str(file_path)], |
| 93 | capture_output=True, |
| 94 | text=True, |
| 95 | check=False, |
| 96 | ) |
| 97 | if result.returncode == 0: |
| 98 | return True, "格式化成功" |
| 99 | else: |
| 100 | return False, result.stderr.strip() or "格式化失败" |
| 101 | except FileNotFoundError: |
| 102 | return ( |
| 103 | False, |
| 104 | f"未找到 {clang_format_cmd},请确保已安装 clang-format 并在 PATH 中", |
| 105 | ) |
| 106 | except Exception as e: |
| 107 | return False, f"错误: {str(e)}" |
| 108 | |
| 109 | |
| 110 | def main(): |