This repository has been archived by the owner on Nov 20, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgitwrapper.py
324 lines (259 loc) · 9.61 KB
/
gitwrapper.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
# -*- coding: utf-8 -*-
"""
gitwrapper.py
Wrapper around various git subcommands
Copyright (C) 2020-2021 Rainer Schwarzbach
License: MIT, see LICENSE file
"""
import datetime
import logging
import subprocess
import sys
# local module
import processwrappers
#
# Constants
#
RETURNCODE_OK = 0
RETURNCODE_ERROR = 1
# Default Git executable
DEFAULT_GIT = 'git'
# 'git config' scopes
CONFIG_GLOBAL = '--global'
CONFIG_LOCAL = '--local'
#
# Helper Functions
#
def exit_with_error(msg, *args):
"""Exit after logging the given error message
(which may stretch over multiple lines).
"""
if args:
msg = msg % args
#
for line in msg.splitlines():
logging.error(line)
#
logging.info('Script aborted at %s', datetime.datetime.now())
sys.exit(RETURNCODE_ERROR)
def process_error_data(error):
"""Return data from a CalledProcessError as a single string"""
lines = [
'[Command failed] %s' % processwrappers.future_shlex_join(error.cmd),
'Returncode: %s' % error.returncode]
if error.stderr:
lines.append('___ Standard error ___')
lines.extend(error.stderr.decode().splitlines())
#
if error.stdout:
lines.append('___ Standard output ___')
lines.extend(error.stdout.decode().splitlines())
#
return '\n'.join(lines)
def get_command_result(*command, exit_on_error=True, **kwargs):
"""Run the specified command and return its result
(i.e. a subprocess.CompletedProcess instance).
If "exit_on_error" is set True (the default),
the calling script will exit with an error mesage
if the command returncode is non-zero.
"""
kwargs.update(
dict(check=exit_on_error))
try:
result = processwrappers.get_command_result(command, **kwargs)
except subprocess.CalledProcessError as error:
exit_with_error(process_error_data(error))
#
return result
#
# Classes
#
class BaseGitWrapper:
"""Wrapper for git command execution, base class"""
def __init__(self,
env=None,
git_command=DEFAULT_GIT):
"""Set the env and git_command attributes"""
self.env = env
self.git_command = git_command
def get_output(self, *arguments, log_output=True, **kwargs):
"""Run git with the specified arguments
and return its output (stderr and stdout) combined.
"""
kwargs.update(
dict(stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
loglevel=logging.DEBUG))
kwargs.setdefault('env', self.env)
command_result = get_command_result(
self.git_command, *arguments, **kwargs)
stderr_text = command_result.stderr.decode()
stdout_text = command_result.stdout.decode()
if log_output:
for stderr_line in stderr_text.splitlines():
logging.debug('[Command stderr] %s', stderr_line)
#
for stdout_line in stdout_text.splitlines():
logging.debug('[Command stdout] %s', stdout_line)
#
#
if not stderr_text:
return stdout_text
#
if not stdout_text:
return stderr_text
#
return '\n'.join((stderr_text, stdout_text))
def get_returncode(self, *arguments, **kwargs):
"""Run git with the specified arguments
and return the command returncode.
The output streams (stdout and stderr) are not captured,
allowing normal user interaction with the command
(eg. for password input).
"""
kwargs.update(
dict(stdout=None,
stderr=None,
loglevel=logging.INFO))
kwargs.setdefault('env', self.env)
command_result = get_command_result(
self.git_command, *arguments, **kwargs)
return command_result.returncode
class GitConfigWrapper(BaseGitWrapper):
"""Wrapper for a subset of possible git config calls:
git config [ --global | --local ] <key> <value>
git --get [ --global | --local ] <key>
git --unset [ --global | --local ] <key>
The --global or --local option is passed via scope
and always defaults to --local.
"""
long_option_prefix = '--'
def __init__(self,
env=None,
git_command=DEFAULT_GIT,
local_config_enabled=True):
"""Set the env and git_command attributes via the parent class,
plus the internal __local_config_enabled attribute.
"""
super().__init__(env=env, git_command=git_command)
self.__local_config_enabled = local_config_enabled
def __check_key(self, key):
"""Prevent programming errors:
raise a ValueError if key starts with '--'
"""
if key.startswith(self.long_option_prefix):
raise ValueError('Invalid key for git config: %r!' % key)
#
def __execute(self, *args, scope=CONFIG_LOCAL, **kwargs):
"""Execute the 'git config' command.
If scope is set to None explicitly, the preferred scope
(--local) is omitted
"""
subcommand = ['config']
if scope == CONFIG_GLOBAL or (
scope == CONFIG_LOCAL and self.__local_config_enabled):
subcommand.append(scope)
#
kwargs.setdefault('env', self.env)
return self.get_output(*subcommand, *args, **kwargs)
def __call__(self, key, value, scope=CONFIG_LOCAL, **kwargs):
"""git config <scope> <key> <value>"""
self.__check_key(key)
return self.__execute(key, value, scope=scope, **kwargs)
def get(self, key, scope=CONFIG_LOCAL, **kwargs):
"""git config <scope> --get <key>"""
self.__check_key(key)
return self.__execute('--get', key, scope=scope, **kwargs)
def unset(self, key, scope=CONFIG_LOCAL, **kwargs):
"""git config <scope> --unset <key>"""
self.__check_key(key)
return self.__execute('--unset', key, scope=scope, **kwargs)
class GitWrapper(BaseGitWrapper):
"""Wrapper for a subset of possible git commands.
The .config instance attribute
is set to a GitConfigWrapper instance.
"""
def __init__(self,
env=None,
git_command=DEFAULT_GIT,
local_config_enabled=True):
"""Set the env and git_command attributes via the parent class,
plus the wrapper for 'git config'.
"""
super().__init__(env=env, git_command=git_command)
self.config = None
self.set_config(local_config_enabled=local_config_enabled)
def set_config(self, local_config_enabled=True):
"""Set the wrapper for 'git config'"""
self.config = GitConfigWrapper(
env=self.env,
git_command=self.git_command,
local_config_enabled=local_config_enabled)
# Commands returning only the returncode
def gc_(self, *arguments, **kwargs):
"""git gc + arguments
Passthru output and return returncode
"""
return self.get_returncode('gc', *arguments, **kwargs)
def push(self, *arguments, **kwargs):
"""git push + arguments
Passthru output and return returncode
"""
return self.get_returncode('push', *arguments, **kwargs)
def showref_rc(self, *arguments, **kwargs):
"""git show-ref + arguments
Passthru output and return returncode
"""
return self.get_returncode('show-ref', *arguments, **kwargs)
def svn_fetch(self, *arguments, **kwargs):
"""git svn fetch + arguments
Passthru output and return returncode
"""
return self.get_returncode('svn', 'fetch', *arguments, **kwargs)
def svn_init(self, *arguments, **kwargs):
"""git svn init + arguments
Passthru output and return returncode
"""
return self.get_returncode('svn', 'init', *arguments, **kwargs)
# Commands returning output
def branch(self, *arguments, **kwargs):
"""git branch + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('branch', *arguments, **kwargs)
def checkout(self, *arguments, **kwargs):
"""git checkout + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('checkout', *arguments, **kwargs)
def log(self, *arguments, **kwargs):
"""git log + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('log', *arguments, **kwargs)
def rebase(self, *arguments, **kwargs):
"""git rebase + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('rebase', *arguments, **kwargs)
def remote(self, *arguments, **kwargs):
"""git remote + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('remote', *arguments, **kwargs)
def showref_output(self, *arguments, **kwargs):
"""git show-ref + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('show-ref', *arguments, **kwargs)
def status(self, *arguments, **kwargs):
"""git status + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('status', *arguments, **kwargs)
def tag(self, *arguments, **kwargs):
"""git tag + arguments
Capture stderr and stdout and return them combined
"""
return self.get_output('tag', *arguments, **kwargs)
# vim: fileencoding=utf-8 sw=4 ts=4 sts=4 expandtab autoindent syntax=python: