-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgit.py
516 lines (365 loc) · 12.7 KB
/
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
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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
__kupfer_name__ = _("Git")
__version__ = "0.1.2"
__author__ = "hugosenari <[email protected]>"
__description__ = _("""Git plugin for kupfer""")
__kupfer_actions__ = ('GitActions', 'GitkAction', 'ChangeBranchAction',
'CreateBranchAction', 'FetchBranchAction', 'PullBranchAction',
'PushBranchAction', 'CommitAction', 'CommitRecursiveAction')
from kupfer.objects import Action, Leaf, FileLeaf, Source, \
TextLeaf, TextSource
from kupfer import uiutils
from sh import git, gitk, ErrorReturnCode
from os import path
# utils function
_ = lambda x: x
def show_msg(msg, title='Info'):
uiutils.show_notification(_(title), _(msg))
def try_or_show_msg(fn):
def wrapper(*args, **kwds):
try:
return fn(*args, **kwds)
except ErrorReturnCode as e:
show_msg(e.stderr or e, 'Error')
return wrapper
def generator(fn):
def generated(*args, **kwds):
items = fn(*args, **kwds)
for item in items:
yield item
return generated
def dir_path(file_path):
is_dir = path.isdir(file_path)
parent_dir = path.dirname(file_path)
result = file_path if is_dir else parent_dir
return result
class GitActionMixin(object):
def valid_for_item(self, leaf):
abs_path = leaf.canonical_path()
return git_is_repo_dir(abs_path)
def item_types(self):
yield FileLeaf
yield GitStatusLeaf
yield BranchSource
def is_factory(self):
return True
def has_result(self):
return True
def activate(self, leaf, *args):
git_status = GitStatusLeaf(leaf)
return self._activate(git_status, *args)
class BranchActionMixin(object):
def object_types(self):
yield GitBranchLeaf
def object_source(self, for_item=None):
git_status = GitStatusLeaf(for_item)
return BranchSource(git_status, self.branch_filter)
def requires_object(self):
return True
class TextActionMixin(object):
def object_types(self):
yield TextLeaf
def object_source(self, for_item=None):
return TextSource()
def requires_object(self):
return True
# actions
class GitActions(GitActionMixin, Action):
def __init__(self):
Action.__init__(self, _("Git Actions"))
def _activate(self, leaf):
return leaf
class ChangeBranchAction(GitActionMixin, BranchActionMixin, Action):
def __init__(self):
self.branch_filter = None
Action.__init__(self, _('Change Branch'))
def _activate(self, leaf, rleaf):
git_ch_branch(leaf.abs_path, rleaf.name, rleaf.remote, False)
return GitStatusLeaf(leaf)
class FetchBranchAction(GitActionMixin, BranchActionMixin, Action):
def __init__(self):
self.branch_filter = fil_remove_local
Action.__init__(self, _('Fetch'))
def _activate(self, leaf, rleaf):
git_fetch(rleaf.remote, rleaf.name, leaf.abs_path)
return GitStatusLeaf(leaf)
class PullBranchAction(GitActionMixin, BranchActionMixin, Action):
def __init__(self):
self.branch_filter = fil_remove_local
Action.__init__(self, _('Pull'))
def _activate(self, leaf, rleaf):
git_pull(rleaf.remote, rleaf.name, leaf.abs_path)
return GitStatusLeaf(leaf)
class PushBranchAction(GitActionMixin, BranchActionMixin, Action):
def __init__(self):
self.branch_filter = fil_remove_local
Action.__init__(self, _('Push'))
def activate(self, leaf, rleaf):
git_push(rleaf.remote, rleaf.name, leaf.abs_path)
class CreateBranchAction(GitActionMixin, TextActionMixin, Action):
def __init__(self):
Action.__init__(self, _('Create Branch'))
def _activate(self, leaf, rleaf):
git_ch_branch(leaf.abs_path, rleaf.object, None)
return GitStatusLeaf(leaf)
class CommitAction(GitActionMixin, TextActionMixin, Action):
def __init__(self):
Action.__init__(self, _('Commit'))
def _activate(self, leaf, rleaf):
leaf = GitStatusLeaf(leaf)
git_commit(leaf.abs_path, rleaf.object, False)
return GitStatusLeaf(leaf)
def valid_for_item(self, leaf):
result = GitActionMixin.valid_for_item(self, leaf)
if result:
leaf = GitStatusLeaf(leaf)
result = git_has_changes(leaf.abs_path)
return result
class CommitRecursiveAction(GitActionMixin, TextActionMixin, Action):
def __init__(self):
Action.__init__(self, _('Commit All In Dir'))
def _activate(self, leaf, rleaf):
git_commit(leaf.abs_path, rleaf.object, leaf.file_name)
return GitStatusLeaf(leaf)
def valid_for_item(self, leaf):
result = GitActionMixin.valid_for_item(self, leaf)
if result:
leaf = GitStatusLeaf(leaf)
result = git_has_changes(dir_path(leaf.abs_path))
return result
class GitkAction(GitActionMixin, Action):
def __init__(self):
Action.__init__(self, _("Gitk"))
def _activate(self, leaf):
''''''
git_ui(leaf.abs_path)
return GitStatusLeaf(leaf)
# Leaf
class GitStatusLeaf(Leaf):
def __init__(self, leaf):
real_path = leaf.canonical_path()
leaf_dict = file_dict(real_path)
self.root = leaf_dict['root']
self.title = leaf_dict['title']
self.status = leaf_dict['status']
self.branch = leaf_dict['branch']
self.abs_path = leaf_dict['abs_path']
self.description = leaf_dict['description']
Leaf.__init__(self, leaf.object, self.title)
def get_description(self):
return self.description
def canonical_path(self):
return self.abs_path
class GitBranchLeaf(Leaf):
def __init__(self, name, path, remote=None):
Leaf.__init__(self,
{'path': path, 'name': name, 'remote': remote},
name)
self.name = name
self.abs_path = path
self.remote = remote
self.is_remote = bool(remote)
def canonical_path(self):
return self.abs_path
def get_description(self):
return (self.remote or 'local') + ': ' + self.name
# sources
class BranchSource(Source):
def __init__(self, obj=None, fil=None):
Source.__init__(self, _("Branch Source"))
self.fil = fil or (lambda x: (y for y in x))
self.abs_path = obj.abs_path if obj else None
def get_items(self):
fil = self.fil
branches = fil(fil_remove_link(git_branchs(self.abs_path)))
for branch in branches:
if 'remotes/' in branch:
splited = branch.split('/')
yield GitBranchLeaf(splited[2], self.abs_path, splited[1])
else:
yield GitBranchLeaf(branch, self.abs_path)
def is_dynamic(self):
return True
# kupfer short-hand
def file_dict(real_path):
result = {}
result['abs_path'] = real_path
result['root'] = str(git_root(real_path))
result['status'] = git_status(real_path)
result['branch'] = git_current_branch(real_path)
result['title'] = path.basename(real_path) + ': ' + result['branch']
result['description'] = _('Git Status: ') + \
str(result['status']).replace("{u'", "{'").replace(", u'", ", '") + \
': ' + path.basename(result['root'])
return result
# git short-hands
@try_or_show_msg
def git_status(file_path):
'''
Return object with {key: count}, with a key for current status,
and count of times for this status
'''
return count_status(
fil_parse_status(
fil_clean_output(
gen_status(file_path))))
def git_has_changes(file_path):
try:
statuses = fil_remove_status_value(
fil_parse_status(
fil_clean_output(
gen_status(file_path))), '??')
for status in statuses:
return True
except Exception as e:
return False
@try_or_show_msg
def git_branchs(file_path):
'''Return all branchs'''
return fil_clean_branch(
fil_clean_output(
gen_branchs(file_path)))
@try_or_show_msg
def git_current_branch(file_path):
'''Return current branch'''
return current_branch(
fil_clean_output(
gen_branchs(file_path)))
@try_or_show_msg
def git_remotes(file_path):
'''Return a list of remotes'''
return fil_clean_output(
gen_remotes(file_path))
@try_or_show_msg
def git_ui(file_path):
'''Show gitk for dir'''
gitk(_cwd=dir_path(file_path))
@try_or_show_msg
def git_ch_branch(file_path, branch, remote=None, create=True):
'''Change current branch'''
args = []
if create:
args.append('-b')
if remote:
branch = remote + '/' + branch
args.append(branch)
git.checkout(*args, _cwd=dir_path(file_path))
show_msg('Now at ' + branch, 'Info')
@try_or_show_msg
def git_fetch(remote, branch, file_path):
'''Fetch for remote changes'''
p = git.fetch(remote, branch, _cwd=dir_path(file_path), _tty_out=False)
p.wait()
show_msg('Repo updated', 'Info')
@try_or_show_msg
def git_pull(remote, branch, file_path):
'''Pull remote changes'''
p = git.pull(remote, branch, _cwd=dir_path(file_path), _tty_out=False)
p.wait()
show_msg('Pull Done', 'Info')
@try_or_show_msg
def git_push(remote, branch, file_path):
'''Push changes to remote'''
p = git.push(remote, branch, _cwd=dir_path(file_path), _tty_out=False)
p.wait()
show_msg('Push Done', 'Info')
@try_or_show_msg
def git_commit(file_path, message, recursive=True):
'''Change current branch'''
args = []
if recursive:
args.append('-a')
file_path = dir_path(file_path)
args.append('-m')
args.append('"' + message + '"')
args.append(file_path)
git.commit(*args, _cwd=dir_path(file_path))
show_msg('Commit Done', 'Info')
@try_or_show_msg
def git_root(file_path):
'''Return git root dir name'''
rev_parse = git.bake('rev-parse')
roots = rev_parse('--show-toplevel', _cwd=dir_path(file_path))
return fil_clean_output(roots).next()
def git_is_repo_dir(file_path):
'''Return git root dir name'''
rev_parse = git.bake('rev-parse')
try:
roots = rev_parse('--show-toplevel', _cwd=dir_path(file_path))
return bool(fil_clean_output(roots).next())
except Exception as e:
return False
# git generators consumer
def count_status(all_parsed_status):
'''return count of status'''
result = {}
for parsed_status in all_parsed_status:
value = parsed_status['value']
if not value in result:
result[value] = 0
result[value] = result[value] + 1
return result
def current_branch(branchs):
'''return current branch name'''
for branch in branchs:
if '*' in branch:
return str(branch.split('* ')[1])
# git generators
@generator
def gen_remotes(file_path):
'''return generetor of remotes'''
remotes = git.remote(_cwd=dir_path(file_path))
return remotes
@generator
def gen_branchs(file_path):
'''return generator with branchs'''
branches = git.branch('--all', '--color=never', _cwd=dir_path(file_path))
return branches
@generator
def gen_status(file_path):
'''return generator with result of git status --porcelain'''
all_status = git.status('--porcelain', file_path, _cwd=dir_path(file_path))
return all_status
# generators filters
def fil_clean_output(lines):
'''return generator with lines without space and \n '''
for line in lines:
yield line.strip(' ').strip('\n')
def fil_remove_link(lines):
'''return generator without git "links" '''
for line in lines:
if not '->' in line:
yield line
def fil_parse_status(all_status):
'''return generator with {'value': status, 'path': file}'''
for status in all_status:
splited = status.split(' ')
value = splited[0]
path = splited[1:]
yield {'value': value, 'path': path}
def fil_remove_status_value(all_status, value):
'''filter parsed status by status[value]'''
for status in all_status:
if status['value'] != value:
yield status
def fil_remove_parent(branchs):
'''Remove status with .. from list'''
for branch in branchs:
if not '..' in branch:
yield branch
def fil_clean_branch(branchs):
'''Remove * from current branch'''
for branch in branchs:
if '*' in branch:
yield str(branch.split('* ')[1])
else:
yield branch
def fil_remove_remote(branchs):
'''Remove branchs with remote'''
for branch in branchs:
if not 'remotes/' in branch:
yield branch
def fil_remove_local(branchs):
'''Remove branchs withour remote'''
for branch in branchs:
if 'remotes/' in branch:
yield branch