forked from kkabt/blendgit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackend_git.py
176 lines (135 loc) · 5.22 KB
/
backend_git.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import subprocess
import os
import platform
import sys
import re
from typing import Union, Generator
PTN_QUOTED = r"'(.*?)(?<!\\)'|\"(.*?)(?<!\\)\""
PTN_WORD = rf"([-\w\.=:]+({PTN_QUOTED})*)"
unquote = lambda w: re.sub(PTN_QUOTED, r"\1" or r"\2", w)
#git command class
class Git:
PATH_GITIGNORE = ".gitignore"
# Status
STATUS_UNMODIFIED = 0b00000
STATUS_IGNORED = 0b00001
STATUS_UNTRACKED = 0b00010
STATUS_UNMERGED = 0b00100
STATUS_NOTSTAGED = 0b01000
STATUS_STAGED = 0b10000
def __init__(self, context):
prefs = context.preferences.addons[__package__].preferences
path = prefs.git_execpath
#try to use user supplied path first
if path:
self.git_execpath = path
else: #try to autodetect
if platform.architecture()[1] == "WindowsPE":
#assume default git path for windows here, since we dont have winreg access via integrated python
if platform.architecture()[0] == "64bit":
self.git_execpath = "C:/Program Files/Git/bin/git.exe"
elif platform.architecture()[0] == "32bit":
self.git_execpath = "C:/Program Files (x86)/Git/bin/git.exe"
else: #Linux, Mac
self.git_execpath = "/usr/bin/git"
self.operative = os.path.isfile(self.git_execpath)
gcon = context.window_manager.git_context
self.chdir(gcon.rootdir)
# Update workdir file with specific version
# def backup(self, filename, dirpath, commit_hash):
def backup(self, blobnr, filepath):
if blobnr!=None:
p = subprocess.Popen(
[self.git_execpath, "cat-file", "blob", blobnr],
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT
)
blob = p.stdout.read()
with open(filepath, "wb+") as tmp:
tmp.write(blob)
return
def get_blobs(self, commit_hash):
blobs = {}
results = self.command(["ls-tree", "-r", commit_hash])
for l in results:
tab = l.split("\t")
name = tab[1]
_,blob,blobnr = tab[0].split(" ")
if blob=="blob":
blobs[name] = blobnr
return blobs
# Miscellaneous
def write_ignore(self, statement: str):
with open(self.PATH_GITIGNORE, "a+") as f:
f.write(statement+"\n")
def clean_ignore(self):
ignore_dict = {}
with open(self.PATH_GITIGNORE, "r") as f:
# fromkeys : remove overwrapping
# reversed : statement priority is last written
lines = list(dict.fromkeys([l.strip() for l in reversed(f.readlines())]))
# reversed : restore order
for line in reversed(lines):
ignore_dict[line.lstrip("!")] = "!" if line.startswith("!") else ""
with open(self.PATH_GITIGNORE, "w+") as f:
f.writelines(
[pattern+file+"\n" for file, pattern in ignore_dict.items()]
)
def chdir(self, dirpath) -> 'bool: Is path exist':
if os.path.isdir(dirpath):
os.chdir(dirpath)
return True
return False
def open_dir(self, dirpath) -> 'exist: bool':
if os.path.exists(dirpath):
if platform.system() == 'Windows':
subprocess.Popen([
'explorer',
dirpath.replace("/", "\\")
])
# elif platform.system() == 'Linux':
# print("%s already exists" % dirpath)
# elif platform.system() == 'Mac':
# subprocess.Popen([
# 'finder',
# dirpath.replace("/", "\\")
# ])
# print(dirpath.replace("/", "\\"))
return True
else:
return False
# generic Git command with [textual feedback]
# => for interactive, get result as generator
def command(self, cmd: Union[str, list, tuple]) -> Generator[str, None, bytes]:
if not self.operative:
return None
args = [self.git_execpath]
if type(cmd) is str:
# (entire-matched, *other_groups) = findall
args += [m[0] for m in re.findall(PTN_WORD, cmd)]
elif type(cmd) in [list, tuple]:
args += cmd
else:
print(f"TypeError: invalid argument type for 'cmd: Union[list, str]': {type(cmd)}", file=sys.stderr)
return None
# remove quote-character overwrapping
args = list(map(unquote, args))
# print(args)
p = subprocess.Popen(
args,
stdout = subprocess.PIPE,
stderr = subprocess.STDOUT
)
while True:
line = p.stdout.readline()
if line:
try:
out = line.decode('utf-8').rstrip('\n')
# print(out)
yield out
except UnicodeDecodeError as e:
print(e)
out = line
yield out
if not line and p.poll() is not None:
break