~bzr-pqm/bzr/bzr.dev

4597.3.48 by Vincent Ladeuil
Start cleaning BRANCH.TODO by pushing changes to either the python modules or the documentation.
1
# Copyright (C) 2005, 2007, 2009 Canonical Ltd
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
2
#
1185.14.3 by Aaron Bentley
Copied conflict lister in
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
7
#
1185.14.3 by Aaron Bentley
Copied conflict lister in
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.
1887.1.1 by Adeodato Simó
Do not separate paragraphs in the copyright statement with blank lines,
12
#
1185.14.3 by Aaron Bentley
Copied conflict lister in
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
4183.7.1 by Sabin Iacob
update FSF mailing address
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
1185.14.3 by Aaron Bentley
Copied conflict lister in
16
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
17
# TODO: 'bzr resolve' should accept a directory name and work from that
1185.16.11 by Martin Pool
todo
18
# point down
19
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
20
import os
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
21
import re
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
22
23
from bzrlib.lazy_import import lazy_import
24
lazy_import(globals(), """
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
25
import errno
26
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
27
from bzrlib import (
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
28
    builtins,
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
29
    commands,
30
    errors,
31
    osutils,
32
    rio,
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
33
    trace,
4597.3.24 by Vincent Ladeuil
Fix imports in bzrlib/conflicts.py.
34
    workingtree,
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
35
    )
36
""")
4597.3.51 by Vincent Ladeuil
Implement conflicts.ResolveActionOption.
37
from bzrlib import (
38
    option,
39
    registry,
40
    )
1534.10.6 by Aaron Bentley
Conflict serialization working for WorkingTree3
41
42
43
CONFLICT_SUFFIXES = ('.THIS', '.BASE', '.OTHER')
44
1185.14.3 by Aaron Bentley
Copied conflict lister in
45
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
46
class cmd_conflicts(commands.Command):
1185.14.3 by Aaron Bentley
Copied conflict lister in
47
    """List files with conflicts.
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
48
49
    Merge will do its best to combine the changes in two branches, but there
50
    are some kinds of problems only a human can fix.  When it encounters those,
51
    it will mark a conflict.  A conflict means that you need to fix something,
52
    before you should commit.
53
1551.9.8 by Aaron Bentley
Add --text parameter to conflicts
54
    Conflicts normally are listed as short, human-readable messages.  If --text
55
    is supplied, the pathnames of files with text conflicts are listed,
56
    instead.  (This is useful for editing all files with text conflicts.)
57
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
58
    Use bzr resolve when you have fixed a problem.
1185.14.3 by Aaron Bentley
Copied conflict lister in
59
    """
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
60
    takes_options = [
4597.3.51 by Vincent Ladeuil
Implement conflicts.ResolveActionOption.
61
            option.Option('text',
62
                          help='List paths of files with text conflicts.'),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
63
        ]
4798.7.1 by Neil Martinsen-Burrell
fix some formatting and see also usage
64
    _see_also = ['resolve']
1551.9.8 by Aaron Bentley
Add --text parameter to conflicts
65
66
    def run(self, text=False):
4597.3.24 by Vincent Ladeuil
Fix imports in bzrlib/conflicts.py.
67
        wt = workingtree.WorkingTree.open_containing(u'.')[0]
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
68
        for conflict in wt.conflicts():
1551.9.8 by Aaron Bentley
Add --text parameter to conflicts
69
            if text:
70
                if conflict.typestring != 'text conflict':
71
                    continue
72
                self.outf.write(conflict.path + '\n')
73
            else:
74
                self.outf.write(str(conflict) + '\n')
1185.14.3 by Aaron Bentley
Copied conflict lister in
75
1652.1.1 by Martin Pool
Fix 'bzr resolve' run from subdirectory
76
4597.3.51 by Vincent Ladeuil
Implement conflicts.ResolveActionOption.
77
resolve_action_registry = registry.Registry()
78
79
80
resolve_action_registry.register(
81
    'done', 'done', 'Marks the conflict as resolved' )
82
resolve_action_registry.register(
83
    'keep-mine', 'keep_mine',
84
    'Resolve the conflict preserving the version in the working tree' )
85
resolve_action_registry.register(
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
86
    'take-their', 'take_their',
4597.3.51 by Vincent Ladeuil
Implement conflicts.ResolveActionOption.
87
    'Resolve the conflict taking the merged version into account' )
88
resolve_action_registry.default_key = 'done'
89
90
class ResolveActionOption(option.RegistryOption):
91
92
    def __init__(self):
93
        super(ResolveActionOption, self).__init__(
94
            'action', 'How to resolve the conflict.',
95
            value_switches=True,
96
            registry=resolve_action_registry)
