/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/workingtree.py

  • Committer: Jelmer Vernooij
  • Date: 2019-08-12 20:24:50 UTC
  • mto: (7290.1.35 work)
  • mto: This revision was merged to the branch mainline in revision 7405.
  • Revision ID: jelmer@jelmer.uk-20190812202450-vdpamxay6sebo93w
Fix path to brz.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""WorkingTree object and friends.
 
18
 
 
19
A WorkingTree represents the editable working copy of a branch.
 
20
Operations which represent the WorkingTree are also done here,
 
21
such as renaming or adding files.
 
22
 
 
23
At the moment every WorkingTree has its own branch.  Remote
 
24
WorkingTrees aren't supported.
 
25
 
 
26
To get a WorkingTree, call controldir.open_workingtree() or
 
27
WorkingTree.open(dir).
 
28
"""
 
29
 
 
30
from __future__ import absolute_import
 
31
 
 
32
import errno
 
33
import os
 
34
import sys
 
35
 
 
36
import breezy
 
37
 
 
38
from .lazy_import import lazy_import
 
39
lazy_import(globals(), """
 
40
import shutil
 
41
import stat
 
42
 
 
43
from breezy import (
 
44
    conflicts as _mod_conflicts,
 
45
    controldir,
 
46
    errors,
 
47
    filters as _mod_filters,
 
48
    merge,
 
49
    revision as _mod_revision,
 
50
    transform,
 
51
    transport,
 
52
    views,
 
53
    )
 
54
from breezy.bzr import (
 
55
    generate_ids,
 
56
    )
 
57
""")
 
58
 
 
59
from . import (
 
60
    osutils,
 
61
    )
 
62
from .i18n import gettext
 
63
from . import mutabletree
 
64
from .symbol_versioning import deprecated_method, deprecated_in
 
65
from .trace import mutter, note
 
66
 
 
67
 
 
68
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
 
69
 
 
70
 
 
71
class SettingFileIdUnsupported(errors.BzrError):
 
72
 
 
73
    _fmt = "This format does not support setting file ids."
 
74
 
 
75
 
 
76
class ShelvingUnsupported(errors.BzrError):
 
77
 
 
78
    _fmt = "This format does not support shelving changes."
 
79
 
 
80
 
 
81
class WorkingTree(mutabletree.MutableTree, controldir.ControlComponent):
 
82
    """Working copy tree.
 
83
 
 
84
    :ivar basedir: The root of the tree on disk. This is a unicode path object
 
85
        (as opposed to a URL).
 
86
    """
 
87
 
 
88
    # override this to set the strategy for storing views
 
89
    def _make_views(self):
 
90
        return views.DisabledViews(self)
 
91
 
 
92
    def __init__(self, basedir='.',
 
93
                 branch=None,
 
94
                 _internal=False,
 
95
                 _transport=None,
 
96
                 _format=None,
 
97
                 _controldir=None):
 
98
        """Construct a WorkingTree instance. This is not a public API.
 
99
 
 
100
        :param branch: A branch to override probing for the branch.
 
101
        """
 
102
        self._format = _format
 
103
        self.controldir = _controldir
 
104
        if not _internal:
 
105
            raise errors.BzrError("Please use controldir.open_workingtree or "
 
106
                                  "WorkingTree.open() to obtain a WorkingTree.")
 
107
        basedir = osutils.safe_unicode(basedir)
 
108
        mutter("opening working tree %r", basedir)
 
109
        if branch is not None:
 
110
            self._branch = branch
 
111
        else:
 
112
            self._branch = self.controldir.open_branch()
 
113
        self.basedir = osutils.realpath(basedir)
 
114
        self._transport = _transport
 
115
        self._rules_searcher = None
 
116
        self.views = self._make_views()
 
117
 
 
118
    @property
 
119
    def user_transport(self):
 
120
        return self.controldir.user_transport
 
121
 
 
122
    @property
 
123
    def control_transport(self):
 
124
        return self._transport
 
125
 
 
126
    def is_control_filename(self, filename):
 
127
        """True if filename is the name of a control file in this tree.
 
128
 
 
129
        :param filename: A filename within the tree. This is a relative path
 
130
            from the root of this tree.
 
131
 
 
132
        This is true IF and ONLY IF the filename is part of the meta data
 
133
        that bzr controls in this tree. I.E. a random .bzr directory placed
 
134
        on disk will not be a control file for this tree.
 
135
        """
 
136
        return self.controldir.is_control_filename(filename)
 
137
 
 
138
    branch = property(
 
139
        fget=lambda self: self._branch,
 
140
        doc="""The branch this WorkingTree is connected to.
 
141
 
 
142
            This cannot be set - it is reflective of the actual disk structure
 
143
            the working tree has been constructed from.
 
144
            """)
 
145
 
 
146
    def has_versioned_directories(self):
 
147
        """See `Tree.has_versioned_directories`."""
 
148
        return self._format.supports_versioned_directories
 
149
 
 
150
    def supports_merge_modified(self):
 
151
        """Indicate whether this workingtree supports storing merge_modified.
 
152
        """
 
153
        return self._format.supports_merge_modified
 
154
 
 
155
    def _supports_executable(self):
 
156
        if sys.platform == 'win32':
 
157
            return False
 
158
        # FIXME: Ideally this should check the file system
 
159
        return True
 
160
 
 
161
    def break_lock(self):
 
162
        """Break a lock if one is present from another instance.
 
163
 
 
164
        Uses the ui factory to ask for confirmation if the lock may be from
 
165
        an active process.
 
166
 
 
167
        This will probe the repository for its lock as well.
 
168
        """
 
169
        raise NotImplementedError(self.break_lock)
 
170
 
 
171
    def requires_rich_root(self):
 
172
        return self._format.requires_rich_root
 
173
 
 
174
    def supports_tree_reference(self):
 
175
        return False
 
176
 
 
177
    def supports_content_filtering(self):
 
178
        return self._format.supports_content_filtering()
 
179
 
 
180
    def supports_views(self):
 
181
        return self.views.supports_views()
 
182
 
 
183
    def supports_setting_file_ids(self):
 
184
        return self._format.supports_setting_file_ids
 
185
 
 
186
    def get_config_stack(self):
 
187
        """Retrieve the config stack for this tree.
 
188
 
 
189
        :return: A ``breezy.config.Stack``
 
190
        """
 
191
        # For the moment, just provide the branch config stack.
 
192
        return self.branch.get_config_stack()
 
193
 
 
194
    @staticmethod
 
195
    def open(path=None, _unsupported=False):
 
196
        """Open an existing working tree at path.
 
197
 
 
198
        """
 
199
        if path is None:
 
200
            path = osutils.getcwd()
 
201
        control = controldir.ControlDir.open(path, _unsupported=_unsupported)
 
202
        return control.open_workingtree(unsupported=_unsupported)
 
203
 
 
204
    @staticmethod
 
205
    def open_containing(path=None):
 
206
        """Open an existing working tree which has its root about path.
 
207
 
 
208
        This probes for a working tree at path and searches upwards from there.
 
209
 
 
210
        Basically we keep looking up until we find the control directory or
 
211
        run into /.  If there isn't one, raises NotBranchError.
 
212
        TODO: give this a new exception.
 
213
        If there is one, it is returned, along with the unused portion of path.
 
214
 
 
215
        :return: The WorkingTree that contains 'path', and the rest of path
 
216
        """
 
217
        if path is None:
 
218
            path = osutils.getcwd()
 
219
        control, relpath = controldir.ControlDir.open_containing(path)
 
220
        return control.open_workingtree(), relpath
 
221
 
 
222
    @staticmethod
 
223
    def open_containing_paths(file_list, default_directory=None,
 
224
                              canonicalize=True, apply_view=True):
 
225
        """Open the WorkingTree that contains a set of paths.
 
226
 
 
227
        Fail if the paths given are not all in a single tree.
 
228
 
 
229
        This is used for the many command-line interfaces that take a list of
 
