1
# Copyright (C) 2005 by Aaron Bentley
1
# Copyright (C) 2005, 2006, 2007, 2009, 2010 Canonical Ltd
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
11
# GNU General Public License for more details.
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17
# TODO: Move this into builtins
19
# TODO: 'bzr resolve' should accept a directory name and work from that
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
# TODO: 'bzr resolve' should accept a directory name and work from that
22
# TODO: bzr revert should resolve; even when reverting the whole tree
23
# or particular directories
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
29
from bzrlib.branch import Branch
30
from bzrlib.errors import BzrCommandError, NotConflicted
31
from bzrlib.commands import register_command
32
from bzrlib.workingtree import CONFLICT_SUFFIXES
34
class cmd_conflicts(bzrlib.commands.Command):
35
"""List files with conflicts.
36
(conflicts are determined by the presence of .BASE .TREE, and .OTHER
44
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
47
class cmd_conflicts(commands.Command):
48
__doc__ = """List files with conflicts.
50
Merge will do its best to combine the changes in two branches, but there
51
are some kinds of problems only a human can fix. When it encounters those,
52
it will mark a conflict. A conflict means that you need to fix something,
53
before you should commit.
55
Conflicts normally are listed as short, human-readable messages. If --text
56
is supplied, the pathnames of files with text conflicts are listed,
57
instead. (This is useful for editing all files with text conflicts.)
59
Use bzr resolve when you have fixed a problem.
40
for path in Branch.open_containing('.')[0].working_tree().iter_conflicts():
43
class cmd_resolve(bzrlib.commands.Command):
44
"""Mark a conflict as resolved.
63
help='List paths of files with text conflicts.'),
65
_see_also = ['resolve', 'conflict-types']
67
def run(self, text=False):
68
wt = workingtree.WorkingTree.open_containing(u'.')[0]
69
for conflict in wt.conflicts():
71
if conflict.typestring != 'text conflict':
73
self.outf.write(conflict.path + '\n')
75
self.outf.write(str(conflict) + '\n')
78
resolve_action_registry = registry.Registry()
81
resolve_action_registry.register(
82
'done', 'done', 'Marks the conflict as resolved' )
83
resolve_action_registry.register(
84
'take-this', 'take_this',
85
'Resolve the conflict preserving the version in the working tree' )
86
resolve_action_registry.register(
87
'take-other', 'take_other',
88
'Resolve the conflict taking the merged version into account' )
89
resolve_action_registry.default_key = 'done'
91
class ResolveActionOption(option.RegistryOption):
94
super(ResolveActionOption, self).__init__(
95
'action', 'How to resolve the conflict.',
97
registry=resolve_action_registry)
100
class cmd_resolve(commands.Command):
101
__doc__ = """Mark a conflict as resolved.
103
Merge will do its best to combine the changes in two branches, but there
104
are some kinds of problems only a human can fix. When it encounters those,
105
it will mark a conflict. A conflict means that you need to fix something,
106
before you should commit.
108
Once you have fixed a problem, use "bzr resolve" to automatically mark
109
text conflicts as fixed, "bzr resolve FILE" to mark a specific conflict as
110
resolved, or "bzr resolve --all" to mark all conflicts as resolved.
46
112
aliases = ['resolved']
47
113
takes_args = ['file*']
48
takes_options = ['all']
49
def run(self, file_list=None, all=False):
52
raise BzrCommandError(
53
"command 'resolve' needs one or more FILE, or --all")
54
tree = Branch.open_containing('.')[0].working_tree()
55
file_list = list(tree.abspath(f) for f in tree.iter_conflicts())
115
option.Option('all', help='Resolve all conflicts in this tree.'),
116
ResolveActionOption(),
118
_see_also = ['conflicts']
119
def run(self, file_list=None, all=False, action=None):
122
raise errors.BzrCommandError("If --all is specified,"
123
" no FILE may be provided")
124
tree = workingtree.WorkingTree.open_containing('.')[0]
58
raise BzrCommandError(
59
"If --all is specified, no FILE may be provided")
60
for filename in file_list:
62
for suffix in CONFLICT_SUFFIXES:
64
os.unlink(filename+suffix)
66
if e.errno != errno.ENOENT:
70
if failures == len(CONFLICT_SUFFIXES):
71
if not os.path.exists(filename):
72
print "%s does not exist" % filename
128
tree, file_list = builtins.tree_files(file_list)
129
if file_list is None:
131
# FIXME: There is a special case here related to the option
132
# handling that could be clearer and easier to discover by
133
# providing an --auto action (bug #344013 and #383396) and
134
# make it mandatory instead of implicit and active only
135
# when no file_list is provided -- vila 091229
141
if file_list is None:
142
un_resolved, resolved = tree.auto_resolve()
143
if len(un_resolved) > 0:
144
trace.note('%d conflict(s) auto-resolved.', len(resolved))
145
trace.note('Remaining conflicts:')
146
for conflict in un_resolved:
74
print "%s is not conflicted" % filename
150
trace.note('All conflicts resolved.')
153
# FIXME: This can never occur but the block above needs some
154
# refactoring to transfer tree.auto_resolve() to
155
# conflict.auto(tree) --vila 091242
158
resolve(tree, file_list, action=action)
161
def resolve(tree, paths=None, ignore_misses=False, recursive=False,
163
"""Resolve some or all of the conflicts in a working tree.
165
:param paths: If None, resolve all conflicts. Otherwise, select only
167
:param recursive: If True, then elements of paths which are directories
168
have all their children resolved, etc. When invoked as part of
169
recursive commands like revert, this should be True. For commands
170
or applications wishing finer-grained control, like the resolve
171
command, this should be False.
172
:param ignore_misses: If False, warnings will be printed if the supplied
173
paths do not have conflicts.
174
:param action: How the conflict should be resolved,
176
tree.lock_tree_write()
178
tree_conflicts = tree.conflicts()
180
new_conflicts = ConflictList()
181
to_process = tree_conflicts
183
new_conflicts, to_process = tree_conflicts.select_conflicts(
184
tree, paths, ignore_misses, recursive)
185
for conflict in to_process:
187
conflict._do(action, tree)
188
conflict.cleanup(tree)
189
except NotImplementedError:
190
new_conflicts.append(conflict)
192
tree.set_conflicts(new_conflicts)
193
except errors.UnsupportedOperation:
76
199
def restore(filename):
78
Restore a conflicted file to the state it was in before merging.
79
Only text restoration supported at present.
200
"""Restore a conflicted file to the state it was in before merging.
202
Only text restoration is supported at present.
81
204
conflicted = False
83
os.rename(filename + ".THIS", filename)
206
osutils.rename(filename + ".THIS", filename)
85
208
except OSError, e:
86
209
if e.errno != errno.ENOENT:
98
221
if e.errno != errno.ENOENT:
100
223
if not conflicted:
101
raise NotConflicted(filename)
224
raise errors.NotConflicted(filename)
227
class ConflictList(object):
228
"""List of conflicts.
230
Typically obtained from WorkingTree.conflicts()
232
Can be instantiated from stanzas or from Conflict subclasses.
235
def __init__(self, conflicts=None):
236
object.__init__(self)
237
if conflicts is None:
240
self.__list = conflicts
243
return len(self.__list) == 0
246
return len(self.__list)
249
return iter(self.__list)
251
def __getitem__(self, key):
252
return self.__list[key]
254
def append(self, conflict):
255
return self.__list.append(conflict)
257
def __eq__(self, other_list):
258
return list(self) == list(other_list)
260
def __ne__(self, other_list):
261
return not (self == other_list)
264
return "ConflictList(%r)" % self.__list
267
def from_stanzas(stanzas):
268
"""Produce a new ConflictList from an iterable of stanzas"""
269
conflicts = ConflictList()
270
for stanza in stanzas:
271
conflicts.append(Conflict.factory(**stanza.as_dict()))
274
def to_stanzas(self):
275
"""Generator of stanzas"""
276
for conflict in self:
277
yield conflict.as_stanza()
279
def to_strings(self):
280
"""Generate strings for the provided conflicts"""
281
for conflict in self:
284
def remove_files(self, tree):
285
"""Remove the THIS, BASE and OTHER files for listed conflicts"""
286
for conflict in self:
287
if not conflict.has_files:
289
conflict.cleanup(tree)
291
def select_conflicts(self, tree, paths, ignore_misses=False,
293
"""Select the conflicts associated with paths in a tree.
295
File-ids are also used for this.
296
:return: a pair of ConflictLists: (not_selected, selected)
298
path_set = set(paths)
300
selected_paths = set()
301
new_conflicts = ConflictList()
302
selected_conflicts = ConflictList()
304
file_id = tree.path2id(path)
305
if file_id is not None:
308
for conflict in self:
310
for key in ('path', 'conflict_path'):
311
cpath = getattr(conflict, key, None)
314
if cpath in path_set:
316
selected_paths.add(cpath)
318
if osutils.is_inside_any(path_set, cpath):
320
selected_paths.add(cpath)
322
for key in ('file_id', 'conflict_file_id'):
323
cfile_id = getattr(conflict, key, None)
327
cpath = ids[cfile_id]
331
selected_paths.add(cpath)
333
selected_conflicts.append(conflict)
335
new_conflicts.append(conflict)
336
if ignore_misses is not True:
337
for path in [p for p in paths if p not in selected_paths]:
338
if not os.path.exists(tree.abspath(path)):
339
print "%s does not exist" % path
341
print "%s is not conflicted" % path
342
return new_conflicts, selected_conflicts
345
class Conflict(object):
346
"""Base class for all types of conflict"""
348
# FIXME: cleanup should take care of that ? -- vila 091229
351
def __init__(self, path, file_id=None):
353
# warn turned off, because the factory blindly transfers the Stanza
354
# values to __init__ and Stanza is purely a Unicode api.
355
self.file_id = osutils.safe_file_id(file_id, warn=False)
358
s = rio.Stanza(type=self.typestring, path=self.path)
359
if self.file_id is not None:
360
# Stanza requires Unicode apis
361
s.add('file_id', self.file_id.decode('utf8'))
365
return [type(self), self.path, self.file_id]
367
def __cmp__(self, other):
368
if getattr(other, "_cmp_list", None) is None:
370
return cmp(self._cmp_list(), other._cmp_list())
373
return hash((type(self), self.path, self.file_id))
375
def __eq__(self, other):
376
return self.__cmp__(other) == 0
378
def __ne__(self, other):
379
return not self.__eq__(other)
382
return self.format % self.__dict__
385
rdict = dict(self.__dict__)
386
rdict['class'] = self.__class__.__name__
387
return self.rformat % rdict
390
def factory(type, **kwargs):
392
return ctype[type](**kwargs)
395
def sort_key(conflict):
396
if conflict.path is not None:
397
return conflict.path, conflict.typestring
398
elif getattr(conflict, "conflict_path", None) is not None:
399
return conflict.conflict_path, conflict.typestring
401
return None, conflict.typestring
403
def _do(self, action, tree):
404
"""Apply the specified action to the conflict.
406
:param action: The method name to call.
408
:param tree: The tree passed as a parameter to the method.
410
meth = getattr(self, 'action_%s' % action, None)
412
raise NotImplementedError(self.__class__.__name__ + '.' + action)
415
def associated_filenames(self):
416
"""The names of the files generated to help resolve the conflict."""
417
raise NotImplementedError(self.associated_filenames)
419
def cleanup(self, tree):
420
for fname in self.associated_filenames():
422
osutils.delete_any(tree.abspath(fname))
424
if e.errno != errno.ENOENT:
427
def action_done(self, tree):
428
"""Mark the conflict as solved once it has been handled."""
429
# This method does nothing but simplifies the design of upper levels.
432
def action_take_this(self, tree):
433
raise NotImplementedError(self.action_take_this)
435
def action_take_other(self, tree):
436
raise NotImplementedError(self.action_take_other)
438
def _resolve_with_cleanups(self, tree, *args, **kwargs):
439
tt = transform.TreeTransform(tree)
440
op = cleanup.OperationWithCleanups(self._resolve)
441
op.add_cleanup(tt.finalize)
442
op.run_simple(tt, *args, **kwargs)
445
class PathConflict(Conflict):
446
"""A conflict was encountered merging file paths"""
448
typestring = 'path conflict'
450
format = 'Path conflict: %(path)s / %(conflict_path)s'
452
rformat = '%(class)s(%(path)r, %(conflict_path)r, %(file_id)r)'
454
def __init__(self, path, conflict_path=None, file_id=None):
455
Conflict.__init__(self, path, file_id)
456
self.conflict_path = conflict_path
459
s = Conflict.as_stanza(self)
460
if self.conflict_path is not None:
461
s.add('conflict_path', self.conflict_path)
464
def associated_filenames(self):
465
# No additional files have been generated here
468
def _resolve(self, tt, file_id, path, winner):
469
"""Resolve the conflict.
471
:param tt: The TreeTransform where the conflict is resolved.
472
:param file_id: The retained file id.
473
:param path: The retained path.
474
:param winner: 'this' or 'other' indicates which side is the winner.
476
path_to_create = None
478
if self.path == '<deleted>':
479
return # Nothing to do
480
if self.conflict_path == '<deleted>':
481
path_to_create = self.path
482
revid = tt._tree.get_parent_ids()[0]
483
elif winner == 'other':
484
if self.conflict_path == '<deleted>':
485
return # Nothing to do
486
if self.path == '<deleted>':
487
path_to_create = self.conflict_path
488
# FIXME: If there are more than two parents we may need to
489
# iterate. Taking the last parent is the safer bet in the mean
490
# time. -- vila 20100309
491
revid = tt._tree.get_parent_ids()[-1]
494
raise AssertionError('bad winner: %r' % (winner,))
495
if path_to_create is not None:
496
tid = tt.trans_id_tree_path(path_to_create)
497
transform.create_from_tree(
498
tt, tt.trans_id_tree_path(path_to_create),
499
self._revision_tree(tt._tree, revid), file_id)
500
tt.version_file(file_id, tid)
502
# Adjust the path for the retained file id
503
tid = tt.trans_id_file_id(file_id)
504
parent_tid = tt.get_tree_parent(tid)
505
tt.adjust_path(path, parent_tid, tid)
508
def _revision_tree(self, tree, revid):
509
return tree.branch.repository.revision_tree(revid)
511
def _infer_file_id(self, tree):
512
# Prior to bug #531967, file_id wasn't always set, there may still be
513
# conflict files in the wild so we need to cope with them
514
# Establish which path we should use to find back the file-id
516
for p in (self.path, self.conflict_path):
518
# special hard-coded path
521
possible_paths.append(p)
522
# Search the file-id in the parents with any path available
524
for revid in tree.get_parent_ids():
525
revtree = self._revision_tree(tree, revid)
526
for p in possible_paths:
527
file_id = revtree.path2id(p)
528
if file_id is not None:
529
return revtree, file_id
532
def action_take_this(self, tree):
533
if self.file_id is not None:
534
self._resolve_with_cleanups(tree, self.file_id, self.path,
537
# Prior to bug #531967 we need to find back the file_id and restore
538
# the content from there
539
revtree, file_id = self._infer_file_id(tree)
540
tree.revert([revtree.id2path(file_id)],
541
old_tree=revtree, backups=False)
543
def action_take_other(self, tree):
544
if self.file_id is not None:
545
self._resolve_with_cleanups(tree, self.file_id,
549
# Prior to bug #531967 we need to find back the file_id and restore
550
# the content from there
551
revtree, file_id = self._infer_file_id(tree)
552
tree.revert([revtree.id2path(file_id)],
553
old_tree=revtree, backups=False)
556
class ContentsConflict(PathConflict):
557
"""The files are of different types (or both binary), or not present"""
561
typestring = 'contents conflict'
563
format = 'Contents conflict in %(path)s'
565
def associated_filenames(self):
566
return [self.path + suffix for suffix in ('.BASE', '.OTHER')]
568
def _resolve(self, tt, suffix_to_remove):
569
"""Resolve the conflict.
571
:param tt: The TreeTransform where the conflict is resolved.
572
:param suffix_to_remove: Either 'THIS' or 'OTHER'
574
The resolution is symmetric, when taking THIS, OTHER is deleted and
575
item.THIS is renamed into item and vice-versa.
578
# Delete 'item.THIS' or 'item.OTHER' depending on
581
tt.trans_id_tree_path(self.path + '.' + suffix_to_remove))
582
except errors.NoSuchFile:
583
# There are valid cases where 'item.suffix_to_remove' either
584
# never existed or was already deleted (including the case
585
# where the user deleted it)
587
# Rename 'item.suffix_to_remove' (note that if
588
# 'item.suffix_to_remove' has been deleted, this is a no-op)
589
this_tid = tt.trans_id_file_id(self.file_id)
590
parent_tid = tt.get_tree_parent(this_tid)
591
tt.adjust_path(self.path, parent_tid, this_tid)
594
def action_take_this(self, tree):
595
self._resolve_with_cleanups(tree, 'OTHER')
597
def action_take_other(self, tree):
598
self._resolve_with_cleanups(tree, 'THIS')
601
# FIXME: TextConflict is about a single file-id, there never is a conflict_path
602
# attribute so we shouldn't inherit from PathConflict but simply from Conflict
604
# TODO: There should be a base revid attribute to better inform the user about
605
# how the conflicts were generated.
606
class TextConflict(PathConflict):
607
"""The merge algorithm could not resolve all differences encountered."""
611
typestring = 'text conflict'
613
format = 'Text conflict in %(path)s'
615
def associated_filenames(self):
616
return [self.path + suffix for suffix in CONFLICT_SUFFIXES]
619
class HandledConflict(Conflict):
620
"""A path problem that has been provisionally resolved.
621
This is intended to be a base class.
624
rformat = "%(class)s(%(action)r, %(path)r, %(file_id)r)"
626
def __init__(self, action, path, file_id=None):
627
Conflict.__init__(self, path, file_id)
631
return Conflict._cmp_list(self) + [self.action]
634
s = Conflict.as_stanza(self)
635
s.add('action', self.action)
638
def associated_filenames(self):
639
# Nothing has been generated here
643
class HandledPathConflict(HandledConflict):
644
"""A provisionally-resolved path problem involving two paths.
645
This is intended to be a base class.
648
rformat = "%(class)s(%(action)r, %(path)r, %(conflict_path)r,"\
649
" %(file_id)r, %(conflict_file_id)r)"
651
def __init__(self, action, path, conflict_path, file_id=None,
652
conflict_file_id=None):
653
HandledConflict.__init__(self, action, path, file_id)
654
self.conflict_path = conflict_path
655
# warn turned off, because the factory blindly transfers the Stanza
656
# values to __init__.
657
self.conflict_file_id = osutils.safe_file_id(conflict_file_id,
661
return HandledConflict._cmp_list(self) + [self.conflict_path,
662
self.conflict_file_id]
665
s = HandledConflict.as_stanza(self)
666
s.add('conflict_path', self.conflict_path)
667
if self.conflict_file_id is not None:
668
s.add('conflict_file_id', self.conflict_file_id.decode('utf8'))
673
class DuplicateID(HandledPathConflict):
674
"""Two files want the same file_id."""
676
typestring = 'duplicate id'
678
format = 'Conflict adding id to %(conflict_path)s. %(action)s %(path)s.'
681
class DuplicateEntry(HandledPathConflict):
682
"""Two directory entries want to have the same name."""
684
typestring = 'duplicate'
686
format = 'Conflict adding file %(conflict_path)s. %(action)s %(path)s.'
688
def action_take_this(self, tree):
689
tree.remove([self.conflict_path], force=True, keep_files=False)
690
tree.rename_one(self.path, self.conflict_path)
692
def action_take_other(self, tree):
693
tree.remove([self.path], force=True, keep_files=False)
696
class ParentLoop(HandledPathConflict):
697
"""An attempt to create an infinitely-looping directory structure.
698
This is rare, but can be produced like so:
707
typestring = 'parent loop'
709
format = 'Conflict moving %(path)s into %(conflict_path)s. %(action)s.'
711
def action_take_this(self, tree):
712
# just acccept bzr proposal
715
def action_take_other(self, tree):
716
# FIXME: We shouldn't have to manipulate so many paths here (and there
717
# is probably a bug or two...)
718
base_path = osutils.basename(self.path)
719
conflict_base_path = osutils.basename(self.conflict_path)
720
tt = transform.TreeTransform(tree)
722
p_tid = tt.trans_id_file_id(self.file_id)
723
parent_tid = tt.get_tree_parent(p_tid)
724
cp_tid = tt.trans_id_file_id(self.conflict_file_id)
725
cparent_tid = tt.get_tree_parent(cp_tid)
726
tt.adjust_path(base_path, cparent_tid, cp_tid)
727
tt.adjust_path(conflict_base_path, parent_tid, p_tid)
733
class UnversionedParent(HandledConflict):
734
"""An attempt to version a file whose parent directory is not versioned.
735
Typically, the result of a merge where one tree unversioned the directory
736
and the other added a versioned file to it.
739
typestring = 'unversioned parent'
741
format = 'Conflict because %(path)s is not versioned, but has versioned'\
742
' children. %(action)s.'
744
# FIXME: We silently do nothing to make tests pass, but most probably the
745
# conflict shouldn't exist (the long story is that the conflict is
746
# generated with another one that can be resolved properly) -- vila 091224
747
def action_take_this(self, tree):
750
def action_take_other(self, tree):
754
class MissingParent(HandledConflict):
755
"""An attempt to add files to a directory that is not present.
756
Typically, the result of a merge where THIS deleted the directory and
757
the OTHER added a file to it.
758
See also: DeletingParent (same situation, THIS and OTHER reversed)
761
typestring = 'missing parent'
763
format = 'Conflict adding files to %(path)s. %(action)s.'
765
def action_take_this(self, tree):
766
tree.remove([self.path], force=True, keep_files=False)
768
def action_take_other(self, tree):
769
# just acccept bzr proposal
773
class DeletingParent(HandledConflict):
774
"""An attempt to add files to a directory that is not present.
775
Typically, the result of a merge where one OTHER deleted the directory and
776
the THIS added a file to it.
779
typestring = 'deleting parent'
781
format = "Conflict: can't delete %(path)s because it is not empty. "\
784
# FIXME: It's a bit strange that the default action is not coherent with
785
# MissingParent from the *user* pov.
787
def action_take_this(self, tree):
788
# just acccept bzr proposal
791
def action_take_other(self, tree):
792
tree.remove([self.path], force=True, keep_files=False)
795
class NonDirectoryParent(HandledConflict):
796
"""An attempt to add files to a directory that is not a directory or
797
an attempt to change the kind of a directory with files.
800
typestring = 'non-directory parent'
802
format = "Conflict: %(path)s is not a directory, but has files in it."\
805
# FIXME: .OTHER should be used instead of .new when the conflict is created
807
def action_take_this(self, tree):
808
# FIXME: we should preserve that path when the conflict is generated !
809
if self.path.endswith('.new'):
810
conflict_path = self.path[:-(len('.new'))]
811
tree.remove([self.path], force=True, keep_files=False)
812
tree.add(conflict_path)
814
raise NotImplementedError(self.action_take_this)
816
def action_take_other(self, tree):
817
# FIXME: we should preserve that path when the conflict is generated !
818
if self.path.endswith('.new'):
819
conflict_path = self.path[:-(len('.new'))]
820
tree.remove([conflict_path], force=True, keep_files=False)
821
tree.rename_one(self.path, conflict_path)
823
raise NotImplementedError(self.action_take_other)
829
def register_types(*conflict_types):
830
"""Register a Conflict subclass for serialization purposes"""
832
for conflict_type in conflict_types:
833
ctype[conflict_type.typestring] = conflict_type
835
register_types(ContentsConflict, TextConflict, PathConflict, DuplicateID,
836
DuplicateEntry, ParentLoop, UnversionedParent, MissingParent,
837
DeletingParent, NonDirectoryParent)