97
98
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
99
class cmd_resolve(commands.Command):
1185.14.3 by Aaron Bentley
Copied conflict lister in
100
    """Mark a conflict as resolved.
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
101
102
    Merge will do its best to combine the changes in two branches, but there
103
    are some kinds of problems only a human can fix.  When it encounters those,
104
    it will mark a conflict.  A conflict means that you need to fix something,
105
    before you should commit.
106
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
107
    Once you have fixed a problem, use "bzr resolve" to automatically mark
4798.7.1 by Neil Martinsen-Burrell
fix some formatting and see also usage
108
    text conflicts as fixed, "bzr resolve FILE" to mark a specific conflict as
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
109
    resolved, or "bzr resolve --all" to mark all conflicts as resolved.
1185.14.3 by Aaron Bentley
Copied conflict lister in
110
    """
1185.33.24 by Martin Pool
Add alias 'resolved'
111
    aliases = ['resolved']
1185.14.3 by Aaron Bentley
Copied conflict lister in
112
    takes_args = ['file*']
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
113
    takes_options = [
4597.3.51 by Vincent Ladeuil
Implement conflicts.ResolveActionOption.
114
            option.Option('all', help='Resolve all conflicts in this tree.'),
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
115
            ResolveActionOption(),
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
116
            ]
4798.7.1 by Neil Martinsen-Burrell
fix some formatting and see also usage
117
    _see_also = ['conflicts']
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
118
    def run(self, file_list=None, all=False, action=None):
1652.1.3 by Martin Pool
Improved bzr resolve command line handling
119
        if all:
120
            if file_list:
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
121
                raise errors.BzrCommandError("If --all is specified,"
122
                                             " no FILE may be provided")
4597.3.24 by Vincent Ladeuil
Fix imports in bzrlib/conflicts.py.
123
            tree = workingtree.WorkingTree.open_containing('.')[0]
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
124
            if action is None:
125
                action = 'done'
1185.14.3 by Aaron Bentley
Copied conflict lister in
126
        else:
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
127
            tree, file_list = builtins.tree_files(file_list)
1652.1.3 by Martin Pool
Improved bzr resolve command line handling
128
            if file_list is None:
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
129
                if action is None:
4597.3.56 by Vincent Ladeuil
Add a NEWS entry and prepare submission.
130
                    # FIXME: There is a special case here related to the option
131
                    # handling that could be clearer and easier to discover by
132
                    # providing an --auto action (bug #344013 and #383396) and
133
                    # make it mandatory instead of implicit and active only
134
                    # when no file_list is provided -- vila 091229
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
135
                    action = 'auto'
136
            else:
137
                if action is None:
138
                    action = 'done'
139
        if action == 'auto':
140
            if file_list is None:
2120.7.3 by Aaron Bentley
Update resolve command to automatically mark conflicts as resolved
141
                un_resolved, resolved = tree.auto_resolve()
142
                if len(un_resolved) > 0:
143
                    trace.note('%d conflict(s) auto-resolved.', len(resolved))
144
                    trace.note('Remaining conflicts:')
145
                    for conflict in un_resolved:
146
                        trace.note(conflict)
147
                    return 1
148
                else:
149
                    trace.note('All conflicts resolved.')
150
                    return 0
151
            else:
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
152
                # FIXME: This can never occur but the block above needs some
4597.3.56 by Vincent Ladeuil
Add a NEWS entry and prepare submission.
153
                # refactoring to transfer tree.auto_resolve() to
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
154
                # conflict.auto(tree) --vila 091242
155
                pass
156
        else:
157
            resolve(tree, file_list, action=action)
158
159
160
def resolve(tree, paths=None, ignore_misses=False, recursive=False,
161
            action='done'):
3017.2.2 by Aaron Bentley
Add docstring to resolve
162
    """Resolve some or all of the conflicts in a working tree.
163
164
    :param paths: If None, resolve all conflicts.  Otherwise, select only
165
        specified conflicts.
166
    :param recursive: If True, then elements of paths which are directories
167
        have all their children resolved, etc.  When invoked as part of
168
        recursive commands like revert, this should be True.  For commands
169
        or applications wishing finer-grained control, like the resolve
170
        command, this should be False.
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
171
    :param ignore_misses: If False, warnings will be printed if the supplied
172
        paths do not have conflicts.
173
    :param action: How the conflict should be resolved,
3017.2.2 by Aaron Bentley
Add docstring to resolve
174
    """
1997.1.3 by Robert Collins
All WorkingTree methods which write to the tree, but not to the branch
175
    tree.lock_tree_write()
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
176
    try:
