/
old_exe_wrapper.py
325 lines (283 loc) · 11.6 KB
/
old_exe_wrapper.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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: owner
#
# Created: 28/10/2013
# Copyright: (c) owner 2013
# Licence: <your licence>
#-------------------------------------------------------------------------------
#!/usr/bin/env python
from subprocess import Popen, PIPE, TimeoutExpired
from custom_path import Path, File, Folder
import git_exceptions
##from git_exceptions import GitWrapperException
import git_exceptions
from shutil_rmtree import onerror
import shlex
import os
import shutil
import logging
import re
re_valid_repo_urls = [
re.compile(r"\Assh://(.*@)?.*\..*(:[0-9]{1,5})?(./)*\Z"),
re.compile(r"\A(git|http(s)?|ftp(s)?)://.*\..*(:[0-9]{1,5})?(./)*\Z"),
re.compile(r"\Arsync://.*\..*(./)*\Z"),
re.compile(r"\A(.*@)?.*\..*(./)*\Z")
]
"""
VALID REPOS URLs:
ssh://[user@]host.xz[:port]/path/to/repo.git/
git://host.xz[:port]/path/to/repo.git/
http[s]://host.xz[:port]/path/to/repo.git/
ftp[s]://host.xz[:port]/path/to/repo.git/
rsync://host.xz/path/to/repo.git/
An alternative scp-like syntax may also be used with the ssh protocol:
[user@]host.xz:path/to/repo.git/
The ssh and git protocols additionally support ~username expansion:
ssh://[user@]host.xz[:port]/~[user]/path/to/repo.git/
git://host.xz[:port]/~[user]/path/to/repo.git/
[user@]host.xz:/~[user]/path/to/repo.git/
For local repositories, also supported by git natively, the following syntaxes may be used:
/path/to/repo.git/
file:///path/to/repo.git/
"""
logger = logging.getLogger()
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
logger.addHandler(ch)
git_exe = os.path.abspath("git-portable/bin/git.exe")
class GitWrapper():
git_exe = Path("git-portable/bin/git.exe")
def __init__(self, local_repo, timeout=15, git_exe=None, must_be_empty=False):
if git_exe is not None:
self.git_exe = Path(git_exe)
if not self.git_exe.exists:
raise git_exceptions.CannotFindGitExecutable("could not find Git exe in path: {}".format(self.git_exe))
self._local = Folder(local_repo)
if must_be_empty and not self._local.isempty:
raise git_exceptions.GitWrapperException("local repo is not empty: {}".format(self._local))
self._wkdir = Path(self._local)
self._cmd = None
self._timeout = 15
self._out = "INIT NEW REPO: {}\n".format(local_repo)
self._last_outs = None
self._last_errs = None
self._return_code = None
self._running = False
self._ran = False
self._is_init = self._local.isarepo
self._nothing_to_commit = False
self._local_already_exists_and_is_not_empty = False
def _set_wkdir(self, wkdir):
wkdir = Path(wkdir)
if not wkdir.exists:
raise git_exceptions.GitWrapperException("Local working dir does not exist: {}".format(wkdir.full_path))
self._wkdir = wkdir
return self
def set_timeout(self, timeout):
if not isinstance(timeout, int) or 1 > timeout or timeout > 120:
raise git_exceptions.GitWrapperException("Invalid timeout: {}".format(timeout))
self._timeout = timeout
return self
def _set_cmd(self, cmd):
if not isinstance(cmd, list):
raise git_exceptions.GitWrapperException("CMD must be a LIST of STR: {}".format(cmd))
for x in cmd:
if not isinstance(x, str):
raise git_exceptions.GitWrapperException("CMD must be a LIST of STR: {}\n{} is not a string".format(cmd, x))
self._cmd = [x for x in cmd if x != ""]
self._cmd.insert(0, self.git_exe.full_path)
return self
def _run(self):
if not self._wkdir.exists:
raise git_exceptions.GitWrapperException("RUN: WKDIR does not exist: {}".format(self._wkdir.nice_full_path))
self._running = True
self._out += "WKDIR: {}\n".format(self._wkdir.nice_full_path)
self._out += "RUNNING: {}\n".format(self._cmd)
proc = Popen(args=self._cmd, cwd=self._wkdir.full_path, stdin=PIPE, stderr=PIPE, stdout=PIPE, shell=True, universal_newlines=True, start_new_session=True)
try:
outs, errs = proc.communicate(timeout=self._timeout)
if outs:
self._out += outs
self._last_outs = outs
else: self._last_outs = None
if errs:
self._out += errs
self._last_errs = errs
else: self._last_errs = None
except TimeoutExpired:
proc.kill()
outs, errs = proc.communicate(timeout=self._timeout)
if outs:
self._out += outs
self._last_outs = outs
else: self._last_outs = None
if errs:
self._errs += errs
self._last_errs = errs
else: self._last_errs = None
self._running = False
self._ran = True
self._return_code = proc.returncode
self._out += "=======================================\n"
if self._return_code != 0:
self._parse_output()
raise git_exceptions.GitWrapperException("RUN: error not handled:\n\nCMD:{}\nWKDIR:{}\nLAST OUT:{}\nLAST ERR:{}\n\nReturn code: {}".format(self._cmd, self._wkdir, self._last_outs, self._last_errs, self._return_code))
self._parse_output()
return self
def _parse_output(self):
if self._last_outs is not None:
s_out = self._last_outs.split("\n")
for s in [
'nothing added to commit but untracked files present (use "git add" to track)',
'nothing to commit (create/copy files and use "git add" to track)',
'nothing to commit, working directory clean'
]:
if s in s_out:
self._nothing_to_commit = True
if self._last_errs is not None:
if "fatal: destination path '{}' already exists and is not an empty directory.".format(self._local.basename) in self._last_errs.split("\n"):
self._local_already_exists_and_is_not_empty = True
raise git_exceptions.GitRepositoryAlreadyExistsAndIsNotEmpty(self._local.nice_full_path)
@property
def out(self):
return self._out
def clear_history(self):
self._out = ""
@property
def return_code(self):
return self._return_code
@property
def full_path(self):
return self._local.nice_full_path
def init(self, bare=False, add_all=False):
wkdir = Path(self._local.dirname)
repo = Path(self._local.basename)
if self._local.exists:
if self._local.isafile:
raise git_exceptions.GitWrapperException("INIT: local repository is a file: {}".format(repo))
cmd = [
"init",
"--bare" if bare else "",
shlex.quote(repo.basename)
]
self._set_wkdir(wkdir)._set_cmd(cmd)._run()._set_wkdir(self._local)
if add_all:
self._set_cmd(["add","."])._run()
return self
def status(self):
self._set_cmd(["status"])._run()
return self
def __str__(self):
return self._out
def add(self, files=".",):
if isinstance(files, str):
files=[shlex.quote(files)]
elif isinstance(files, list):
files = [shlex.quote(f) for f in files]
else:
raise git_exceptions.GitWrapperException("ADD: files can only be STR or LIST\nReceived {} ({})".format(files, type(files)))
self._nothing_to_commit = False
cmd = [
"add"
]
for f in files:
cmd.append(f)
try:
self._set_cmd(cmd)._run()
except git_exceptions.GitWrapperException:
if self._nothing_to_commit:
pass
else:
raise
return self
def commit(self, files="-a", msg="auto-commit", amend=False, dry_run=False):
if isinstance(files, str):
files=[shlex.quote(files)]
elif isinstance(files, list):
files = [shlex.quote(f) for f in files]
else:
raise git_exceptions.GitWrapperException("COMMIT: files can only be STR or LIST\nReceived {} ({})".format(files, type(files)))
self._nothing_to_commit = False
cmd = [
"commit",
"--amend" if amend else "",
"--dry-run" if dry_run else "",
"-m {}".format(shlex.quote(msg))
]
for f in files:
cmd.append(f)
try:
self._set_wkdir(self._local)._set_cmd(cmd)._run()
except git_exceptions.GitWrapperException:
if self._nothing_to_commit:
pass
else:
raise
return self
def push(self, remote_name="origin", branch="master", with_tags=True, force=False, dry_run=False, prune=False, mirror=False):
if not self._local.exists:
raise git_exceptions.GitWrapperException("PUSH: local repo does not exist yet: {}".format(self._local.full_path))
remote_name = shlex.quote(remote_name) if remote_name else ""
branch = shlex.quote(branch) if branch else ""
cmd = [
"push",
remote_name,
branch,
"--tags" if with_tags else "",
"--force" if force else "",
"--prune" if prune else "",
"-n" if dry_run else "",
"--mirror" if mirror else "",
]
self._set_wkdir(self._local)._set_cmd(cmd)._run()
return self
def pull(self, remote_name="origin", branch="master", update_submodules=False, no_commit=False,
no_fast_forward=False, only_fast_forward=False, rebase=False):
if not self._local.exists:
raise git_exceptions.GitWrapperException("PULL: local repo does not exist yet: {}".format(self._local.full_path))
remote_name, branch = shlex.quote(remote_name), shlex.quote(branch)
cmd = [
"pull",
"--recurse-submodules" if update_submodules else "",
"--no-commit" if no_commit else "",
"--no-ff" if no_fast_forward else "",
"--ff-only" if only_fast_forward else "",
"--rebase" if rebase else "",
remote_name,
branch
]
self._set_wkdir(self._local)._set_cmd(cmd)._run()
return self
def clone(self, remote_address, target_directory=None, bare=False, recursive=True,
branch=None, no_checkout=False, add_as_origin=False):
if target_directory is not None:
target_directory = Path(target_directory)
self._set_wkdir(target_directory.dirname)
cmd = [
"clone",
"--bare" if bare else "",
"--recursive" if recursive else "",
"--branch {}".format(shlex.quote(branch)) if branch is not None else "",
"--no-checkout" if no_checkout else "",
remote_address,
## shlex.quote(Path(remote_address).nice_full_path),
shlex.quote(Path(target_directory).basename) if target_directory is not None else ""
]
if target_directory is None:
self._local = Path(os.path.join(self._wkdir.full_path, Path(remote_address).basename))
else:
self._local = Path(target_directory)
self._set_cmd(cmd)._run()
if add_as_origin:
self._set_cmd([
"remote",
'add',
'origin',
remote_address
])._run()
return self