-
Notifications
You must be signed in to change notification settings - Fork 126
/
gitimerge.py
4366 lines (3587 loc) · 142 KB
/
gitimerge.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
# -*- coding: utf-8 -*-
# Copyright 2012-2013 Michael Haggerty <mhagger@alum.mit.edu>
#
# This file is part of git-imerge.
#
# git-imerge is free software: you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see
# <https://www.gnu.org/licenses/>.
r"""Git incremental merge
Perform the merge between two branches incrementally. If conflicts
are encountered, figure out exactly which pairs of commits conflict,
and present the user with one pairwise conflict at a time for
resolution.
Multiple incremental merges can be in progress at the same time. Each
incremental merge has a name, and its progress is recorded in the Git
repository as references under 'refs/imerge/NAME'.
An incremental merge can be interrupted and resumed arbitrarily, or
even pushed to a server to allow somebody else to work on it.
Instructions:
To start an incremental merge or rebase, use one of the following
commands:
git-imerge merge BRANCH
Analogous to "git merge BRANCH"
git-imerge rebase BRANCH
Analogous to "git rebase BRANCH"
git-imerge drop [commit | commit1..commit2]
Drop the specified commit(s) from the current branch
git-imerge revert [commit | commit1..commit2]
Revert the specified commits by adding new commits that
reverse their effects
git-imerge start --name=NAME --goal=GOAL BRANCH
Start a general imerge
Then the tool will present conflicts to you one at a time, similar to
"git rebase --incremental". Resolve each conflict, and then
git add FILE...
git-imerge continue
You can view your progress at any time with
git-imerge diagram
When you have resolved all of the conflicts, simplify and record the
result by typing
git-imerge finish
To get more help about any git-imerge subcommand, type
git-imerge SUBCOMMAND --help
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import locale
import sys
import re
import subprocess
from subprocess import CalledProcessError
from subprocess import check_call
import itertools
import argparse
from io import StringIO
import json
import os
PREFERRED_ENCODING = locale.getpreferredencoding()
# Define check_output() for ourselves, including decoding of the
# output into PREFERRED_ENCODING:
def check_output(*popenargs, **kwargs):
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)
output = communicate(process)[0]
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
# We don't store output in the CalledProcessError because
# the "output" keyword parameter was not supported in
# Python 2.6:
raise CalledProcessError(retcode, cmd)
return output
STATE_VERSION = (1, 3, 0)
ZEROS = '0' * 40
ALLOWED_GOALS = [
'full',
'rebase',
'rebase-with-history',
'border',
'border-with-history',
'border-with-history2',
'merge',
'drop',
'revert',
]
DEFAULT_GOAL = 'merge'
class Failure(Exception):
"""An exception that indicates a normal failure of the script.
Failures are reported at top level via sys.exit(str(e)) rather
than via a Python stack dump."""
pass
class AnsiColor:
BLACK = '\033[0;30m'
RED = '\033[0;31m'
GREEN = '\033[0;32m'
YELLOW = '\033[0;33m'
BLUE = '\033[0;34m'
MAGENTA = '\033[0;35m'
CYAN = '\033[0;36m'
B_GRAY = '\033[0;37m'
D_GRAY = '\033[1;30m'
B_RED = '\033[1;31m'
B_GREEN = '\033[1;32m'
B_YELLOW = '\033[1;33m'
B_BLUE = '\033[1;34m'
B_MAGENTA = '\033[1;35m'
B_CYAN = '\033[1;36m'
WHITE = '\033[1;37m'
END = '\033[0m'
@classmethod
def disable(cls):
cls.BLACK = ''
cls.RED = ''
cls.GREEN = ''
cls.YELLOW = ''
cls.BLUE = ''
cls.MAGENTA = ''
cls.CYAN = ''
cls.B_GRAY = ''
cls.D_GRAY = ''
cls.B_RED = ''
cls.B_GREEN = ''
cls.B_YELLOW = ''
cls.B_BLUE = ''
cls.B_MAGENTA = ''
cls.B_CYAN = ''
cls.WHITE = ''
cls.END = ''
def iter_neighbors(iterable):
"""For an iterable (x0, x1, x2, ...) generate [(x0,x1), (x1,x2), ...]."""
i = iter(iterable)
try:
last = next(i)
except StopIteration:
return
for x in i:
yield (last, x)
last = x
def find_first_false(f, lo, hi):
"""Return the smallest i in lo <= i < hi for which f(i) returns False using bisection.
If there is no such i, return hi.
"""
# Loop invariant: f(i) returns True for i < lo; f(i) returns False
# for i >= hi.
while lo < hi:
mid = (lo + hi) // 2
if f(mid):
lo = mid + 1
else:
hi = mid
return lo
def call_silently(cmd):
try:
NULL = open(os.devnull, 'w')
except (IOError, AttributeError):
NULL = subprocess.PIPE
p = subprocess.Popen(cmd, stdout=NULL, stderr=NULL)
p.communicate()
retcode = p.wait()
if retcode:
raise CalledProcessError(retcode, cmd)
def communicate(process, input=None):
"""Return decoded output from process."""
if input is not None:
input = input.encode(PREFERRED_ENCODING)
output, error = process.communicate(input)
output = None if output is None else output.decode(PREFERRED_ENCODING)
error = None if error is None else error.decode(PREFERRED_ENCODING)
return (output, error)
if sys.hexversion >= 0x03000000:
# In Python 3.x, os.environ keys and values must be unicode
# strings:
def env_encode(s):
"""Use unicode keys or values unchanged in os.environ."""
return s
else:
# In Python 2.x, os.environ keys and values must be byte
# strings:
def env_encode(s):
"""Encode unicode keys or values for use in os.environ."""
return s.encode(PREFERRED_ENCODING)
class UncleanWorkTreeError(Failure):
pass
class AutomaticMergeFailed(Exception):
def __init__(self, commit1, commit2):
Exception.__init__(
self, 'Automatic merge of %s and %s failed' % (commit1, commit2,)
)
self.commit1, self.commit2 = commit1, commit2
class InvalidBranchNameError(Failure):
pass
class NotFirstParentAncestorError(Failure):
def __init__(self, commit1, commit2):
Failure.__init__(
self,
'Commit "%s" is not a first-parent ancestor of "%s"'
% (commit1, commit2),
)
class NonlinearAncestryError(Failure):
def __init__(self, commit1, commit2):
Failure.__init__(
self,
'The history "%s..%s" is not linear'
% (commit1, commit2),
)
class NothingToDoError(Failure):
def __init__(self, src_tip, dst_tip):
Failure.__init__(
self,
'There are no commits on "%s" that are not already in "%s"'
% (src_tip, dst_tip),
)
class GitTemporaryHead(object):
"""A context manager that records the current HEAD state then restores it.
This should only be used when the working copy is clean. message
is used for the reflog.
"""
def __init__(self, git, message):
self.git = git
self.message = message
def __enter__(self):
self.head_name = self.git.get_head_refname()
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if self.head_name:
try:
self.git.restore_head(self.head_name, self.message)
except CalledProcessError as e:
raise Failure(
'Could not restore HEAD to %r!: %s\n'
% (self.head_name, e.message,)
)
return False
class GitRepository(object):
BRANCH_PREFIX = 'refs/heads/'
MERGE_STATE_REFNAME_RE = re.compile(
r"""
^
refs\/imerge\/
(?P<name>.+)
\/state
$
""",
re.VERBOSE,
)
def __init__(self):
self.git_dir_cache = None
def git_dir(self):
if self.git_dir_cache is None:
self.git_dir_cache = check_output(
['git', 'rev-parse', '--git-dir']
).rstrip('\n')
return self.git_dir_cache
def check_imerge_name_format(self, name):
"""Check that name is a valid imerge name."""
try:
call_silently(
['git', 'check-ref-format', 'refs/imerge/%s' % (name,)]
)
except CalledProcessError:
raise Failure('Name %r is not a valid refname component!' % (name,))
def check_branch_name_format(self, name):
"""Check that name is a valid branch name."""
try:
call_silently(
['git', 'check-ref-format', 'refs/heads/%s' % (name,)]
)
except CalledProcessError:
raise InvalidBranchNameError('Name %r is not a valid branch name!' % (name,))
def iter_existing_imerge_names(self):
"""Iterate over the names of existing MergeStates in this repo."""
for line in check_output(['git', 'for-each-ref', 'refs/imerge']).splitlines():
(sha1, type, refname) = line.split()
if type == 'blob':
m = GitRepository.MERGE_STATE_REFNAME_RE.match(refname)
if m:
yield m.group('name')
def set_default_imerge_name(self, name):
"""Set the default merge to the specified one.
name can be None to cause the default to be cleared."""
if name is None:
try:
check_call(['git', 'config', '--unset', 'imerge.default'])
except CalledProcessError as e:
if e.returncode == 5:
# Value was not set
pass
else:
raise
else:
check_call(['git', 'config', 'imerge.default', name])
def get_default_imerge_name(self):
"""Get the name of the default merge, or None if it is currently unset."""
try:
return check_output(['git', 'config', 'imerge.default']).rstrip()
except CalledProcessError:
return None
def get_default_edit(self):
"""Should '--edit' be used when committing intermediate user merges?
When 'git imerge continue' or 'git imerge record' finds a user
merge that can be committed, should it (by default) ask the user
to edit the commit message? This behavior can be configured via
'imerge.editmergemessages'. If it is not configured, return False.
Please note that this function is only used to choose the default
value. It can be overridden on the command line using '--edit' or
'--no-edit'.
"""
try:
return {'true' : True, 'false' : False}[
check_output(
['git', 'config', '--bool', 'imerge.editmergemessages']
).rstrip()
]
except CalledProcessError:
return False
def unstaged_changes(self):
"""Return True iff there are unstaged changes in the working copy"""
try:
check_call(['git', 'diff-files', '--quiet', '--ignore-submodules'])
return False
except CalledProcessError:
return True
def uncommitted_changes(self):
"""Return True iff the index contains uncommitted changes."""
try:
check_call([
'git', 'diff-index', '--cached', '--quiet',
'--ignore-submodules', 'HEAD', '--',
])
return False
except CalledProcessError:
return True
def get_commit_sha1(self, arg):
"""Convert arg into a SHA1 and verify that it refers to a commit.
If not, raise ValueError."""
try:
return self.rev_parse('%s^{commit}' % (arg,))
except CalledProcessError:
raise ValueError('%r does not refer to a valid git commit' % (arg,))
def refresh_index(self):
process = subprocess.Popen(
['git', 'update-index', '-q', '--ignore-submodules', '--refresh'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
out, err = communicate(process)
retcode = process.poll()
if retcode:
raise UncleanWorkTreeError(err.rstrip() or out.rstrip())
def verify_imerge_name_available(self, name):
self.check_imerge_name_format(name)
if check_output(['git', 'for-each-ref', 'refs/imerge/%s' % (name,)]):
raise Failure('Name %r is already in use!' % (name,))
def check_imerge_exists(self, name):
"""Verify that a MergeState with the given name exists.
Just check for the existence, readability, and compatible
version of the 'state' reference. If the reference doesn't
exist, just return False. If it exists but is unusable for
some other reason, raise an exception."""
self.check_imerge_name_format(name)
state_refname = 'refs/imerge/%s/state' % (name,)
for line in check_output(['git', 'for-each-ref', state_refname]).splitlines():
(sha1, type, refname) = line.split()
if refname == state_refname and type == 'blob':
self.read_imerge_state_dict(name)
# If that didn't throw an exception:
return True
else:
return False
def read_imerge_state_dict(self, name):
state_string = check_output(
['git', 'cat-file', 'blob', 'refs/imerge/%s/state' % (name,)],
)
state = json.loads(state_string)
# Convert state['version'] to a tuple of integers, and verify
# that it is compatible with this version of the script:
version = tuple(int(i) for i in state['version'].split('.'))
if version[0] != STATE_VERSION[0] or version[1] > STATE_VERSION[1]:
raise Failure(
'The format of imerge %s (%s) is not compatible with this script version.'
% (name, state['version'],)
)
state['version'] = version
return state
def read_imerge_state(self, name):
"""Read the state associated with the specified imerge.
Return the tuple
(state_dict, {(i1, i2) : (sha1, source), ...})
, where source is 'auto' or 'manual'. Validity is checked only
lightly.
"""
merge_ref_re = re.compile(
r"""
^
refs\/imerge\/
""" + re.escape(name) + r"""
\/(?P<source>auto|manual)\/
(?P<i1>0|[1-9][0-9]*)
\-
(?P<i2>0|[1-9][0-9]*)
$
""",
re.VERBOSE,
)
state_ref_re = re.compile(
r"""
^
refs\/imerge\/
""" + re.escape(name) + r"""
\/state
$
""",
re.VERBOSE,
)
state = None
# A map {(i1, i2) : (sha1, source)}:
merges = {}
# refnames that were found but not understood:
unexpected = []
for line in check_output([
'git', 'for-each-ref', 'refs/imerge/%s' % (name,)
]).splitlines():
(sha1, type, refname) = line.split()
m = merge_ref_re.match(refname)
if m:
if type != 'commit':
raise Failure('Reference %r is not a commit!' % (refname,))
i1, i2 = int(m.group('i1')), int(m.group('i2'))
source = m.group('source')
merges[i1, i2] = (sha1, source)
continue
m = state_ref_re.match(refname)
if m:
if type != 'blob':
raise Failure('Reference %r is not a blob!' % (refname,))
state = self.read_imerge_state_dict(name)
continue
unexpected.append(refname)
if state is None:
raise Failure(
'No state found; it should have been a blob reference at '
'"refs/imerge/%s/state"' % (name,)
)
if unexpected:
raise Failure(
'Unexpected reference(s) found in "refs/imerge/%s" namespace:\n %s\n'
% (name, '\n '.join(unexpected),)
)
return (state, merges)
def write_imerge_state_dict(self, name, state):
state_string = json.dumps(state, sort_keys=True) + '\n'
cmd = ['git', 'hash-object', '-t', 'blob', '-w', '--stdin']
p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out = communicate(p, input=state_string)[0]
retcode = p.poll()
if retcode:
raise CalledProcessError(retcode, cmd)
sha1 = out.strip()
check_call([
'git', 'update-ref',
'-m', 'imerge %r: Record state' % (name,),
'refs/imerge/%s/state' % (name,),
sha1,
])
def is_ancestor(self, commit1, commit2):
"""Return True iff commit1 is an ancestor (or equal to) commit2."""
if commit1 == commit2:
return True
else:
return int(
check_output([
'git', 'rev-list', '--count', '--ancestry-path',
'%s..%s' % (commit1, commit2,),
]).strip()
) != 0
def is_ff(self, refname, commit):
"""Would updating refname to commit be a fast-forward update?
Return True iff refname is not currently set or it points to an
ancestor of commit.
"""
try:
ref_oldval = self.get_commit_sha1(refname)
except ValueError:
# refname doesn't already exist; no problem.
return True
else:
return self.is_ancestor(ref_oldval, commit)
def automerge(self, commit1, commit2, msg=None):
"""Attempt an automatic merge of commit1 and commit2.
Return the SHA1 of the resulting commit, or raise
AutomaticMergeFailed on error. This must be called with a clean
worktree."""
call_silently(['git', 'checkout', '-f', commit1])
cmd = ['git', '-c', 'rerere.enabled=false', 'merge']
if msg is not None:
cmd += ['-m', msg]
cmd += [commit2]
try:
call_silently(cmd)
except CalledProcessError:
self.abort_merge()
raise AutomaticMergeFailed(commit1, commit2)
else:
return self.get_commit_sha1('HEAD')
def manualmerge(self, commit, msg):
"""Initiate a merge of commit into the current HEAD."""
check_call(['git', 'merge', '--no-commit', '-m', msg, commit,])
def require_clean_work_tree(self, action):
"""Verify that the current tree is clean.
The code is a Python translation of the git-sh-setup(1) function
of the same name."""
process = subprocess.Popen(
['git', 'rev-parse', '--verify', 'HEAD'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
err = communicate(process)[1]
retcode = process.poll()
if retcode:
raise UncleanWorkTreeError(err.rstrip())
self.refresh_index()
error = []
if self.unstaged_changes():
error.append('Cannot %s: You have unstaged changes.' % (action,))
if self.uncommitted_changes():
if not error:
error.append('Cannot %s: Your index contains uncommitted changes.' % (action,))
else:
error.append('Additionally, your index contains uncommitted changes.')
if error:
raise UncleanWorkTreeError('\n'.join(error))
def simple_merge_in_progress(self):
"""Return True iff a merge (of a single branch) is in progress."""
try:
with open(os.path.join(self.git_dir(), 'MERGE_HEAD')) as f:
heads = [line.rstrip() for line in f]
except IOError:
return False
return len(heads) == 1
def commit_user_merge(self, edit_log_msg=None):
"""If a merge is in progress and ready to be committed, commit it.
If a simple merge is in progress and any changes in the working
tree are staged, commit the merge commit and return True.
Otherwise, return False.
"""
if not self.simple_merge_in_progress():
return False
# Check if all conflicts are resolved and everything in the
# working tree is staged:
self.refresh_index()
if self.unstaged_changes():
raise UncleanWorkTreeError(
'Cannot proceed: You have unstaged changes.'
)
# A merge is in progress, and either all changes have been staged
# or no changes are necessary. Create a merge commit.
cmd = ['git', 'commit', '--no-verify']
if edit_log_msg is None:
edit_log_msg = self.get_default_edit()
if edit_log_msg:
cmd += ['--edit']
else:
cmd += ['--no-edit']
try:
check_call(cmd)
except CalledProcessError:
raise Failure('Could not commit staged changes.')
return True
def create_commit_chain(self, base, path):
"""Point refname at the chain of commits indicated by path.
path is a list [(commit, metadata), ...]. Create a series of
commits corresponding to the entries in path. Each commit's tree
is taken from the corresponding old commit, and each commit's
metadata is taken from the corresponding metadata commit. Use base
as the parent of the first commit, or make the first commit a root
commit if base is None. Reuse existing commits from the list
whenever possible.
Return a commit object corresponding to the last commit in the
chain.
"""
reusing = True
if base is None:
if not path:
raise ValueError('neither base nor path specified')
parents = []
else:
parents = [base]
for (commit, metadata) in path:
if reusing:
if commit == metadata and self.get_commit_parents(commit) == parents:
# We can reuse this commit, too.
parents = [commit]
continue
else:
reusing = False
# Create a commit, copying the old log message and author info
# from the metadata commit:
tree = self.get_tree(commit)
new_commit = self.commit_tree(
tree, parents,
msg=self.get_log_message(metadata),
metadata=self.get_author_info(metadata),
)
parents = [new_commit]
[commit] = parents
return commit
def rev_parse(self, arg):
return check_output(['git', 'rev-parse', '--verify', '--quiet', arg]).strip()
def rev_list_with_parents(self, *args):
"""Iterate over (commit, [parent,...])."""
cmd = ['git', 'log', '--format=%H %P'] + list(args)
for line in check_output(cmd).splitlines():
commits = line.strip().split()
yield (commits[0], commits[1:])
def summarize_commit(self, commit):
"""Summarize `commit` to stdout."""
check_call(['git', '--no-pager', 'log', '--no-walk', commit])
def get_author_info(self, commit):
"""Return environment settings to set author metadata.
Return a map {str : str}."""
# We use newlines as separators here because msysgit has problems
# with NUL characters; see
#
# https://github.com/mhagger/git-imerge/pull/71
a = check_output([
'git', '--no-pager', 'log', '-n1',
'--format=%an%n%ae%n%ai', commit
]).strip().splitlines()
return {
'GIT_AUTHOR_NAME': env_encode(a[0]),
'GIT_AUTHOR_EMAIL': env_encode(a[1]),
'GIT_AUTHOR_DATE': env_encode(a[2]),
}
def get_log_message(self, commit):
contents = check_output([
'git', 'cat-file', 'commit', commit,
]).splitlines(True)
contents = contents[contents.index('\n') + 1:]
if contents and contents[-1][-1:] != '\n':
contents.append('\n')
return ''.join(contents)
def get_commit_parents(self, commit):
"""Return a list containing the parents of commit."""
return check_output(
['git', '--no-pager', 'log', '--no-walk', '--pretty=format:%P', commit]
).strip().split()
def get_tree(self, arg):
return self.rev_parse('%s^{tree}' % (arg,))
def update_ref(self, refname, value, msg, deref=True):
if deref:
opt = []
else:
opt = ['--no-deref']
check_call(['git', 'update-ref'] + opt + ['-m', msg, refname, value])
def delete_ref(self, refname, msg, deref=True):
if deref:
opt = []
else:
opt = ['--no-deref']
check_call(['git', 'update-ref'] + opt + ['-m', msg, '-d', refname])
def delete_imerge_refs(self, name):
stdin = ''.join(
'delete %s\n' % (refname,)
for refname in check_output([
'git', 'for-each-ref',
'--format=%(refname)',
'refs/imerge/%s' % (name,)
]).splitlines()
)
process = subprocess.Popen(
[
'git', 'update-ref',
'-m', 'imerge: remove merge %r' % (name,),
'--stdin',
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
)
out = communicate(process, input=stdin)[0]
retcode = process.poll()
if retcode:
sys.stderr.write(
'Warning: error removing references:\n%s' % (out,)
)
def detach(self, msg):
"""Detach HEAD. msg is used for the reflog."""
self.update_ref('HEAD', 'HEAD^0', msg, deref=False)
def reset_hard(self, commit):
check_call(['git', 'reset', '--hard', commit])
def amend(self):
check_call(['git', 'commit', '--amend'])
def abort_merge(self):
# We don't use "git merge --abort" here because it was
# only added in git version 1.7.4.
check_call(['git', 'reset', '--merge'])
def compute_best_merge_base(self, tip1, tip2):
try:
merge_bases = check_output(['git', 'merge-base', '--all', tip1, tip2]).splitlines()
except CalledProcessError:
raise Failure('Cannot compute merge base for %r and %r' % (tip1, tip2))
if not merge_bases:
raise Failure('%r and %r do not have a common merge base' % (tip1, tip2))
if len(merge_bases) == 1:
return merge_bases[0]
# There are multiple merge bases. The "best" one is the one that
# is the "closest" to the tips, which we define to be the one with
# the fewest non-merge commits in "merge_base..tip". (It can be
# shown that the result is independent of which tip is used in the
# computation.)
best_base = best_count = None
for merge_base in merge_bases:
cmd = ['git', 'rev-list', '--no-merges', '--count', '%s..%s' % (merge_base, tip1)]
count = int(check_output(cmd).strip())
if best_base is None or count < best_count:
best_base = merge_base
best_count = count
return best_base
def linear_ancestry(self, commit1, commit2, first_parent):
"""Compute a linear ancestry between commit1 and commit2.
Our goal is to find a linear series of commits connecting
`commit1` and `commit2`. We do so as follows:
* If all of the commits in
git rev-list --ancestry-path commit1..commit2
are on a linear chain, return that.
* If there are multiple paths between `commit1` and `commit2` in
that list of commits, then
* If `first_parent` is not set, then raise an
`NonlinearAncestryError` exception.
* If `first_parent` is set, then, at each merge commit, follow
the first parent that is in that list of commits.
Return a list of SHA-1s in 'chronological' order.
Raise NotFirstParentAncestorError if commit1 is not an ancestor of
commit2.
"""
oid1 = self.rev_parse(commit1)
oid2 = self.rev_parse(commit2)
parentage = {oid1 : []}
for (commit, parents) in self.rev_list_with_parents(
'--ancestry-path', '--topo-order', '%s..%s' % (oid1, oid2)
):
parentage[commit] = parents
commits = []
commit = oid2
while commit != oid1:
parents = parentage.get(commit, [])
# Only consider parents that are in the ancestry path:
included_parents = [
parent
for parent in parents
if parent in parentage
]
if not included_parents:
raise NotFirstParentAncestorError(commit1, commit2)
elif len(included_parents) == 1 or first_parent:
parent = included_parents[0]
else:
raise NonlinearAncestryError(commit1, commit2)
commits.append(commit)
commit = parent
commits.reverse()
return commits