230
        any number of files and that require they all be in the same tree.
 
231
        """
 
232
        if default_directory is None:
 
233
            default_directory = u'.'
 
234
        # recommended replacement for builtins.internal_tree_files
 
235
        if file_list is None or len(file_list) == 0:
 
236
            tree = WorkingTree.open_containing(default_directory)[0]
 
237
            # XXX: doesn't really belong here, and seems to have the strange
 
238
            # side effect of making it return a bunch of files, not the whole
 
239
            # tree -- mbp 20100716
 
240
            if tree.supports_views() and apply_view:
 
241
                view_files = tree.views.lookup_view()
 
242
                if view_files:
 
243
                    file_list = view_files
 
244
                    view_str = views.view_display_str(view_files)
 
245
                    note(gettext("Ignoring files outside view. View is %s") % view_str)
 
246
            return tree, file_list
 
247
        if default_directory == u'.':
 
248
            seed = file_list[0]
 
249
        else:
 
250
            seed = default_directory
 
251
            file_list = [osutils.pathjoin(default_directory, f)
 
252
                         for f in file_list]
 
253
        tree = WorkingTree.open_containing(seed)[0]
 
254
        return tree, tree.safe_relpath_files(file_list, canonicalize,
 
255
                                             apply_view=apply_view)
 
256
 
 
257
    def safe_relpath_files(self, file_list, canonicalize=True, apply_view=True):
 
258
        """Convert file_list into a list of relpaths in tree.
 
259
 
 
260
        :param self: A tree to operate on.
 
261
        :param file_list: A list of user provided paths or None.
 
262
        :param apply_view: if True and a view is set, apply it or check that
 
263
            specified files are within it
 
264
        :return: A list of relative paths.
 
265
        :raises errors.PathNotChild: When a provided path is in a different self
 
266
            than self.
 
267
        """
 
268
        if file_list is None:
 
269
            return None
 
270
        if self.supports_views() and apply_view:
 
271
            view_files = self.views.lookup_view()
 
272
        else:
 
273
            view_files = []
 
274
        new_list = []
 
275
        # self.relpath exists as a "thunk" to osutils, but canonical_relpath
 
276
        # doesn't - fix that up here before we enter the loop.
 
277
        if canonicalize:
 
278
            def fixer(p):
 
279
                return osutils.canonical_relpath(self.basedir, p)
 
280
        else:
 
281
            fixer = self.relpath
 
282
        for filename in file_list:
 
283
            relpath = fixer(osutils.dereference_path(filename))
 
284
            if view_files and not osutils.is_inside_any(view_files, relpath):
 
285
                raise views.FileOutsideView(filename, view_files)
 
286
            new_list.append(relpath)
 
287
        return new_list
 
288
 
 
289
    @staticmethod
 
290
    def open_downlevel(path=None):
 
291
        """Open an unsupported working tree.
 
292
 
 
293
        Only intended for advanced situations like upgrading part of a controldir.
 
294
        """
 
295
        return WorkingTree.open(path, _unsupported=True)
 
296
 
 
297
    @staticmethod
 
298
    def find_trees(location):
 
299
        def list_current(transport):
 
300
            return [d for d in transport.list_dir('')
 
301
                    if not controldir.is_control_filename(d)]
 
302
 
 
303
        def evaluate(controldir):
 
304
            try:
 
305
                tree = controldir.open_workingtree()
 
306
            except errors.NoWorkingTree:
 
307
                return True, None
 
308
            else:
 
309
                return True, tree
 
310
        t = transport.get_transport(location)
 
311
        iterator = controldir.ControlDir.find_controldirs(t, evaluate=evaluate,
 
312
                                                          list_current=list_current)
 
313
        return [tr for tr in iterator if tr is not None]
 
314
 
 
315
    def __repr__(self):
 
316
        return "<%s of %s>" % (self.__class__.__name__,
 
317
                               getattr(self, 'basedir', None))
 
318
 
 
319
    def abspath(self, filename):
 
320
        return osutils.pathjoin(self.basedir, filename)
 
321
 
 
322
    def basis_tree(self):
 
323
        """Return RevisionTree for the current last revision.
 
324
 
 
325
        If the left most parent is a ghost then the returned tree will be an
 
326
        empty tree - one obtained by calling
 
327
        repository.revision_tree(NULL_REVISION).
 
328
        """
 
329
        try:
 
330
            revision_id = self.get_parent_ids()[0]
 
331
        except IndexError:
 
332
            # no parents, return an empty revision tree.
 
333
            # in the future this should return the tree for
 
334
            # 'empty:' - the implicit root empty tree.
 
335
            return self.branch.repository.revision_tree(
 
336
                _mod_revision.NULL_REVISION)
 
337
        try:
 
338
            return self.revision_tree(revision_id)
 
339
        except errors.NoSuchRevision:
 
340
            pass
 
341
        # No cached copy available, retrieve from the repository.
 
342
        # FIXME? RBC 20060403 should we cache the tree locally
 
343
        # at this point ?
 
344
        try:
 
345
            return self.branch.repository.revision_tree(revision_id)
 
346
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
 
347
            # the basis tree *may* be a ghost or a low level error may have
 
348
            # occurred. If the revision is present, its a problem, if its not
 
349
            # its a ghost.
 
350
            if self.branch.repository.has_revision(revision_id):
 
351
                raise
 
352
            # the basis tree is a ghost so return an empty tree.
 
353
            return self.branch.repository.revision_tree(
 
354
                _mod_revision.NULL_REVISION)
 
355
 
 
356
    def relpath(self, path):
 
357
        """Return the local path portion from a given path.
 
358
 
 
359
        The path may be absolute or relative. If its a relative path it is
 
360
        interpreted relative to the python current working directory.
 
361
        """
 
362
        return osutils.relpath(self.basedir, path)
 
363
 
 
364
    def has_filename(self, filename):
 
365
        return osutils.lexists(self.abspath(filename))
 
366
 
 
367
    def get_file(self, path, filtered=True):
 
368
        return self.get_file_with_stat(path, filtered=filtered)[0]
 
369
 
 
370
    def get_file_with_stat(self, path, filtered=True,
 
371
                           _fstat=osutils.fstat):
 
372
        """See Tree.get_file_with_stat."""
 
373
        abspath = self.abspath(path)
 
374
        try:
 
375
            file_obj = open(abspath, 'rb')
 
376
        except EnvironmentError as e:
 
377
            if e.errno == errno.ENOENT:
 
378
                raise errors.NoSuchFile(path)
 
379
            raise
 
380
        stat_value = _fstat(file_obj.fileno())
 
381
        if filtered and self.supports_content_filtering():
 
382
            filters = self._content_filter_stack(path)
 
383
            file_obj = _mod_filters.filtered_input_file(file_obj, filters)
 
384
        return (file_obj, stat_value)
 
385
 
 
386
    def get_file_text(self, path, filtered=True):
 
387
        with self.get_file(path, filtered=filtered) as my_file:
 
388
            return my_file.read()
 
389
 
 
390
    def get_file_lines(self, path, filtered=True):
 
391
        """See Tree.get_file_lines()"""
 
392
        with self.get_file(path, filtered=filtered) as file:
 
393
            return file.readlines()
 
394
 
 
395
    def get_parent_ids(self):
 
396
        """See Tree.get_parent_ids.
 
397
 
 
398
        This implementation reads the pending merges list and last_revision
 
399
        value and uses that to decide what the parents list should be.
 
400
        """
 
401
        last_rev = _mod_revision.ensure_null(self._last_revision())
 
402
        if _mod_revision.NULL_REVISION == last_rev:
 
403
            parents = []
 
404
        else:
 
405
            parents = [last_rev]
 
406
        try:
 
407
            merges_bytes = self._transport.get_bytes('pending-merges')
 
408
        except errors.NoSuchFile:
 
409
            pass
 
410
        else:
 
411
            for l in osutils.split_lines(merges_bytes):
 
412
                revision_id = l.rstrip(b'\n')
 
413
                parents.append(revision_id)
 
414
        return parents
 
415
 
 
416
    def get_root_id(self):
 
417
        """Return the id of this trees root"""
 
418
        raise NotImplementedError(self.get_root_id)
 
419
 
 
420
    def clone(self, to_controldir, revision_id=None):
 
421
        """Duplicate this working tree into to_bzr, including all state.
 
