/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: Martin
  • Date: 2018-11-16 19:10:17 UTC
  • mto: This revision was merged to the branch mainline in revision 7177.
  • Revision ID: gzlist@googlemail.com-20181116191017-kyedz1qck0ovon3h
Remove lazy_regexp reset in bt.test_source

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