-
Notifications
You must be signed in to change notification settings - Fork 0
/
littlegit.py
73 lines (51 loc) · 1.89 KB
/
littlegit.py
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
import functools
import logging
import subprocess
from pathlib import Path
from typing import List, Union
__version__ = "0.2.0"
logger = logging.getLogger(__name__)
class GitError(Exception):
__slots__ = ["cli_args", "output", "exit_code"]
def __init__(self, cli_args, output, exit_code):
self.cli_args = cli_args
self.output = output
self.exit_code = exit_code
class Git:
def __init__(self, working_dir: Union[str, Path]):
self.working_dir = Path(working_dir)
def __getattr__(self, attr):
cmd = attr.replace("_", "-")
return functools.partial(self.__execute, cmd)
def build_cli_args(self, *args, **kwds) -> List[str]:
cli_args = []
for k, v in kwds.items():
if k.startswith("_"):
k = k[1:]
short_arg = len(k) == 1
if short_arg:
arg = f"-{k}"
else:
arg = "--{}".format(k.replace("_", "-"))
if isinstance(v, bool):
cli_args.append(arg)
elif v:
if short_arg:
cli_args.append(f"{arg}{v}")
else:
cli_args.append(f"{arg}={v}")
cli_args += [str(a) for a in args]
return cli_args
def __execute(self, cmd, *args, **kwds):
cli_cmd = ["git", cmd] + self.build_cli_args(*args, **kwds)
logger.info(" ".join(cli_cmd))
try:
output = subprocess.check_output(
cli_cmd, stderr=subprocess.STDOUT, cwd=self.working_dir.as_posix()
)
except subprocess.CalledProcessError as e:
logger.error("Exit code %d: %s'n%s", e.returncode, e, e.output)
raise GitError(cli_cmd, e.output, e.returncode)
return output.decode("utf8")
def init(self, **kwds):
return self.__execute("init", self.working_dir.as_posix(), **kwds)