1
# Copyright (C) 2005 Aaron Bentley, Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
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
24
from bzrlib.lazy_import import lazy_import
25
lazy_import(globals(), """
37
from bzrlib.option import Option
40
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
43
class cmd_conflicts(commands.Command):
44
"""List files with conflicts.
46
Merge will do its best to combine the changes in two branches, but there
47
are some kinds of problems only a human can fix. When it encounters those,
48
it will mark a conflict. A conflict means that you need to fix something,
49
before you should commit.
51
Conflicts normally are listed as short, human-readable messages. If --text
52
is supplied, the pathnames of files with text conflicts are listed,
53
instead. (This is useful for editing all files with text conflicts.)
55
Use bzr resolve when you have fixed a problem.
61
help='List paths of files with text conflicts.'),
64
def run(self, text=False):
65
from bzrlib.workingtree import WorkingTree
66
wt = WorkingTree.open_containing(u'.')[0]
67
for conflict in wt.conflicts():
69
if conflict.typestring != 'text conflict':
71
self.outf.write(conflict.path + '\n')
73
self.outf.write(str(conflict) + '\n')
76
class cmd_resolve(commands.Command):
77
"""Mark a conflict as resolved.
79
Merge will do its best to combine the changes in two branches, but there
80
are some kinds of problems only a human can fix. When it encounters those,
81
it will mark a conflict. A conflict means that you need to fix something,
82
before you should commit.
84
Once you have fixed a problem, use "bzr resolve" to automatically mark
85
text conflicts as fixed, resolve FILE to mark a specific conflict as
86
resolved, or "bzr resolve --all" to mark all conflicts as resolved.
88
See also bzr conflicts.
90
aliases = ['resolved']
91
takes_args = ['file*']
93
Option('all', help='Resolve all conflicts in this tree.'),
95
def run(self, file_list=None, all=False):
96
from bzrlib.workingtree import WorkingTree
99
raise errors.BzrCommandError("If --all is specified,"
100
" no FILE may be provided")
101
tree = WorkingTree.open_containing('.')[0]
104
tree, file_list = builtins.tree_files(file_list)
105
if file_list is None:
106
un_resolved, resolved = tree.auto_resolve()
107
if len(un_resolved) > 0:
108
trace.note('%d conflict(s) auto-resolved.', len(resolved))
109
trace.note('Remaining conflicts:')
110
for conflict in un_resolved:
114
trace.note('All conflicts resolved.')
117
resolve(tree, file_list)
120
def resolve(tree, paths=None, ignore_misses=False, recursive=False):
121
tree.lock_tree_write()
123
tree_conflicts = tree.conflicts()
125
new_conflicts = ConflictList()
126
selected_conflicts = tree_conflicts
128
new_conflicts, selected_conflicts = \
129
tree_conflicts.select_conflicts(tree, paths, ignore_misses,
132
tree.set_conflicts(new_conflicts)
133
except errors.UnsupportedOperation:
135
selected_conflicts.remove_files(tree)
140
def restore(filename):
142
Restore a conflicted file to the state it was in before merging.
143
Only text restoration supported at present.
147
osutils.rename(filename + ".THIS", filename)
150
if e.errno != errno.ENOENT:
153
os.unlink(filename + ".BASE")
156
if e.errno != errno.ENOENT:
159
os.unlink(filename + ".OTHER")
162
if e.errno != errno.ENOENT:
165
raise errors.NotConflicted(filename)
168
class ConflictList(object):
169
"""List of conflicts.
171
Typically obtained from WorkingTree.conflicts()
173
Can be instantiated from stanzas or from Conflict subclasses.
176
def __init__(self, conflicts=None):
177
object.__init__(self)
178
if conflicts is None:
181
self.__list = conflicts
184
return len(self.__list) == 0
187
return len(self.__list)
190
return iter(self.__list)
192
def __getitem__(self, key):
193
return self.__list[key]
195
def append(self, conflict):
196
return self.__list.append(conflict)
198
def __eq__(self, other_list):
199
return list(self) == list(other_list)
201
def __ne__(self, other_list):
202
return not (self == other_list)
205
return "ConflictList(%r)" % self.__list
208
def from_stanzas(stanzas):
209
"""Produce a new ConflictList from an iterable of stanzas"""
210
conflicts = ConflictList()
211
for stanza in stanzas:
212
conflicts.append(Conflict.factory(**stanza.as_dict()))
215
def to_stanzas(self):
216
"""Generator of stanzas"""
217
for conflict in self:
218
yield conflict.as_stanza()
220
def to_strings(self):
221
"""Generate strings for the provided conflicts"""
222
for conflict in self:
225
def remove_files(self, tree):
226
"""Remove the THIS, BASE and OTHER files for listed conflicts"""
227
for conflict in self:
228
if not conflict.has_files:
230
for suffix in CONFLICT_SUFFIXES:
232
osutils.delete_any(tree.abspath(conflict.path+suffix))
234
if e.errno != errno.ENOENT:
237
def select_conflicts(self, tree, paths, ignore_misses=False,
239
"""Select the conflicts associated with paths in a tree.
241
File-ids are also used for this.
242
:return: a pair of ConflictLists: (not_selected, selected)
244
path_set = set(paths)
246
selected_paths = set()
247
new_conflicts = ConflictList()
248
selected_conflicts = ConflictList()
250
file_id = tree.path2id(path)
251
if file_id is not None:
254
for conflict in self:
256
for key in ('path', 'conflict_path'):
257
cpath = getattr(conflict, key, None)
260
if cpath in path_set:
262
selected_paths.add(cpath)
264
if osutils.is_inside_any(path_set, cpath):
266
selected_paths.add(cpath)
268
for key in ('file_id', 'conflict_file_id'):
269
cfile_id = getattr(conflict, key, None)
273
cpath = ids[cfile_id]
277
selected_paths.add(cpath)
279
selected_conflicts.append(conflict)
281
new_conflicts.append(conflict)
282
if ignore_misses is not True:
283
for path in [p for p in paths if p not in selected_paths]:
284
if not os.path.exists(tree.abspath(path)):
285
print "%s does not exist" % path
287
print "%s is not conflicted" % path
288
return new_conflicts, selected_conflicts
291
class Conflict(object):
292
"""Base class for all types of conflict"""
296
def __init__(self, path, file_id=None):
298
# warn turned off, because the factory blindly transfers the Stanza
299
# values to __init__ and Stanza is purely a Unicode api.
300
self.file_id = osutils.safe_file_id(file_id, warn=False)
303
s = rio.Stanza(type=self.typestring, path=self.path)
304
if self.file_id is not None:
305
# Stanza requires Unicode apis
306
s.add('file_id', self.file_id.decode('utf8'))
310
return [type(self), self.path, self.file_id]
312
def __cmp__(self, other):
313
if getattr(other, "_cmp_list", None) is None:
315
return cmp(self._cmp_list(), other._cmp_list())
318
return hash((type(self), self.path, self.file_id))
320
def __eq__(self, other):
321
return self.__cmp__(other) == 0
323
def __ne__(self, other):
324
return not self.__eq__(other)
327
return self.format % self.__dict__
330
rdict = dict(self.__dict__)
331
rdict['class'] = self.__class__.__name__
332
return self.rformat % rdict
335
def factory(type, **kwargs):
337
return ctype[type](**kwargs)
340
def sort_key(conflict):
341
if conflict.path is not None:
342
return conflict.path, conflict.typestring
343
elif getattr(conflict, "conflict_path", None) is not None:
344
return conflict.conflict_path, conflict.typestring
346
return None, conflict.typestring
349
class PathConflict(Conflict):
350
"""A conflict was encountered merging file paths"""
352
typestring = 'path conflict'
354
format = 'Path conflict: %(path)s / %(conflict_path)s'
356
rformat = '%(class)s(%(path)r, %(conflict_path)r, %(file_id)r)'
357
def __init__(self, path, conflict_path=None, file_id=None):
358
Conflict.__init__(self, path, file_id)
359
self.conflict_path = conflict_path
362
s = Conflict.as_stanza(self)
363
if self.conflict_path is not None:
364
s.add('conflict_path', self.conflict_path)
368
class ContentsConflict(PathConflict):
369
"""The files are of different types, or not present"""
373
typestring = 'contents conflict'
375
format = 'Contents conflict in %(path)s'
378
class TextConflict(PathConflict):
379
"""The merge algorithm could not resolve all differences encountered."""
383
typestring = 'text conflict'
385
format = 'Text conflict in %(path)s'
388
class HandledConflict(Conflict):
389
"""A path problem that has been provisionally resolved.
390
This is intended to be a base class.
393
rformat = "%(class)s(%(action)r, %(path)r, %(file_id)r)"
395
def __init__(self, action, path, file_id=None):
396
Conflict.__init__(self, path, file_id)
400
return Conflict._cmp_list(self) + [self.action]
403
s = Conflict.as_stanza(self)
404
s.add('action', self.action)
408
class HandledPathConflict(HandledConflict):
409
"""A provisionally-resolved path problem involving two paths.
410
This is intended to be a base class.
413
rformat = "%(class)s(%(action)r, %(path)r, %(conflict_path)r,"\
414
" %(file_id)r, %(conflict_file_id)r)"
416
def __init__(self, action, path, conflict_path, file_id=None,
417
conflict_file_id=None):
418
HandledConflict.__init__(self, action, path, file_id)
419
self.conflict_path = conflict_path
420
# warn turned off, because the factory blindly transfers the Stanza
421
# values to __init__.
422
self.conflict_file_id = osutils.safe_file_id(conflict_file_id,
426
return HandledConflict._cmp_list(self) + [self.conflict_path,
427
self.conflict_file_id]
430
s = HandledConflict.as_stanza(self)
431
s.add('conflict_path', self.conflict_path)
432
if self.conflict_file_id is not None:
433
s.add('conflict_file_id', self.conflict_file_id.decode('utf8'))
438
class DuplicateID(HandledPathConflict):
439
"""Two files want the same file_id."""
441
typestring = 'duplicate id'
443
format = 'Conflict adding id to %(conflict_path)s. %(action)s %(path)s.'
446
class DuplicateEntry(HandledPathConflict):
447
"""Two directory entries want to have the same name."""
449
typestring = 'duplicate'
451
format = 'Conflict adding file %(conflict_path)s. %(action)s %(path)s.'
454
class ParentLoop(HandledPathConflict):
455
"""An attempt to create an infinitely-looping directory structure.
456
This is rare, but can be produced like so:
465
typestring = 'parent loop'
467
format = 'Conflict moving %(conflict_path)s into %(path)s. %(action)s.'
470
class UnversionedParent(HandledConflict):
471
"""An attempt to version an file whose parent directory is not versioned.
472
Typically, the result of a merge where one tree unversioned the directory
473
and the other added a versioned file to it.
476
typestring = 'unversioned parent'
478
format = 'Conflict because %(path)s is not versioned, but has versioned'\
479
' children. %(action)s.'
482
class MissingParent(HandledConflict):
483
"""An attempt to add files to a directory that is not present.
484
Typically, the result of a merge where THIS deleted the directory and
485
the OTHER added a file to it.
486
See also: DeletingParent (same situation, reversed THIS and OTHER)
489
typestring = 'missing parent'
491
format = 'Conflict adding files to %(path)s. %(action)s.'
494
class DeletingParent(HandledConflict):
495
"""An attempt to add files to a directory that is not present.
496
Typically, the result of a merge where one OTHER deleted the directory and
497
the THIS added a file to it.
500
typestring = 'deleting parent'
502
format = "Conflict: can't delete %(path)s because it is not empty. "\
509
def register_types(*conflict_types):
510
"""Register a Conflict subclass for serialization purposes"""
512
for conflict_type in conflict_types:
513
ctype[conflict_type.typestring] = conflict_type
516
register_types(ContentsConflict, TextConflict, PathConflict, DuplicateID,
517
DuplicateEntry, ParentLoop, UnversionedParent, MissingParent,