1534.10.23 by Aaron Bentley
Removed conflicts_to_stanzas and stanzas_to_conflicts
177
        tree_conflicts = tree.conflicts()
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
178
        if paths is None:
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
179
            new_conflicts = ConflictList()
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
180
            to_process = tree_conflicts
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
181
        else:
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
182
            new_conflicts, to_process = tree_conflicts.select_conflicts(
183
                tree, paths, ignore_misses, recursive)
184
        for conflict in to_process:
185
            try:
186
                conflict._do(action, tree)
187
                conflict.cleanup(tree)
188
            except NotImplementedError:
189
                new_conflicts.append(conflict)
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
190
        try:
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
191
            tree.set_conflicts(new_conflicts)
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
192
        except errors.UnsupportedOperation:
1534.10.10 by Aaron Bentley
Resolve uses the new stuff.
193
            pass
4597.3.26 by Vincent Ladeuil
Tests passing for a minimal --interactive implementation.
194
    finally:
195
        tree.unlock()
196
197
1185.35.1 by Aaron Bentley
Implemented conflicts.restore
198
def restore(filename):
4597.2.6 by Vincent Ladeuil
Cleanup doc string.
199
    """Restore a conflicted file to the state it was in before merging.
200
201
    Only text restoration is supported at present.
1185.35.1 by Aaron Bentley
Implemented conflicts.restore
202
    """
203
    conflicted = False
204
    try:
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
205
        osutils.rename(filename + ".THIS", filename)
1185.35.1 by Aaron Bentley
Implemented conflicts.restore
206
        conflicted = True
207
    except OSError, e:
208
        if e.errno != errno.ENOENT:
209
            raise
210
    try:
211
        os.unlink(filename + ".BASE")
212
        conflicted = True
213
    except OSError, e:
214
        if e.errno != errno.ENOENT:
215
            raise
216
    try:
217
        os.unlink(filename + ".OTHER")
218
        conflicted = True
219
    except OSError, e:
220
        if e.errno != errno.ENOENT:
221
            raise
222
    if not conflicted:
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
223
        raise errors.NotConflicted(filename)
1534.10.4 by Aaron Bentley
Implemented conflict serialization
224
225
1534.10.22 by Aaron Bentley
Got ConflictList implemented
226
class ConflictList(object):
1652.1.1 by Martin Pool
Fix 'bzr resolve' run from subdirectory
227
    """List of conflicts.
228
229
    Typically obtained from WorkingTree.conflicts()
230
1534.10.22 by Aaron Bentley
Got ConflictList implemented
231
    Can be instantiated from stanzas or from Conflict subclasses.
232
    """
233
234
    def __init__(self, conflicts=None):
235
        object.__init__(self)
236
        if conflicts is None:
237
            self.__list = []
238
        else:
239
            self.__list = conflicts
240
1652.1.1 by Martin Pool
Fix 'bzr resolve' run from subdirectory
241
    def is_empty(self):
242
        return len(self.__list) == 0
243
1534.10.22 by Aaron Bentley
Got ConflictList implemented
244
    def __len__(self):
245
        return len(self.__list)
246
247
    def __iter__(self):
248
        return iter(self.__list)
249
250
    def __getitem__(self, key):
251
        return self.__list[key]
252
253
    def append(self, conflict):
254
        return self.__list.append(conflict)
255
256
    def __eq__(self, other_list):
257
        return list(self) == list(other_list)
258
259
    def __ne__(self, other_list):
260
        return not (self == other_list)
261
262
    def __repr__(self):
263
        return "ConflictList(%r)" % self.__list
264
265
    @staticmethod
266
    def from_stanzas(stanzas):
267
        """Produce a new ConflictList from an iterable of stanzas"""
268
        conflicts = ConflictList()
269
        for stanza in stanzas:
270
            conflicts.append(Conflict.factory(**stanza.as_dict()))
271
        return conflicts
272
273
    def to_stanzas(self):
274
        """Generator of stanzas"""
275
        for conflict in self:
276
            yield conflict.as_stanza()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
277
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
278
    def to_strings(self):
279
        """Generate strings for the provided conflicts"""
280
        for conflict in self:
281
            yield str(conflict)
282
283
    def remove_files(self, tree):
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
284
        """Remove the THIS, BASE and OTHER files for listed conflicts"""
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
285
        for conflict in self:
286
            if not conflict.has_files:
287
                continue
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
288
            conflict.cleanup(tree)