422
 
 
423
        Specifically modified files are kept as modified, but
 
424
        ignored and unknown files are discarded.
 
425
 
 
426
        If you want to make a new line of development, see ControlDir.sprout()
 
427
 
 
428
        revision
 
429
            If not None, the cloned tree will have its last revision set to
 
430
            revision, and difference between the source trees last revision
 
431
            and this one merged in.
 
432
        """
 
433
        with self.lock_read():
 
434
            # assumes the target bzr dir format is compatible.
 
435
            result = to_controldir.create_workingtree()
 
436
            self.copy_content_into(result, revision_id)
 
437
            return result
 
438
 
 
439
    def copy_content_into(self, tree, revision_id=None):
 
440
        """Copy the current content and user files of this tree into tree."""
 
441
        with self.lock_read():
 
442
            tree.set_root_id(self.get_root_id())
 
443
            if revision_id is None:
 
444
                merge.transform_tree(tree, self)
 
445
            else:
 
446
                # TODO now merge from tree.last_revision to revision (to
 
447
                # preserve user local changes)
 
448
                try:
 
449
                    other_tree = self.revision_tree(revision_id)
 
450
                except errors.NoSuchRevision:
 
451
                    other_tree = self.branch.repository.revision_tree(
 
452
                        revision_id)
 
453
 
 
454
                merge.transform_tree(tree, other_tree)
 
455
                if revision_id == _mod_revision.NULL_REVISION:
 
456
                    new_parents = []
 
457
                else:
 
458
                    new_parents = [revision_id]
 
459
                tree.set_parent_ids(new_parents)
 
460
 
 
461
    def get_file_size(self, path):
 
462
        """See Tree.get_file_size"""
 
463
        # XXX: this returns the on-disk size; it should probably return the
 
464
        # canonical size
 
465
        try:
 
466
            return os.path.getsize(self.abspath(path))
 
467
        except OSError as e:
 
468
            if e.errno != errno.ENOENT:
 
469
                raise
 
470
            else:
 
471
                return None
 
472
 
 
473
    def _gather_kinds(self, files, kinds):
 
474
        """See MutableTree._gather_kinds."""
 
475
        with self.lock_tree_write():
 
476
            for pos, f in enumerate(files):
 
477
                if kinds[pos] is None:
 
478
                    fullpath = osutils.normpath(self.abspath(f))
 
479
                    try:
 
480
                        kinds[pos] = osutils.file_kind(fullpath)
 
481
                    except OSError as e:
 
482
                        if e.errno == errno.ENOENT:
 
483
                            raise errors.NoSuchFile(fullpath)
 
484
 
 
485
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
 
486
        """Add revision_id as a parent.
 
487
 
 
488
        This is equivalent to retrieving the current list of parent ids
 
489
        and setting the list to its value plus revision_id.
 
490
 
 
491
        :param revision_id: The revision id to add to the parent list. It may
 
492
            be a ghost revision as long as its not the first parent to be
 
493
            added, or the allow_leftmost_as_ghost parameter is set True.
 
494
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
 
495
        """
 
496
        with self.lock_write():
 
497
            parents = self.get_parent_ids() + [revision_id]
 
498
            self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
 
499
                                or allow_leftmost_as_ghost)
 
500
 
 
501
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
 
502
        """Add revision_id, tree tuple as a parent.
 
503
 
 
504
        This is equivalent to retrieving the current list of parent trees
 
505
        and setting the list to its value plus parent_tuple. See also
 
506
        add_parent_tree_id - if you only have a parent id available it will be
 
507
        simpler to use that api. If you have the parent already available, using
 
508
        this api is preferred.
 
509
 
 
510
        :param parent_tuple: The (revision id, tree) to add to the parent list.
 
511
            If the revision_id is a ghost, pass None for the tree.
 
512
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
 
513
        """
 
514
        with self.lock_tree_write():
 
515
            parent_ids = self.get_parent_ids() + [parent_tuple[0]]
 
516
            if len(parent_ids) > 1:
 
517
                # the leftmost may have already been a ghost, preserve that if it
 
518
                # was.
 
519
                allow_leftmost_as_ghost = True
 
520
            self.set_parent_ids(parent_ids,
 
521
                                allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
522
 
 
523
    def add_pending_merge(self, *revision_ids):
 
524
        with self.lock_tree_write():
 
525
            # TODO: Perhaps should check at this point that the
 
526
            # history of the revision is actually present?
 
527
            parents = self.get_parent_ids()
 
528
            updated = False
 
529
            for rev_id in revision_ids:
 
530
                if rev_id in parents:
 
531
                    continue
 
532
                parents.append(rev_id)
 
533
                updated = True
 
534
            if updated:
 
535
                self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
 
536
 
 
537
    def path_content_summary(self, path, _lstat=os.lstat,
 
538
                             _mapper=osutils.file_kind_from_stat_mode):
 
539
        """See Tree.path_content_summary."""
 
540
        abspath = self.abspath(path)
 
541
        try:
 
542
            stat_result = _lstat(abspath)
 
543
        except OSError as e:
 
544
            if getattr(e, 'errno', None) == errno.ENOENT:
 
545
                # no file.
 
546
                return ('missing', None, None, None)
 
547
            # propagate other errors
 
548
            raise
 
549
        kind = _mapper(stat_result.st_mode)
 
550
        if kind == 'file':
 
551
            return self._file_content_summary(path, stat_result)
 
552
        elif kind == 'directory':
 
553
            # perhaps it looks like a plain directory, but it's really a
 
554
            # reference.
 
555
            if self._directory_is_tree_reference(path):
 
556
                kind = 'tree-reference'
 
557
            return kind, None, None, None
 
558
        elif kind == 'symlink':
 
559
            target = osutils.readlink(abspath)
 
560
            return ('symlink', None, None, target)
 
561
        else:
 
562
            return (kind, None, None, None)
 
563
 
 
564
    def _file_content_summary(self, path, stat_result):
 
565
        size = stat_result.st_size
 
566
        executable = self._is_executable_from_path_and_stat(path, stat_result)
 
567
        # try for a stat cache lookup
 
568
        return ('file', size, executable, self._sha_from_stat(
 
569
            path, stat_result))
 
570
 
 
571
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
 
572
        """Common ghost checking functionality from set_parent_*.
 
573
 
 
574
        This checks that the left hand-parent exists if there are any
 
575
        revisions present.
 
576
        """
 
577
        if len(revision_ids) > 0:
 
578
            leftmost_id = revision_ids[0]
 
579
            if (not allow_leftmost_as_ghost and not
 
580
                    self.branch.repository.has_revision(leftmost_id)):
 
581
                raise errors.GhostRevisionUnusableHere(leftmost_id)
 
582
 
 
583
    def _set_merges_from_parent_ids(self, parent_ids):
 
584
        merges = parent_ids[1:]
 
585
        self._transport.put_bytes('pending-merges', b'\n'.join(merges),
 
586
                                  mode=self.controldir._get_file_mode())
 
587
 
 
588
    def _filter_parent_ids_by_ancestry(self, revision_ids):
 
589
        """Check that all merged revisions are proper 'heads'.
 
590
 
 
591
        This will always return the first revision_id, and any merged revisions
 
592
        which are
 
