11import subprocess
2+ import sys
23from argparse import ArgumentParser
34from typing import Tuple
45
@@ -16,35 +17,58 @@ def run_clang_format(args=None) -> Tuple[int, str]:
1617 hook_args , other_args = parser .parse_known_args (args )
1718 path = ensure_installed ("clang-format" , hook_args .version )
1819 command = [str (path ), "-i" ]
20+
21+ # Add verbose flag if requested
22+ if hook_args .verbose :
23+ command .append ("--verbose" )
24+
1925 command .extend (other_args )
2026
21- retval = 0
22- output = ""
2327 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
2440 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
3342 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+
3749 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 )
4161
4262
4363def main () -> int :
4464 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 ():
4668 print (output )
47- return retval
69+
70+ # Convert dry-run special code to success
71+ return 0 if retval == - 1 else retval
4872
4973
5074if __name__ == "__main__" :
0 commit comments