1+ import os
12import shlex
23import subprocess
34import sys
4- from typing import List , Any , Optional , Dict
5+ from typing import List , Any , Optional , Dict , Tuple
6+
7+
8+ class GitException (Exception ):
9+ """
10+ Exception raised when a Git command execution fails.
11+
12+ Attributes
13+ ----------
14+ returncode : int
15+ The return code from the failed Git command.
16+ command : List[str]
17+ The Git command that was executed.
18+ repo_name : str
19+ The name of the Git repository.
20+ stderr : str
21+ The output of the failed Git command.
22+ """
23+
24+ def __init__ (
25+ self ,
26+ returncode : int ,
27+ command : List [str ],
28+ repo_name : str ,
29+ output : str ,
30+ ):
31+ super ().__init__ ()
32+ self .returncode = returncode
33+ self .command = command
34+ self .repo_name = repo_name
35+ self .stderr = output
36+
37+ def __str__ (self ):
38+ return (
39+ f"[{ self .repo_name } ] { Git ._quote_command (self .command )} "
40+ f"returned ({ self .returncode } ) with the following { self .stderr } ."
41+ )
542
643
744class Git :
@@ -15,9 +52,9 @@ def run(
1552 allow_non_zero_exit : bool = False ,
1653 fatal : bool = False ,
1754 ** kwargs ,
18- ):
55+ ) -> Tuple [ str , int , List [ str ]] :
1956 command = Git ._build_command (args )
20-
57+ output = ""
2158 try :
2259 result = subprocess .run (
2360 command ,
@@ -38,20 +75,15 @@ def run(
3875 if fatal :
3976 sys .exit (
4077 f"command `{ command } ` terminated with a non-zero exit "
41- f"status { str (e .returncode )} , aborting" )
42- eout = Exception (
43- f"[{ repo_path } ] '{ Git ._quote_command (command )} ' failed with '{ output } '"
78+ f"status { str (e .returncode )} , aborting"
79+ )
80+ raise GitException (
81+ e .returncode , command , os .path .dirname (repo_path ), output
4482 )
45- eout .ret = e .returncode
46- eout .arguments = command
47- eout .repo_path = repo_path
48- eout .stderr = output
49- raise eout
5083 except OSError as e :
5184 if fatal :
5285 sys .exit (
53- f"could not execute '{ Git ._quote_command (command )} ': "
54- f"{ e .strerror } "
86+ f"could not execute '{ Git ._quote_command (command )} ': { e .strerror } "
5587 )
5688 return (output .strip (), result .returncode , command )
5789
@@ -73,7 +105,7 @@ def _echo_command(
73105 print (f"{ prefix } + { ' ' .join (command_str )} " , file = sys .stderr )
74106 if output :
75107 for line in output .splitlines ():
76- print (prefix + line )
108+ print (prefix + line )
77109 sys .stdout .flush ()
78110 sys .stderr .flush ()
79111
@@ -86,5 +118,5 @@ def _quote(arg: Any) -> str:
86118 return shlex .quote (str (arg ))
87119
88120 @staticmethod
89- def _quote_command (command : Any ) -> str :
121+ def _quote_command (command : List [ Any ] ) -> str :
90122 return " " .join (Git ._quote (arg ) for arg in command )
0 commit comments