593
        """
 
594
        if len(revision_ids) == 0:
 
595
            return revision_ids
 
596
        graph = self.branch.repository.get_graph()
 
597
        heads = graph.heads(revision_ids)
 
598
        new_revision_ids = revision_ids[:1]
 
599
        for revision_id in revision_ids[1:]:
 
600
            if revision_id in heads and revision_id not in new_revision_ids:
 
601
                new_revision_ids.append(revision_id)
 
602
        if new_revision_ids != revision_ids:
 
603
            mutter('requested to set revision_ids = %s,'
 
604
                   ' but filtered to %s', revision_ids, new_revision_ids)
 
605
        return new_revision_ids
 
606
 
 
607
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
 
608
        """Set the parent ids to revision_ids.
 
609
 
 
610
        See also set_parent_trees. This api will try to retrieve the tree data
 
611
        for each element of revision_ids from the trees repository. If you have
 
612
        tree data already available, it is more efficient to use
 
613
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
 
614
        an easier API to use.
 
615
 
 
616
        :param revision_ids: The revision_ids to set as the parent ids of this
 
617
            working tree. Any of these may be ghosts.
 
618
        """
 
619
        with self.lock_tree_write():
 
620
            self._check_parents_for_ghosts(revision_ids,
 
621
                                           allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
622
            for revision_id in revision_ids:
 
623
                _mod_revision.check_not_reserved_id(revision_id)
 
624
 
 
625
            revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
 
626
 
 
627
            if len(revision_ids) > 0:
 
628
                self.set_last_revision(revision_ids[0])
 
629
            else:
 
630
                self.set_last_revision(_mod_revision.NULL_REVISION)
 
631
 
 
632
            self._set_merges_from_parent_ids(revision_ids)
 
633
 
 
634
    def set_pending_merges(self, rev_list):
 
635
        with self.lock_tree_write():
 
636
            parents = self.get_parent_ids()
 
637
            leftmost = parents[:1]
 
638
            new_parents = leftmost + rev_list
 
639
            self.set_parent_ids(new_parents)
 
640
 
 
641
    def set_merge_modified(self, modified_hashes):
 
642
        """Set the merge modified hashes."""
 
643
        raise NotImplementedError(self.set_merge_modified)
 
644
 
 
645
    def _sha_from_stat(self, path, stat_result):
 
646
        """Get a sha digest from the tree's stat cache.
 
647
 
 
648
        The default implementation assumes no stat cache is present.
 
649
 
 
650
        :param path: The path.
 
651
        :param stat_result: The stat result being looked up.
 
652
        """
 
653
        return None
 
654
 
 
655
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
 
656
                          merge_type=None, force=False):
 
657
        """Merge from a branch into this working tree.
 
658
 
 
659
        :param branch: The branch to merge from.
 
660
        :param to_revision: If non-None, the merge will merge to to_revision,
 
661
            but not beyond it. to_revision does not need to be in the history
 
662
            of the branch when it is supplied. If None, to_revision defaults to
 
663
            branch.last_revision().
 
664
        """
 
665
        from .merge import Merger, Merge3Merger
 
666
        with self.lock_write():
 
667
            merger = Merger(self.branch, this_tree=self)
 
668
            # check that there are no local alterations
 
669
            if not force and self.has_changes():
 
670
                raise errors.UncommittedChanges(self)
 
671
            if to_revision is None:
 
672
                to_revision = _mod_revision.ensure_null(branch.last_revision())
 
673
            merger.other_rev_id = to_revision
 
674
            if _mod_revision.is_null(merger.other_rev_id):
 
675
                raise errors.NoCommits(branch)
 
676
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
 
677
            merger.other_basis = merger.other_rev_id
 
678
            merger.other_tree = self.branch.repository.revision_tree(
 
679
                merger.other_rev_id)
 
680
            merger.other_branch = branch
 
681
            if from_revision is None:
 
682
                merger.find_base()
 
683
            else:
 
684
                merger.set_base_revision(from_revision, branch)
 
685
            if merger.base_rev_id == merger.other_rev_id:
 
686
                raise errors.PointlessMerge
 
687
            merger.backup_files = False
 
688
            if merge_type is None:
 
689
                merger.merge_type = Merge3Merger
 
690
            else:
 
691
                merger.merge_type = merge_type
 
692
            merger.set_interesting_files(None)
 
693
            merger.show_base = False
 
694
            merger.reprocess = False
 
695
            conflicts = merger.do_merge()
 
696
            merger.set_pending()
 
697
            return conflicts
 
698
 
 
699
    def merge_modified(self):
 
700
        """Return a dictionary of files modified by a merge.
 
701
 
 
702
        The list is initialized by WorkingTree.set_merge_modified, which is
 
703
        typically called after we make some automatic updates to the tree
 
704
        because of a merge.
 
705
 
 
706
        This returns a map of file_id->sha1, containing only files which are
 
707
        still in the working tree and have that text hash.
 
708
        """
 
709
        raise NotImplementedError(self.merge_modified)
 
710
 
 
711
    def mkdir(self, path, file_id=None):
 
712
        """See MutableTree.mkdir()."""
 
713
        if file_id is None:
 
714
            if self.supports_setting_file_ids():
 
715
                file_id = generate_ids.gen_file_id(os.path.basename(path))
 
716
        else:
 
717
            if not self.supports_setting_file_ids():
 
718
                raise SettingFileIdUnsupported()
 
719
        with self.lock_write():
 
720
            os.mkdir(self.abspath(path))
 
721
            self.add(path, file_id, 'directory')
 
722
            return file_id
 
723
 
 
724
    def get_symlink_target(self, path):
 
725
        abspath = self.abspath(path)
 
726
        target = osutils.readlink(abspath)
 
727
        return target
 
728
 
 
729
    def subsume(self, other_tree):
 
730
        raise NotImplementedError(self.subsume)
 
731
 
 
732
    def _setup_directory_is_tree_reference(self):
 
733
        if self._branch.repository._format.supports_tree_reference:
 
734
            self._directory_is_tree_reference = \
 
735
                self._directory_may_be_tree_reference
 
736
        else:
 
737
            self._directory_is_tree_reference = \
 
738
                self._directory_is_never_tree_reference
 
739
 
 
740
    def _directory_is_never_tree_reference(self, relpath):
 
741
        return False
 
742
 
 
743
    def _directory_may_be_tree_reference(self, relpath):
 
744
        # as a special case, if a directory contains control files then
 
745
        # it's a tree reference, except that the root of the tree is not
 
746
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
 
747
        # TODO: We could ask all the control formats whether they
 
748
        # recognize this directory, but at the moment there's no cheap api
 
749
        # to do that.  Since we probably can only nest bzr checkouts and
 
750
        # they always use this name it's ok for now.  -- mbp 20060306
 
751
        #
 
752
        # FIXME: There is an unhandled case here of a subdirectory
 
753
        # containing .bzr but not a branch; that will probably blow up
 
754
        # when you try to commit it.  It might happen if there is a
 
755
        # checkout in a subdirectory.  This can be avoided by not adding
 
756
        # it.  mbp 20070306
 
757
 
 
758
    def extract(self, path, format=None):
 
759
        """Extract a subtree from this tree.
 
760
 
 
761
        A new branch will be created, relative to the path for this tree.
 
762
        """
 
763
        raise NotImplementedError(self.extract)
 
764
 
 
765
    def flush(self):
 
766
        """Write the in memory meta data to disk."""
 
767
        raise NotImplementedError(self.flush)
 
768
 
 
769
    def kind(self, relpath):
 
770
        return osutils.file_kind(self.abspath(relpath))
 
771
 
 
772
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
773
        """List all files as (path, class, kind, id, entry).
 
774
 
 
775
        Lists, but does not descend into unversioned directories.
 
776
        This does not include files that have been deleted in this
 
777
        tree. Skips the control directory.
 
778
 
 
779
        :param include_root: if True, return an entry for the root
 
780
        :param from_dir: start from this directory or None for the root
 
781
        :param recursive: whether to recurse into subdirectories or not
 
782
        """
 
783
        raise NotImplementedError(self.list_files)
 
784
 
 
785
    def move(self, from_paths, to_dir=None, after=False):
 
786
        """Rename files.
 
