forked from git-cola/git-cola
/
cmds.py
2508 lines (1927 loc) · 74.4 KB
/
cmds.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division, absolute_import, unicode_literals
import os
import re
import sys
from fnmatch import fnmatch
from io import StringIO
try:
from send2trash import send2trash
except ImportError:
send2trash = None
from . import compat
from . import core
from . import fsmonitor
from . import gitcfg
from . import gitcmds
from . import icons
from . import resources
from . import utils
from .diffparse import DiffParser
from .git import STDOUT
from .i18n import N_
from .interaction import Interaction
from .models import main
from .models import prefs
from .models import selection
class UsageError(Exception):
"""Exception class for usage errors."""
def __init__(self, title, message):
Exception.__init__(self, message)
self.title = title
self.msg = message
class CommandMixin(object):
"""Mixin interface for commands"""
UNDOABLE = False
@staticmethod
def name():
return '(undefined)'
@classmethod
def is_undoable(cls):
"""Can this be undone?"""
return cls.UNDOABLE
def do(self):
pass
def undo(self):
pass
class ContextCommand(CommandMixin):
def __init__(self, context):
self.context = context
self.model = context.model
self.cfg = context.cfg
self.git = context.git
self.selection = context.selection
class ConfirmAction(CommandMixin):
def ok_to_run(self):
return True
def confirm(self):
return True
def action(self):
return (-1, '', '')
def success(self):
pass
def command(self):
return 'git'
def error_message(self):
return ''
def do(self):
status = -1
out = err = ''
ok = self.ok_to_run() and self.confirm()
if ok:
status, out, err = self.action()
if status == 0:
self.success()
title = self.error_message()
cmd = self.command()
Interaction.command(title, cmd, status, out, err)
return ok, status, out, err
class ModelCommand(CommandMixin):
"""Commands that manipulate the main model"""
def __init__(self, model=None):
if model is None: # TODO context
model = main.model()
self.model = model
class EditModel(ModelCommand):
"""Commands that mutate the main model diff data"""
def __init__(self):
"""Common edit operations on the main model"""
# TODO context
super(EditModel, self).__init__()
self.old_diff_text = self.model.diff_text
self.old_filename = self.model.filename
self.old_mode = self.model.mode
self.old_diff_type = self.model.diff_type
self.new_diff_text = self.old_diff_text
self.new_filename = self.old_filename
self.new_mode = self.old_mode
self.new_diff_type = self.old_diff_type
def do(self):
"""Perform the operation."""
self.model.set_filename(self.new_filename)
self.model.set_mode(self.new_mode)
self.model.set_diff_text(self.new_diff_text)
self.model.set_diff_type(self.new_diff_type)
def undo(self):
"""Undo the operation."""
self.model.set_filename(self.old_filename)
self.model.set_mode(self.old_mode)
self.model.set_diff_text(self.old_diff_text)
self.model.set_diff_type(self.old_diff_type)
class AbortMerge(ConfirmAction):
"""Reset an in-progress merge back to HEAD"""
def __init__(self):
self.model = main.model() # TODO context
def confirm(self):
title = N_('Abort Merge...')
question = N_('Aborting the current merge?')
info = N_('Aborting the current merge will cause '
'*ALL* uncommitted changes to be lost.\n'
'Recovering uncommitted changes is not possible.')
ok_txt = N_('Abort Merge')
return Interaction.confirm(title, question, info, ok_txt,
default=False, icon=icons.undo())
def action(self):
status, out, err = gitcmds.abort_merge()
self.model.update_file_status()
return status, out, err
def success(self):
self.model.set_commitmsg('')
def error_message(self):
return N_('Error')
def command(self):
return 'git merge'
class AmendMode(EditModel):
"""Try to amend a commit."""
UNDOABLE = True
LAST_MESSAGE = None
@staticmethod
def name():
return N_('Amend')
def __init__(self, amend):
super(AmendMode, self).__init__() # TODO context
self.skip = False
self.amending = amend
self.old_commitmsg = self.model.commitmsg
self.old_mode = self.model.mode
if self.amending:
self.new_mode = self.model.mode_amend
self.new_commitmsg = gitcmds.prev_commitmsg()
AmendMode.LAST_MESSAGE = self.model.commitmsg
return
# else, amend unchecked, regular commit
self.new_mode = self.model.mode_none
self.new_diff_text = ''
self.new_commitmsg = self.model.commitmsg
# If we're going back into new-commit-mode then search the
# undo stack for a previous amend-commit-mode and grab the
# commit message at that point in time.
if AmendMode.LAST_MESSAGE is not None:
self.new_commitmsg = AmendMode.LAST_MESSAGE
AmendMode.LAST_MESSAGE = None
def do(self):
"""Leave/enter amend mode."""
"""Attempt to enter amend mode. Do not allow this when merging."""
if self.amending:
if self.model.is_merging:
self.skip = True
self.model.set_mode(self.old_mode)
Interaction.information(
N_('Cannot Amend'),
N_('You are in the middle of a merge.\n'
'Cannot amend while merging.'))
return
self.skip = False
super(AmendMode, self).do()
self.model.set_commitmsg(self.new_commitmsg)
self.model.update_file_status()
def undo(self):
if self.skip:
return
self.model.set_commitmsg(self.old_commitmsg)
super(AmendMode, self).undo()
self.model.update_file_status()
class AnnexAdd(ContextCommand):
def __init__(self, context):
super(AnnexAdd, self).__init__(context)
self.filename = self.selection.filename()
def do(self):
status, out, err = self.git.annex('add', self.filename)
Interaction.command(N_('Error'), 'git annex add', status, out, err)
self.model.update_status()
class AnnexInit(ModelCommand):
def do(self):
git = self.model.git
status, out, err = git.annex('init')
Interaction.command(N_('Error'), 'git annex init', status, out, err)
self.model.cfg.reset()
self.model.emit_updated()
class LFSTrack(ContextCommand):
def __init__(self, context):
super(LFSTrack, self).__init__(context)
self.filename = self.selection.filename()
self.stage_cmd = Stage([self.filename])
def do(self):
status, out, err = self.git.lfs('track', self.filename)
Interaction.command(
N_('Error'), 'git lfs track', status, out, err)
if status == 0:
self.stage_cmd.do()
class LFSInstall(ModelCommand):
def do(self):
git = self.model.git
status, out, err = git.lfs('install')
Interaction.command(
N_('Error'), 'git lfs install', status, out, err)
self.model.emit_updated()
class ApplyDiffSelection(ModelCommand):
def __init__(self, first_line_idx, last_line_idx, has_selection,
reverse, apply_to_worktree):
super(ApplyDiffSelection, self).__init__() # TODO context
self.first_line_idx = first_line_idx
self.last_line_idx = last_line_idx
self.has_selection = has_selection
self.reverse = reverse
self.apply_to_worktree = apply_to_worktree
def do(self):
diff_text = self.model.diff_text
parser = DiffParser(self.model.filename, diff_text)
if self.has_selection:
patch = parser.generate_patch(self.first_line_idx,
self.last_line_idx,
reverse=self.reverse)
else:
patch = parser.generate_hunk_patch(self.first_line_idx,
reverse=self.reverse)
if patch is None:
return
if isinstance(diff_text, core.UStr):
# original encoding must prevail
encoding = diff_text.encoding
else:
cfg = gitcfg.current()
encoding = cfg.file_encoding(self.model.filename)
tmp_file = utils.tmp_filename('patch')
try:
core.write(tmp_file, patch, encoding=encoding)
if self.apply_to_worktree:
status, out, err = gitcmds.apply_diff_to_worktree(tmp_file)
else:
status, out, err = gitcmds.apply_diff(tmp_file)
finally:
core.unlink(tmp_file)
Interaction.log_status(status, out, err)
self.model.update_file_status(update_index=True)
class ApplyPatches(ModelCommand):
def __init__(self, patches):
super(ApplyPatches, self).__init__() # TODO context
self.patches = patches
def do(self):
diff_text = ''
num_patches = len(self.patches)
orig_head = self.model.git.rev_parse('HEAD')[STDOUT]
for idx, patch in enumerate(self.patches):
status, out, err = self.model.git.am(patch)
# Log the git-am command
Interaction.log_status(status, out, err)
if num_patches > 1:
diff = self.model.git.diff('HEAD^!', stat=True)[STDOUT]
diff_text += (N_('PATCH %(current)d/%(count)d') %
dict(current=idx+1, count=num_patches))
diff_text += ' - %s:\n%s\n\n' % (os.path.basename(patch), diff)
diff_text += N_('Summary:') + '\n'
diff_text += self.model.git.diff(orig_head, stat=True)[STDOUT]
# Display a diffstat
self.model.set_diff_text(diff_text)
self.model.update_file_status()
basenames = '\n'.join([os.path.basename(p) for p in self.patches])
Interaction.information(
N_('Patch(es) Applied'),
(N_('%d patch(es) applied.') +
'\n\n%s') % (len(self.patches), basenames))
class Archive(CommandMixin):
def __init__(self, ref, fmt, prefix, filename):
self.ref = ref
self.fmt = fmt
self.prefix = prefix
self.filename = filename
def do(self):
fp = core.xopen(self.filename, 'wb')
cmd = ['git', 'archive', '--format='+self.fmt]
if self.fmt in ('tgz', 'tar.gz'):
cmd.append('-9')
if self.prefix:
cmd.append('--prefix=' + self.prefix)
cmd.append(self.ref)
proc = core.start_command(cmd, stdout=fp)
out, err = proc.communicate()
fp.close()
status = proc.returncode
Interaction.log_status(status, out or '', err or '')
class Checkout(EditModel):
"""A command object for git-checkout.
'argv' is handed off directly to git.
"""
def __init__(self, argv, checkout_branch=False):
super(Checkout, self).__init__() # TODO context
self.argv = argv
self.checkout_branch = checkout_branch
self.new_diff_text = ''
self.new_diff_type = 'text'
def do(self):
super(Checkout, self).do()
status, out, err = self.model.git.checkout(*self.argv)
if self.checkout_branch:
self.model.update_status()
else:
self.model.update_file_status()
Interaction.command(N_('Error'), 'git checkout', status, out, err)
class BlamePaths(CommandMixin):
"""Blame view for paths."""
def __init__(self, paths):
viewer = utils.shell_split(prefs.blame_viewer())
self.argv = viewer + list(paths)
def do(self):
try:
core.fork(self.argv)
except Exception as e:
_, details = utils.format_exception(e)
title = N_('Error Launching Blame Viewer')
msg = (N_('Cannot exec "%s": please configure a blame viewer') %
' '.join(self.argv))
Interaction.critical(title, message=msg, details=details)
class CheckoutBranch(Checkout):
"""Checkout a branch."""
def __init__(self, branch):
args = [branch]
super(CheckoutBranch, self).__init__(args, checkout_branch=True)
class CherryPick(ModelCommand):
"""Cherry pick commits into the current branch."""
def __init__(self, commits):
super(CherryPick, self).__init__() # TODO context
self.commits = commits
def do(self):
self.model.cherry_pick_list(self.commits)
self.model.update_file_status()
class ResetMode(EditModel):
"""Reset the mode and clear the model's diff text."""
def __init__(self):
super(ResetMode, self).__init__()
self.new_mode = self.model.mode_none
self.new_diff_text = ''
self.new_diff_type = 'text'
self.new_filename = ''
def do(self):
super(ResetMode, self).do()
self.model.update_file_status()
class ResetCommand(ConfirmAction):
def __init__(self, ref):
self.model = main.model() # TODO context
self.ref = ref
def action(self):
return self.reset()
def command(self):
return 'git reset'
def error_message(self):
return N_('Error')
def success(self):
self.model.update_file_status()
def confirm(self):
raise NotImplemented('confirm() must be overridden')
def reset(self):
raise NotImplemented('reset() must be overridden')
class ResetBranchHead(ResetCommand):
def confirm(self):
title = N_('Reset Branch')
question = N_('Point the current branch head to a new commit?')
info = N_('The branch will be reset using "git reset --mixed %s"')
ok_text = N_('Reset Branch')
info = info % self.ref
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.model.git.reset(self.ref, '--', mixed=True)
class ResetWorktree(ResetCommand):
def confirm(self):
title = N_('Reset Worktree')
question = N_('Reset worktree?')
info = N_('The worktree will be reset using "git reset --keep %s"')
ok_text = N_('Reset Worktree')
info = info % self.ref
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.model.git.reset(self.ref, '--', keep=True)
class ResetMerge(ResetCommand):
def confirm(self):
title = N_('Reset Merge')
question = N_('Reset merge?')
info = N_('The branch will be reset using "git reset --merge %s"')
ok_text = N_('Reset Merge')
info = info % self.ref
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.model.git.reset(self.ref, '--', merge=True)
class ResetSoft(ResetCommand):
def confirm(self):
title = N_('Reset Soft')
question = N_('Reset soft?')
info = N_('The branch will be reset using "git reset --soft %s"')
ok_text = N_('Reset Soft')
info = info % self.ref
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.model.git.reset(self.ref, '--', soft=True)
class ResetHard(ResetCommand):
def confirm(self):
title = N_('Reset Hard')
question = N_('Reset hard?')
info = N_('The branch will be reset using "git reset --hard %s"')
ok_text = N_('Reset Hard')
info = info % self.ref
return Interaction.confirm(title, question, info, ok_text)
def reset(self):
return self.model.git.reset(self.ref, '--', hard=True)
class Commit(ResetMode):
"""Attempt to create a new commit."""
def __init__(self, amend, msg, sign, no_verify=False):
super(Commit, self).__init__() # TODO context
self.amend = amend
self.msg = msg
self.sign = sign
self.no_verify = no_verify
self.old_commitmsg = self.model.commitmsg
self.new_commitmsg = ''
def do(self):
# Create the commit message file
comment_char = prefs.comment_char()
msg = self.strip_comments(self.msg, comment_char=comment_char)
tmp_file = utils.tmp_filename('commit-message')
try:
core.write(tmp_file, msg)
# Run 'git commit'
status, out, err = self.model.git.commit(F=tmp_file,
v=True,
gpg_sign=self.sign,
amend=self.amend,
no_verify=self.no_verify)
finally:
core.unlink(tmp_file)
if status == 0:
super(Commit, self).do()
self.model.set_commitmsg(self.new_commitmsg)
title = N_('Commit failed')
Interaction.command(title, 'git commit', status, out, err)
return status, out, err
@staticmethod
def strip_comments(msg, comment_char='#'):
# Strip off comments
message_lines = [line for line in msg.split('\n')
if not line.startswith(comment_char)]
msg = '\n'.join(message_lines)
if not msg.endswith('\n'):
msg += '\n'
return msg
class Ignore(ModelCommand):
"""Add files to .gitignore"""
def __init__(self, filenames):
super(Ignore, self).__init__() # TODO context
self.filenames = list(filenames)
def do(self):
if not self.filenames:
return
new_additions = '\n'.join(self.filenames) + '\n'
for_status = new_additions
if core.exists('.gitignore'):
current_list = core.read('.gitignore')
new_additions = current_list.rstrip() + '\n' + new_additions
core.write('.gitignore', new_additions)
Interaction.log_status(0, 'Added to .gitignore:\n%s' % for_status, '')
self.model.update_file_status()
def file_summary(files):
txt = core.list2cmdline(files)
if len(txt) > 768:
txt = txt[:768].rstrip() + '...'
return txt
class RemoteCommand(ConfirmAction):
def __init__(self, name):
self.model = main.model() # TODO context
self.name = name # TODO base class method/member variable conflict
def success(self):
self.model.cfg.reset()
self.model.update_remotes()
class RemoteAdd(RemoteCommand):
def __init__(self, name, url):
super(RemoteAdd, self).__init__(name) # TODO context
self.url = url
def action(self):
git = self.model.git
return git.remote('add', self.name, self.url)
def error_message(self):
return N_('Error creating remote "%s"') % self.name
def command(self):
return 'git remote add "%s" "%s"' % (self.name, self.url)
class RemoteRemove(RemoteCommand):
def confirm(self):
title = N_('Delete Remote')
question = N_('Delete remote?')
info = N_('Delete remote "%s"') % self.name
ok_text = N_('Delete')
return Interaction.confirm(title, question, info, ok_text)
def action(self):
git = self.model.git
return git.remote('rm', self.name)
def error_message(self):
return N_('Error deleting remote "%s"') % self.name
def command(self):
return 'git remote rm "%s"' % self.name
class RemoteRename(RemoteCommand):
def __init__(self, name, new_name):
super(RemoteRename, self).__init__(name) # TODO context
self.new_name = new_name
def confirm(self):
title = N_('Rename Remote')
info = (N_('Rename remote "%(current)s" to "%(new)s"?') %
dict(current=self.name, new=self.new_name))
return Interaction.question(title, info)
def action(self):
git = self.model.git
return git.remote('rename', self.name, self.new_name)
def error_message(self):
return (N_('Error renaming "%(name)s" to "%(new_name)s"')
% dict(name=self.name, new_name=self.new_name))
def command(self):
return 'git remote rename "%s" "%s"' % (self.name, self.new_name)
class RemoteSetURL(RemoteCommand):
def __init__(self, name, url):
super(RemoteSetURL, self).__init__(name) # TODO context
self.url = url
def action(self):
git = self.model.git
return git.remote('set-url', self.name, self.url)
def error_message(self):
return (N_('Unable to set URL for "%(name)s" to "%(url)s"')
% dict(name=self.name, url=self.url))
def command(self):
return 'git remote set-url "%s" "%s"' % (self.name, self.url)
class RemoteEdit(CommandMixin):
"""Combine RemoteRename and RemoteSetURL"""
def __init__(self, old_name, name, url):
# TODO context
self.old_name = old_name
self.name = name
self.url = url
self.rename = RemoteRename(old_name, name)
self.set_url = RemoteSetURL(name, url)
def do(self):
result = self.rename.do()
name_ok = result[0]
url_ok = False
if name_ok:
result = self.set_url.do()
url_ok = result[0]
return name_ok, url_ok
class RemoveFromSettings(ConfirmAction):
def __init__(self, settings, repo, name, icon=None):
# TODO context
self.settings = settings
self.repo = repo
self.name = name
self.icon = icon
def success(self):
self.settings.save()
class RemoveBookmark(RemoveFromSettings):
def confirm(self):
name = self.name
title = msg = N_('Delete Bookmark?')
info = N_('%s will be removed from your bookmarks.') % name
ok_text = N_('Delete Bookmark')
return Interaction.confirm(title, msg, info, ok_text, icon=self.icon)
def action(self):
self.settings.remove_bookmark(self.repo, self.name)
return (0, '', '')
class RemoveRecent(RemoveFromSettings):
def confirm(self):
repo = self.repo
title = msg = N_('Remove %s from the recent list?') % repo
info = N_('%s will be removed from your recent repositories.') % repo
ok_text = N_('Remove')
return Interaction.confirm(title, msg, info, ok_text, icon=self.icon)
def action(self):
self.settings.remove_recent(self.repo)
return (0, '', '')
class RemoveFiles(ModelCommand):
"""Removes files"""
def __init__(self, remover, filenames):
super(RemoveFiles, self).__init__() # TODO context
if remover is None:
remover = os.remove
self.remover = remover
self.filenames = filenames
# We could git-hash-object stuff and provide undo-ability
# as an option. Heh.
def do(self):
files = self.filenames
if not files:
return
rescan = False
bad_filenames = []
remove = self.remover
for filename in files:
if filename:
try:
remove(filename)
rescan = True
except:
bad_filenames.append(filename)
if bad_filenames:
Interaction.information(
N_('Error'),
N_('Deleting "%s" failed') % file_summary(files))
if rescan:
self.model.update_file_status()
class Delete(RemoveFiles):
"""Delete files."""
def __init__(self, filenames):
super(Delete, self).__init__(os.remove, filenames) # TODO context
def do(self):
files = self.filenames
if not files:
return
title = N_('Delete Files?')
msg = N_('The following files will be deleted:') + '\n\n'
msg += file_summary(files)
info_txt = N_('Delete %d file(s)?') % len(files)
ok_txt = N_('Delete Files')
if not Interaction.confirm(title, msg, info_txt, ok_txt,
default=True, icon=icons.remove()):
return
return super(Delete, self).do()
class MoveToTrash(RemoveFiles):
"""Move files to the trash using send2trash"""
AVAILABLE = send2trash is not None
def __init__(self, filenames):
# TODO context
super(MoveToTrash, self).__init__(send2trash, filenames)
class DeleteBranch(EditModel):
"""Delete a git branch."""
def __init__(self, branch):
super(DeleteBranch, self).__init__() # TODO context
self.branch = branch
def do(self):
status, out, err = self.model.delete_branch(self.branch)
Interaction.log_status(status, out, err)
class Rename(ModelCommand):
"""Rename a set of paths."""
def __init__(self, paths):
super(Rename, self).__init__() # TODO context
self.paths = paths
def do(self):
msg = N_('Untracking: %s') % (', '.join(self.paths))
Interaction.log(msg)
for path in self.paths:
ok = self.rename(path)
if not ok:
return
self.model.update_status()
def rename(self, path):
git = self.model.git
title = N_('Rename "%s"') % path
if os.path.isdir(path):
base_path = os.path.dirname(path)
else:
base_path = path
new_path = Interaction.save_as(base_path, title)
if not new_path:
return False
status, out, err = git.mv(path, new_path, force=True, verbose=True)
Interaction.command(N_('Error'), 'git mv', status, out, err)
return status == 0
class RenameBranch(ModelCommand):
"""Rename a git branch."""
def __init__(self, branch, new_branch):
super(RenameBranch, self).__init__() # TODO context
self.branch = branch
self.new_branch = new_branch
def do(self):
status, out, err = self.model.rename_branch(self.branch,
self.new_branch)
Interaction.log_status(status, out, err)
class DeleteRemoteBranch(ModelCommand):
"""Delete a remote git branch."""
def __init__(self, remote, branch):
super(DeleteRemoteBranch, self).__init__() # TODO context
self.remote = remote
self.branch = branch
def do(self):
status, out, err = self.model.git.push(self.remote, self.branch,
delete=True)
self.model.update_status()
title = N_('Error Deleting Remote Branch')
Interaction.command(title, 'git push', status, out, err)
if status == 0:
Interaction.information(
N_('Remote Branch Deleted'),
N_('"%(branch)s" has been deleted from "%(remote)s".')
% dict(branch=self.branch, remote=self.remote))
class DiffImage(EditModel):
def __init__(self,
filename, deleted, staged, modified, unmerged, untracked):
super(DiffImage, self).__init__() # TODO context
self.new_filename = filename
self.new_diff_text = ''
self.new_diff_type = 'image'
self.staged = staged
self.modified = modified
self.unmerged = unmerged
self.untracked = untracked
self.deleted = deleted
self.annex = self.model.cfg.is_annex()
def do(self):
cfg = self.model.cfg
git = self.model.git
head = self.model.head
filename = self.new_filename
annex = self.annex
if self.staged:
images = self.staged_images()
elif self.modified:
images = self.modified_images()
elif self.unmerged:
images = self.unmerged_images()
elif self.untracked:
images = [(filename, False)]
else:
images = []
self.model.set_images(images)
super(DiffImage, self).do()
def staged_images(self):
git = self.model.git
cfg = self.model.cfg
head = self.model.head
filename = self.new_filename
annex = self.annex
images = []
index = git.diff_index(head, '--', filename, cached=True)[STDOUT]
if index:
# Example:
# :100644 100644 fabadb8... 4866510... M describe.c
parts = index.split(' ')
if len(parts) > 3:
old_oid = parts[2]
new_oid = parts[3]
if old_oid != gitcmds.MISSING_BLOB_OID:
# First, check if we can get a pre-image from git-annex
annex_image = None
if annex:
annex_image = gitcmds.annex_path(
head, filename, config=cfg)
if annex_image: