-
-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathclang_format.py
More file actions
75 lines (54 loc) · 2.14 KB
/
clang_format.py
File metadata and controls
75 lines (54 loc) · 2.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
import subprocess
import sys
from argparse import ArgumentParser
from typing import Tuple
from .util import ensure_installed, DEFAULT_CLANG_FORMAT_VERSION
parser = ArgumentParser()
parser.add_argument("--version", default=DEFAULT_CLANG_FORMAT_VERSION)
parser.add_argument(
"-v", "--verbose", action="store_true", help="Enable verbose output"
)
def run_clang_format(args=None) -> Tuple[int, str]:
hook_args, other_args = parser.parse_known_args(args)
ensure_installed("clang-format", hook_args.version)
command = ["clang-format", "-i"]
# Add verbose flag if requested
if hook_args.verbose:
command.append("--verbose")
command.extend(other_args)
try:
# Run the clang-format command with captured output
sp = subprocess.run(
command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
encoding="utf-8",
)
# Combine stdout and stderr for complete output
output = (sp.stdout or "") + (sp.stderr or "")
# Handle special case for dry-run mode
if "--dry-run" in command:
retval = -1 # Special code to identify dry-run mode
else:
retval = sp.returncode
# Print verbose information if requested
if hook_args.verbose:
_print_verbose_info(command, retval, output)
return retval, output
except FileNotFoundError as e:
return 1, str(e)
def _print_verbose_info(command: list, retval: int, output: str) -> None:
"""Print verbose debugging information to stderr."""
print(f"Command executed: {' '.join(command)}", file=sys.stderr)
print(f"Exit code: {retval}", file=sys.stderr)
if output.strip():
print(f"Output: {output}", file=sys.stderr)
def main() -> int:
retval, output = run_clang_format() # pragma: no cover
# Print output for errors, but not for dry-run mode
if retval != 0 and retval != -1 and output.strip(): # pragma: no cover
print(output)
# Convert dry-run special code to success
return 0 if retval == -1 else retval # pragma: no cover
if __name__ == "__main__":
raise SystemExit(main())