787
 
 
788
        to_dir must be known to the working tree.
 
789
 
 
790
        If to_dir exists and is a directory, the files are moved into
 
791
        it, keeping their old names.
 
792
 
 
793
        Note that to_dir is only the last component of the new name;
 
794
        this doesn't change the directory.
 
795
 
 
796
        For each entry in from_paths the move mode will be determined
 
797
        independently.
 
798
 
 
799
        The first mode moves the file in the filesystem and updates the
 
800
        working tree metadata. The second mode only updates the working tree
 
801
        metadata without touching the file on the filesystem.
 
802
 
 
803
        move uses the second mode if 'after == True' and the target is not
 
804
        versioned but present in the working tree.
 
805
 
 
806
        move uses the second mode if 'after == False' and the source is
 
807
        versioned but no longer in the working tree, and the target is not
 
808
        versioned but present in the working tree.
 
809
 
 
810
        move uses the first mode if 'after == False' and the source is
 
811
        versioned and present in the working tree, and the target is not
 
812
        versioned and not present in the working tree.
 
813
 
 
814
        Everything else results in an error.
 
815
 
 
816
        This returns a list of (from_path, to_path) pairs for each
 
817
        entry that is moved.
 
818
        """
 
819
        raise NotImplementedError(self.move)
 
820
 
 
821
    def copy_one(self, from_rel, to_rel):
 
822
        """Copy a file in the tree to a new location.
 
823
 
 
824
        This default implementation just copies the file, then
 
825
        adds the target.
 
826
 
 
827
        :param from_rel: From location (relative to tree root)
 
828
        :param to_rel: Target location (relative to tree root)
 
829
        """
 
830
        shutil.copyfile(self.abspath(from_rel), self.abspath(to_rel))
 
831
        self.add(to_rel)
 
832
 
 
833
    def unknowns(self):
 
834
        """Return all unknown files.
 
835
 
 
836
        These are files in the working directory that are not versioned or
 
837
        control files or ignored.
 
838
        """
 
839
        with self.lock_read():
 
840
            # force the extras method to be fully executed before returning, to
 
841
            # prevent race conditions with the lock
 
842
            return iter(
 
843
                [subp for subp in self.extras() if not self.is_ignored(subp)])
 
844
 
 
845
    def unversion(self, paths):
 
846
        """Remove the path in pahs from the current versioned set.
 
847
 
 
848
        When a path is unversioned, all of its children are automatically
 
849
        unversioned.
 
850
 
 
851
        :param paths: The paths to stop versioning.
 
852
        :raises NoSuchFile: if any path is not currently versioned.
 
853
        """
 
854
        raise NotImplementedError(self.unversion)
 
855
 
 
856
    def pull(self, source, overwrite=False, stop_revision=None,
 
857
             change_reporter=None, possible_transports=None, local=False,
 
858
             show_base=False):
 
859
        with self.lock_write(), source.lock_read():
 
860
            old_revision_info = self.branch.last_revision_info()
 
861
            basis_tree = self.basis_tree()
 
862
            count = self.branch.pull(source, overwrite, stop_revision,
 
863
                                     possible_transports=possible_transports,
 
864
                                     local=local)
 
865
            new_revision_info = self.branch.last_revision_info()
 
866
            if new_revision_info != old_revision_info:
 
867
                repository = self.branch.repository
 
868
                if repository._format.fast_deltas:
 
869
                    parent_ids = self.get_parent_ids()
 
870
                    if parent_ids:
 
871
                        basis_id = parent_ids[0]
 
872
                        basis_tree = repository.revision_tree(basis_id)
 
873
                with basis_tree.lock_read():
 
874
                    new_basis_tree = self.branch.basis_tree()
 
875
                    merge.merge_inner(
 
876
                        self.branch,
 
877
                        new_basis_tree,
 
878
                        basis_tree,
 
879
                        this_tree=self,
 
880
                        change_reporter=change_reporter,
 
881
                        show_base=show_base)
 
882
                    basis_root_id = basis_tree.get_root_id()
 
883
                    new_root_id = new_basis_tree.get_root_id()
 
884
                    if new_root_id is not None and basis_root_id != new_root_id:
 
885
                        self.set_root_id(new_root_id)
 
886
                # TODO - dedup parents list with things merged by pull ?
 
887
                # reuse the revisiontree we merged against to set the new
 
888
                # tree data.
 
889
                parent_trees = []
 
890
                if self.branch.last_revision() != _mod_revision.NULL_REVISION:
 
891
                    parent_trees.append(
 
892
                        (self.branch.last_revision(), new_basis_tree))
 
893
                # we have to pull the merge trees out again, because
 
894
                # merge_inner has set the ids. - this corner is not yet
 
895
                # layered well enough to prevent double handling.
 
896
                # XXX TODO: Fix the double handling: telling the tree about
 
897
                # the already known parent data is wasteful.
 
898
                merges = self.get_parent_ids()[1:]
 
899
                parent_trees.extend([
 
900
                    (parent, repository.revision_tree(parent)) for
 
901
                    parent in merges])
 
902
                self.set_parent_trees(parent_trees)
 
903
            return count
 
904
 
 
905
    def put_file_bytes_non_atomic(self, path, bytes):
 
906
        """See MutableTree.put_file_bytes_non_atomic."""
 
907
        with self.lock_write(), open(self.abspath(path), 'wb') as stream:
 
908
            stream.write(bytes)
 
909
 
 
910
    def extras(self):
 
911
        """Yield all unversioned files in this WorkingTree.
 
912
 
 
913
        If there are any unversioned directories and the file format
 
914
        supports versioning directories, then only the directory is returned,
 
915
        not all its children. But if there are unversioned files under a
 
916
        versioned subdirectory, they are returned.
 
917
 
 
918
        Currently returned depth-first, sorted by name within directories.
 
919
        This is the same order used by 'osutils.walkdirs'.
 
920
        """
 
921
        raise NotImplementedError(self.extras)
 
922
 
 
923
    def ignored_files(self):
 
924
        """Yield list of PATH, IGNORE_PATTERN"""
 
925
        for subp in self.extras():
 
926
            pat = self.is_ignored(subp)
 
927
            if pat is not None:
 
928
                yield subp, pat
 
929
 
 
930
    def is_ignored(self, filename):
 
931
        r"""Check whether the filename matches an ignore pattern.
 
932
        """
 
933
        raise NotImplementedError(self.is_ignored)
 
934
 
 
935
    def stored_kind(self, path):
 
936
        """See Tree.stored_kind"""
 
937
        raise NotImplementedError(self.stored_kind)
 
938
 
 
939
    def _comparison_data(self, entry, path):
 
940
        abspath = self.abspath(path)
 
941
        try:
 
942
            stat_value = os.lstat(abspath)
 
943
        except OSError as e:
 
944
            if getattr(e, 'errno', None) == errno.ENOENT:
 
945
                stat_value = None
 
946
                kind = None
 
947
                executable = False
 
948
            else:
 
949
                raise
 
950
        else:
 
951
            mode = stat_value.st_mode
 
952
            kind = osutils.file_kind_from_stat_mode(mode)
 
953
            if not self._supports_executable():
 
954
                executable = entry is not None and entry.executable
 
955
            else:
 
956
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
957
        return kind, executable, stat_value
 
958
 
 
959
    def last_revision(self):
 
960
        """Return the last revision of the branch for this tree.
 
961
 
 
962
        This format tree does not support a separate marker for last-revision
 
963
        compared to the branch.
 
964
 
 
965
        See MutableTree.last_revision
 
966
        """
 
967
        return self._last_revision()
 
968
 
 
969
    def _last_revision(self):
 
970
        """helper for get_parent_ids."""
 
971
        with self.lock_read():
 
972
            return _mod_revision.ensure_null(self.branch.last_revision())
 
973
 
 
974
    def is_locked(self):
 
975
        """Check if this tree is locked."""
 
976
        raise NotImplementedError(self.is_locked)
 
977
 
 
978
    def lock_read(self):
 
979
        """Lock the tree for reading.
 