1534.10.21 by Aaron Bentley
Moved and renamed conflict functions
289
1551.15.58 by Aaron Bentley
Status honours selected paths for conflicts (#127606)
290
    def select_conflicts(self, tree, paths, ignore_misses=False,
291
                         recurse=False):
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
292
        """Select the conflicts associated with paths in a tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
293
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
294
        File-ids are also used for this.
1551.7.10 by Aaron Bentley
Remerge doesn't clear unrelated conflicts
295
        :return: a pair of ConflictLists: (not_selected, selected)
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
296
        """
297
        path_set = set(paths)
298
        ids = {}
299
        selected_paths = set()
300
        new_conflicts = ConflictList()
301
        selected_conflicts = ConflictList()
302
        for path in paths:
303
            file_id = tree.path2id(path)
304
            if file_id is not None:
305
                ids[file_id] = path
306
307
        for conflict in self:
308
            selected = False
309
            for key in ('path', 'conflict_path'):
310
                cpath = getattr(conflict, key, None)
311
                if cpath is None:
312
                    continue
313
                if cpath in path_set:
314
                    selected = True
315
                    selected_paths.add(cpath)
1551.15.58 by Aaron Bentley
Status honours selected paths for conflicts (#127606)
316
                if recurse:
317
                    if osutils.is_inside_any(path_set, cpath):
318
                        selected = True
319
                        selected_paths.add(cpath)
320
1534.10.25 by Aaron Bentley
Move select_conflicts into ConflictList
321
            for key in ('file_id', 'conflict_file_id'):
322
                cfile_id = getattr(conflict, key, None)
323
                if cfile_id is None:
324
                    continue
325
                try:
326
                    cpath = ids[cfile_id]
327
                except KeyError:
328
                    continue
329
                selected = True
330
                selected_paths.add(cpath)
331
            if selected:
332
                selected_conflicts.append(conflict)
333
            else:
334
                new_conflicts.append(conflict)
335
        if ignore_misses is not True:
336
            for path in [p for p in paths if p not in selected_paths]:
337
                if not os.path.exists(tree.abspath(path)):
338
                    print "%s does not exist" % path
339
                else:
340
                    print "%s is not conflicted" % path
341
        return new_conflicts, selected_conflicts
342
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
343
1534.10.18 by Aaron Bentley
Defined all new Conflict types
344
class Conflict(object):
345
    """Base class for all types of conflict"""
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
346
4597.3.56 by Vincent Ladeuil
Add a NEWS entry and prepare submission.
347
    # FIXME: cleanup should take care of that ? -- vila 091229
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
348
    has_files = False
349
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
350
    def __init__(self, path, file_id=None):
1534.10.18 by Aaron Bentley
Defined all new Conflict types
351
        self.path = path
2309.4.13 by John Arbash Meinel
Conflicts go through Stanza so the need to be aware of utf8 versus unicode file ids.
352
        # warn turned off, because the factory blindly transfers the Stanza
353
        # values to __init__ and Stanza is purely a Unicode api.
354
        self.file_id = osutils.safe_file_id(file_id, warn=False)
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
355
356
    def as_stanza(self):
1996.3.33 by John Arbash Meinel
make bzrlib/conflicts.py lazy
357
        s = rio.Stanza(type=self.typestring, path=self.path)
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
358
        if self.file_id is not None:
2309.4.13 by John Arbash Meinel
Conflicts go through Stanza so the need to be aware of utf8 versus unicode file ids.
359
            # Stanza requires Unicode apis
360
            s.add('file_id', self.file_id.decode('utf8'))
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
361
        return s
362
1534.10.22 by Aaron Bentley
Got ConflictList implemented
363
    def _cmp_list(self):
364
        return [type(self), self.path, self.file_id]
365
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
366
    def __cmp__(self, other):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
367
        if getattr(other, "_cmp_list", None) is None:
368
            return -1
369
        return cmp(self._cmp_list(), other._cmp_list())
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
370
1551.7.11 by Aaron Bentley
Add WorkingTree.add_conflicts
371
    def __hash__(self):
372
        return hash((type(self), self.path, self.file_id))
373
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
374
    def __eq__(self, other):
375
        return self.__cmp__(other) == 0
376
377
    def __ne__(self, other):
378
        return not self.__eq__(other)
1534.10.18 by Aaron Bentley
Defined all new Conflict types
379
1534.10.20 by Aaron Bentley
Got all tests passing
380
    def __str__(self):
381
        return self.format % self.__dict__
382
1534.10.22 by Aaron Bentley
Got ConflictList implemented
383
    def __repr__(self):
384
        rdict = dict(self.__dict__)
385
        rdict['class'] = self.__class__.__name__
386
        return self.rformat % rdict
387
1534.10.18 by Aaron Bentley
Defined all new Conflict types
388
    @staticmethod
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
389
    def factory(type, **kwargs):
1534.10.18 by Aaron Bentley
Defined all new Conflict types
390
        global ctype
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
391
        return ctype[type](**kwargs)
1534.10.18 by Aaron Bentley
Defined all new Conflict types
392
1666.1.4 by Robert Collins
* 'Metadir' is now the default disk format. This improves behaviour in
393
    @staticmethod
394
    def sort_key(conflict):
395
        if conflict.path is not None:
396
            return conflict.path, conflict.typestring
397
        elif getattr(conflict, "conflict_path", None) is not None:
398
            return conflict.conflict_path, conflict.typestring
399
        else:
400
            return None, conflict.typestring
401
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
402
    def _do(self, action, tree):
403
        """Apply the specified action to the conflict.
404
405
        :param action: The method name to call.
406
407
        :param tree: The tree passed as a parameter to the method.
408
        """
409
        meth = getattr(self, action, None)
410
        if meth is None:
411
            raise NotImplementedError(self.__class__.__name__ + '.' + action)
412
        meth(tree)
413
414
    def cleanup(self, tree):
415
        raise NotImplementedError(self.cleanup)
416
417
    def done(self, tree):
4597.3.54 by Vincent Ladeuil
There is no point to define Conflict.done() multiple times.
418
        """Mark the conflict as solved once it has been handled."""
419
        # This method does nothing but simplifies the design of upper levels.
420
        pass
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
421
422
    def keep_mine(self, tree):
423
        raise NotImplementedError(self.keep_mine)
424
425
    def take_their(self, tree):
426
        raise NotImplementedError(self.take_their)
427
1534.10.18 by Aaron Bentley
Defined all new Conflict types
428
429
class PathConflict(Conflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
430
    """A conflict was encountered merging file paths"""
431
1534.10.18 by Aaron Bentley
Defined all new Conflict types
432
    typestring = 'path conflict'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
433
1534.10.20 by Aaron Bentley
Got all tests passing
434
    format = 'Path conflict: %(path)s / %(conflict_path)s'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
435
436
    rformat = '%(class)s(%(path)r, %(conflict_path)r, %(file_id)r)'
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
437
1534.10.20 by Aaron Bentley
Got all tests passing
438
    def __init__(self, path, conflict_path=None, file_id=None):
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
439
        Conflict.__init__(self, path, file_id)
1534.10.18 by Aaron Bentley
Defined all new Conflict types
440
        self.conflict_path = conflict_path
441
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
442
    def as_stanza(self):
443
        s = Conflict.as_stanza(self)
1534.10.20 by Aaron Bentley
Got all tests passing
444
        if self.conflict_path is not None:
445
            s.add('conflict_path', self.conflict_path)
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
446
        return s
447
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
448
    def cleanup(self, tree):
4597.3.55 by Vincent Ladeuil
More cleanup.
449
        # No additional files have been generated here
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
450
        pass
451
4597.3.33 by Vincent Ladeuil
Implement --interactive for PathConflict.
452
    def keep_mine(self, tree):
453
        tree.rename_one(self.conflict_path, self.path)
454
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
455
    def take_their(self, tree):
4597.3.33 by Vincent Ladeuil
Implement --interactive for PathConflict.
456
        # just acccept bzr proposal
457
        pass
458
1534.10.20 by Aaron Bentley
Got all tests passing
459
460
class ContentsConflict(PathConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
461
    """The files are of different types, or not present"""
462
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
463
    has_files = True
464
1534.10.20 by Aaron Bentley
Got all tests passing
465
    typestring = 'contents conflict'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
466
1534.10.20 by Aaron Bentley
Got all tests passing
467
    format = 'Contents conflict in %(path)s'
468
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
469
    def cleanup(self, tree):
470
        for suffix in ('.BASE', '.OTHER'):
471
            try:
472
                osutils.delete_any(tree.abspath(self.path + suffix))
473
            except OSError, e:
474
                if e.errno != errno.ENOENT:
475
                    raise
476
477
    # FIXME: I smell something weird here and it seems we should be able to be
478
    # more coherent with some other conflict ? bzr *did* a choice there but
479
    # neither keep_mine nor take_their reflect that... -- vila 091224
4597.3.28 by Vincent Ladeuil
Implement --interactive for ContentsConflict.
480
    def keep_mine(self, tree):
481
        tree.remove([self.path + '.OTHER'], force=True, keep_files=False)
482
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
483
    def take_their(self, tree):
4597.3.28 by Vincent Ladeuil
Implement --interactive for ContentsConflict.
484
        tree.remove([self.path], force=True, keep_files=False)
485
4597.3.30 by Vincent Ladeuil
Light changes learned while starting to understand multiple conflicts on
486
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
487
4597.3.29 by Vincent Ladeuil
Fix bogus tests.
488
# FIXME: TextConflict is about a single file-id, there never is a conflict_path
489
# attribute so we shouldn't inherit from PathConflict but simply from Conflict
4597.3.48 by Vincent Ladeuil
Start cleaning BRANCH.TODO by pushing changes to either the python modules or the documentation.
490
491
# TODO: There should be a base revid attribute to better inform the user about
492
# how the conflicts were generated.
1534.10.20 by Aaron Bentley
Got all tests passing
493
class TextConflict(PathConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
494
    """The merge algorithm could not resolve all differences encountered."""
495
1534.10.24 by Aaron Bentley
Eliminated conflicts_to_strings, made remove_files a ConflictList member
496
    has_files = True
497
1534.10.20 by Aaron Bentley
Got all tests passing
498
    typestring = 'text conflict'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
499
1534.10.20 by Aaron Bentley
Got all tests passing
500
    format = 'Text conflict in %(path)s'
501
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
502
    def cleanup(self, tree):
503
        for suffix in CONFLICT_SUFFIXES:
504
            try:
505
                osutils.delete_any(tree.abspath(self.path+suffix))
506
            except OSError, e:
507
                if e.errno != errno.ENOENT:
508
                    raise
4597.3.33 by Vincent Ladeuil
Implement --interactive for PathConflict.
509
1534.10.20 by Aaron Bentley
Got all tests passing
510
1534.10.18 by Aaron Bentley
Defined all new Conflict types
511
class HandledConflict(Conflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
512
    """A path problem that has been provisionally resolved.
513
    This is intended to be a base class.
514
    """
515
516
    rformat = "%(class)s(%(action)r, %(path)r, %(file_id)r)"
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
517
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
518
    def __init__(self, action, path, file_id=None):
519
        Conflict.__init__(self, path, file_id)
1534.10.18 by Aaron Bentley
Defined all new Conflict types
520
        self.action = action
521
1534.10.22 by Aaron Bentley
Got ConflictList implemented
522
    def _cmp_list(self):
523
        return Conflict._cmp_list(self) + [self.action]
524
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
525
    def as_stanza(self):
526
        s = Conflict.as_stanza(self)
527
        s.add('action', self.action)
528
        return s
529
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
530
    def cleanup(self, tree):
531
        """Nothing to cleanup."""
532
        pass
533
1534.10.20 by Aaron Bentley
Got all tests passing
534
1534.10.18 by Aaron Bentley
Defined all new Conflict types
535
class HandledPathConflict(HandledConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
536
    """A provisionally-resolved path problem involving two paths.
537
    This is intended to be a base class.
538
    """
539
540
    rformat = "%(class)s(%(action)r, %(path)r, %(conflict_path)r,"\
541
        " %(file_id)r, %(conflict_file_id)r)"
542
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
543
    def __init__(self, action, path, conflict_path, file_id=None,
1534.10.18 by Aaron Bentley
Defined all new Conflict types
544
                 conflict_file_id=None):
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
545
        HandledConflict.__init__(self, action, path, file_id)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
546
        self.conflict_path = conflict_path
2309.4.13 by John Arbash Meinel
Conflicts go through Stanza so the need to be aware of utf8 versus unicode file ids.
547
        # warn turned off, because the factory blindly transfers the Stanza
548
        # values to __init__.
549
        self.conflict_file_id = osutils.safe_file_id(conflict_file_id,
550
                                                     warn=False)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
551
1534.10.22 by Aaron Bentley
Got ConflictList implemented
552
    def _cmp_list(self):
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
553
        return HandledConflict._cmp_list(self) + [self.conflict_path,
1534.10.22 by Aaron Bentley
Got ConflictList implemented
554
                                                  self.conflict_file_id]
555
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
556
    def as_stanza(self):
557
        s = HandledConflict.as_stanza(self)
558
        s.add('conflict_path', self.conflict_path)
559
        if self.conflict_file_id is not None:
2309.4.13 by John Arbash Meinel
Conflicts go through Stanza so the need to be aware of utf8 versus unicode file ids.
560
            s.add('conflict_file_id', self.conflict_file_id.decode('utf8'))
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
561
1534.10.19 by Aaron Bentley
Stanza conversion, cooking
562
        return s
1534.10.20 by Aaron Bentley
Got all tests passing
563
564
1534.10.18 by Aaron Bentley
Defined all new Conflict types
565
class DuplicateID(HandledPathConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
566
    """Two files want the same file_id."""
567
1534.10.18 by Aaron Bentley
Defined all new Conflict types
568
    typestring = 'duplicate id'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
569
1534.10.20 by Aaron Bentley
Got all tests passing
570
    format = 'Conflict adding id to %(conflict_path)s.  %(action)s %(path)s.'
571
1534.10.18 by Aaron Bentley
Defined all new Conflict types
572
573
class DuplicateEntry(HandledPathConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
574
    """Two directory entries want to have the same name."""
575
1534.10.18 by Aaron Bentley
Defined all new Conflict types
576
    typestring = 'duplicate'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
577
1534.10.20 by Aaron Bentley
Got all tests passing
578
    format = 'Conflict adding file %(conflict_path)s.  %(action)s %(path)s.'
579
4597.3.27 by Vincent Ladeuil
(keep_mine, take_theirs) sounds clearer than (keep_this, keep_other).
580
    def keep_mine(self, tree):
4597.3.26 by Vincent Ladeuil
Tests passing for a minimal --interactive implementation.
581
        tree.remove([self.conflict_path], force=True, keep_files=False)
582
        tree.rename_one(self.path, self.conflict_path)
583
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
584
    def take_their(self, tree):
4597.3.26 by Vincent Ladeuil
Tests passing for a minimal --interactive implementation.
585
        tree.remove([self.path], force=True, keep_files=False)
586
1534.10.18 by Aaron Bentley
Defined all new Conflict types
587
588
class ParentLoop(HandledPathConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
589
    """An attempt to create an infinitely-looping directory structure.
590
    This is rare, but can be produced like so:
591
592
    tree A:
4597.3.50 by Vincent Ladeuil
Integrate most of BRANCH.TOTO into bzrlib/help_topics/en/conflicts.txt, fix a typo in a test.
593
      mv foo bar
1534.10.22 by Aaron Bentley
Got ConflictList implemented
594
    tree B:
4597.3.50 by Vincent Ladeuil
Integrate most of BRANCH.TOTO into bzrlib/help_topics/en/conflicts.txt, fix a typo in a test.
595
      mv bar foo
1534.10.22 by Aaron Bentley
Got ConflictList implemented
596
    merge A and B
597
    """
598
1534.10.18 by Aaron Bentley
Defined all new Conflict types
599
    typestring = 'parent loop'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
600
1534.10.20 by Aaron Bentley
Got all tests passing
601
    format = 'Conflict moving %(conflict_path)s into %(path)s.  %(action)s.'
602
4597.3.34 by Vincent Ladeuil
Implement --interactive for ParentLoop.
603
    def keep_mine(self, tree):
604
        # just acccept bzr proposal
605
        pass
606
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
607
    def take_their(self, tree):
4597.3.50 by Vincent Ladeuil
Integrate most of BRANCH.TOTO into bzrlib/help_topics/en/conflicts.txt, fix a typo in a test.
608
        # FIXME: We shouldn't have to manipulate so many paths here (and there
609
        # is probably a bug or two...)
4597.3.34 by Vincent Ladeuil
Implement --interactive for ParentLoop.
610
        conflict_base_path = osutils.basename(self.conflict_path)
611
        base_path = osutils.basename(self.path)
612
        tree.rename_one(self.conflict_path, conflict_base_path)
613
        tree.rename_one(self.path,
614
                        osutils.joinpath([conflict_base_path, base_path]))
615
1534.10.18 by Aaron Bentley
Defined all new Conflict types
616
617
class UnversionedParent(HandledConflict):
4597.2.1 by Vincent Ladeuil
Fix some typos.
618
    """An attempt to version a file whose parent directory is not versioned.
1534.10.22 by Aaron Bentley
Got ConflictList implemented
619
    Typically, the result of a merge where one tree unversioned the directory
620
    and the other added a versioned file to it.
621
    """
622
1534.10.18 by Aaron Bentley
Defined all new Conflict types
623
    typestring = 'unversioned parent'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
624
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
625
    format = 'Conflict because %(path)s is not versioned, but has versioned'\
626
             ' children.  %(action)s.'
1534.10.20 by Aaron Bentley
Got all tests passing
627
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
628
    # FIXME: We silently do nothing to make tests pass, but most probably the
629
    # conflict shouldn't exist (the long story is that the conflict is
630
    # generated with another one that can be resolved properly) -- vila 091224
631
    def keep_mine(self, tree):
632
        pass
633
634
    def take_their(self, tree):
635
        pass
636
1534.10.18 by Aaron Bentley
Defined all new Conflict types
637
638
class MissingParent(HandledConflict):
1534.10.22 by Aaron Bentley
Got ConflictList implemented
639
    """An attempt to add files to a directory that is not present.
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
640
    Typically, the result of a merge where THIS deleted the directory and
641
    the OTHER added a file to it.
4597.3.50 by Vincent Ladeuil
Integrate most of BRANCH.TOTO into bzrlib/help_topics/en/conflicts.txt, fix a typo in a test.
642
    See also: DeletingParent (same situation, THIS and OTHER reversed)
1534.10.22 by Aaron Bentley
Got ConflictList implemented
643
    """
644
1534.10.18 by Aaron Bentley
Defined all new Conflict types
645
    typestring = 'missing parent'
1534.10.22 by Aaron Bentley
Got ConflictList implemented
646
1534.10.20 by Aaron Bentley
Got all tests passing
647
    format = 'Conflict adding files to %(path)s.  %(action)s.'
648
4597.3.31 by Vincent Ladeuil
Implement --interactive for MissingParent.
649
    def keep_mine(self, tree):
650
        tree.remove([self.path], force=True, keep_files=False)
651
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
652
    def take_their(self, tree):
4597.3.31 by Vincent Ladeuil
Implement --interactive for MissingParent.
653
        # just acccept bzr proposal
654
        pass
655
1534.10.20 by Aaron Bentley
Got all tests passing
656
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
657
class DeletingParent(HandledConflict):
658
    """An attempt to add files to a directory that is not present.
659
    Typically, the result of a merge where one OTHER deleted the directory and
660
    the THIS added a file to it.
661
    """
662
663
    typestring = 'deleting parent'
664
1551.8.23 by Aaron Bentley
Tweaked conflict message to be more understandable
665
    format = "Conflict: can't delete %(path)s because it is not empty.  "\
666
             "%(action)s."
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
667
4597.3.32 by Vincent Ladeuil
Implement --interactive for DeletingParent noting the inconsistency.
668
    # FIXME: It's a bit strange that the default action is not coherent with
669
    # MissingParent from the *user* pov.
670
671
    def keep_mine(self, tree):
672
        # just acccept bzr proposal
673
        pass
674
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
675
    def take_their(self, tree):
4597.3.32 by Vincent Ladeuil
Implement --interactive for DeletingParent noting the inconsistency.
676
        tree.remove([self.path], force=True, keep_files=False)
677
1534.10.18 by Aaron Bentley
Defined all new Conflict types
678
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
679
class NonDirectoryParent(HandledConflict):
4597.3.35 by Vincent Ladeuil
Implement --interactive for NonDirectoryParent, sort of.
680
    """An attempt to add files to a directory that is not a directory or
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
681
    an attempt to change the kind of a directory with files.
682
    """
683
684
    typestring = 'non-directory parent'
685
686
    format = "Conflict: %(path)s is not a directory, but has files in it."\
687
             "  %(action)s."
688
4597.3.35 by Vincent Ladeuil
Implement --interactive for NonDirectoryParent, sort of.
689
    def keep_mine(self, tree):
4597.3.55 by Vincent Ladeuil
More cleanup.
690
        # FIXME: we should preserve that path when the conflict is generated !
4597.3.35 by Vincent Ladeuil
Implement --interactive for NonDirectoryParent, sort of.
691
        if self.path.endswith('.new'):
692
            conflict_path = self.path[:-(len('.new'))]
693
            tree.remove([self.path], force=True, keep_files=False)
694
            tree.add(conflict_path)
695
        else:
696
            raise NotImplementedError(self.keep_mine)
697
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
698
    def take_their(self, tree):
4597.3.55 by Vincent Ladeuil
More cleanup.
699
        # FIXME: we should preserve that path when the conflict is generated !
4597.3.35 by Vincent Ladeuil
Implement --interactive for NonDirectoryParent, sort of.
700
        if self.path.endswith('.new'):
701
            conflict_path = self.path[:-(len('.new'))]
702
            tree.remove([conflict_path], force=True, keep_files=False)
703
            tree.rename_one(self.path, conflict_path)
704
        else:
4597.3.52 by Vincent Ladeuil
Replace --interactive by --action.
705
            raise NotImplementedError(self.take_their)
4597.3.35 by Vincent Ladeuil
Implement --interactive for NonDirectoryParent, sort of.
706
707
1534.10.18 by Aaron Bentley
Defined all new Conflict types
708
ctype = {}
1534.10.20 by Aaron Bentley
Got all tests passing
709
710
1534.10.18 by Aaron Bentley
Defined all new Conflict types
711
def register_types(*conflict_types):
712
    """Register a Conflict subclass for serialization purposes"""
713
    global ctype
714
    for conflict_type in conflict_types:
715
        ctype[conflict_type.typestring] = conflict_type
716
717
register_types(ContentsConflict, TextConflict, PathConflict, DuplicateID,
1551.8.22 by Aaron Bentley
Improve message when OTHER deletes an in-use tree
718
               DuplicateEntry, ParentLoop, UnversionedParent, MissingParent,
3144.4.2 by Aaron Bentley
Handle non-directory parent conflicts (abentley, #177390)
719
               DeletingParent, NonDirectoryParent)