1
1
import subprocess
2
+ import sys
2
3
from argparse import ArgumentParser
3
4
from typing import Tuple
4
5
@@ -16,35 +17,58 @@ def run_clang_format(args=None) -> Tuple[int, str]:
16
17
hook_args , other_args = parser .parse_known_args (args )
17
18
path = ensure_installed ("clang-format" , hook_args .version )
18
19
command = [str (path ), "-i" ]
20
+
21
+ # Add verbose flag if requested
22
+ if hook_args .verbose :
23
+ command .append ("--verbose" )
24
+
19
25
command .extend (other_args )
20
26
21
- retval = 0
22
- output = ""
23
27
try :
28
+ # Run the clang-format command with captured output
29
+ sp = subprocess .run (
30
+ command ,
31
+ stdout = subprocess .PIPE ,
32
+ stderr = subprocess .PIPE ,
33
+ encoding = "utf-8" ,
34
+ )
35
+
36
+ # Combine stdout and stderr for complete output
37
+ output = (sp .stdout or "" ) + (sp .stderr or "" )
38
+
39
+ # Handle special case for dry-run mode
24
40
if "--dry-run" in command :
25
- sp = subprocess .run (
26
- command ,
27
- stdout = subprocess .PIPE ,
28
- stderr = subprocess .PIPE ,
29
- encoding = "utf-8" ,
30
- )
31
- retval = - 1 # Not a fail just identify it's a dry-run.
32
- output = sp .stdout + sp .stderr
41
+ retval = - 1 # Special code to identify dry-run mode
33
42
else :
34
- retval = subprocess .run (
35
- command , stdout = subprocess .PIPE , stderr = subprocess .PIPE
36
- ).returncode
43
+ retval = sp .returncode
44
+
45
+ # Print verbose information if requested
46
+ if hook_args .verbose :
47
+ _print_verbose_info (command , retval , output )
48
+
37
49
return retval , output
38
- except FileNotFoundError as stderr :
39
- retval = 1
40
- return retval , str (stderr )
50
+
51
+ except FileNotFoundError as e :
52
+ return 1 , str (e )
53
+
54
+
55
+ def _print_verbose_info (command : list , retval : int , output : str ) -> None :
56
+ """Print verbose debugging information to stderr."""
57
+ print (f"Command executed: { ' ' .join (command )} " , file = sys .stderr )
58
+ print (f"Exit code: { retval } " , file = sys .stderr )
59
+ if output .strip ():
60
+ print (f"Output: { output } " , file = sys .stderr )
41
61
42
62
43
63
def main () -> int :
44
64
retval , output = run_clang_format ()
45
- if retval != 0 :
65
+
66
+ # Print output for errors, but not for dry-run mode
67
+ if retval != 0 and retval != - 1 and output .strip ():
46
68
print (output )
47
- return retval
69
+
70
+ # Convert dry-run special code to success
71
+ return 0 if retval == - 1 else retval
48
72
49
73
50
74
if __name__ == "__main__" :
0 commit comments