980
 
 
981
        This also locks the branch, and can be unlocked via self.unlock().
 
982
 
 
983
        :return: A breezy.lock.LogicalLockResult.
 
984
        """
 
985
        raise NotImplementedError(self.lock_read)
 
986
 
 
987
    def lock_tree_write(self):
 
988
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
 
989
 
 
990
        :return: A breezy.lock.LogicalLockResult.
 
991
        """
 
992
        raise NotImplementedError(self.lock_tree_write)
 
993
 
 
994
    def lock_write(self):
 
995
        """See MutableTree.lock_write, and WorkingTree.unlock.
 
996
 
 
997
        :return: A breezy.lock.LogicalLockResult.
 
998
        """
 
999
        raise NotImplementedError(self.lock_write)
 
1000
 
 
1001
    def get_physical_lock_status(self):
 
1002
        raise NotImplementedError(self.get_physical_lock_status)
 
1003
 
 
1004
    def set_last_revision(self, new_revision):
 
1005
        """Change the last revision in the working tree."""
 
1006
        raise NotImplementedError(self.set_last_revision)
 
1007
 
 
1008
    def _change_last_revision(self, new_revision):
 
1009
        """Template method part of set_last_revision to perform the change.
 
1010
 
 
1011
        This is used to allow WorkingTree3 instances to not affect branch
 
1012
        when their last revision is set.
 
1013
        """
 
1014
        if _mod_revision.is_null(new_revision):
 
1015
            self.branch.set_last_revision_info(0, new_revision)
 
1016
            return False
 
1017
        _mod_revision.check_not_reserved_id(new_revision)
 
1018
        try:
 
1019
            self.branch.generate_revision_history(new_revision)
 
1020
        except errors.NoSuchRevision:
 
1021
            # not present in the repo - dont try to set it deeper than the tip
 
1022
            self.branch._set_revision_history([new_revision])
 
1023
        return True
 
1024
 
 
1025
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
 
1026
               force=False):
 
1027
        """Remove nominated files from the working tree metadata.
 
1028
 
 
1029
        :files: File paths relative to the basedir.
 
1030
        :keep_files: If true, the files will also be kept.
 
1031
        :force: Delete files and directories, even if they are changed and
 
1032
            even if the directories are not empty.
 
1033
        """
 
1034
        raise NotImplementedError(self.remove)
 
1035
 
 
1036
    def revert(self, filenames=None, old_tree=None, backups=True,
 
1037
               pb=None, report_changes=False):
 
1038
        from .conflicts import resolve
 
1039
        with self.lock_tree_write():
 
1040
            if old_tree is None:
 
1041
                basis_tree = self.basis_tree()
 
1042
                basis_tree.lock_read()
 
1043
                old_tree = basis_tree
 
1044
            else:
 
1045
                basis_tree = None
 
1046
            try:
 
1047
                conflicts = transform.revert(self, old_tree, filenames, backups, pb,
 
1048
                                             report_changes)
 
1049
                if filenames is None and len(self.get_parent_ids()) > 1:
 
1050
                    parent_trees = []
 
1051
                    last_revision = self.last_revision()
 
1052
                    if last_revision != _mod_revision.NULL_REVISION:
 
1053
                        if basis_tree is None:
 
1054
                            basis_tree = self.basis_tree()
 
1055
                            basis_tree.lock_read()
 
1056
                        parent_trees.append((last_revision, basis_tree))
 
1057
                    self.set_parent_trees(parent_trees)
 
1058
                    resolve(self)
 
1059
                else:
 
1060
                    resolve(self, filenames, ignore_misses=True, recursive=True)
 
1061
            finally:
 
1062
                if basis_tree is not None:
 
1063
                    basis_tree.unlock()
 
1064
            return conflicts
 
1065
 
 
1066
    def store_uncommitted(self):
 
1067
        """Store uncommitted changes from the tree in the branch."""
 
1068
        raise NotImplementedError(self.store_uncommitted)
 
1069
 
 
1070
    def restore_uncommitted(self):
 
1071
        """Restore uncommitted changes from the branch into the tree."""
 
1072
        raise NotImplementedError(self.restore_uncommitted)
 
1073
 
 
1074
    def revision_tree(self, revision_id):
 
1075
        """See Tree.revision_tree.
 
1076
 
 
1077
        For trees that can be obtained from the working tree, this
 
1078
        will do so. For other trees, it will fall back to the repository.
 
1079
        """
 
1080
        raise NotImplementedError(self.revision_tree)
 
1081
 
 
1082
    def set_root_id(self, file_id):
 
1083
        """Set the root id for this tree."""
 
1084
        if not self.supports_setting_file_ids():
 
1085
            raise SettingFileIdUnsupported()
 
1086
        with self.lock_tree_write():
 
1087
            # for compatibility
 
1088
            if file_id is None:
 
1089
                raise ValueError(
 
1090
                    'WorkingTree.set_root_id with fileid=None')
 
1091
            file_id = osutils.safe_file_id(file_id)
 
1092
            self._set_root_id(file_id)
 
1093
 
 
1094
    def _set_root_id(self, file_id):
 
1095
        """Set the root id for this tree, in a format specific manner.
 
1096
 
 
1097
        :param file_id: The file id to assign to the root. It must not be
 
1098
            present in the current inventory or an error will occur. It must
 
1099
            not be None, but rather a valid file id.
 
1100
        """
 
1101
        raise NotImplementedError(self._set_root_id)
 
1102
 
 
1103
    def unlock(self):
 
1104
        """See Branch.unlock.
 
1105
 
 
1106
        WorkingTree locking just uses the Branch locking facilities.
 
1107
        This is current because all working trees have an embedded branch
 
1108
        within them. IF in the future, we were to make branch data shareable
 
1109
        between multiple working trees, i.e. via shared storage, then we
 
1110
        would probably want to lock both the local tree, and the branch.
 
1111
        """
 
1112
        raise NotImplementedError(self.unlock)
 
1113
 
 
1114
    _marker = object()
 
1115
 
 
1116
    def update(self, change_reporter=None, possible_transports=None,
 
1117
               revision=None, old_tip=_marker, show_base=False):
 
1118
        """Update a working tree along its branch.
 
1119
 
 
1120
        This will update the branch if its bound too, which means we have
 
1121
        multiple trees involved:
 
1122
 
 
1123
        - The new basis tree of the master.
 
1124
        - The old basis tree of the branch.
 
1125
        - The old basis tree of the working tree.
 
1126
        - The current working tree state.
 
1127
 
 
1128
        Pathologically, all three may be different, and non-ancestors of each
 
1129
        other.  Conceptually we want to:
 
1130
 
 
1131
        - Preserve the wt.basis->wt.state changes
 
1132
        - Transform the wt.basis to the new master basis.
 
1133
        - Apply a merge of the old branch basis to get any 'local' changes from
 
1134
          it into the tree.
 
1135
        - Restore the wt.basis->wt.state changes.
 
1136
 
 
1137
        There isn't a single operation at the moment to do that, so we:
 
1138
 
 
1139
        - Merge current state -> basis tree of the master w.r.t. the old tree
 
1140
          basis.
 
1141
        - Do a 'normal' merge of the old branch basis if it is relevant.
 
1142
 
 
1143
        :param revision: The target revision to update to. Must be in the
 
1144
            revision history.
 
1145
        :param old_tip: If branch.update() has already been run, the value it
 
1146
            returned (old tip of the branch or None). _marker is used
 
1147
            otherwise.
 
1148
        """
 
1149
        if self.branch.get_bound_location() is not None:
 
1150
            self.lock_write()
 
1151
            update_branch = (old_tip is self._marker)
 
1152
        else:
 
1153
            self.lock_tree_write()
 
1154
            update_branch = False
 
1155
        try:
 
1156
            if update_branch:
 
