-
Notifications
You must be signed in to change notification settings - Fork 217
/
scm.py
398 lines (303 loc) · 12.1 KB
/
scm.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
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
"""
legit.scm
~~~~~~~~~
This module provides the main interface to Git.
"""
import fnmatch
import os
import sys
from collections import namedtuple
from operator import attrgetter
import click
from clint.textui import colored, columns
import crayons
from git import Repo
from git.exc import BadName, GitCommandError, InvalidGitRepositoryError
from .settings import legit_settings
from .utils import black, status_log
LEGIT_TEMPLATE = 'Legit: stashing before {0}.'
Branch = namedtuple('Branch', ['name', 'is_published'])
class SCMRepo:
git = None
repo = None
remote = None
verbose = False
fake = False
stash_index = None
def __init__(self):
self.git = os.environ.get('GIT_PYTHON_GIT_EXECUTABLE', 'git')
try:
self.repo = Repo(search_parent_directories=True)
self.remote = self.get_remote()
except InvalidGitRepositoryError:
self.repo = None
def git_exec(self, command, **kwargs):
"""Execute git commands"""
from .cli import verbose_echo
command.insert(0, self.git)
if kwargs.pop('no_verbose', False): # used when git output isn't helpful to user
verbose = False
else:
verbose = self.verbose
verbose_echo(' '.join(command), verbose, self.fake)
if not self.fake:
result = self.repo.git.execute(command, **kwargs)
else:
if 'with_extended_output' in kwargs:
result = (0, '', '')
else:
result = ''
return result
def repo_check(self, require_remote=False, require_refs=False):
if self.repo is None:
click.echo('Not a git repository.')
sys.exit(128)
if self.repo.heads == []:
click.echo('Repo is empty.')
sys.exit(128)
if require_refs:
try:
self.repo.commit('HEAD^')
except BadName:
click.echo('Repo only contains root commit.')
sys.exit(128)
# TODO: no remote fail
if not self.repo.remotes and require_remote:
click.echo('No git remotes configured. Please add one.')
sys.exit(128)
# TODO: You're in a merge state.
def stash_log(self, sync=False):
if self.repo.is_dirty():
status_log(self.stash_it, 'Saving local changes.', sync=sync)
def unstash_log(self, sync=False):
self.stash_index = self.unstash_index(sync=sync)
if self.stash_index:
status_log(self.unstash_it, 'Restoring local changes.', sync=sync)
def unstash_index(self, sync=False, branch=None):
"""Returns an unstash index if one is available."""
stash_list = self.git_exec(['stash', 'list'], no_verbose=True)
if branch is None:
branch = self.get_current_branch_name()
for stash in stash_list.splitlines():
verb = 'syncing' if sync else 'switching'
if (
(('Legit' in stash) and
('On {}:'.format(branch) in stash) and
(verb in stash)
) or
(('GitHub' in stash) and
('On {}:'.format(branch) in stash) and
(verb in stash)
)
):
return stash[7]
def stash_it(self, sync=False):
msg = 'syncing branch' if sync else 'switching branches'
return self.git_exec(
['stash', 'save', '--include-untracked', LEGIT_TEMPLATE.format(msg)])
def unstash_it(self, sync=False):
"""
Unstashes changes from current branch for branch sync.
Requires prior code setting self.stash_index.
"""
if self.stash_index is not None:
return self.git_exec(
['stash', 'pop', 'stash@{{{0}}}'.format(self.stash_index)])
def smart_pull(self):
"""
'git log --merges origin/master..master'
"""
branch = self.get_current_branch_name()
self.git_exec(['fetch', self.remote.name])
return self.smart_merge('{}/{}'.format(self.remote.name, branch),
self.smart_merge_enabled())
def smart_merge_enabled(self):
reader = self.repo.config_reader()
if reader.has_option('legit', 'smartMerge'):
return reader.getboolean('legit', 'smartMerge')
else:
return True
def smart_merge(self, branch, allow_rebase=True):
from_branch = self.get_current_branch_name()
merges = self.git_exec(
['log', '--merges', '{}..{}'.format(branch, from_branch)])
if allow_rebase:
verb = 'merge' if merges.count('commit') else 'rebase'
else:
if self.pull_rebase():
verb = 'rebase'
else:
verb = 'merge'
if verb != 'rebase' and self.pull_ff_only():
return self.git_exec([verb, '--ff-only', branch])
else:
try:
return self.git_exec([verb, branch])
except GitCommandError as why:
log = self.git_exec([verb, '--abort'])
abort('Merge failed. Reverting.',
log='{}\n{}'.format(why, log), type='merge')
def pull_rebase(self):
reader = self.repo.config_reader()
if reader.has_option('pull', 'rebase'):
return reader.getboolean('pull', 'rebase')
else:
return False
def pull_ff_only(self):
reader = self.repo.config_reader()
if reader.has_option('pull', 'ff'):
if reader.get('pull', 'ff') == 'only':
return True
else:
return False
else:
return False
def push(self, branch=None):
if branch is None:
return self.git_exec(['push'])
else:
return self.git_exec(['push', self.remote.name, branch])
def checkout_branch(self, branch):
"""Checks out given branch."""
_, stdout, stderr = self.git_exec(
['checkout', branch],
with_extended_output=True)
return '\n'.join([stderr, stdout])
def unpublish_branch(self, branch):
"""Unpublishes given branch."""
try:
return self.git_exec(
['push', self.remote.name, ':{}'.format(branch)])
except GitCommandError:
_, _, log = self.git_exec(
['fetch', self.remote.name, '--prune'],
with_extended_output=True)
abort('Unpublish failed. Fetching.', log=log, type='unpublish')
def publish_branch(self, branch):
"""Publishes given branch."""
return self.git_exec(
['push', '-u', self.remote.name, branch])
def undo(self, hard=False):
"""Makes last commit not exist"""
if not self.fake:
return self.repo.git.reset('HEAD^', working_tree=hard)
else:
click.echo(crayons.red('Faked! >>> git reset {}{}'
.format('--hard ' if hard else '', 'HEAD^')))
return 0
def get_remote(self):
self.repo_check()
reader = self.repo.config_reader()
# If there is no remote option in legit section, return default
if reader.has_option('legit', 'remote'):
remote_name = reader.get('legit', 'remote')
if remote_name not in [r.name for r in self.repo.remotes]:
if fallback_enabled(reader):
return self.get_default_remote()
else:
click.echo('Remote "{}" does not exist!'.format(remote_name))
will_aborted = click.confirm(
'\nPress `Y` to abort now,\n' +
'`n` to use default remote and turn fallback on for this repo:')
if will_aborted:
click.echo('\nAborted. Please update your git configuration.')
sys.exit(64) # EX_USAGE
else:
writer = self.repo.config_writer()
writer.set_value('legit', 'remoteFallback', 'true')
click.echo('\n`legit.RemoteFallback` changed to true for current repo.')
return self.get_default_remote()
else:
return self.repo.remote(remote_name)
else:
return self.get_default_remote()
def get_default_remote(self):
if len(self.repo.remotes) == 0:
return None
else:
return self.repo.remotes[0]
def get_current_branch_name(self):
"""Returns current branch name"""
return self.repo.head.ref.name
def fuzzy_match_branch(self, branch):
if not branch:
return False
all_branches = self.get_branch_names()
if branch in all_branches:
return branch
def branch_fuzzy_match(b):
return b.startswith(branch)
possible_branches = list(filter(branch_fuzzy_match, all_branches))
if len(possible_branches) == 1:
return possible_branches[0]
return branch
def get_branches(self, local=True, remote_branches=True, wildcard_pattern='*'):
"""Returns a list of local and remote branches matching wildcard_pattern."""
if not self.repo.remotes:
remote_branches = False
branches = []
if remote_branches:
# Remote refs.
try:
for b in self.remote.refs:
name = '/'.join(b.name.split('/')[1:])
if name not in legit_settings.forbidden_branches:
branches.append(Branch(name, is_published=True))
except (IndexError, AssertionError):
pass
if local:
# Local refs.
for b in [h.name for h in self.repo.heads]:
if (not remote_branches) or (b not in [br.name for br in branches]):
if b not in legit_settings.forbidden_branches:
branches.append(Branch(b, is_published=False))
matching_branch_names = fnmatch.filter(
[branch.name for branch in branches], wildcard_pattern
)
branches = [branch for branch in branches if branch.name in matching_branch_names]
return sorted(branches, key=attrgetter('name'))
def get_branch_names(self, local=True, remote_branches=True):
branches = self.get_branches(local=local, remote_branches=remote_branches)
return [b.name for b in branches]
def display_available_branches(self, wildcard_pattern='*'):
"""Displays available branches."""
if not self.repo.remotes:
remote_branches = False
else:
remote_branches = True
branches = self.get_branches(
local=True, remote_branches=remote_branches, wildcard_pattern=wildcard_pattern
)
if not branches:
click.echo(crayons.red('No branches available'))
return
branch_col = len(max([b.name for b in branches], key=len)) + 1
for branch in branches:
try:
branch_is_selected = (branch.name == self.get_current_branch_name())
except TypeError:
branch_is_selected = False
marker = '*' if branch_is_selected else ' '
color = colored.green if branch_is_selected else colored.yellow
pub = '(published)' if branch.is_published else '(unpublished)'
click.echo(columns(
[colored.red(marker), 2],
[color(branch.name, bold=True), branch_col],
[black(pub), 14]
))
# Instead of getboolean('legit', 'remoteFallback', fallback=False)
# since getboolean in Python 2 does not have fallback argument.
def fallback_enabled(reader):
if reader.has_option('legit', 'remoteFallback'):
return reader.getboolean('legit', 'remoteFallback')
else:
return False
class Aborted:
def __init__(self):
self.message = None
self.log = None
def abort(message, log=None, type=None):
a = Aborted()
a.message = message
a.log = log
legit_settings.abort_handler(a, type=type)