1
# Copyright (C) 2005, 2007 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
"""Resolve some or all of the conflicts in a working tree.
123
:param paths: If None, resolve all conflicts. Otherwise, select only
125
:param recursive: If True, then elements of paths which are directories
126
have all their children resolved, etc. When invoked as part of
127
recursive commands like revert, this should be True. For commands
128
or applications wishing finer-grained control, like the resolve
129
command, this should be False.
130
:ignore_misses: If False, warnings will be printed if the supplied paths
131
do not have conflicts.
133
tree.lock_tree_write()
135
tree_conflicts = tree.conflicts()
137
new_conflicts = ConflictList()
138
selected_conflicts = tree_conflicts
140
new_conflicts, selected_conflicts = \
141
tree_conflicts.select_conflicts(tree, paths, ignore_misses,
144
tree.set_conflicts(new_conflicts)
145
except errors.UnsupportedOperation:
147
selected_conflicts.remove_files(tree)
152
def restore(filename):
154
Restore a conflicted file to the state it was in before merging.
155
Only text restoration supported at present.
159
osutils.rename(filename + ".THIS", filename)
162
if e.errno != errno.ENOENT:
165
os.unlink(filename + ".BASE")
168
if e.errno != errno.ENOENT:
171
os.unlink(filename + ".OTHER")
174
if e.errno != errno.ENOENT:
177
raise errors.NotConflicted(filename)
180
class ConflictList(object):
181
"""List of conflicts.
183
Typically obtained from WorkingTree.conflicts()
185
Can be instantiated from stanzas or from Conflict subclasses.
188
def __init__(self, conflicts=None):
189
object.__init__(self)
190
if conflicts is None:
193
self.__list = conflicts
196
return len(self.__list) == 0
199
return len(self.__list)
202
return iter(self.__list)
204
def __getitem__(self, key):
205
return self.__list[key]
207
def append(self, conflict):
208
return self.__list.append(conflict)
210
def __eq__(self, other_list):
211
return list(self) == list(other_list)
213
def __ne__(self, other_list):
214
return not (self == other_list)
217
return "ConflictList(%r)" % self.__list
220
def from_stanzas(stanzas):
221
"""Produce a new ConflictList from an iterable of stanzas"""
222
conflicts = ConflictList()
223
for stanza in stanzas:
224
conflicts.append(Conflict.factory(**stanza.as_dict()))
227
def to_stanzas(self):
228
"""Generator of stanzas"""
229
for conflict in self:
230
yield conflict.as_stanza()
232
def to_strings(self):
233
"""Generate strings for the provided conflicts"""
234
for conflict in self:
237
def remove_files(self, tree):
238
"""Remove the THIS, BASE and OTHER files for listed conflicts"""
239
for conflict in self:
240
if not conflict.has_files:
242
for suffix in CONFLICT_SUFFIXES:
244
osutils.delete_any(tree.abspath(conflict.path+suffix))
246
if e.errno != errno.ENOENT:
249
def select_conflicts(self, tree, paths, ignore_misses=False,
251
"""Select the conflicts associated with paths in a tree.
253
File-ids are also used for this.
254
:return: a pair of ConflictLists: (not_selected, selected)
256
path_set = set(paths)
258
selected_paths = set()
259
new_conflicts = ConflictList()
260
selected_conflicts = ConflictList()
262
file_id = tree.path2id(path)
263
if file_id is not None:
266
for conflict in self:
268
for key in ('path', 'conflict_path'):
269
cpath = getattr(conflict, key, None)
272
if cpath in path_set:
274
selected_paths.add(cpath)
276
if osutils.is_inside_any(path_set, cpath):
278
selected_paths.add(cpath)
280
for key in ('file_id', 'conflict_file_id'):
281
cfile_id = getattr(conflict, key, None)
285
cpath = ids[cfile_id]
289
selected_paths.add(cpath)
291
selected_conflicts.append(conflict)
293
new_conflicts.append(conflict)
294
if ignore_misses is not True:
295
for path in [p for p in paths if p not in selected_paths]:
296
if not os.path.exists(tree.abspath(path)):
297
print "%s does not exist" % path
299
print "%s is not conflicted" % path
300
return new_conflicts, selected_conflicts
303
class Conflict(object):
304
"""Base class for all types of conflict"""
308
def __init__(self, path, file_id=None):
310
# warn turned off, because the factory blindly transfers the Stanza
311
# values to __init__ and Stanza is purely a Unicode api.
312
self.file_id = osutils.safe_file_id(file_id, warn=False)
315
s = rio.Stanza(type=self.typestring, path=self.path)
316
if self.file_id is not None:
317
# Stanza requires Unicode apis
318
s.add('file_id', self.file_id.decode('utf8'))
322
return [type(self), self.path, self.file_id]
324
def __cmp__(self, other):
325
if getattr(other, "_cmp_list", None) is None:
327
return cmp(self._cmp_list(), other._cmp_list())
330
return hash((type(self), self.path, self.file_id))
332
def __eq__(self, other):
333
return self.__cmp__(other) == 0
335
def __ne__(self, other):
336
return not self.__eq__(other)
339
return self.format % self.__dict__
342
rdict = dict(self.__dict__)
343
rdict['class'] = self.__class__.__name__
344
return self.rformat % rdict
347
def factory(type, **kwargs):
349
return ctype[type](**kwargs)
352
def sort_key(conflict):
353
if conflict.path is not None:
354
return conflict.path, conflict.typestring
355
elif getattr(conflict, "conflict_path", None) is not None:
356
return conflict.conflict_path, conflict.typestring
358
return None, conflict.typestring
361
class PathConflict(Conflict):
362
"""A conflict was encountered merging file paths"""
364
typestring = 'path conflict'
366
format = 'Path conflict: %(path)s / %(conflict_path)s'
368
rformat = '%(class)s(%(path)r, %(conflict_path)r, %(file_id)r)'
369
def __init__(self, path, conflict_path=None, file_id=None):
370
Conflict.__init__(self, path, file_id)
371
self.conflict_path = conflict_path
374
s = Conflict.as_stanza(self)
375
if self.conflict_path is not None:
376
s.add('conflict_path', self.conflict_path)
380
class ContentsConflict(PathConflict):
381
"""The files are of different types, or not present"""
385
typestring = 'contents conflict'
387
format = 'Contents conflict in %(path)s'
390
class TextConflict(PathConflict):
391
"""The merge algorithm could not resolve all differences encountered."""
395
typestring = 'text conflict'
397
format = 'Text conflict in %(path)s'
400
class HandledConflict(Conflict):
401
"""A path problem that has been provisionally resolved.
402
This is intended to be a base class.
405
rformat = "%(class)s(%(action)r, %(path)r, %(file_id)r)"
407
def __init__(self, action, path, file_id=None):
408
Conflict.__init__(self, path, file_id)
412
return Conflict._cmp_list(self) + [self.action]
415
s = Conflict.as_stanza(self)
416
s.add('action', self.action)
420
class HandledPathConflict(HandledConflict):
421
"""A provisionally-resolved path problem involving two paths.
422
This is intended to be a base class.
425
rformat = "%(class)s(%(action)r, %(path)r, %(conflict_path)r,"\
426
" %(file_id)r, %(conflict_file_id)r)"
428
def __init__(self, action, path, conflict_path, file_id=None,
429
conflict_file_id=None):
430
HandledConflict.__init__(self, action, path, file_id)
431
self.conflict_path = conflict_path
432
# warn turned off, because the factory blindly transfers the Stanza
433
# values to __init__.
434
self.conflict_file_id = osutils.safe_file_id(conflict_file_id,
438
return HandledConflict._cmp_list(self) + [self.conflict_path,
439
self.conflict_file_id]
442
s = HandledConflict.as_stanza(self)
443
s.add('conflict_path', self.conflict_path)
444
if self.conflict_file_id is not None:
445
s.add('conflict_file_id', self.conflict_file_id.decode('utf8'))
450
class DuplicateID(HandledPathConflict):
451
"""Two files want the same file_id."""
453
typestring = 'duplicate id'
455
format = 'Conflict adding id to %(conflict_path)s. %(action)s %(path)s.'
458
class DuplicateEntry(HandledPathConflict):
459
"""Two directory entries want to have the same name."""
461
typestring = 'duplicate'
463
format = 'Conflict adding file %(conflict_path)s. %(action)s %(path)s.'
466
class ParentLoop(HandledPathConflict):
467
"""An attempt to create an infinitely-looping directory structure.
468
This is rare, but can be produced like so:
477
typestring = 'parent loop'
479
format = 'Conflict moving %(conflict_path)s into %(path)s. %(action)s.'
482
class UnversionedParent(HandledConflict):
483
"""An attempt to version an file whose parent directory is not versioned.
484
Typically, the result of a merge where one tree unversioned the directory
485
and the other added a versioned file to it.
488
typestring = 'unversioned parent'
490
format = 'Conflict because %(path)s is not versioned, but has versioned'\
491
' children. %(action)s.'
494
class MissingParent(HandledConflict):
495
"""An attempt to add files to a directory that is not present.
496
Typically, the result of a merge where THIS deleted the directory and
497
the OTHER added a file to it.
498
See also: DeletingParent (same situation, reversed THIS and OTHER)
501
typestring = 'missing parent'
503
format = 'Conflict adding files to %(path)s. %(action)s.'
506
class DeletingParent(HandledConflict):
507
"""An attempt to add files to a directory that is not present.
508
Typically, the result of a merge where one OTHER deleted the directory and
509
the THIS added a file to it.
512
typestring = 'deleting parent'
514
format = "Conflict: can't delete %(path)s because it is not empty. "\
518
class NonDirectoryParent(HandledConflict):
519
"""An attempt to add files to a directory that is not a director or
520
an attempt to change the kind of a directory with files.
523
typestring = 'non-directory parent'
525
format = "Conflict: %(path)s is not a directory, but has files in it."\
531
def register_types(*conflict_types):
532
"""Register a Conflict subclass for serialization purposes"""
534
for conflict_type in conflict_types:
535
ctype[conflict_type.typestring] = conflict_type
538
register_types(ContentsConflict, TextConflict, PathConflict, DuplicateID,
539
DuplicateEntry, ParentLoop, UnversionedParent, MissingParent,
540
DeletingParent, NonDirectoryParent)