1157
                old_tip = self.branch.update(possible_transports)
 
1158
            else:
 
1159
                if old_tip is self._marker:
 
1160
                    old_tip = None
 
1161
            return self._update_tree(old_tip, change_reporter, revision, show_base)
 
1162
        finally:
 
1163
            self.unlock()
 
1164
 
 
1165
    def _update_tree(self, old_tip=None, change_reporter=None, revision=None,
 
1166
                     show_base=False):
 
1167
        """Update a tree to the master branch.
 
1168
 
 
1169
        :param old_tip: if supplied, the previous tip revision the branch,
 
1170
            before it was changed to the master branch's tip.
 
1171
        """
 
1172
        # here if old_tip is not None, it is the old tip of the branch before
 
1173
        # it was updated from the master branch. This should become a pending
 
1174
        # merge in the working tree to preserve the user existing work.  we
 
1175
        # cant set that until we update the working trees last revision to be
 
1176
        # one from the new branch, because it will just get absorbed by the
 
1177
        # parent de-duplication logic.
 
1178
        #
 
1179
        # We MUST save it even if an error occurs, because otherwise the users
 
1180
        # local work is unreferenced and will appear to have been lost.
 
1181
        #
 
1182
        with self.lock_tree_write():
 
1183
            nb_conflicts = 0
 
1184
            try:
 
1185
                last_rev = self.get_parent_ids()[0]
 
1186
            except IndexError:
 
1187
                last_rev = _mod_revision.NULL_REVISION
 
1188
            if revision is None:
 
1189
                revision = self.branch.last_revision()
 
1190
 
 
1191
            old_tip = old_tip or _mod_revision.NULL_REVISION
 
1192
 
 
1193
            if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
 
1194
                # the branch we are bound to was updated
 
1195
                # merge those changes in first
 
1196
                base_tree = self.basis_tree()
 
1197
                other_tree = self.branch.repository.revision_tree(old_tip)
 
1198
                nb_conflicts = merge.merge_inner(self.branch, other_tree,
 
1199
                                                 base_tree, this_tree=self,
 
1200
                                                 change_reporter=change_reporter,
 
1201
                                                 show_base=show_base)
 
1202
                if nb_conflicts:
 
1203
                    self.add_parent_tree((old_tip, other_tree))
 
1204
                    note(gettext('Rerun update after fixing the conflicts.'))
 
1205
                    return nb_conflicts
 
1206
 
 
1207
            if last_rev != _mod_revision.ensure_null(revision):
 
1208
                # the working tree is up to date with the branch
 
1209
                # we can merge the specified revision from master
 
1210
                to_tree = self.branch.repository.revision_tree(revision)
 
1211
                to_root_id = to_tree.get_root_id()
 
1212
 
 
1213
                basis = self.basis_tree()
 
1214
                with basis.lock_read():
 
1215
                    if (basis.get_root_id() is None or basis.get_root_id() != to_root_id):
 
1216
                        self.set_root_id(to_root_id)
 
1217
                        self.flush()
 
1218
 
 
1219
                # determine the branch point
 
1220
                graph = self.branch.repository.get_graph()
 
1221
                base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
 
1222
                                                    last_rev)
 
1223
                base_tree = self.branch.repository.revision_tree(base_rev_id)
 
1224
 
 
1225
                nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
 
1226
                                                 this_tree=self,
 
1227
                                                 change_reporter=change_reporter,
 
1228
                                                 show_base=show_base)
 
1229
                self.set_last_revision(revision)
 
1230
                # TODO - dedup parents list with things merged by pull ?
 
1231
                # reuse the tree we've updated to to set the basis:
 
1232
                parent_trees = [(revision, to_tree)]
 
1233
                merges = self.get_parent_ids()[1:]
 
1234
                # Ideally we ask the tree for the trees here, that way the working
 
1235
                # tree can decide whether to give us the entire tree or give us a
 
1236
                # lazy initialised tree. dirstate for instance will have the trees
 
1237
                # in ram already, whereas a last-revision + basis-inventory tree
 
1238
                # will not, but also does not need them when setting parents.
 
1239
                for parent in merges:
 
1240
                    parent_trees.append(
 
1241
                        (parent, self.branch.repository.revision_tree(parent)))
 
1242
                if not _mod_revision.is_null(old_tip):
 
1243
                    parent_trees.append(
 
1244
                        (old_tip, self.branch.repository.revision_tree(old_tip)))
 
1245
                self.set_parent_trees(parent_trees)
 
1246
                last_rev = parent_trees[0][0]
 
1247
            return nb_conflicts
 
1248
 
 
1249
    def set_conflicts(self, arg):
 
1250
        raise errors.UnsupportedOperation(self.set_conflicts, self)
 
1251
 
 
1252
    def add_conflicts(self, arg):
 
1253
        raise errors.UnsupportedOperation(self.add_conflicts, self)
 
1254
 
 
1255
    def conflicts(self):
 
1256
        raise NotImplementedError(self.conflicts)
 
1257
 
 
1258
    def walkdirs(self, prefix=""):
 
1259
        """Walk the directories of this tree.
 
1260
 
 
1261
        returns a generator which yields items in the form:
 
1262
                ((curren_directory_path, fileid),
 
1263
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
 
1264
                   file1_kind), ... ])
 
1265
 
 
1266
        This API returns a generator, which is only valid during the current
 
1267
        tree transaction - within a single lock_read or lock_write duration.
 
1268
 
 
1269
        If the tree is not locked, it may cause an error to be raised,
 
1270
        depending on the tree implementation.
 
1271
        """
 
1272
        raise NotImplementedError(self.walkdirs)
 
1273
 
 
1274
    @deprecated_method(deprecated_in((3, 0, 1)))
 
1275
    def auto_resolve(self):
 
1276
        """Automatically resolve text conflicts according to contents.
 
1277
 
 
1278
        Only text conflicts are auto_resolvable. Files with no conflict markers
 
1279
        are considered 'resolved', because bzr always puts conflict markers
 
1280
        into files that have text conflicts.  The corresponding .THIS .BASE and
 
1281
        .OTHER files are deleted, as per 'resolve'.
 
1282
 
 
1283
        :return: a tuple of ConflictLists: (un_resolved, resolved).
 
1284
        """
 
1285
        with self.lock_tree_write():
 
1286
            un_resolved = _mod_conflicts.ConflictList()
 
1287
            resolved = _mod_conflicts.ConflictList()
 
1288
            for conflict in self.conflicts():
 
1289
                try:
 
1290
                    conflict.action_auto(self)
 
1291
                except NotImplementedError:
 
1292
                    un_resolved.append(conflict)
 
1293
                else:
 
1294
                    conflict.cleanup(self)
 
1295
                    resolved.append(conflict)
 
1296
            self.set_conflicts(un_resolved)
 
1297
            return un_resolved, resolved
 
1298
 
 
1299
    def _validate(self):
 
1300
        """Validate internal structures.
 
1301
 
 
1302
        This is meant mostly for the test suite. To give it a chance to detect
 
1303
        corruption after actions have occurred. The default implementation is a
 
1304
        just a no-op.
 
1305
 
 
1306
        :return: None. An exception should be raised if there is an error.
 
1307
        """
 
1308
        return
 
1309
 
 
1310
    def check_state(self):
 
1311
        """Check that the working state is/isn't valid."""
 
1312
        raise NotImplementedError(self.check_state)
 
1313
 
 
1314
    def reset_state(self, revision_ids=None):
 
1315
        """Reset the state of the working tree.
 
1316
 
 
1317
        This does a hard-reset to a last-known-good state. This is a way to
 
1318
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
 
1319
        """
 
1320
        raise NotImplementedError(self.reset_state)
 
1321
 
 
1322
    def _get_rules_searcher(self, default_searcher):
 
1323
        """See Tree._get_rules_searcher."""
 
1324
        if self._rules_searcher is None:
 
1325
            self._rules_searcher = super(WorkingTree,
 
1326
                                         self)._get_rules_searcher(default_searcher)
 
1327
        return self._rules_searcher
 
1328
 
 
1329
    def get_shelf_manager(self):
 
1330
        """Return the ShelfManager for this WorkingTree."""
 
1331
        raise NotImplementedError(self.get_shelf_manager)
 
1332
 
 
1333
    def get_canonical_paths(self, paths):
 
1334
        """Like get_canonical_path() but works on multiple items.
 
1335
 
 
1336
        :param paths: A sequence of paths relative to the root of the tree.
 
1337
        :return: A list of paths, with each item the corresponding input path
 
1338
            adjusted to account for existing elements that match case
 
1339
            insensitively.
 
1340
        """
 
1341
        with self.lock_read():
 
1342
            for path in paths:
 
1343
                yield path
 
1344
 
 
1345
    def get_canonical_path(self, path):
 
1346
        """Returns the first item in the tree that matches a path.
 
1347
 
 
1348
        This is meant to allow case-insensitive path lookups on e.g.
 
1349
        FAT filesystems.
 
1350
 
 
1351
        If a path matches exactly, it is returned. If no path matches exactly
 
1352
        but more than one path matches according to the underlying file system,
 
1353
        it is implementation defined which is returned.
 
1354
 
 
1355
        If no path matches according to the file system, the input path is
 
1356
        returned, but with as many path entries that do exist changed to their
 
1357
        canonical form.
 
1358
 
 
1359
        If you need to resolve many names from the same tree, you should
 
1360
        use get_canonical_paths() to avoid O(N) behaviour.
 
1361
 
 
1362
        :param path: A paths relative to the root of the tree.
 
1363
        :return: The input path adjusted to account for existing elements
 
1364
        that match case insensitively.
 
1365
        """
 
1366
        with self.lock_read():
 
1367
            return next(self.get_canonical_paths([path]))
 
1368
 
 
1369
 
 
1370
class WorkingTreeFormatRegistry(controldir.ControlComponentFormatRegistry):
 
1371
    """Registry for working tree formats."""
 
1372
 
 
1373
    def __init__(self, other_registry=None):
 
1374
        super(WorkingTreeFormatRegistry, self).__init__(other_registry)
 
1375
        self._default_format = None
 
1376
        self._default_format_key = None
 
1377
 
 
1378
    def get_default(self):
 
1379
        """Return the current default format."""
 
1380
        if (self._default_format_key is not None and
 
1381
                self._default_format is None):
 
1382
            self._default_format = self.get(self._default_format_key)
 
1383
        return self._default_format
 
1384
 
 
1385
    def set_default(self, format):
 
1386
        """Set the default format."""
 
1387
        self._default_format = format
 
1388
        self._default_format_key = None
 
1389
 
 
1390
    def set_default_key(self, format_string):
 
1391
        """Set the default format by its format string."""
 
1392
        self._default_format_key = format_string
 
1393
        self._default_format = None
 
1394
 
 
1395
 
 
1396
format_registry = WorkingTreeFormatRegistry()
 
1397
 
 
1398
 
 
1399
class WorkingTreeFormat(controldir.ControlComponentFormat):
 
1400
    """An encapsulation of the initialization and open routines for a format.
 
1401
 
 
1402
    Formats provide three things:
 
1403
     * An initialization routine,
 
1404
     * a format string,
 
1405
     * an open routine.
 
1406
 
 
1407
    Formats are placed in an dict by their format string for reference
 
1408
    during workingtree opening. Its not required that these be instances, they
 
1409
    can be classes themselves with class methods - it simply depends on
 
1410
    whether state is needed for a given format or not.
 
1411
 
 
1412
    Once a format is deprecated, just deprecate the initialize and open
 
1413
    methods on the format class. Do not deprecate the object, as the
 
1414
    object will be created every time regardless.
 
1415
    """
 
1416
 
 
1417
    requires_rich_root = False
 
1418
 
 
1419
    upgrade_recommended = False
 
1420
 
 
1421
    requires_normalized_unicode_filenames = False
 
1422
 
 
1423
    case_sensitive_filename = "FoRMaT"
 
1424
 
 
1425
    missing_parent_conflicts = False
 
1426
    """If this format supports missing parent conflicts."""
 
1427
 
 
1428
    supports_versioned_directories = None
 
1429
 
 
1430
    supports_merge_modified = True
 
1431
    """If this format supports storing merge modified hashes."""
 
1432
 
 
1433
    supports_setting_file_ids = True
 
1434
    """If this format allows setting the file id."""
 
1435
 
 
1436
    supports_store_uncommitted = True
 
1437
    """If this format supports shelve-like functionality."""
 
1438
 
 
1439
    supports_leftmost_parent_id_as_ghost = True
 
1440
 
 
1441
    supports_righthand_parent_id_as_ghost = True
 
1442
 
 
1443
    ignore_filename = None
 
1444
    """Name of file with ignore patterns, if any. """
 
1445
 
 
1446
    def initialize(self, controldir, revision_id=None, from_branch=None,
 
1447
                   accelerator_tree=None, hardlink=False):
 
1448
        """Initialize a new working tree in controldir.
 
1449
 
 
1450
        :param controldir: ControlDir to initialize the working tree in.
 
1451
        :param revision_id: allows creating a working tree at a different
 
1452
            revision than the branch is at.
 
1453
        :param from_branch: Branch to checkout
 
1454
        :param accelerator_tree: A tree which can be used for retrieving file
 
1455
            contents more quickly than the revision tree, i.e. a workingtree.
 
1456
            The revision tree will be used for cases where accelerator_tree's
 
1457
            content is different.
 
1458
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1459
            where possible.
 
1460
        """
 
1461
        raise NotImplementedError(self.initialize)
 
1462
 
 
1463
    def __eq__(self, other):
 
1464
        return self.__class__ is other.__class__
 
1465
 
 
1466
    def __ne__(self, other):
 
1467
        return not (self == other)
 
1468
 
 
1469
    def get_format_description(self):
 
1470
        """Return the short description for this format."""
 
1471
        raise NotImplementedError(self.get_format_description)
 
1472
 
 
1473
    def is_supported(self):
 
1474
        """Is this format supported?
 
1475
 
 
1476
        Supported formats can be initialized and opened.
 
1477
        Unsupported formats may not support initialization or committing or
 
1478
        some other features depending on the reason for not being supported.
 
1479
        """
 
1480
        return True
 
1481
 
 
1482
    def supports_content_filtering(self):
 
1483
        """True if this format supports content filtering."""
 
1484
        return False
 
1485
 
 
1486
    def supports_views(self):
 
1487
        """True if this format supports stored views."""
 
1488
        return False
 
1489
 
 
1490
    def get_controldir_for_branch(self):
 
1491
        """Get the control directory format for creating branches.
 
1492
 
 
1493
        This is to support testing of working tree formats that can not exist
 
1494
        in the same control directory as a branch.
 
1495
        """
 
1496
        return self._matchingcontroldir
 
1497
 
 
1498
 
 
1499
format_registry.register_lazy(b"Bazaar Working Tree Format 4 (bzr 0.15)\n",
 
1500
                              "breezy.bzr.workingtree_4", "WorkingTreeFormat4")
 
1501
format_registry.register_lazy(b"Bazaar Working Tree Format 5 (bzr 1.11)\n",
 
1502
                              "breezy.bzr.workingtree_4", "WorkingTreeFormat5")
 
1503
format_registry.register_lazy(b"Bazaar Working Tree Format 6 (bzr 1.14)\n",
 
1504
                              "breezy.bzr.workingtree_4", "WorkingTreeFormat6")
 
1505
format_registry.register_lazy(b"Bazaar-NG Working Tree format 3",
 
1506
                              "breezy.bzr.workingtree_3", "WorkingTreeFormat3")
 
1507
format_registry.set_default_key(b"Bazaar Working Tree Format 6 (bzr 1.14)\n")