~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Robert Collins
  • Date: 2009-03-27 04:10:25 UTC
  • mfrom: (4208 +trunk)
  • mto: This revision was merged to the branch mainline in revision 4216.
  • Revision ID: robertc@robertcollins.net-20090327041025-rgutx4q03xo4pq6l
Resolve NEWS conflicts.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
29
29
WorkingTree.open(dir).
30
30
"""
31
31
 
 
32
# TODO: Give the workingtree sole responsibility for the working inventory;
 
33
# remove the variable and references to it from the branch.  This may require
 
34
# updating the commit code so as to update the inventory within the working
 
35
# copy, and making sure there's only one WorkingTree for any directory on disk.
 
36
# At the moment they may alias the inventory and have old copies of it in
 
37
# memory.  (Now done? -- mbp 20060309)
32
38
 
33
39
from cStringIO import StringIO
34
40
import os
42
48
import itertools
43
49
import operator
44
50
import stat
 
51
from time import time
 
52
import warnings
45
53
import re
46
54
 
 
55
import bzrlib
47
56
from bzrlib import (
48
57
    branch,
49
58
    bzrdir,
50
59
    conflicts as _mod_conflicts,
51
 
    controldir,
 
60
    dirstate,
52
61
    errors,
53
 
    filters as _mod_filters,
54
62
    generate_ids,
55
63
    globbing,
56
 
    graph as _mod_graph,
57
64
    hashcache,
58
65
    ignores,
59
 
    inventory,
60
66
    merge,
61
67
    revision as _mod_revision,
62
68
    revisiontree,
63
 
    rio as _mod_rio,
 
69
    repository,
 
70
    textui,
 
71
    trace,
64
72
    transform,
65
 
    transport,
66
73
    ui,
 
74
    urlutils,
67
75
    views,
68
76
    xml5,
 
77
    xml6,
69
78
    xml7,
70
79
    )
 
80
import bzrlib.branch
 
81
from bzrlib.transport import get_transport
 
82
import bzrlib.ui
 
83
from bzrlib.workingtree_4 import WorkingTreeFormat4, WorkingTreeFormat5
71
84
""")
72
85
 
73
86
from bzrlib import symbol_versioning
74
87
from bzrlib.decorators import needs_read_lock, needs_write_lock
75
 
from bzrlib.lock import LogicalLockResult
 
88
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
 
89
from bzrlib.lockable_files import LockableFiles
 
90
from bzrlib.lockdir import LockDir
76
91
import bzrlib.mutabletree
77
92
from bzrlib.mutabletree import needs_tree_write_lock
78
93
from bzrlib import osutils
79
94
from bzrlib.osutils import (
 
95
    compact_date,
80
96
    file_kind,
81
97
    isdir,
82
98
    normpath,
83
99
    pathjoin,
 
100
    rand_chars,
84
101
    realpath,
85
102
    safe_unicode,
86
103
    splitpath,
87
104
    supports_executable,
88
105
    )
 
106
from bzrlib.filters import filtered_input_file
89
107
from bzrlib.trace import mutter, note
90
 
from bzrlib.revision import CURRENT_REVISION
91
 
from bzrlib.symbol_versioning import (
92
 
    deprecated_passed,
93
 
    DEPRECATED_PARAMETER,
94
 
    )
 
108
from bzrlib.transport.local import LocalTransport
 
109
from bzrlib.progress import DummyProgress, ProgressPhase
 
110
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
 
111
from bzrlib.rio import RioReader, rio_file, Stanza
 
112
from bzrlib.symbol_versioning import (deprecated_passed,
 
113
        deprecated_method,
 
114
        deprecated_function,
 
115
        DEPRECATED_PARAMETER,
 
116
        )
95
117
 
96
118
 
97
119
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
98
 
# TODO: Modifying the conflict objects or their type is currently nearly
99
 
# impossible as there is no clear relationship between the working tree format
100
 
# and the conflict list file format.
101
120
CONFLICT_HEADER_1 = "BZR conflict list format 1"
102
121
 
103
122
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
158
177
        return ''
159
178
 
160
179
 
161
 
class WorkingTree(bzrlib.mutabletree.MutableTree,
162
 
    controldir.ControlComponent):
 
180
class WorkingTree(bzrlib.mutabletree.MutableTree):
163
181
    """Working copy tree.
164
182
 
165
 
    :ivar basedir: The root of the tree on disk. This is a unicode path object
166
 
        (as opposed to a URL).
 
183
    The inventory is held in the `Branch` working-inventory, and the
 
184
    files are in a directory on disk.
 
185
 
 
186
    It is possible for a `WorkingTree` to have a filename which is
 
187
    not listed in the Inventory and vice versa.
167
188
    """
168
189
 
169
190
    # override this to set the strategy for storing views
172
193
 
173
194
    def __init__(self, basedir='.',
174
195
                 branch=DEPRECATED_PARAMETER,
 
196
                 _inventory=None,
175
197
                 _control_files=None,
176
198
                 _internal=False,
177
199
                 _format=None,
192
214
        else:
193
215
            self._branch = self.bzrdir.open_branch()
194
216
        self.basedir = realpath(basedir)
195
 
        self._control_files = _control_files
 
217
        # if branch is at our basedir and is a format 6 or less
 
218
        if isinstance(self._format, WorkingTreeFormat2):
 
219
            # share control object
 
220
            self._control_files = self.branch.control_files
 
221
        else:
 
222
            # assume all other formats have their own control files.
 
223
            self._control_files = _control_files
196
224
        self._transport = self._control_files._transport
197
225
        # update the whole cache up front and write to disk if anything changed;
198
226
        # in the future we might want to do this more selectively
214
242
            mutter("write hc")
215
243
            hc.write()
216
244
 
 
245
        if _inventory is None:
 
246
            # This will be acquired on lock_read() or lock_write()
 
247
            self._inventory_is_modified = False
 
248
            self._inventory = None
 
249
        else:
 
250
            # the caller of __init__ has provided an inventory,
 
251
            # we assume they know what they are doing - as its only
 
252
            # the Format factory and creation methods that are
 
253
            # permitted to do this.
 
254
            self._set_inventory(_inventory, dirty=False)
217
255
        self._detect_case_handling()
218
256
        self._rules_searcher = None
219
257
        self.views = self._make_views()
220
258
 
221
 
    @property
222
 
    def user_transport(self):
223
 
        return self.bzrdir.user_transport
224
 
 
225
 
    @property
226
 
    def control_transport(self):
227
 
        return self._transport
228
 
 
229
 
    def is_control_filename(self, filename):
230
 
        """True if filename is the name of a control file in this tree.
231
 
 
232
 
        :param filename: A filename within the tree. This is a relative path
233
 
            from the root of this tree.
234
 
 
235
 
        This is true IF and ONLY IF the filename is part of the meta data
236
 
        that bzr controls in this tree. I.E. a random .bzr directory placed
237
 
        on disk will not be a control file for this tree.
238
 
        """
239
 
        return self.bzrdir.is_control_filename(filename)
240
 
 
241
259
    def _detect_case_handling(self):
242
260
        wt_trans = self.bzrdir.get_workingtree_transport(None)
243
261
        try:
244
 
            wt_trans.stat(self._format.case_sensitive_filename)
 
262
            wt_trans.stat("FoRMaT")
245
263
        except errors.NoSuchFile:
246
264
            self.case_sensitive = True
247
265
        else:
280
298
    def supports_views(self):
281
299
        return self.views.supports_views()
282
300
 
 
301
    def _set_inventory(self, inv, dirty):
 
302
        """Set the internal cached inventory.
 
303
 
 
304
        :param inv: The inventory to set.
 
305
        :param dirty: A boolean indicating whether the inventory is the same
 
306
            logical inventory as whats on disk. If True the inventory is not
 
307
            the same and should be written to disk or data will be lost, if
 
308
            False then the inventory is the same as that on disk and any
 
309
            serialisation would be unneeded overhead.
 
310
        """
 
311
        self._inventory = inv
 
312
        self._inventory_is_modified = dirty
 
313
 
283
314
    @staticmethod
284
315
    def open(path=None, _unsupported=False):
285
316
        """Open an existing working tree at path.
306
337
        if path is None:
307
338
            path = osutils.getcwd()
308
339
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
340
 
309
341
        return control.open_workingtree(), relpath
310
342
 
311
343
    @staticmethod
312
 
    def open_containing_paths(file_list, default_directory=None,
313
 
                              canonicalize=True, apply_view=True):
314
 
        """Open the WorkingTree that contains a set of paths.
315
 
 
316
 
        Fail if the paths given are not all in a single tree.
317
 
 
318
 
        This is used for the many command-line interfaces that take a list of
319
 
        any number of files and that require they all be in the same tree.
320
 
        """
321
 
        if default_directory is None:
322
 
            default_directory = u'.'
323
 
        # recommended replacement for builtins.internal_tree_files
324
 
        if file_list is None or len(file_list) == 0:
325
 
            tree = WorkingTree.open_containing(default_directory)[0]
326
 
            # XXX: doesn't really belong here, and seems to have the strange
327
 
            # side effect of making it return a bunch of files, not the whole
328
 
            # tree -- mbp 20100716
329
 
            if tree.supports_views() and apply_view:
330
 
                view_files = tree.views.lookup_view()
331
 
                if view_files:
332
 
                    file_list = view_files
333
 
                    view_str = views.view_display_str(view_files)
334
 
                    note("Ignoring files outside view. View is %s" % view_str)
335
 
            return tree, file_list
336
 
        if default_directory == u'.':
337
 
            seed = file_list[0]
338
 
        else:
339
 
            seed = default_directory
340
 
            file_list = [osutils.pathjoin(default_directory, f)
341
 
                         for f in file_list]
342
 
        tree = WorkingTree.open_containing(seed)[0]
343
 
        return tree, tree.safe_relpath_files(file_list, canonicalize,
344
 
                                             apply_view=apply_view)
345
 
 
346
 
    def safe_relpath_files(self, file_list, canonicalize=True, apply_view=True):
347
 
        """Convert file_list into a list of relpaths in tree.
348
 
 
349
 
        :param self: A tree to operate on.
350
 
        :param file_list: A list of user provided paths or None.
351
 
        :param apply_view: if True and a view is set, apply it or check that
352
 
            specified files are within it
353
 
        :return: A list of relative paths.
354
 
        :raises errors.PathNotChild: When a provided path is in a different self
355
 
            than self.
356
 
        """
357
 
        if file_list is None:
358
 
            return None
359
 
        if self.supports_views() and apply_view:
360
 
            view_files = self.views.lookup_view()
361
 
        else:
362
 
            view_files = []
363
 
        new_list = []
364
 
        # self.relpath exists as a "thunk" to osutils, but canonical_relpath
365
 
        # doesn't - fix that up here before we enter the loop.
366
 
        if canonicalize:
367
 
            fixer = lambda p: osutils.canonical_relpath(self.basedir, p)
368
 
        else:
369
 
            fixer = self.relpath
370
 
        for filename in file_list:
371
 
            relpath = fixer(osutils.dereference_path(filename))
372
 
            if view_files and not osutils.is_inside_any(view_files, relpath):
373
 
                raise errors.FileOutsideView(filename, view_files)
374
 
            new_list.append(relpath)
375
 
        return new_list
376
 
 
377
 
    @staticmethod
378
344
    def open_downlevel(path=None):
379
345
        """Open an unsupported working tree.
380
346
 
393
359
                return True, None
394
360
            else:
395
361
                return True, tree
396
 
        t = transport.get_transport(location)
397
 
        iterator = bzrdir.BzrDir.find_bzrdirs(t, evaluate=evaluate,
 
362
        transport = get_transport(location)
 
363
        iterator = bzrdir.BzrDir.find_bzrdirs(transport, evaluate=evaluate,
398
364
                                              list_current=list_current)
399
 
        return [tr for tr in iterator if tr is not None]
 
365
        return [t for t in iterator if t is not None]
 
366
 
 
367
    # should be deprecated - this is slow and in any case treating them as a
 
368
    # container is (we now know) bad style -- mbp 20070302
 
369
    ## @deprecated_method(zero_fifteen)
 
370
    def __iter__(self):
 
371
        """Iterate through file_ids for this tree.
 
372
 
 
373
        file_ids are in a WorkingTree if they are in the working inventory
 
374
        and the working file exists.
 
375
        """
 
376
        inv = self._inventory
 
377
        for path, ie in inv.iter_entries():
 
378
            if osutils.lexists(self.abspath(path)):
 
379
                yield ie.file_id
400
380
 
401
381
    def all_file_ids(self):
402
382
        """See Tree.iter_all_file_ids"""
403
 
        raise NotImplementedError(self.all_file_ids)
 
383
        return set(self.inventory)
404
384
 
405
385
    def __repr__(self):
406
386
        return "<%s of %s>" % (self.__class__.__name__,
435
415
            return self.branch.repository.revision_tree(revision_id)
436
416
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
437
417
            # the basis tree *may* be a ghost or a low level error may have
438
 
            # occurred. If the revision is present, its a problem, if its not
 
418
            # occured. If the revision is present, its a problem, if its not
439
419
            # its a ghost.
440
420
            if self.branch.repository.has_revision(revision_id):
441
421
                raise
461
441
        return self.get_file_with_stat(file_id, path, filtered=filtered)[0]
462
442
 
463
443
    def get_file_with_stat(self, file_id, path=None, filtered=True,
464
 
                           _fstat=osutils.fstat):
465
 
        """See Tree.get_file_with_stat."""
 
444
        _fstat=os.fstat):
 
445
        """See MutableTree.get_file_with_stat."""
466
446
        if path is None:
467
447
            path = self.id2path(file_id)
468
448
        file_obj = self.get_file_byname(path, filtered=False)
469
449
        stat_value = _fstat(file_obj.fileno())
470
 
        if filtered and self.supports_content_filtering():
 
450
        if self.supports_content_filtering() and filtered:
471
451
            filters = self._content_filter_stack(path)
472
 
            file_obj = _mod_filters.filtered_input_file(file_obj, filters)
 
452
            file_obj = filtered_input_file(file_obj, filters)
473
453
        return (file_obj, stat_value)
474
454
 
475
455
    def get_file_text(self, file_id, path=None, filtered=True):
476
 
        my_file = self.get_file(file_id, path=path, filtered=filtered)
477
 
        try:
478
 
            return my_file.read()
479
 
        finally:
480
 
            my_file.close()
 
456
        return self.get_file(file_id, path=path, filtered=filtered).read()
481
457
 
482
458
    def get_file_byname(self, filename, filtered=True):
483
459
        path = self.abspath(filename)
484
460
        f = file(path, 'rb')
485
 
        if filtered and self.supports_content_filtering():
 
461
        if self.supports_content_filtering() and filtered:
486
462
            filters = self._content_filter_stack(filename)
487
 
            return _mod_filters.filtered_input_file(f, filters)
 
463
            return filtered_input_file(f, filters)
488
464
        else:
489
465
            return f
490
466
 
496
472
        finally:
497
473
            file.close()
498
474
 
 
475
    @needs_read_lock
 
476
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
 
477
        """See Tree.annotate_iter
 
478
 
 
479
        This implementation will use the basis tree implementation if possible.
 
480
        Lines not in the basis are attributed to CURRENT_REVISION
 
481
 
 
482
        If there are pending merges, lines added by those merges will be
 
483
        incorrectly attributed to CURRENT_REVISION (but after committing, the
 
484
        attribution will be correct).
 
485
        """
 
486
        basis = self.basis_tree()
 
487
        basis.lock_read()
 
488
        try:
 
489
            changes = self.iter_changes(basis, True, [self.id2path(file_id)],
 
490
                require_versioned=True).next()
 
491
            changed_content, kind = changes[2], changes[6]
 
492
            if not changed_content:
 
493
                return basis.annotate_iter(file_id)
 
494
            if kind[1] is None:
 
495
                return None
 
496
            import annotate
 
497
            if kind[0] != 'file':
 
498
                old_lines = []
 
499
            else:
 
500
                old_lines = list(basis.annotate_iter(file_id))
 
501
            old = [old_lines]
 
502
            for tree in self.branch.repository.revision_trees(
 
503
                self.get_parent_ids()[1:]):
 
504
                if file_id not in tree:
 
505
                    continue
 
506
                old.append(list(tree.annotate_iter(file_id)))
 
507
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
508
                                       default_revision)
 
509
        finally:
 
510
            basis.unlock()
 
511
 
 
512
    def _get_ancestors(self, default_revision):
 
513
        ancestors = set([default_revision])
 
514
        for parent_id in self.get_parent_ids():
 
515
            ancestors.update(self.branch.repository.get_ancestry(
 
516
                             parent_id, topo_sorted=False))
 
517
        return ancestors
 
518
 
499
519
    def get_parent_ids(self):
500
520
        """See Tree.get_parent_ids.
501
521
 
508
528
        else:
509
529
            parents = [last_rev]
510
530
        try:
511
 
            merges_bytes = self._transport.get_bytes('pending-merges')
 
531
            merges_file = self._transport.get('pending-merges')
512
532
        except errors.NoSuchFile:
513
533
            pass
514
534
        else:
515
 
            for l in osutils.split_lines(merges_bytes):
 
535
            for l in merges_file.readlines():
516
536
                revision_id = l.rstrip('\n')
517
537
                parents.append(revision_id)
518
538
        return parents
519
539
 
 
540
    @needs_read_lock
520
541
    def get_root_id(self):
521
542
        """Return the id of this trees root"""
522
 
        raise NotImplementedError(self.get_root_id)
 
543
        return self._inventory.root.file_id
 
544
 
 
545
    def _get_store_filename(self, file_id):
 
546
        ## XXX: badly named; this is not in the store at all
 
547
        return self.abspath(self.id2path(file_id))
523
548
 
524
549
    @needs_read_lock
525
550
    def clone(self, to_bzrdir, revision_id=None):
532
557
 
533
558
        revision
534
559
            If not None, the cloned tree will have its last revision set to
535
 
            revision, and difference between the source trees last revision
 
560
            revision, and and difference between the source trees last revision
536
561
            and this one merged in.
537
562
        """
538
563
        # assumes the target bzr dir format is compatible.
555
580
    def id2abspath(self, file_id):
556
581
        return self.abspath(self.id2path(file_id))
557
582
 
558
 
    def _check_for_tree_references(self, iterator):
559
 
        """See if directories have become tree-references."""
560
 
        blocked_parent_ids = set()
561
 
        for path, ie in iterator:
562
 
            if ie.parent_id in blocked_parent_ids:
563
 
                # This entry was pruned because one of its parents became a
564
 
                # TreeReference. If this is a directory, mark it as blocked.
565
 
                if ie.kind == 'directory':
566
 
                    blocked_parent_ids.add(ie.file_id)
567
 
                continue
568
 
            if ie.kind == 'directory' and self._directory_is_tree_reference(path):
569
 
                # This InventoryDirectory needs to be a TreeReference
570
 
                ie = inventory.TreeReference(ie.file_id, ie.name, ie.parent_id)
571
 
                blocked_parent_ids.add(ie.file_id)
572
 
            yield path, ie
573
 
 
574
 
    def iter_entries_by_dir(self, specific_file_ids=None, yield_parents=False):
575
 
        """See Tree.iter_entries_by_dir()"""
576
 
        # The only trick here is that if we supports_tree_reference then we
577
 
        # need to detect if a directory becomes a tree-reference.
578
 
        iterator = super(WorkingTree, self).iter_entries_by_dir(
579
 
                specific_file_ids=specific_file_ids,
580
 
                yield_parents=yield_parents)
581
 
        if not self.supports_tree_reference():
582
 
            return iterator
583
 
        else:
584
 
            return self._check_for_tree_references(iterator)
 
583
    def has_id(self, file_id):
 
584
        # files that have been deleted are excluded
 
585
        inv = self.inventory
 
586
        if not inv.has_id(file_id):
 
587
            return False
 
588
        path = inv.id2path(file_id)
 
589
        return osutils.lexists(self.abspath(path))
 
590
 
 
591
    def has_or_had_id(self, file_id):
 
592
        if file_id == self.inventory.root.file_id:
 
593
            return True
 
594
        return self.inventory.has_id(file_id)
 
595
 
 
596
    __contains__ = has_id
585
597
 
586
598
    def get_file_size(self, file_id):
587
599
        """See Tree.get_file_size"""
588
 
        # XXX: this returns the on-disk size; it should probably return the
589
 
        # canonical size
590
600
        try:
591
601
            return os.path.getsize(self.id2abspath(file_id))
592
602
        except OSError, e:
595
605
            else:
596
606
                return None
597
607
 
 
608
    @needs_read_lock
598
609
    def get_file_sha1(self, file_id, path=None, stat_value=None):
599
 
        # FIXME: Shouldn't this be in Tree?
600
 
        raise NotImplementedError(self.get_file_sha1)
 
610
        if not path:
 
611
            path = self._inventory.id2path(file_id)
 
612
        return self._hashcache.get_sha1(path, stat_value)
 
613
 
 
614
    def get_file_mtime(self, file_id, path=None):
 
615
        if not path:
 
616
            path = self.inventory.id2path(file_id)
 
617
        return os.lstat(self.abspath(path)).st_mtime
 
618
 
 
619
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
 
620
        file_id = self.path2id(path)
 
621
        return self._inventory[file_id].executable
 
622
 
 
623
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
624
        mode = stat_result.st_mode
 
625
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
626
 
 
627
    if not supports_executable():
 
628
        def is_executable(self, file_id, path=None):
 
629
            return self._inventory[file_id].executable
 
630
 
 
631
        _is_executable_from_path_and_stat = \
 
632
            _is_executable_from_path_and_stat_from_basis
 
633
    else:
 
634
        def is_executable(self, file_id, path=None):
 
635
            if not path:
 
636
                path = self.id2path(file_id)
 
637
            mode = os.lstat(self.abspath(path)).st_mode
 
638
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
639
 
 
640
        _is_executable_from_path_and_stat = \
 
641
            _is_executable_from_path_and_stat_from_stat
 
642
 
 
643
    @needs_tree_write_lock
 
644
    def _add(self, files, ids, kinds):
 
645
        """See MutableTree._add."""
 
646
        # TODO: Re-adding a file that is removed in the working copy
 
647
        # should probably put it back with the previous ID.
 
648
        # the read and write working inventory should not occur in this
 
649
        # function - they should be part of lock_write and unlock.
 
650
        inv = self.inventory
 
651
        for f, file_id, kind in zip(files, ids, kinds):
 
652
            if file_id is None:
 
653
                inv.add_path(f, kind=kind)
 
654
            else:
 
655
                inv.add_path(f, kind=kind, file_id=file_id)
 
656
            self._inventory_is_modified = True
601
657
 
602
658
    @needs_tree_write_lock
603
659
    def _gather_kinds(self, files, kinds):
619
675
        and setting the list to its value plus revision_id.
620
676
 
621
677
        :param revision_id: The revision id to add to the parent list. It may
622
 
            be a ghost revision as long as its not the first parent to be
623
 
            added, or the allow_leftmost_as_ghost parameter is set True.
 
678
        be a ghost revision as long as its not the first parent to be added,
 
679
        or the allow_leftmost_as_ghost parameter is set True.
624
680
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
625
681
        """
626
682
        parents = self.get_parent_ids() + [revision_id]
677
733
            raise
678
734
        kind = _mapper(stat_result.st_mode)
679
735
        if kind == 'file':
680
 
            return self._file_content_summary(path, stat_result)
 
736
            size = stat_result.st_size
 
737
            # try for a stat cache lookup
 
738
            executable = self._is_executable_from_path_and_stat(path, stat_result)
 
739
            return (kind, size, executable, self._sha_from_stat(
 
740
                path, stat_result))
681
741
        elif kind == 'directory':
682
742
            # perhaps it looks like a plain directory, but it's really a
683
743
            # reference.
685
745
                kind = 'tree-reference'
686
746
            return kind, None, None, None
687
747
        elif kind == 'symlink':
688
 
            target = osutils.readlink(abspath)
689
 
            return ('symlink', None, None, target)
 
748
            return ('symlink', None, None,
 
749
                    os.readlink(abspath.encode(osutils._fs_enc)
 
750
                                ).decode(osutils._fs_enc))
690
751
        else:
691
752
            return (kind, None, None, None)
692
753
 
693
 
    def _file_content_summary(self, path, stat_result):
694
 
        size = stat_result.st_size
695
 
        executable = self._is_executable_from_path_and_stat(path, stat_result)
696
 
        # try for a stat cache lookup
697
 
        return ('file', size, executable, self._sha_from_stat(
698
 
            path, stat_result))
699
 
 
700
754
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
701
755
        """Common ghost checking functionality from set_parent_*.
702
756
 
729
783
            if revision_id in heads and revision_id not in new_revision_ids:
730
784
                new_revision_ids.append(revision_id)
731
785
        if new_revision_ids != revision_ids:
732
 
            mutter('requested to set revision_ids = %s,'
 
786
            trace.mutter('requested to set revision_ids = %s,'
733
787
                         ' but filtered to %s', revision_ids, new_revision_ids)
734
788
        return new_revision_ids
735
789
 
761
815
        self._set_merges_from_parent_ids(revision_ids)
762
816
 
763
817
    @needs_tree_write_lock
 
818
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
 
819
        """See MutableTree.set_parent_trees."""
 
820
        parent_ids = [rev for (rev, tree) in parents_list]
 
821
        for revision_id in parent_ids:
 
822
            _mod_revision.check_not_reserved_id(revision_id)
 
823
 
 
824
        self._check_parents_for_ghosts(parent_ids,
 
825
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
826
 
 
827
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
 
828
 
 
829
        if len(parent_ids) == 0:
 
830
            leftmost_parent_id = _mod_revision.NULL_REVISION
 
831
            leftmost_parent_tree = None
 
832
        else:
 
833
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
 
834
 
 
835
        if self._change_last_revision(leftmost_parent_id):
 
836
            if leftmost_parent_tree is None:
 
837
                # If we don't have a tree, fall back to reading the
 
838
                # parent tree from the repository.
 
839
                self._cache_basis_inventory(leftmost_parent_id)
 
840
            else:
 
841
                inv = leftmost_parent_tree.inventory
 
842
                xml = self._create_basis_xml_from_inventory(
 
843
                                        leftmost_parent_id, inv)
 
844
                self._write_basis_inventory(xml)
 
845
        self._set_merges_from_parent_ids(parent_ids)
 
846
 
 
847
    @needs_tree_write_lock
764
848
    def set_pending_merges(self, rev_list):
765
849
        parents = self.get_parent_ids()
766
850
        leftmost = parents[:1]
771
855
    def set_merge_modified(self, modified_hashes):
772
856
        def iter_stanzas():
773
857
            for file_id, hash in modified_hashes.iteritems():
774
 
                yield _mod_rio.Stanza(file_id=file_id.decode('utf8'),
775
 
                    hash=hash)
 
858
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
776
859
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
777
860
 
778
861
    def _sha_from_stat(self, path, stat_result):
787
870
 
788
871
    def _put_rio(self, filename, stanzas, header):
789
872
        self._must_be_locked()
790
 
        my_file = _mod_rio.rio_file(stanzas, header)
 
873
        my_file = rio_file(stanzas, header)
791
874
        self._transport.put_file(filename, my_file,
792
875
            mode=self.bzrdir._get_file_mode())
793
876
 
794
877
    @needs_write_lock # because merge pulls data into the branch.
795
878
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
796
 
                          merge_type=None, force=False):
 
879
        merge_type=None):
797
880
        """Merge from a branch into this working tree.
798
881
 
799
882
        :param branch: The branch to merge from.
803
886
            branch.last_revision().
804
887
        """
805
888
        from bzrlib.merge import Merger, Merge3Merger
806
 
        merger = Merger(self.branch, this_tree=self)
807
 
        # check that there are no local alterations
808
 
        if not force and self.has_changes():
809
 
            raise errors.UncommittedChanges(self)
810
 
        if to_revision is None:
811
 
            to_revision = _mod_revision.ensure_null(branch.last_revision())
812
 
        merger.other_rev_id = to_revision
813
 
        if _mod_revision.is_null(merger.other_rev_id):
814
 
            raise errors.NoCommits(branch)
815
 
        self.branch.fetch(branch, last_revision=merger.other_rev_id)
816
 
        merger.other_basis = merger.other_rev_id
817
 
        merger.other_tree = self.branch.repository.revision_tree(
818
 
            merger.other_rev_id)
819
 
        merger.other_branch = branch
820
 
        if from_revision is None:
821
 
            merger.find_base()
822
 
        else:
823
 
            merger.set_base_revision(from_revision, branch)
824
 
        if merger.base_rev_id == merger.other_rev_id:
825
 
            raise errors.PointlessMerge
826
 
        merger.backup_files = False
827
 
        if merge_type is None:
828
 
            merger.merge_type = Merge3Merger
829
 
        else:
830
 
            merger.merge_type = merge_type
831
 
        merger.set_interesting_files(None)
832
 
        merger.show_base = False
833
 
        merger.reprocess = False
834
 
        conflicts = merger.do_merge()
835
 
        merger.set_pending()
 
889
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
890
        try:
 
891
            merger = Merger(self.branch, this_tree=self, pb=pb)
 
892
            merger.pp = ProgressPhase("Merge phase", 5, pb)
 
893
            merger.pp.next_phase()
 
894
            # check that there are no
 
895
            # local alterations
 
896
            merger.check_basis(check_clean=True, require_commits=False)
 
897
            if to_revision is None:
 
898
                to_revision = _mod_revision.ensure_null(branch.last_revision())
 
899
            merger.other_rev_id = to_revision
 
900
            if _mod_revision.is_null(merger.other_rev_id):
 
901
                raise errors.NoCommits(branch)
 
902
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
 
903
            merger.other_basis = merger.other_rev_id
 
904
            merger.other_tree = self.branch.repository.revision_tree(
 
905
                merger.other_rev_id)
 
906
            merger.other_branch = branch
 
907
            merger.pp.next_phase()
 
908
            if from_revision is None:
 
909
                merger.find_base()
 
910
            else:
 
911
                merger.set_base_revision(from_revision, branch)
 
912
            if merger.base_rev_id == merger.other_rev_id:
 
913
                raise errors.PointlessMerge
 
914
            merger.backup_files = False
 
915
            if merge_type is None:
 
916
                merger.merge_type = Merge3Merger
 
917
            else:
 
918
                merger.merge_type = merge_type
 
919
            merger.set_interesting_files(None)
 
920
            merger.show_base = False
 
921
            merger.reprocess = False
 
922
            conflicts = merger.do_merge()
 
923
            merger.set_pending()
 
924
        finally:
 
925
            pb.finished()
836
926
        return conflicts
837
927
 
 
928
    @needs_read_lock
838
929
    def merge_modified(self):
839
930
        """Return a dictionary of files modified by a merge.
840
931
 
845
936
        This returns a map of file_id->sha1, containing only files which are
846
937
        still in the working inventory and have that text hash.
847
938
        """
848
 
        raise NotImplementedError(self.merge_modified)
 
939
        try:
 
940
            hashfile = self._transport.get('merge-hashes')
 
941
        except errors.NoSuchFile:
 
942
            return {}
 
943
        try:
 
944
            merge_hashes = {}
 
945
            try:
 
946
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
 
947
                    raise errors.MergeModifiedFormatError()
 
948
            except StopIteration:
 
949
                raise errors.MergeModifiedFormatError()
 
950
            for s in RioReader(hashfile):
 
951
                # RioReader reads in Unicode, so convert file_ids back to utf8
 
952
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
 
953
                if file_id not in self.inventory:
 
954
                    continue
 
955
                text_hash = s.get("hash")
 
956
                if text_hash == self.get_file_sha1(file_id):
 
957
                    merge_hashes[file_id] = text_hash
 
958
            return merge_hashes
 
959
        finally:
 
960
            hashfile.close()
849
961
 
850
962
    @needs_write_lock
851
963
    def mkdir(self, path, file_id=None):
856
968
        self.add(path, file_id, 'directory')
857
969
        return file_id
858
970
 
859
 
    def get_symlink_target(self, file_id, path=None):
860
 
        if path is not None:
861
 
            abspath = self.abspath(path)
862
 
        else:
863
 
            abspath = self.id2abspath(file_id)
864
 
        target = osutils.readlink(abspath)
865
 
        return target
 
971
    def get_symlink_target(self, file_id):
 
972
        return os.readlink(self.id2abspath(file_id).encode(osutils._fs_enc))
866
973
 
 
974
    @needs_write_lock
867
975
    def subsume(self, other_tree):
868
 
        raise NotImplementedError(self.subsume)
 
976
        def add_children(inventory, entry):
 
977
            for child_entry in entry.children.values():
 
978
                inventory._byid[child_entry.file_id] = child_entry
 
979
                if child_entry.kind == 'directory':
 
980
                    add_children(inventory, child_entry)
 
981
        if other_tree.get_root_id() == self.get_root_id():
 
982
            raise errors.BadSubsumeSource(self, other_tree,
 
983
                                          'Trees have the same root')
 
984
        try:
 
985
            other_tree_path = self.relpath(other_tree.basedir)
 
986
        except errors.PathNotChild:
 
987
            raise errors.BadSubsumeSource(self, other_tree,
 
988
                'Tree is not contained by the other')
 
989
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
 
990
        if new_root_parent is None:
 
991
            raise errors.BadSubsumeSource(self, other_tree,
 
992
                'Parent directory is not versioned.')
 
993
        # We need to ensure that the result of a fetch will have a
 
994
        # versionedfile for the other_tree root, and only fetching into
 
995
        # RepositoryKnit2 guarantees that.
 
996
        if not self.branch.repository.supports_rich_root():
 
997
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
 
998
        other_tree.lock_tree_write()
 
999
        try:
 
1000
            new_parents = other_tree.get_parent_ids()
 
1001
            other_root = other_tree.inventory.root
 
1002
            other_root.parent_id = new_root_parent
 
1003
            other_root.name = osutils.basename(other_tree_path)
 
1004
            self.inventory.add(other_root)
 
1005
            add_children(self.inventory, other_root)
 
1006
            self._write_inventory(self.inventory)
 
1007
            # normally we don't want to fetch whole repositories, but i think
 
1008
            # here we really do want to consolidate the whole thing.
 
1009
            for parent_id in other_tree.get_parent_ids():
 
1010
                self.branch.fetch(other_tree.branch, parent_id)
 
1011
                self.add_parent_tree_id(parent_id)
 
1012
        finally:
 
1013
            other_tree.unlock()
 
1014
        other_tree.bzrdir.retire_bzrdir()
869
1015
 
870
1016
    def _setup_directory_is_tree_reference(self):
871
1017
        if self._branch.repository._format.supports_tree_reference:
893
1039
        # checkout in a subdirectory.  This can be avoided by not adding
894
1040
        # it.  mbp 20070306
895
1041
 
 
1042
    @needs_tree_write_lock
896
1043
    def extract(self, file_id, format=None):
897
1044
        """Extract a subtree from this tree.
898
1045
 
899
1046
        A new branch will be created, relative to the path for this tree.
900
1047
        """
901
 
        raise NotImplementedError(self.extract)
 
1048
        self.flush()
 
1049
        def mkdirs(path):
 
1050
            segments = osutils.splitpath(path)
 
1051
            transport = self.branch.bzrdir.root_transport
 
1052
            for name in segments:
 
1053
                transport = transport.clone(name)
 
1054
                transport.ensure_base()
 
1055
            return transport
 
1056
 
 
1057
        sub_path = self.id2path(file_id)
 
1058
        branch_transport = mkdirs(sub_path)
 
1059
        if format is None:
 
1060
            format = self.bzrdir.cloning_metadir()
 
1061
        branch_transport.ensure_base()
 
1062
        branch_bzrdir = format.initialize_on_transport(branch_transport)
 
1063
        try:
 
1064
            repo = branch_bzrdir.find_repository()
 
1065
        except errors.NoRepositoryPresent:
 
1066
            repo = branch_bzrdir.create_repository()
 
1067
        if not repo.supports_rich_root():
 
1068
            raise errors.RootNotRich()
 
1069
        new_branch = branch_bzrdir.create_branch()
 
1070
        new_branch.pull(self.branch)
 
1071
        for parent_id in self.get_parent_ids():
 
1072
            new_branch.fetch(self.branch, parent_id)
 
1073
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
 
1074
        if tree_transport.base != branch_transport.base:
 
1075
            tree_bzrdir = format.initialize_on_transport(tree_transport)
 
1076
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
 
1077
        else:
 
1078
            tree_bzrdir = branch_bzrdir
 
1079
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
 
1080
        wt.set_parent_ids(self.get_parent_ids())
 
1081
        my_inv = self.inventory
 
1082
        child_inv = Inventory(root_id=None)
 
1083
        new_root = my_inv[file_id]
 
1084
        my_inv.remove_recursive_id(file_id)
 
1085
        new_root.parent_id = None
 
1086
        child_inv.add(new_root)
 
1087
        self._write_inventory(my_inv)
 
1088
        wt._write_inventory(child_inv)
 
1089
        return wt
 
1090
 
 
1091
    def _serialize(self, inventory, out_file):
 
1092
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
 
1093
            working=True)
 
1094
 
 
1095
    def _deserialize(selt, in_file):
 
1096
        return xml5.serializer_v5.read_inventory(in_file)
902
1097
 
903
1098
    def flush(self):
904
 
        """Write the in memory meta data to disk."""
905
 
        raise NotImplementedError(self.flush)
 
1099
        """Write the in memory inventory to disk."""
 
1100
        # TODO: Maybe this should only write on dirty ?
 
1101
        if self._control_files._lock_mode != 'w':
 
1102
            raise errors.NotWriteLocked(self)
 
1103
        sio = StringIO()
 
1104
        self._serialize(self._inventory, sio)
 
1105
        sio.seek(0)
 
1106
        self._transport.put_file('inventory', sio,
 
1107
            mode=self.bzrdir._get_file_mode())
 
1108
        self._inventory_is_modified = False
906
1109
 
907
1110
    def _kind(self, relpath):
908
1111
        return osutils.file_kind(self.abspath(relpath))
909
1112
 
910
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
911
 
        """List all files as (path, class, kind, id, entry).
 
1113
    def list_files(self, include_root=False):
 
1114
        """Recursively list all files as (path, class, kind, id, entry).
912
1115
 
913
1116
        Lists, but does not descend into unversioned directories.
 
1117
 
914
1118
        This does not include files that have been deleted in this
915
 
        tree. Skips the control directory.
 
1119
        tree.
916
1120
 
917
 
        :param include_root: if True, return an entry for the root
918
 
        :param from_dir: start from this directory or None for the root
919
 
        :param recursive: whether to recurse into subdirectories or not
 
1121
        Skips the control directory.
920
1122
        """
921
 
        raise NotImplementedError(self.list_files)
922
 
 
923
 
    def move(self, from_paths, to_dir=None, after=False):
 
1123
        # list_files is an iterator, so @needs_read_lock doesn't work properly
 
1124
        # with it. So callers should be careful to always read_lock the tree.
 
1125
        if not self.is_locked():
 
1126
            raise errors.ObjectNotLocked(self)
 
1127
 
 
1128
        inv = self.inventory
 
1129
        if include_root is True:
 
1130
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
 
1131
        # Convert these into local objects to save lookup times
 
1132
        pathjoin = osutils.pathjoin
 
1133
        file_kind = self._kind
 
1134
 
 
1135
        # transport.base ends in a slash, we want the piece
 
1136
        # between the last two slashes
 
1137
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
 
1138
 
 
1139
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
 
1140
 
 
1141
        # directory file_id, relative path, absolute path, reverse sorted children
 
1142
        children = os.listdir(self.basedir)
 
1143
        children.sort()
 
1144
        # jam 20060527 The kernel sized tree seems equivalent whether we
 
1145
        # use a deque and popleft to keep them sorted, or if we use a plain
 
1146
        # list and just reverse() them.
 
1147
        children = collections.deque(children)
 
1148
        stack = [(inv.root.file_id, u'', self.basedir, children)]
 
1149
        while stack:
 
1150
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
 
1151
 
 
1152
            while children:
 
1153
                f = children.popleft()
 
1154
                ## TODO: If we find a subdirectory with its own .bzr
 
1155
                ## directory, then that is a separate tree and we
 
1156
                ## should exclude it.
 
1157
 
 
1158
                # the bzrdir for this tree
 
1159
                if transport_base_dir == f:
 
1160
                    continue
 
1161
 
 
1162
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
 
1163
                # and 'f' doesn't begin with one, we can do a string op, rather
 
1164
                # than the checks of pathjoin(), all relative paths will have an extra slash
 
1165
                # at the beginning
 
1166
                fp = from_dir_relpath + '/' + f
 
1167
 
 
1168
                # absolute path
 
1169
                fap = from_dir_abspath + '/' + f
 
1170
 
 
1171
                f_ie = inv.get_child(from_dir_id, f)
 
1172
                if f_ie:
 
1173
                    c = 'V'
 
1174
                elif self.is_ignored(fp[1:]):
 
1175
                    c = 'I'
 
1176
                else:
 
1177
                    # we may not have found this file, because of a unicode issue
 
1178
                    f_norm, can_access = osutils.normalized_filename(f)
 
1179
                    if f == f_norm or not can_access:
 
1180
                        # No change, so treat this file normally
 
1181
                        c = '?'
 
1182
                    else:
 
1183
                        # this file can be accessed by a normalized path
 
1184
                        # check again if it is versioned
 
1185
                        # these lines are repeated here for performance
 
1186
                        f = f_norm
 
1187
                        fp = from_dir_relpath + '/' + f
 
1188
                        fap = from_dir_abspath + '/' + f
 
1189
                        f_ie = inv.get_child(from_dir_id, f)
 
1190
                        if f_ie:
 
1191
                            c = 'V'
 
1192
                        elif self.is_ignored(fp[1:]):
 
1193
                            c = 'I'
 
1194
                        else:
 
1195
                            c = '?'
 
1196
 
 
1197
                fk = file_kind(fap)
 
1198
 
 
1199
                # make a last minute entry
 
1200
                if f_ie:
 
1201
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
 
1202
                else:
 
1203
                    try:
 
1204
                        yield fp[1:], c, fk, None, fk_entries[fk]()
 
1205
                    except KeyError:
 
1206
                        yield fp[1:], c, fk, None, TreeEntry()
 
1207
                    continue
 
1208
 
 
1209
                if fk != 'directory':
 
1210
                    continue
 
1211
 
 
1212
                # But do this child first
 
1213
                new_children = os.listdir(fap)
 
1214
                new_children.sort()
 
1215
                new_children = collections.deque(new_children)
 
1216
                stack.append((f_ie.file_id, fp, fap, new_children))
 
1217
                # Break out of inner loop,
 
1218
                # so that we start outer loop with child
 
1219
                break
 
1220
            else:
 
1221
                # if we finished all children, pop it off the stack
 
1222
                stack.pop()
 
1223
 
 
1224
    @needs_tree_write_lock
 
1225
    def move(self, from_paths, to_dir=None, after=False, **kwargs):
924
1226
        """Rename files.
925
1227
 
926
 
        to_dir must be known to the working tree.
 
1228
        to_dir must exist in the inventory.
927
1229
 
928
1230
        If to_dir exists and is a directory, the files are moved into
929
1231
        it, keeping their old names.
935
1237
        independently.
936
1238
 
937
1239
        The first mode moves the file in the filesystem and updates the
938
 
        working tree metadata. The second mode only updates the working tree
939
 
        metadata without touching the file on the filesystem.
 
1240
        inventory. The second mode only updates the inventory without
 
1241
        touching the file on the filesystem. This is the new mode introduced
 
1242
        in version 0.15.
940
1243
 
941
1244
        move uses the second mode if 'after == True' and the target is not
942
1245
        versioned but present in the working tree.
954
1257
        This returns a list of (from_path, to_path) pairs for each
955
1258
        entry that is moved.
956
1259
        """
957
 
        raise NotImplementedError(self.move)
 
1260
        rename_entries = []
 
1261
        rename_tuples = []
 
1262
 
 
1263
        # check for deprecated use of signature
 
1264
        if to_dir is None:
 
1265
            to_dir = kwargs.get('to_name', None)
 
1266
            if to_dir is None:
 
1267
                raise TypeError('You must supply a target directory')
 
1268
            else:
 
1269
                symbol_versioning.warn('The parameter to_name was deprecated'
 
1270
                                       ' in version 0.13. Use to_dir instead',
 
1271
                                       DeprecationWarning)
 
1272
 
 
1273
        # check destination directory
 
1274
        if isinstance(from_paths, basestring):
 
1275
            raise ValueError()
 
1276
        inv = self.inventory
 
1277
        to_abs = self.abspath(to_dir)
 
1278
        if not isdir(to_abs):
 
1279
            raise errors.BzrMoveFailedError('',to_dir,
 
1280
                errors.NotADirectory(to_abs))
 
1281
        if not self.has_filename(to_dir):
 
1282
            raise errors.BzrMoveFailedError('',to_dir,
 
1283
                errors.NotInWorkingDirectory(to_dir))
 
1284
        to_dir_id = inv.path2id(to_dir)
 
1285
        if to_dir_id is None:
 
1286
            raise errors.BzrMoveFailedError('',to_dir,
 
1287
                errors.NotVersionedError(path=str(to_dir)))
 
1288
 
 
1289
        to_dir_ie = inv[to_dir_id]
 
1290
        if to_dir_ie.kind != 'directory':
 
1291
            raise errors.BzrMoveFailedError('',to_dir,
 
1292
                errors.NotADirectory(to_abs))
 
1293
 
 
1294
        # create rename entries and tuples
 
1295
        for from_rel in from_paths:
 
1296
            from_tail = splitpath(from_rel)[-1]
 
1297
            from_id = inv.path2id(from_rel)
 
1298
            if from_id is None:
 
1299
                raise errors.BzrMoveFailedError(from_rel,to_dir,
 
1300
                    errors.NotVersionedError(path=str(from_rel)))
 
1301
 
 
1302
            from_entry = inv[from_id]
 
1303
            from_parent_id = from_entry.parent_id
 
1304
            to_rel = pathjoin(to_dir, from_tail)
 
1305
            rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
 
1306
                                         from_id=from_id,
 
1307
                                         from_tail=from_tail,
 
1308
                                         from_parent_id=from_parent_id,
 
1309
                                         to_rel=to_rel, to_tail=from_tail,
 
1310
                                         to_parent_id=to_dir_id)
 
1311
            rename_entries.append(rename_entry)
 
1312
            rename_tuples.append((from_rel, to_rel))
 
1313
 
 
1314
        # determine which move mode to use. checks also for movability
 
1315
        rename_entries = self._determine_mv_mode(rename_entries, after)
 
1316
 
 
1317
        original_modified = self._inventory_is_modified
 
1318
        try:
 
1319
            if len(from_paths):
 
1320
                self._inventory_is_modified = True
 
1321
            self._move(rename_entries)
 
1322
        except:
 
1323
            # restore the inventory on error
 
1324
            self._inventory_is_modified = original_modified
 
1325
            raise
 
1326
        self._write_inventory(inv)
 
1327
        return rename_tuples
 
1328
 
 
1329
    def _determine_mv_mode(self, rename_entries, after=False):
 
1330
        """Determines for each from-to pair if both inventory and working tree
 
1331
        or only the inventory has to be changed.
 
1332
 
 
1333
        Also does basic plausability tests.
 
1334
        """
 
1335
        inv = self.inventory
 
1336
 
 
1337
        for rename_entry in rename_entries:
 
1338
            # store to local variables for easier reference
 
1339
            from_rel = rename_entry.from_rel
 
1340
            from_id = rename_entry.from_id
 
1341
            to_rel = rename_entry.to_rel
 
1342
            to_id = inv.path2id(to_rel)
 
1343
            only_change_inv = False
 
1344
 
 
1345
            # check the inventory for source and destination
 
1346
            if from_id is None:
 
1347
                raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1348
                    errors.NotVersionedError(path=str(from_rel)))
 
1349
            if to_id is not None:
 
1350
                raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1351
                    errors.AlreadyVersionedError(path=str(to_rel)))
 
1352
 
 
1353
            # try to determine the mode for rename (only change inv or change
 
1354
            # inv and file system)
 
1355
            if after:
 
1356
                if not self.has_filename(to_rel):
 
1357
                    raise errors.BzrMoveFailedError(from_id,to_rel,
 
1358
                        errors.NoSuchFile(path=str(to_rel),
 
1359
                        extra="New file has not been created yet"))
 
1360
                only_change_inv = True
 
1361
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
 
1362
                only_change_inv = True
 
1363
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
 
1364
                only_change_inv = False
 
1365
            elif (not self.case_sensitive
 
1366
                  and from_rel.lower() == to_rel.lower()
 
1367
                  and self.has_filename(from_rel)):
 
1368
                only_change_inv = False
 
1369
            else:
 
1370
                # something is wrong, so lets determine what exactly
 
1371
                if not self.has_filename(from_rel) and \
 
1372
                   not self.has_filename(to_rel):
 
1373
                    raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1374
                        errors.PathsDoNotExist(paths=(str(from_rel),
 
1375
                        str(to_rel))))
 
1376
                else:
 
1377
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
 
1378
            rename_entry.only_change_inv = only_change_inv
 
1379
        return rename_entries
 
1380
 
 
1381
    def _move(self, rename_entries):
 
1382
        """Moves a list of files.
 
1383
 
 
1384
        Depending on the value of the flag 'only_change_inv', the
 
1385
        file will be moved on the file system or not.
 
1386
        """
 
1387
        inv = self.inventory
 
1388
        moved = []
 
1389
 
 
1390
        for entry in rename_entries:
 
1391
            try:
 
1392
                self._move_entry(entry)
 
1393
            except:
 
1394
                self._rollback_move(moved)
 
1395
                raise
 
1396
            moved.append(entry)
 
1397
 
 
1398
    def _rollback_move(self, moved):
 
1399
        """Try to rollback a previous move in case of an filesystem error."""
 
1400
        inv = self.inventory
 
1401
        for entry in moved:
 
1402
            try:
 
1403
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
 
1404
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
 
1405
                    entry.from_tail, entry.from_parent_id,
 
1406
                    entry.only_change_inv))
 
1407
            except errors.BzrMoveFailedError, e:
 
1408
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
 
1409
                        " The working tree is in an inconsistent state."
 
1410
                        " Please consider doing a 'bzr revert'."
 
1411
                        " Error message is: %s" % e)
 
1412
 
 
1413
    def _move_entry(self, entry):
 
1414
        inv = self.inventory
 
1415
        from_rel_abs = self.abspath(entry.from_rel)
 
1416
        to_rel_abs = self.abspath(entry.to_rel)
 
1417
        if from_rel_abs == to_rel_abs:
 
1418
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
 
1419
                "Source and target are identical.")
 
1420
 
 
1421
        if not entry.only_change_inv:
 
1422
            try:
 
1423
                osutils.rename(from_rel_abs, to_rel_abs)
 
1424
            except OSError, e:
 
1425
                raise errors.BzrMoveFailedError(entry.from_rel,
 
1426
                    entry.to_rel, e[1])
 
1427
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
958
1428
 
959
1429
    @needs_tree_write_lock
960
1430
    def rename_one(self, from_rel, to_rel, after=False):
964
1434
 
965
1435
        rename_one has several 'modes' to work. First, it can rename a physical
966
1436
        file and change the file_id. That is the normal mode. Second, it can
967
 
        only change the file_id without touching any physical file.
 
1437
        only change the file_id without touching any physical file. This is
 
1438
        the new mode introduced in version 0.15.
968
1439
 
969
 
        rename_one uses the second mode if 'after == True' and 'to_rel' is
970
 
        either not versioned or newly added, and present in the working tree.
 
1440
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
 
1441
        versioned but present in the working tree.
971
1442
 
972
1443
        rename_one uses the second mode if 'after == False' and 'from_rel' is
973
1444
        versioned but no longer in the working tree, and 'to_rel' is not
979
1450
 
980
1451
        Everything else results in an error.
981
1452
        """
982
 
        raise NotImplementedError(self.rename_one)
 
1453
        inv = self.inventory
 
1454
        rename_entries = []
 
1455
 
 
1456
        # create rename entries and tuples
 
1457
        from_tail = splitpath(from_rel)[-1]
 
1458
        from_id = inv.path2id(from_rel)
 
1459
        if from_id is None:
 
1460
            raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1461
                errors.NotVersionedError(path=str(from_rel)))
 
1462
        from_entry = inv[from_id]
 
1463
        from_parent_id = from_entry.parent_id
 
1464
        to_dir, to_tail = os.path.split(to_rel)
 
1465
        to_dir_id = inv.path2id(to_dir)
 
1466
        rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
 
1467
                                     from_id=from_id,
 
1468
                                     from_tail=from_tail,
 
1469
                                     from_parent_id=from_parent_id,
 
1470
                                     to_rel=to_rel, to_tail=to_tail,
 
1471
                                     to_parent_id=to_dir_id)
 
1472
        rename_entries.append(rename_entry)
 
1473
 
 
1474
        # determine which move mode to use. checks also for movability
 
1475
        rename_entries = self._determine_mv_mode(rename_entries, after)
 
1476
 
 
1477
        # check if the target changed directory and if the target directory is
 
1478
        # versioned
 
1479
        if to_dir_id is None:
 
1480
            raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1481
                errors.NotVersionedError(path=str(to_dir)))
 
1482
 
 
1483
        # all checks done. now we can continue with our actual work
 
1484
        mutter('rename_one:\n'
 
1485
               '  from_id   {%s}\n'
 
1486
               '  from_rel: %r\n'
 
1487
               '  to_rel:   %r\n'
 
1488
               '  to_dir    %r\n'
 
1489
               '  to_dir_id {%s}\n',
 
1490
               from_id, from_rel, to_rel, to_dir, to_dir_id)
 
1491
 
 
1492
        self._move(rename_entries)
 
1493
        self._write_inventory(inv)
 
1494
 
 
1495
    class _RenameEntry(object):
 
1496
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
 
1497
                     to_rel, to_tail, to_parent_id, only_change_inv=False):
 
1498
            self.from_rel = from_rel
 
1499
            self.from_id = from_id
 
1500
            self.from_tail = from_tail
 
1501
            self.from_parent_id = from_parent_id
 
1502
            self.to_rel = to_rel
 
1503
            self.to_tail = to_tail
 
1504
            self.to_parent_id = to_parent_id
 
1505
            self.only_change_inv = only_change_inv
983
1506
 
984
1507
    @needs_read_lock
985
1508
    def unknowns(self):
993
1516
        return iter(
994
1517
            [subp for subp in self.extras() if not self.is_ignored(subp)])
995
1518
 
 
1519
    @needs_tree_write_lock
996
1520
    def unversion(self, file_ids):
997
1521
        """Remove the file ids in file_ids from the current versioned set.
998
1522
 
1002
1526
        :param file_ids: The file ids to stop versioning.
1003
1527
        :raises: NoSuchId if any fileid is not currently versioned.
1004
1528
        """
1005
 
        raise NotImplementedError(self.unversion)
 
1529
        for file_id in file_ids:
 
1530
            if file_id not in self._inventory:
 
1531
                raise errors.NoSuchId(self, file_id)
 
1532
        for file_id in file_ids:
 
1533
            if self._inventory.has_id(file_id):
 
1534
                self._inventory.remove_recursive_id(file_id)
 
1535
        if len(file_ids):
 
1536
            # in the future this should just set a dirty bit to wait for the
 
1537
            # final unlock. However, until all methods of workingtree start
 
1538
            # with the current in -memory inventory rather than triggering
 
1539
            # a read, it is more complex - we need to teach read_inventory
 
1540
            # to know when to read, and when to not read first... and possibly
 
1541
            # to save first when the in memory one may be corrupted.
 
1542
            # so for now, we just only write it if it is indeed dirty.
 
1543
            # - RBC 20060907
 
1544
            self._write_inventory(self._inventory)
 
1545
 
 
1546
    def _iter_conflicts(self):
 
1547
        conflicted = set()
 
1548
        for info in self.list_files():
 
1549
            path = info[0]
 
1550
            stem = get_conflicted_stem(path)
 
1551
            if stem is None:
 
1552
                continue
 
1553
            if stem not in conflicted:
 
1554
                conflicted.add(stem)
 
1555
                yield stem
1006
1556
 
1007
1557
    @needs_write_lock
1008
1558
    def pull(self, source, overwrite=False, stop_revision=None,
1009
 
             change_reporter=None, possible_transports=None, local=False,
1010
 
             show_base=False):
 
1559
             change_reporter=None, possible_transports=None):
 
1560
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1011
1561
        source.lock_read()
1012
1562
        try:
 
1563
            pp = ProgressPhase("Pull phase", 2, top_pb)
 
1564
            pp.next_phase()
1013
1565
            old_revision_info = self.branch.last_revision_info()
1014
1566
            basis_tree = self.basis_tree()
1015
1567
            count = self.branch.pull(source, overwrite, stop_revision,
1016
 
                                     possible_transports=possible_transports,
1017
 
                                     local=local)
 
1568
                                     possible_transports=possible_transports)
1018
1569
            new_revision_info = self.branch.last_revision_info()
1019
1570
            if new_revision_info != old_revision_info:
 
1571
                pp.next_phase()
1020
1572
                repository = self.branch.repository
1021
 
                if repository._format.fast_deltas:
1022
 
                    parent_ids = self.get_parent_ids()
1023
 
                    if parent_ids:
1024
 
                        basis_id = parent_ids[0]
1025
 
                        basis_tree = repository.revision_tree(basis_id)
 
1573
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1026
1574
                basis_tree.lock_read()
1027
1575
                try:
1028
1576
                    new_basis_tree = self.branch.basis_tree()
1031
1579
                                new_basis_tree,
1032
1580
                                basis_tree,
1033
1581
                                this_tree=self,
1034
 
                                pb=None,
1035
 
                                change_reporter=change_reporter,
1036
 
                                show_base=show_base)
1037
 
                    basis_root_id = basis_tree.get_root_id()
1038
 
                    new_root_id = new_basis_tree.get_root_id()
1039
 
                    if basis_root_id != new_root_id:
1040
 
                        self.set_root_id(new_root_id)
 
1582
                                pb=pb,
 
1583
                                change_reporter=change_reporter)
 
1584
                    if (basis_tree.inventory.root is None and
 
1585
                        new_basis_tree.inventory.root is not None):
 
1586
                        self.set_root_id(new_basis_tree.get_root_id())
1041
1587
                finally:
 
1588
                    pb.finished()
1042
1589
                    basis_tree.unlock()
1043
1590
                # TODO - dedup parents list with things merged by pull ?
1044
1591
                # reuse the revisiontree we merged against to set the new
1057
1604
            return count
1058
1605
        finally:
1059
1606
            source.unlock()
 
1607
            top_pb.finished()
1060
1608
 
1061
1609
    @needs_write_lock
1062
1610
    def put_file_bytes_non_atomic(self, file_id, bytes):
1078
1626
        Currently returned depth-first, sorted by name within directories.
1079
1627
        This is the same order used by 'osutils.walkdirs'.
1080
1628
        """
1081
 
        raise NotImplementedError(self.extras)
 
1629
        ## TODO: Work from given directory downwards
 
1630
        for path, dir_entry in self.inventory.directories():
 
1631
            # mutter("search for unknowns in %r", path)
 
1632
            dirabs = self.abspath(path)
 
1633
            if not isdir(dirabs):
 
1634
                # e.g. directory deleted
 
1635
                continue
 
1636
 
 
1637
            fl = []
 
1638
            for subf in os.listdir(dirabs):
 
1639
                if subf == '.bzr':
 
1640
                    continue
 
1641
                if subf not in dir_entry.children:
 
1642
                    try:
 
1643
                        (subf_norm,
 
1644
                         can_access) = osutils.normalized_filename(subf)
 
1645
                    except UnicodeDecodeError:
 
1646
                        path_os_enc = path.encode(osutils._fs_enc)
 
1647
                        relpath = path_os_enc + '/' + subf
 
1648
                        raise errors.BadFilenameEncoding(relpath,
 
1649
                                                         osutils._fs_enc)
 
1650
                    if subf_norm != subf and can_access:
 
1651
                        if subf_norm not in dir_entry.children:
 
1652
                            fl.append(subf_norm)
 
1653
                    else:
 
1654
                        fl.append(subf)
 
1655
 
 
1656
            fl.sort()
 
1657
            for subf in fl:
 
1658
                subp = pathjoin(path, subf)
 
1659
                yield subp
1082
1660
 
1083
1661
    def ignored_files(self):
1084
1662
        """Yield list of PATH, IGNORE_PATTERN"""
1117
1695
        r"""Check whether the filename matches an ignore pattern.
1118
1696
 
1119
1697
        Patterns containing '/' or '\' need to match the whole path;
1120
 
        others match against only the last component.  Patterns starting
1121
 
        with '!' are ignore exceptions.  Exceptions take precedence
1122
 
        over regular patterns and cause the filename to not be ignored.
 
1698
        others match against only the last component.
1123
1699
 
1124
1700
        If the file is ignored, returns the pattern which caused it to
1125
1701
        be ignored, otherwise None.  So this can simply be used as a
1126
1702
        boolean if desired."""
1127
1703
        if getattr(self, '_ignoreglobster', None) is None:
1128
 
            self._ignoreglobster = globbing.ExceptionGlobster(self.get_ignore_list())
 
1704
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1129
1705
        return self._ignoreglobster.match(filename)
1130
1706
 
1131
1707
    def kind(self, file_id):
1133
1709
 
1134
1710
    def stored_kind(self, file_id):
1135
1711
        """See Tree.stored_kind"""
1136
 
        raise NotImplementedError(self.stored_kind)
 
1712
        return self.inventory[file_id].kind
1137
1713
 
1138
1714
    def _comparison_data(self, entry, path):
1139
1715
        abspath = self.abspath(path)
1181
1757
            raise errors.ObjectNotLocked(self)
1182
1758
 
1183
1759
    def lock_read(self):
1184
 
        """Lock the tree for reading.
1185
 
 
1186
 
        This also locks the branch, and can be unlocked via self.unlock().
1187
 
 
1188
 
        :return: A bzrlib.lock.LogicalLockResult.
1189
 
        """
 
1760
        """See Branch.lock_read, and WorkingTree.unlock."""
1190
1761
        if not self.is_locked():
1191
1762
            self._reset_data()
1192
1763
        self.branch.lock_read()
1193
1764
        try:
1194
 
            self._control_files.lock_read()
1195
 
            return LogicalLockResult(self.unlock)
 
1765
            return self._control_files.lock_read()
1196
1766
        except:
1197
1767
            self.branch.unlock()
1198
1768
            raise
1199
1769
 
1200
1770
    def lock_tree_write(self):
1201
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
1202
 
 
1203
 
        :return: A bzrlib.lock.LogicalLockResult.
1204
 
        """
 
1771
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1205
1772
        if not self.is_locked():
1206
1773
            self._reset_data()
1207
1774
        self.branch.lock_read()
1208
1775
        try:
1209
 
            self._control_files.lock_write()
1210
 
            return LogicalLockResult(self.unlock)
 
1776
            return self._control_files.lock_write()
1211
1777
        except:
1212
1778
            self.branch.unlock()
1213
1779
            raise
1214
1780
 
1215
1781
    def lock_write(self):
1216
 
        """See MutableTree.lock_write, and WorkingTree.unlock.
1217
 
 
1218
 
        :return: A bzrlib.lock.LogicalLockResult.
1219
 
        """
 
1782
        """See MutableTree.lock_write, and WorkingTree.unlock."""
1220
1783
        if not self.is_locked():
1221
1784
            self._reset_data()
1222
1785
        self.branch.lock_write()
1223
1786
        try:
1224
 
            self._control_files.lock_write()
1225
 
            return LogicalLockResult(self.unlock)
 
1787
            return self._control_files.lock_write()
1226
1788
        except:
1227
1789
            self.branch.unlock()
1228
1790
            raise
1230
1792
    def get_physical_lock_status(self):
1231
1793
        return self._control_files.get_physical_lock_status()
1232
1794
 
 
1795
    def _basis_inventory_name(self):
 
1796
        return 'basis-inventory-cache'
 
1797
 
1233
1798
    def _reset_data(self):
1234
1799
        """Reset transient data that cannot be revalidated."""
1235
 
        raise NotImplementedError(self._reset_data)
 
1800
        self._inventory_is_modified = False
 
1801
        result = self._deserialize(self._transport.get('inventory'))
 
1802
        self._set_inventory(result, dirty=False)
1236
1803
 
 
1804
    @needs_tree_write_lock
1237
1805
    def set_last_revision(self, new_revision):
1238
1806
        """Change the last revision in the working tree."""
1239
 
        raise NotImplementedError(self.set_last_revision)
 
1807
        if self._change_last_revision(new_revision):
 
1808
            self._cache_basis_inventory(new_revision)
1240
1809
 
1241
1810
    def _change_last_revision(self, new_revision):
1242
1811
        """Template method part of set_last_revision to perform the change.
1245
1814
        when their last revision is set.
1246
1815
        """
1247
1816
        if _mod_revision.is_null(new_revision):
1248
 
            self.branch.set_last_revision_info(0, new_revision)
 
1817
            self.branch.set_revision_history([])
1249
1818
            return False
1250
 
        _mod_revision.check_not_reserved_id(new_revision)
1251
1819
        try:
1252
1820
            self.branch.generate_revision_history(new_revision)
1253
1821
        except errors.NoSuchRevision:
1254
1822
            # not present in the repo - dont try to set it deeper than the tip
1255
 
            self.branch._set_revision_history([new_revision])
 
1823
            self.branch.set_revision_history([new_revision])
1256
1824
        return True
1257
1825
 
 
1826
    def _write_basis_inventory(self, xml):
 
1827
        """Write the basis inventory XML to the basis-inventory file"""
 
1828
        path = self._basis_inventory_name()
 
1829
        sio = StringIO(xml)
 
1830
        self._transport.put_file(path, sio,
 
1831
            mode=self.bzrdir._get_file_mode())
 
1832
 
 
1833
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
 
1834
        """Create the text that will be saved in basis-inventory"""
 
1835
        inventory.revision_id = revision_id
 
1836
        return xml7.serializer_v7.write_inventory_to_string(inventory)
 
1837
 
 
1838
    def _cache_basis_inventory(self, new_revision):
 
1839
        """Cache new_revision as the basis inventory."""
 
1840
        # TODO: this should allow the ready-to-use inventory to be passed in,
 
1841
        # as commit already has that ready-to-use [while the format is the
 
1842
        # same, that is].
 
1843
        try:
 
1844
            # this double handles the inventory - unpack and repack -
 
1845
            # but is easier to understand. We can/should put a conditional
 
1846
            # in here based on whether the inventory is in the latest format
 
1847
            # - perhaps we should repack all inventories on a repository
 
1848
            # upgrade ?
 
1849
            # the fast path is to copy the raw xml from the repository. If the
 
1850
            # xml contains 'revision_id="', then we assume the right
 
1851
            # revision_id is set. We must check for this full string, because a
 
1852
            # root node id can legitimately look like 'revision_id' but cannot
 
1853
            # contain a '"'.
 
1854
            xml = self.branch.repository.get_inventory_xml(new_revision)
 
1855
            firstline = xml.split('\n', 1)[0]
 
1856
            if (not 'revision_id="' in firstline or
 
1857
                'format="7"' not in firstline):
 
1858
                inv = self.branch.repository.deserialise_inventory(
 
1859
                    new_revision, xml)
 
1860
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
 
1861
            self._write_basis_inventory(xml)
 
1862
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
 
1863
            pass
 
1864
 
 
1865
    def read_basis_inventory(self):
 
1866
        """Read the cached basis inventory."""
 
1867
        path = self._basis_inventory_name()
 
1868
        return self._transport.get_bytes(path)
 
1869
 
 
1870
    @needs_read_lock
 
1871
    def read_working_inventory(self):
 
1872
        """Read the working inventory.
 
1873
 
 
1874
        :raises errors.InventoryModified: read_working_inventory will fail
 
1875
            when the current in memory inventory has been modified.
 
1876
        """
 
1877
        # conceptually this should be an implementation detail of the tree.
 
1878
        # XXX: Deprecate this.
 
1879
        # ElementTree does its own conversion from UTF-8, so open in
 
1880
        # binary.
 
1881
        if self._inventory_is_modified:
 
1882
            raise errors.InventoryModified(self)
 
1883
        result = self._deserialize(self._transport.get('inventory'))
 
1884
        self._set_inventory(result, dirty=False)
 
1885
        return result
 
1886
 
1258
1887
    @needs_tree_write_lock
1259
1888
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
1260
1889
        force=False):
1261
 
        """Remove nominated files from the working tree metadata.
 
1890
        """Remove nominated files from the working inventory.
1262
1891
 
1263
1892
        :files: File paths relative to the basedir.
1264
1893
        :keep_files: If true, the files will also be kept.
1270
1899
 
1271
1900
        inv_delta = []
1272
1901
 
1273
 
        all_files = set() # specified and nested files 
 
1902
        new_files=set()
1274
1903
        unknown_nested_files=set()
1275
 
        if to_file is None:
1276
 
            to_file = sys.stdout
1277
 
 
1278
 
        files_to_backup = []
1279
1904
 
1280
1905
        def recurse_directory_to_add_files(directory):
1281
1906
            # Recurse directory and add all files
1282
1907
            # so we can check if they have changed.
1283
 
            for parent_info, file_infos in self.walkdirs(directory):
 
1908
            for parent_info, file_infos in\
 
1909
                self.walkdirs(directory):
1284
1910
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
1285
1911
                    # Is it versioned or ignored?
1286
 
                    if self.path2id(relpath):
 
1912
                    if self.path2id(relpath) or self.is_ignored(relpath):
1287
1913
                        # Add nested content for deletion.
1288
 
                        all_files.add(relpath)
 
1914
                        new_files.add(relpath)
1289
1915
                    else:
1290
 
                        # Files which are not versioned
 
1916
                        # Files which are not versioned and not ignored
1291
1917
                        # should be treated as unknown.
1292
 
                        files_to_backup.append(relpath)
 
1918
                        unknown_nested_files.add((relpath, None, kind))
1293
1919
 
1294
1920
        for filename in files:
1295
1921
            # Get file name into canonical form.
1296
1922
            abspath = self.abspath(filename)
1297
1923
            filename = self.relpath(abspath)
1298
1924
            if len(filename) > 0:
1299
 
                all_files.add(filename)
 
1925
                new_files.add(filename)
1300
1926
                recurse_directory_to_add_files(filename)
1301
1927
 
1302
 
        files = list(all_files)
 
1928
        files = list(new_files)
1303
1929
 
1304
1930
        if len(files) == 0:
1305
1931
            return # nothing to do
1309
1935
 
1310
1936
        # Bail out if we are going to delete files we shouldn't
1311
1937
        if not keep_files and not force:
1312
 
            for (file_id, path, content_change, versioned, parent_id, name,
1313
 
                 kind, executable) in self.iter_changes(self.basis_tree(),
1314
 
                     include_unchanged=True, require_versioned=False,
1315
 
                     want_unversioned=True, specific_files=files):
1316
 
                if versioned[0] == False:
1317
 
                    # The record is unknown or newly added
1318
 
                    files_to_backup.append(path[1])
1319
 
                elif (content_change and (kind[1] is not None) and
1320
 
                        osutils.is_inside_any(files, path[1])):
1321
 
                    # Versioned and changed, but not deleted, and still
1322
 
                    # in one of the dirs to be deleted.
1323
 
                    files_to_backup.append(path[1])
1324
 
 
1325
 
        def backup(file_to_backup):
1326
 
            backup_name = self.bzrdir._available_backup_name(file_to_backup)
1327
 
            osutils.rename(abs_path, self.abspath(backup_name))
1328
 
            return "removed %s (but kept a copy: %s)" % (file_to_backup,
1329
 
                                                         backup_name)
1330
 
 
1331
 
        # Build inv_delta and delete files where applicable,
1332
 
        # do this before any modifications to meta data.
 
1938
            has_changed_files = len(unknown_nested_files) > 0
 
1939
            if not has_changed_files:
 
1940
                for (file_id, path, content_change, versioned, parent_id, name,
 
1941
                     kind, executable) in self.iter_changes(self.basis_tree(),
 
1942
                         include_unchanged=True, require_versioned=False,
 
1943
                         want_unversioned=True, specific_files=files):
 
1944
                    if versioned == (False, False):
 
1945
                        # The record is unknown ...
 
1946
                        if not self.is_ignored(path[1]):
 
1947
                            # ... but not ignored
 
1948
                            has_changed_files = True
 
1949
                            break
 
1950
                    elif content_change and (kind[1] is not None):
 
1951
                        # Versioned and changed, but not deleted
 
1952
                        has_changed_files = True
 
1953
                        break
 
1954
 
 
1955
            if has_changed_files:
 
1956
                # Make delta show ALL applicable changes in error message.
 
1957
                tree_delta = self.changes_from(self.basis_tree(),
 
1958
                    require_versioned=False, want_unversioned=True,
 
1959
                    specific_files=files)
 
1960
                for unknown_file in unknown_nested_files:
 
1961
                    if unknown_file not in tree_delta.unversioned:
 
1962
                        tree_delta.unversioned.extend((unknown_file,))
 
1963
                raise errors.BzrRemoveChangedFilesError(tree_delta)
 
1964
 
 
1965
        # Build inv_delta and delete files where applicaple,
 
1966
        # do this before any modifications to inventory.
1333
1967
        for f in files:
1334
1968
            fid = self.path2id(f)
1335
1969
            message = None
1342
1976
                        new_status = 'I'
1343
1977
                    else:
1344
1978
                        new_status = '?'
1345
 
                    # XXX: Really should be a more abstract reporter interface
1346
 
                    kind_ch = osutils.kind_marker(self.kind(fid))
1347
 
                    to_file.write(new_status + '       ' + f + kind_ch + '\n')
 
1979
                    textui.show_status(new_status, self.kind(fid), f,
 
1980
                                       to_file=to_file)
1348
1981
                # Unversion file
1349
1982
                inv_delta.append((f, None, fid, None))
1350
1983
                message = "removed %s" % (f,)
1356
1989
                        len(os.listdir(abs_path)) > 0):
1357
1990
                        if force:
1358
1991
                            osutils.rmtree(abs_path)
1359
 
                            message = "deleted %s" % (f,)
1360
1992
                        else:
1361
 
                            message = backup(f)
 
1993
                            message = "%s is not an empty directory "\
 
1994
                                "and won't be deleted." % (f,)
1362
1995
                    else:
1363
 
                        if f in files_to_backup:
1364
 
                            message = backup(f)
1365
 
                        else:
1366
 
                            osutils.delete_any(abs_path)
1367
 
                            message = "deleted %s" % (f,)
 
1996
                        osutils.delete_any(abs_path)
 
1997
                        message = "deleted %s" % (f,)
1368
1998
                elif message is not None:
1369
1999
                    # Only care if we haven't done anything yet.
1370
2000
                    message = "%s does not exist." % (f,)
1376
2006
 
1377
2007
    @needs_tree_write_lock
1378
2008
    def revert(self, filenames=None, old_tree=None, backups=True,
1379
 
               pb=None, report_changes=False):
 
2009
               pb=DummyProgress(), report_changes=False):
1380
2010
        from bzrlib.conflicts import resolve
 
2011
        if filenames == []:
 
2012
            filenames = None
 
2013
            symbol_versioning.warn('Using [] to revert all files is deprecated'
 
2014
                ' as of bzr 0.91.  Please use None (the default) instead.',
 
2015
                DeprecationWarning, stacklevel=2)
1381
2016
        if old_tree is None:
1382
2017
            basis_tree = self.basis_tree()
1383
2018
            basis_tree.lock_read()
1390
2025
            if filenames is None and len(self.get_parent_ids()) > 1:
1391
2026
                parent_trees = []
1392
2027
                last_revision = self.last_revision()
1393
 
                if last_revision != _mod_revision.NULL_REVISION:
 
2028
                if last_revision != NULL_REVISION:
1394
2029
                    if basis_tree is None:
1395
2030
                        basis_tree = self.basis_tree()
1396
2031
                        basis_tree.lock_read()
1410
2045
        WorkingTree can supply revision_trees for the basis revision only
1411
2046
        because there is only one cached inventory in the bzr directory.
1412
2047
        """
1413
 
        raise NotImplementedError(self.revision_tree)
 
2048
        if revision_id == self.last_revision():
 
2049
            try:
 
2050
                xml = self.read_basis_inventory()
 
2051
            except errors.NoSuchFile:
 
2052
                pass
 
2053
            else:
 
2054
                try:
 
2055
                    inv = xml7.serializer_v7.read_inventory_from_string(xml)
 
2056
                    # dont use the repository revision_tree api because we want
 
2057
                    # to supply the inventory.
 
2058
                    if inv.revision_id == revision_id:
 
2059
                        return revisiontree.RevisionTree(self.branch.repository,
 
2060
                            inv, revision_id)
 
2061
                except errors.BadInventoryFormat:
 
2062
                    pass
 
2063
        # raise if there was no inventory, or if we read the wrong inventory.
 
2064
        raise errors.NoSuchRevisionInTree(self, revision_id)
 
2065
 
 
2066
    # XXX: This method should be deprecated in favour of taking in a proper
 
2067
    # new Inventory object.
 
2068
    @needs_tree_write_lock
 
2069
    def set_inventory(self, new_inventory_list):
 
2070
        from bzrlib.inventory import (Inventory,
 
2071
                                      InventoryDirectory,
 
2072
                                      InventoryEntry,
 
2073
                                      InventoryFile,
 
2074
                                      InventoryLink)
 
2075
        inv = Inventory(self.get_root_id())
 
2076
        for path, file_id, parent, kind in new_inventory_list:
 
2077
            name = os.path.basename(path)
 
2078
            if name == "":
 
2079
                continue
 
2080
            # fixme, there should be a factory function inv,add_??
 
2081
            if kind == 'directory':
 
2082
                inv.add(InventoryDirectory(file_id, name, parent))
 
2083
            elif kind == 'file':
 
2084
                inv.add(InventoryFile(file_id, name, parent))
 
2085
            elif kind == 'symlink':
 
2086
                inv.add(InventoryLink(file_id, name, parent))
 
2087
            else:
 
2088
                raise errors.BzrError("unknown kind %r" % kind)
 
2089
        self._write_inventory(inv)
1414
2090
 
1415
2091
    @needs_tree_write_lock
1416
2092
    def set_root_id(self, file_id):
1429
2105
            present in the current inventory or an error will occur. It must
1430
2106
            not be None, but rather a valid file id.
1431
2107
        """
1432
 
        raise NotImplementedError(self._set_root_id)
 
2108
        inv = self._inventory
 
2109
        orig_root_id = inv.root.file_id
 
2110
        # TODO: it might be nice to exit early if there was nothing
 
2111
        # to do, saving us from trigger a sync on unlock.
 
2112
        self._inventory_is_modified = True
 
2113
        # we preserve the root inventory entry object, but
 
2114
        # unlinkit from the byid index
 
2115
        del inv._byid[inv.root.file_id]
 
2116
        inv.root.file_id = file_id
 
2117
        # and link it into the index with the new changed id.
 
2118
        inv._byid[inv.root.file_id] = inv.root
 
2119
        # and finally update all children to reference the new id.
 
2120
        # XXX: this should be safe to just look at the root.children
 
2121
        # list, not the WHOLE INVENTORY.
 
2122
        for fid in inv:
 
2123
            entry = inv[fid]
 
2124
            if entry.parent_id == orig_root_id:
 
2125
                entry.parent_id = inv.root.file_id
1433
2126
 
1434
2127
    def unlock(self):
1435
2128
        """See Branch.unlock.
1442
2135
        """
1443
2136
        raise NotImplementedError(self.unlock)
1444
2137
 
1445
 
    _marker = object()
1446
 
 
1447
 
    def update(self, change_reporter=None, possible_transports=None,
1448
 
               revision=None, old_tip=_marker, show_base=False):
 
2138
    def update(self, change_reporter=None, possible_transports=None):
1449
2139
        """Update a working tree along its branch.
1450
2140
 
1451
2141
        This will update the branch if its bound too, which means we have
1466
2156
        - Restore the wt.basis->wt.state changes.
1467
2157
 
1468
2158
        There isn't a single operation at the moment to do that, so we:
1469
 
 
1470
2159
        - Merge current state -> basis tree of the master w.r.t. the old tree
1471
2160
          basis.
1472
2161
        - Do a 'normal' merge of the old branch basis if it is relevant.
1473
 
 
1474
 
        :param revision: The target revision to update to. Must be in the
1475
 
            revision history.
1476
 
        :param old_tip: If branch.update() has already been run, the value it
1477
 
            returned (old tip of the branch or None). _marker is used
1478
 
            otherwise.
1479
2162
        """
1480
2163
        if self.branch.get_bound_location() is not None:
1481
2164
            self.lock_write()
1482
 
            update_branch = (old_tip is self._marker)
 
2165
            update_branch = True
1483
2166
        else:
1484
2167
            self.lock_tree_write()
1485
2168
            update_branch = False
1487
2170
            if update_branch:
1488
2171
                old_tip = self.branch.update(possible_transports)
1489
2172
            else:
1490
 
                if old_tip is self._marker:
1491
 
                    old_tip = None
1492
 
            return self._update_tree(old_tip, change_reporter, revision, show_base)
 
2173
                old_tip = None
 
2174
            return self._update_tree(old_tip, change_reporter)
1493
2175
        finally:
1494
2176
            self.unlock()
1495
2177
 
1496
2178
    @needs_tree_write_lock
1497
 
    def _update_tree(self, old_tip=None, change_reporter=None, revision=None,
1498
 
                     show_base=False):
 
2179
    def _update_tree(self, old_tip=None, change_reporter=None):
1499
2180
        """Update a tree to the master branch.
1500
2181
 
1501
2182
        :param old_tip: if supplied, the previous tip revision the branch,
1511
2192
        # We MUST save it even if an error occurs, because otherwise the users
1512
2193
        # local work is unreferenced and will appear to have been lost.
1513
2194
        #
1514
 
        nb_conflicts = 0
 
2195
        result = 0
1515
2196
        try:
1516
2197
            last_rev = self.get_parent_ids()[0]
1517
2198
        except IndexError:
1518
2199
            last_rev = _mod_revision.NULL_REVISION
1519
 
        if revision is None:
1520
 
            revision = self.branch.last_revision()
1521
 
 
1522
 
        old_tip = old_tip or _mod_revision.NULL_REVISION
1523
 
 
1524
 
        if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
1525
 
            # the branch we are bound to was updated
1526
 
            # merge those changes in first
1527
 
            base_tree  = self.basis_tree()
1528
 
            other_tree = self.branch.repository.revision_tree(old_tip)
1529
 
            nb_conflicts = merge.merge_inner(self.branch, other_tree,
1530
 
                                             base_tree, this_tree=self,
1531
 
                                             change_reporter=change_reporter,
1532
 
                                             show_base=show_base)
1533
 
            if nb_conflicts:
1534
 
                self.add_parent_tree((old_tip, other_tree))
1535
 
                note('Rerun update after fixing the conflicts.')
1536
 
                return nb_conflicts
1537
 
 
1538
 
        if last_rev != _mod_revision.ensure_null(revision):
1539
 
            # the working tree is up to date with the branch
1540
 
            # we can merge the specified revision from master
1541
 
            to_tree = self.branch.repository.revision_tree(revision)
1542
 
            to_root_id = to_tree.get_root_id()
1543
 
 
 
2200
        if last_rev != _mod_revision.ensure_null(self.branch.last_revision()):
 
2201
            # merge tree state up to new branch tip.
1544
2202
            basis = self.basis_tree()
1545
2203
            basis.lock_read()
1546
2204
            try:
1547
 
                if (basis.get_root_id() is None or basis.get_root_id() != to_root_id):
1548
 
                    self.set_root_id(to_root_id)
 
2205
                to_tree = self.branch.basis_tree()
 
2206
                if basis.inventory.root is None:
 
2207
                    self.set_root_id(to_tree.get_root_id())
1549
2208
                    self.flush()
 
2209
                result += merge.merge_inner(
 
2210
                                      self.branch,
 
2211
                                      to_tree,
 
2212
                                      basis,
 
2213
                                      this_tree=self,
 
2214
                                      change_reporter=change_reporter)
1550
2215
            finally:
1551
2216
                basis.unlock()
1552
 
 
1553
 
            # determine the branch point
1554
 
            graph = self.branch.repository.get_graph()
1555
 
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
1556
 
                                                last_rev)
1557
 
            base_tree = self.branch.repository.revision_tree(base_rev_id)
1558
 
 
1559
 
            nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
1560
 
                                             this_tree=self,
1561
 
                                             change_reporter=change_reporter,
1562
 
                                             show_base=show_base)
1563
 
            self.set_last_revision(revision)
1564
2217
            # TODO - dedup parents list with things merged by pull ?
1565
2218
            # reuse the tree we've updated to to set the basis:
1566
 
            parent_trees = [(revision, to_tree)]
 
2219
            parent_trees = [(self.branch.last_revision(), to_tree)]
1567
2220
            merges = self.get_parent_ids()[1:]
1568
2221
            # Ideally we ask the tree for the trees here, that way the working
1569
 
            # tree can decide whether to give us the entire tree or give us a
 
2222
            # tree can decide whether to give us teh entire tree or give us a
1570
2223
            # lazy initialised tree. dirstate for instance will have the trees
1571
2224
            # in ram already, whereas a last-revision + basis-inventory tree
1572
2225
            # will not, but also does not need them when setting parents.
1573
2226
            for parent in merges:
1574
2227
                parent_trees.append(
1575
2228
                    (parent, self.branch.repository.revision_tree(parent)))
1576
 
            if not _mod_revision.is_null(old_tip):
 
2229
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
1577
2230
                parent_trees.append(
1578
2231
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
1579
2232
            self.set_parent_trees(parent_trees)
1580
2233
            last_rev = parent_trees[0][0]
1581
 
        return nb_conflicts
 
2234
        else:
 
2235
            # the working tree had the same last-revision as the master
 
2236
            # branch did. We may still have pivot local work from the local
 
2237
            # branch into old_tip:
 
2238
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
 
2239
                self.add_parent_tree_id(old_tip)
 
2240
        if (old_tip is not None and not _mod_revision.is_null(old_tip)
 
2241
            and old_tip != last_rev):
 
2242
            # our last revision was not the prior branch last revision
 
2243
            # and we have converted that last revision to a pending merge.
 
2244
            # base is somewhere between the branch tip now
 
2245
            # and the now pending merge
 
2246
 
 
2247
            # Since we just modified the working tree and inventory, flush out
 
2248
            # the current state, before we modify it again.
 
2249
            # TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
 
2250
            #       requires it only because TreeTransform directly munges the
 
2251
            #       inventory and calls tree._write_inventory(). Ultimately we
 
2252
            #       should be able to remove this extra flush.
 
2253
            self.flush()
 
2254
            graph = self.branch.repository.get_graph()
 
2255
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
 
2256
                                                old_tip)
 
2257
            base_tree = self.branch.repository.revision_tree(base_rev_id)
 
2258
            other_tree = self.branch.repository.revision_tree(old_tip)
 
2259
            result += merge.merge_inner(
 
2260
                                  self.branch,
 
2261
                                  other_tree,
 
2262
                                  base_tree,
 
2263
                                  this_tree=self,
 
2264
                                  change_reporter=change_reporter)
 
2265
        return result
1582
2266
 
1583
2267
    def _write_hashcache_if_dirty(self):
1584
2268
        """Write out the hashcache if it is dirty."""
1592
2276
                #       warning might be sufficient to let the user know what
1593
2277
                #       is going on.
1594
2278
                mutter('Could not write hashcache for %s\nError: %s',
1595
 
                              self._hashcache.cache_file_name(), e)
 
2279
                       self._hashcache.cache_file_name(), e)
 
2280
 
 
2281
    @needs_tree_write_lock
 
2282
    def _write_inventory(self, inv):
 
2283
        """Write inventory as the current inventory."""
 
2284
        self._set_inventory(inv, dirty=True)
 
2285
        self.flush()
1596
2286
 
1597
2287
    def set_conflicts(self, arg):
1598
2288
        raise errors.UnsupportedOperation(self.set_conflicts, self)
1600
2290
    def add_conflicts(self, arg):
1601
2291
        raise errors.UnsupportedOperation(self.add_conflicts, self)
1602
2292
 
 
2293
    @needs_read_lock
1603
2294
    def conflicts(self):
1604
 
        raise NotImplementedError(self.conflicts)
 
2295
        conflicts = _mod_conflicts.ConflictList()
 
2296
        for conflicted in self._iter_conflicts():
 
2297
            text = True
 
2298
            try:
 
2299
                if file_kind(self.abspath(conflicted)) != "file":
 
2300
                    text = False
 
2301
            except errors.NoSuchFile:
 
2302
                text = False
 
2303
            if text is True:
 
2304
                for suffix in ('.THIS', '.OTHER'):
 
2305
                    try:
 
2306
                        kind = file_kind(self.abspath(conflicted+suffix))
 
2307
                        if kind != "file":
 
2308
                            text = False
 
2309
                    except errors.NoSuchFile:
 
2310
                        text = False
 
2311
                    if text == False:
 
2312
                        break
 
2313
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
 
2314
            conflicts.append(_mod_conflicts.Conflict.factory(ctype,
 
2315
                             path=conflicted,
 
2316
                             file_id=self.path2id(conflicted)))
 
2317
        return conflicts
1605
2318
 
1606
2319
    def walkdirs(self, prefix=""):
1607
2320
        """Walk the directories of this tree.
1655
2368
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
1656
2369
                        ('.bzr', '.bzr'))
1657
2370
                    if (bzrdir_loc < len(cur_disk_dir_content)
1658
 
                        and self.bzrdir.is_control_filename(
1659
 
                            cur_disk_dir_content[bzrdir_loc][0])):
 
2371
                        and cur_disk_dir_content[bzrdir_loc][0] == '.bzr'):
1660
2372
                        # we dont yield the contents of, or, .bzr itself.
1661
2373
                        del cur_disk_dir_content[bzrdir_loc]
1662
2374
            if inv_finished:
1727
2439
    def _walkdirs(self, prefix=""):
1728
2440
        """Walk the directories of this tree.
1729
2441
 
1730
 
        :param prefix: is used as the directrory to start with.
1731
 
        :returns: a generator which yields items in the form::
1732
 
 
1733
 
            ((curren_directory_path, fileid),
1734
 
             [(file1_path, file1_name, file1_kind, None, file1_id,
1735
 
               file1_kind), ... ])
 
2442
           :prefix: is used as the directrory to start with.
 
2443
           returns a generator which yields items in the form:
 
2444
                ((curren_directory_path, fileid),
 
2445
                 [(file1_path, file1_name, file1_kind, None, file1_id,
 
2446
                   file1_kind), ... ])
1736
2447
        """
1737
 
        raise NotImplementedError(self._walkdirs)
 
2448
        _directory = 'directory'
 
2449
        # get the root in the inventory
 
2450
        inv = self.inventory
 
2451
        top_id = inv.path2id(prefix)
 
2452
        if top_id is None:
 
2453
            pending = []
 
2454
        else:
 
2455
            pending = [(prefix, '', _directory, None, top_id, None)]
 
2456
        while pending:
 
2457
            dirblock = []
 
2458
            currentdir = pending.pop()
 
2459
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
 
2460
            top_id = currentdir[4]
 
2461
            if currentdir[0]:
 
2462
                relroot = currentdir[0] + '/'
 
2463
            else:
 
2464
                relroot = ""
 
2465
            # FIXME: stash the node in pending
 
2466
            entry = inv[top_id]
 
2467
            if entry.kind == 'directory':
 
2468
                for name, child in entry.sorted_children():
 
2469
                    dirblock.append((relroot + name, name, child.kind, None,
 
2470
                        child.file_id, child.kind
 
2471
                        ))
 
2472
            yield (currentdir[0], entry.file_id), dirblock
 
2473
            # push the user specified dirs from dirblock
 
2474
            for dir in reversed(dirblock):
 
2475
                if dir[2] == _directory:
 
2476
                    pending.append(dir)
1738
2477
 
1739
2478
    @needs_tree_write_lock
1740
2479
    def auto_resolve(self):
1744
2483
        are considered 'resolved', because bzr always puts conflict markers
1745
2484
        into files that have text conflicts.  The corresponding .THIS .BASE and
1746
2485
        .OTHER files are deleted, as per 'resolve'.
1747
 
 
1748
2486
        :return: a tuple of ConflictLists: (un_resolved, resolved).
1749
2487
        """
1750
2488
        un_resolved = _mod_conflicts.ConflictList()
1769
2507
        self.set_conflicts(un_resolved)
1770
2508
        return un_resolved, resolved
1771
2509
 
 
2510
    @needs_read_lock
 
2511
    def _check(self):
 
2512
        tree_basis = self.basis_tree()
 
2513
        tree_basis.lock_read()
 
2514
        try:
 
2515
            repo_basis = self.branch.repository.revision_tree(
 
2516
                self.last_revision())
 
2517
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
 
2518
                raise errors.BzrCheckError(
 
2519
                    "Mismatched basis inventory content.")
 
2520
            self._validate()
 
2521
        finally:
 
2522
            tree_basis.unlock()
 
2523
 
1772
2524
    def _validate(self):
1773
2525
        """Validate internal structures.
1774
2526
 
1780
2532
        """
1781
2533
        return
1782
2534
 
1783
 
    def check_state(self):
1784
 
        """Check that the working state is/isn't valid."""
1785
 
        raise NotImplementedError(self.check_state)
1786
 
 
1787
 
    def reset_state(self, revision_ids=None):
1788
 
        """Reset the state of the working tree.
1789
 
 
1790
 
        This does a hard-reset to a last-known-good state. This is a way to
1791
 
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
1792
 
        """
1793
 
        raise NotImplementedError(self.reset_state)
1794
 
 
 
2535
    @needs_read_lock
1795
2536
    def _get_rules_searcher(self, default_searcher):
1796
2537
        """See Tree._get_rules_searcher."""
1797
2538
        if self._rules_searcher is None:
1805
2546
        return ShelfManager(self, self._transport)
1806
2547
 
1807
2548
 
1808
 
class InventoryWorkingTree(WorkingTree,
1809
 
        bzrlib.mutabletree.MutableInventoryTree):
1810
 
    """Base class for working trees that are inventory-oriented.
1811
 
 
1812
 
    The inventory is held in the `Branch` working-inventory, and the
1813
 
    files are in a directory on disk.
1814
 
 
1815
 
    It is possible for a `WorkingTree` to have a filename which is
1816
 
    not listed in the Inventory and vice versa.
 
2549
class WorkingTree2(WorkingTree):
 
2550
    """This is the Format 2 working tree.
 
2551
 
 
2552
    This was the first weave based working tree.
 
2553
     - uses os locks for locking.
 
2554
     - uses the branch last-revision.
1817
2555
    """
1818
2556
 
1819
 
    def __init__(self, basedir='.',
1820
 
                 branch=DEPRECATED_PARAMETER,
1821
 
                 _inventory=None,
1822
 
                 _control_files=None,
1823
 
                 _internal=False,
1824
 
                 _format=None,
1825
 
                 _bzrdir=None):
1826
 
        """Construct a InventoryWorkingTree instance. This is not a public API.
1827
 
 
1828
 
        :param branch: A branch to override probing for the branch.
1829
 
        """
1830
 
        super(InventoryWorkingTree, self).__init__(basedir=basedir,
1831
 
            branch=branch, _control_files=_control_files, _internal=_internal,
1832
 
            _format=_format, _bzrdir=_bzrdir)
1833
 
 
1834
 
        if _inventory is None:
1835
 
            # This will be acquired on lock_read() or lock_write()
1836
 
            self._inventory_is_modified = False
1837
 
            self._inventory = None
1838
 
        else:
1839
 
            # the caller of __init__ has provided an inventory,
1840
 
            # we assume they know what they are doing - as its only
1841
 
            # the Format factory and creation methods that are
1842
 
            # permitted to do this.
1843
 
            self._set_inventory(_inventory, dirty=False)
1844
 
 
1845
 
    def _set_inventory(self, inv, dirty):
1846
 
        """Set the internal cached inventory.
1847
 
 
1848
 
        :param inv: The inventory to set.
1849
 
        :param dirty: A boolean indicating whether the inventory is the same
1850
 
            logical inventory as whats on disk. If True the inventory is not
1851
 
            the same and should be written to disk or data will be lost, if
1852
 
            False then the inventory is the same as that on disk and any
1853
 
            serialisation would be unneeded overhead.
1854
 
        """
1855
 
        self._inventory = inv
1856
 
        self._inventory_is_modified = dirty
1857
 
 
1858
 
    def _serialize(self, inventory, out_file):
1859
 
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
1860
 
            working=True)
1861
 
 
1862
 
    def _deserialize(selt, in_file):
1863
 
        return xml5.serializer_v5.read_inventory(in_file)
1864
 
 
1865
 
    @needs_tree_write_lock
1866
 
    def _write_inventory(self, inv):
1867
 
        """Write inventory as the current inventory."""
1868
 
        self._set_inventory(inv, dirty=True)
1869
 
        self.flush()
1870
 
 
1871
 
    # XXX: This method should be deprecated in favour of taking in a proper
1872
 
    # new Inventory object.
1873
 
    @needs_tree_write_lock
1874
 
    def set_inventory(self, new_inventory_list):
1875
 
        from bzrlib.inventory import (Inventory,
1876
 
                                      InventoryDirectory,
1877
 
                                      InventoryFile,
1878
 
                                      InventoryLink)
1879
 
        inv = Inventory(self.get_root_id())
1880
 
        for path, file_id, parent, kind in new_inventory_list:
1881
 
            name = os.path.basename(path)
1882
 
            if name == "":
1883
 
                continue
1884
 
            # fixme, there should be a factory function inv,add_??
1885
 
            if kind == 'directory':
1886
 
                inv.add(InventoryDirectory(file_id, name, parent))
1887
 
            elif kind == 'file':
1888
 
                inv.add(InventoryFile(file_id, name, parent))
1889
 
            elif kind == 'symlink':
1890
 
                inv.add(InventoryLink(file_id, name, parent))
1891
 
            else:
1892
 
                raise errors.BzrError("unknown kind %r" % kind)
1893
 
        self._write_inventory(inv)
1894
 
 
1895
 
    def _write_basis_inventory(self, xml):
1896
 
        """Write the basis inventory XML to the basis-inventory file"""
1897
 
        path = self._basis_inventory_name()
1898
 
        sio = StringIO(xml)
1899
 
        self._transport.put_file(path, sio,
1900
 
            mode=self.bzrdir._get_file_mode())
1901
 
 
1902
 
    def _reset_data(self):
1903
 
        """Reset transient data that cannot be revalidated."""
1904
 
        self._inventory_is_modified = False
1905
 
        f = self._transport.get('inventory')
1906
 
        try:
1907
 
            result = self._deserialize(f)
 
2557
    def __init__(self, *args, **kwargs):
 
2558
        super(WorkingTree2, self).__init__(*args, **kwargs)
 
2559
        # WorkingTree2 has more of a constraint that self._inventory must
 
2560
        # exist. Because this is an older format, we don't mind the overhead
 
2561
        # caused by the extra computation here.
 
2562
 
 
2563
        # Newer WorkingTree's should only have self._inventory set when they
 
2564
        # have a read lock.
 
2565
        if self._inventory is None:
 
2566
            self.read_working_inventory()
 
2567
 
 
2568
    def lock_tree_write(self):
 
2569
        """See WorkingTree.lock_tree_write().
 
2570
 
 
2571
        In Format2 WorkingTrees we have a single lock for the branch and tree
 
2572
        so lock_tree_write() degrades to lock_write().
 
2573
        """
 
2574
        self.branch.lock_write()
 
2575
        try:
 
2576
            return self._control_files.lock_write()
 
2577
        except:
 
2578
            self.branch.unlock()
 
2579
            raise
 
2580
 
 
2581
    def unlock(self):
 
2582
        # do non-implementation specific cleanup
 
2583
        self._cleanup()
 
2584
 
 
2585
        # we share control files:
 
2586
        if self._control_files._lock_count == 3:
 
2587
            # _inventory_is_modified is always False during a read lock.
 
2588
            if self._inventory_is_modified:
 
2589
                self.flush()
 
2590
            self._write_hashcache_if_dirty()
 
2591
 
 
2592
        # reverse order of locking.
 
2593
        try:
 
2594
            return self._control_files.unlock()
1908
2595
        finally:
1909
 
            f.close()
1910
 
        self._set_inventory(result, dirty=False)
1911
 
 
1912
 
    def _set_root_id(self, file_id):
1913
 
        """Set the root id for this tree, in a format specific manner.
1914
 
 
1915
 
        :param file_id: The file id to assign to the root. It must not be
1916
 
            present in the current inventory or an error will occur. It must
1917
 
            not be None, but rather a valid file id.
1918
 
        """
1919
 
        inv = self._inventory
1920
 
        orig_root_id = inv.root.file_id
1921
 
        # TODO: it might be nice to exit early if there was nothing
1922
 
        # to do, saving us from trigger a sync on unlock.
1923
 
        self._inventory_is_modified = True
1924
 
        # we preserve the root inventory entry object, but
1925
 
        # unlinkit from the byid index
1926
 
        del inv._byid[inv.root.file_id]
1927
 
        inv.root.file_id = file_id
1928
 
        # and link it into the index with the new changed id.
1929
 
        inv._byid[inv.root.file_id] = inv.root
1930
 
        # and finally update all children to reference the new id.
1931
 
        # XXX: this should be safe to just look at the root.children
1932
 
        # list, not the WHOLE INVENTORY.
1933
 
        for fid in inv:
1934
 
            entry = inv[fid]
1935
 
            if entry.parent_id == orig_root_id:
1936
 
                entry.parent_id = inv.root.file_id
1937
 
 
1938
 
    def all_file_ids(self):
1939
 
        """See Tree.iter_all_file_ids"""
1940
 
        return set(self.inventory)
1941
 
 
1942
 
    @needs_tree_write_lock
1943
 
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1944
 
        """See MutableTree.set_parent_trees."""
1945
 
        parent_ids = [rev for (rev, tree) in parents_list]
1946
 
        for revision_id in parent_ids:
1947
 
            _mod_revision.check_not_reserved_id(revision_id)
1948
 
 
1949
 
        self._check_parents_for_ghosts(parent_ids,
1950
 
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
1951
 
 
1952
 
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
1953
 
 
1954
 
        if len(parent_ids) == 0:
1955
 
            leftmost_parent_id = _mod_revision.NULL_REVISION
1956
 
            leftmost_parent_tree = None
 
2596
            self.branch.unlock()
 
2597
 
 
2598
 
 
2599
class WorkingTree3(WorkingTree):
 
2600
    """This is the Format 3 working tree.
 
2601
 
 
2602
    This differs from the base WorkingTree by:
 
2603
     - having its own file lock
 
2604
     - having its own last-revision property.
 
2605
 
 
2606
    This is new in bzr 0.8
 
2607
    """
 
2608
 
 
2609
    @needs_read_lock
 
2610
    def _last_revision(self):
 
2611
        """See Mutable.last_revision."""
 
2612
        try:
 
2613
            return self._transport.get_bytes('last-revision')
 
2614
        except errors.NoSuchFile:
 
2615
            return _mod_revision.NULL_REVISION
 
2616
 
 
2617
    def _change_last_revision(self, revision_id):
 
2618
        """See WorkingTree._change_last_revision."""
 
2619
        if revision_id is None or revision_id == NULL_REVISION:
 
2620
            try:
 
2621
                self._transport.delete('last-revision')
 
2622
            except errors.NoSuchFile:
 
2623
                pass
 
2624
            return False
1957
2625
        else:
1958
 
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
1959
 
 
1960
 
        if self._change_last_revision(leftmost_parent_id):
1961
 
            if leftmost_parent_tree is None:
1962
 
                # If we don't have a tree, fall back to reading the
1963
 
                # parent tree from the repository.
1964
 
                self._cache_basis_inventory(leftmost_parent_id)
1965
 
            else:
1966
 
                inv = leftmost_parent_tree.inventory
1967
 
                xml = self._create_basis_xml_from_inventory(
1968
 
                                        leftmost_parent_id, inv)
1969
 
                self._write_basis_inventory(xml)
1970
 
        self._set_merges_from_parent_ids(parent_ids)
1971
 
 
1972
 
    def _cache_basis_inventory(self, new_revision):
1973
 
        """Cache new_revision as the basis inventory."""
1974
 
        # TODO: this should allow the ready-to-use inventory to be passed in,
1975
 
        # as commit already has that ready-to-use [while the format is the
1976
 
        # same, that is].
1977
 
        try:
1978
 
            # this double handles the inventory - unpack and repack -
1979
 
            # but is easier to understand. We can/should put a conditional
1980
 
            # in here based on whether the inventory is in the latest format
1981
 
            # - perhaps we should repack all inventories on a repository
1982
 
            # upgrade ?
1983
 
            # the fast path is to copy the raw xml from the repository. If the
1984
 
            # xml contains 'revision_id="', then we assume the right
1985
 
            # revision_id is set. We must check for this full string, because a
1986
 
            # root node id can legitimately look like 'revision_id' but cannot
1987
 
            # contain a '"'.
1988
 
            xml = self.branch.repository._get_inventory_xml(new_revision)
1989
 
            firstline = xml.split('\n', 1)[0]
1990
 
            if (not 'revision_id="' in firstline or
1991
 
                'format="7"' not in firstline):
1992
 
                inv = self.branch.repository._serializer.read_inventory_from_string(
1993
 
                    xml, new_revision)
1994
 
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
1995
 
            self._write_basis_inventory(xml)
1996
 
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1997
 
            pass
1998
 
 
1999
 
    def _basis_inventory_name(self):
2000
 
        return 'basis-inventory-cache'
2001
 
 
2002
 
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
2003
 
        """Create the text that will be saved in basis-inventory"""
2004
 
        inventory.revision_id = revision_id
2005
 
        return xml7.serializer_v7.write_inventory_to_string(inventory)
 
2626
            self._transport.put_bytes('last-revision', revision_id,
 
2627
                mode=self.bzrdir._get_file_mode())
 
2628
            return True
2006
2629
 
2007
2630
    @needs_tree_write_lock
2008
2631
    def set_conflicts(self, conflicts):
2028
2651
                    raise errors.ConflictFormatError()
2029
2652
            except StopIteration:
2030
2653
                raise errors.ConflictFormatError()
2031
 
            reader = _mod_rio.RioReader(confile)
2032
 
            return _mod_conflicts.ConflictList.from_stanzas(reader)
 
2654
            return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2033
2655
        finally:
2034
2656
            confile.close()
2035
2657
 
2036
 
    def read_basis_inventory(self):
2037
 
        """Read the cached basis inventory."""
2038
 
        path = self._basis_inventory_name()
2039
 
        return self._transport.get_bytes(path)
2040
 
 
2041
 
    @needs_read_lock
2042
 
    def read_working_inventory(self):
2043
 
        """Read the working inventory.
2044
 
 
2045
 
        :raises errors.InventoryModified: read_working_inventory will fail
2046
 
            when the current in memory inventory has been modified.
2047
 
        """
2048
 
        # conceptually this should be an implementation detail of the tree.
2049
 
        # XXX: Deprecate this.
2050
 
        # ElementTree does its own conversion from UTF-8, so open in
2051
 
        # binary.
2052
 
        if self._inventory_is_modified:
2053
 
            raise errors.InventoryModified(self)
2054
 
        f = self._transport.get('inventory')
2055
 
        try:
2056
 
            result = self._deserialize(f)
2057
 
        finally:
2058
 
            f.close()
2059
 
        self._set_inventory(result, dirty=False)
2060
 
        return result
2061
 
 
2062
 
    @needs_read_lock
2063
 
    def get_root_id(self):
2064
 
        """Return the id of this trees root"""
2065
 
        return self._inventory.root.file_id
2066
 
 
2067
 
    def has_id(self, file_id):
2068
 
        # files that have been deleted are excluded
2069
 
        inv = self.inventory
2070
 
        if not inv.has_id(file_id):
2071
 
            return False
2072
 
        path = inv.id2path(file_id)
2073
 
        return osutils.lexists(self.abspath(path))
2074
 
 
2075
 
    def has_or_had_id(self, file_id):
2076
 
        if file_id == self.inventory.root.file_id:
2077
 
            return True
2078
 
        return self.inventory.has_id(file_id)
2079
 
 
2080
 
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
2081
 
    def __iter__(self):
2082
 
        """Iterate through file_ids for this tree.
2083
 
 
2084
 
        file_ids are in a WorkingTree if they are in the working inventory
2085
 
        and the working file exists.
2086
 
        """
2087
 
        inv = self._inventory
2088
 
        for path, ie in inv.iter_entries():
2089
 
            if osutils.lexists(self.abspath(path)):
2090
 
                yield ie.file_id
2091
 
 
2092
 
    @needs_tree_write_lock
2093
 
    def set_last_revision(self, new_revision):
2094
 
        """Change the last revision in the working tree."""
2095
 
        if self._change_last_revision(new_revision):
2096
 
            self._cache_basis_inventory(new_revision)
2097
 
 
2098
 
    def _get_check_refs(self):
2099
 
        """Return the references needed to perform a check of this tree.
2100
 
        
2101
 
        The default implementation returns no refs, and is only suitable for
2102
 
        trees that have no local caching and can commit on ghosts at any time.
2103
 
 
2104
 
        :seealso: bzrlib.check for details about check_refs.
2105
 
        """
2106
 
        return []
2107
 
 
2108
 
    @needs_read_lock
2109
 
    def _check(self, references):
2110
 
        """Check the tree for consistency.
2111
 
 
2112
 
        :param references: A dict with keys matching the items returned by
2113
 
            self._get_check_refs(), and values from looking those keys up in
2114
 
            the repository.
2115
 
        """
2116
 
        tree_basis = self.basis_tree()
2117
 
        tree_basis.lock_read()
2118
 
        try:
2119
 
            repo_basis = references[('trees', self.last_revision())]
2120
 
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2121
 
                raise errors.BzrCheckError(
2122
 
                    "Mismatched basis inventory content.")
2123
 
            self._validate()
2124
 
        finally:
2125
 
            tree_basis.unlock()
2126
 
 
2127
 
    @needs_read_lock
2128
 
    def check_state(self):
2129
 
        """Check that the working state is/isn't valid."""
2130
 
        check_refs = self._get_check_refs()
2131
 
        refs = {}
2132
 
        for ref in check_refs:
2133
 
            kind, value = ref
2134
 
            if kind == 'trees':
2135
 
                refs[ref] = self.branch.repository.revision_tree(value)
2136
 
        self._check(refs)
2137
 
 
2138
 
    @needs_tree_write_lock
2139
 
    def reset_state(self, revision_ids=None):
2140
 
        """Reset the state of the working tree.
2141
 
 
2142
 
        This does a hard-reset to a last-known-good state. This is a way to
2143
 
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
2144
 
        """
2145
 
        if revision_ids is None:
2146
 
            revision_ids = self.get_parent_ids()
2147
 
        if not revision_ids:
2148
 
            rt = self.branch.repository.revision_tree(
2149
 
                _mod_revision.NULL_REVISION)
2150
 
        else:
2151
 
            rt = self.branch.repository.revision_tree(revision_ids[0])
2152
 
        self._write_inventory(rt.inventory)
2153
 
        self.set_parent_ids(revision_ids)
2154
 
 
2155
 
    def flush(self):
2156
 
        """Write the in memory inventory to disk."""
2157
 
        # TODO: Maybe this should only write on dirty ?
2158
 
        if self._control_files._lock_mode != 'w':
2159
 
            raise errors.NotWriteLocked(self)
2160
 
        sio = StringIO()
2161
 
        self._serialize(self._inventory, sio)
2162
 
        sio.seek(0)
2163
 
        self._transport.put_file('inventory', sio,
2164
 
            mode=self.bzrdir._get_file_mode())
2165
 
        self._inventory_is_modified = False
2166
 
 
2167
 
    @needs_read_lock
2168
 
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2169
 
        if not path:
2170
 
            path = self._inventory.id2path(file_id)
2171
 
        return self._hashcache.get_sha1(path, stat_value)
2172
 
 
2173
 
    def get_file_mtime(self, file_id, path=None):
2174
 
        """See Tree.get_file_mtime."""
2175
 
        if not path:
2176
 
            path = self.inventory.id2path(file_id)
2177
 
        return os.lstat(self.abspath(path)).st_mtime
2178
 
 
2179
 
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
2180
 
        file_id = self.path2id(path)
2181
 
        if file_id is None:
2182
 
            # For unversioned files on win32, we just assume they are not
2183
 
            # executable
2184
 
            return False
2185
 
        return self._inventory[file_id].executable
2186
 
 
2187
 
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
2188
 
        mode = stat_result.st_mode
2189
 
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
2190
 
 
2191
 
    if not supports_executable():
2192
 
        def is_executable(self, file_id, path=None):
2193
 
            return self._inventory[file_id].executable
2194
 
 
2195
 
        _is_executable_from_path_and_stat = \
2196
 
            _is_executable_from_path_and_stat_from_basis
2197
 
    else:
2198
 
        def is_executable(self, file_id, path=None):
2199
 
            if not path:
2200
 
                path = self.id2path(file_id)
2201
 
            mode = os.lstat(self.abspath(path)).st_mode
2202
 
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
2203
 
 
2204
 
        _is_executable_from_path_and_stat = \
2205
 
            _is_executable_from_path_and_stat_from_stat
2206
 
 
2207
 
    @needs_tree_write_lock
2208
 
    def _add(self, files, ids, kinds):
2209
 
        """See MutableTree._add."""
2210
 
        # TODO: Re-adding a file that is removed in the working copy
2211
 
        # should probably put it back with the previous ID.
2212
 
        # the read and write working inventory should not occur in this
2213
 
        # function - they should be part of lock_write and unlock.
2214
 
        inv = self.inventory
2215
 
        for f, file_id, kind in zip(files, ids, kinds):
2216
 
            if file_id is None:
2217
 
                inv.add_path(f, kind=kind)
2218
 
            else:
2219
 
                inv.add_path(f, kind=kind, file_id=file_id)
2220
 
            self._inventory_is_modified = True
2221
 
 
2222
 
    def revision_tree(self, revision_id):
2223
 
        """See WorkingTree.revision_id."""
2224
 
        if revision_id == self.last_revision():
2225
 
            try:
2226
 
                xml = self.read_basis_inventory()
2227
 
            except errors.NoSuchFile:
2228
 
                pass
2229
 
            else:
2230
 
                try:
2231
 
                    inv = xml7.serializer_v7.read_inventory_from_string(xml)
2232
 
                    # dont use the repository revision_tree api because we want
2233
 
                    # to supply the inventory.
2234
 
                    if inv.revision_id == revision_id:
2235
 
                        return revisiontree.InventoryRevisionTree(
2236
 
                            self.branch.repository, inv, revision_id)
2237
 
                except errors.BadInventoryFormat:
2238
 
                    pass
2239
 
        # raise if there was no inventory, or if we read the wrong inventory.
2240
 
        raise errors.NoSuchRevisionInTree(self, revision_id)
2241
 
 
2242
 
    @needs_read_lock
2243
 
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
2244
 
        """See Tree.annotate_iter
2245
 
 
2246
 
        This implementation will use the basis tree implementation if possible.
2247
 
        Lines not in the basis are attributed to CURRENT_REVISION
2248
 
 
2249
 
        If there are pending merges, lines added by those merges will be
2250
 
        incorrectly attributed to CURRENT_REVISION (but after committing, the
2251
 
        attribution will be correct).
2252
 
        """
2253
 
        maybe_file_parent_keys = []
2254
 
        for parent_id in self.get_parent_ids():
2255
 
            try:
2256
 
                parent_tree = self.revision_tree(parent_id)
2257
 
            except errors.NoSuchRevisionInTree:
2258
 
                parent_tree = self.branch.repository.revision_tree(parent_id)
2259
 
            parent_tree.lock_read()
2260
 
            try:
2261
 
                if not parent_tree.has_id(file_id):
2262
 
                    continue
2263
 
                ie = parent_tree.inventory[file_id]
2264
 
                if ie.kind != 'file':
2265
 
                    # Note: this is slightly unnecessary, because symlinks and
2266
 
                    # directories have a "text" which is the empty text, and we
2267
 
                    # know that won't mess up annotations. But it seems cleaner
2268
 
                    continue
2269
 
                parent_text_key = (file_id, ie.revision)
2270
 
                if parent_text_key not in maybe_file_parent_keys:
2271
 
                    maybe_file_parent_keys.append(parent_text_key)
2272
 
            finally:
2273
 
                parent_tree.unlock()
2274
 
        graph = _mod_graph.Graph(self.branch.repository.texts)
2275
 
        heads = graph.heads(maybe_file_parent_keys)
2276
 
        file_parent_keys = []
2277
 
        for key in maybe_file_parent_keys:
2278
 
            if key in heads:
2279
 
                file_parent_keys.append(key)
2280
 
 
2281
 
        # Now we have the parents of this content
2282
 
        annotator = self.branch.repository.texts.get_annotator()
2283
 
        text = self.get_file_text(file_id)
2284
 
        this_key =(file_id, default_revision)
2285
 
        annotator.add_special_text(this_key, file_parent_keys, text)
2286
 
        annotations = [(key[-1], line)
2287
 
                       for key, line in annotator.annotate_flat(this_key)]
2288
 
        return annotations
2289
 
 
2290
 
    @needs_read_lock
2291
 
    def merge_modified(self):
2292
 
        """Return a dictionary of files modified by a merge.
2293
 
 
2294
 
        The list is initialized by WorkingTree.set_merge_modified, which is
2295
 
        typically called after we make some automatic updates to the tree
2296
 
        because of a merge.
2297
 
 
2298
 
        This returns a map of file_id->sha1, containing only files which are
2299
 
        still in the working inventory and have that text hash.
2300
 
        """
2301
 
        try:
2302
 
            hashfile = self._transport.get('merge-hashes')
2303
 
        except errors.NoSuchFile:
2304
 
            return {}
2305
 
        try:
2306
 
            merge_hashes = {}
2307
 
            try:
2308
 
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
2309
 
                    raise errors.MergeModifiedFormatError()
2310
 
            except StopIteration:
2311
 
                raise errors.MergeModifiedFormatError()
2312
 
            for s in _mod_rio.RioReader(hashfile):
2313
 
                # RioReader reads in Unicode, so convert file_ids back to utf8
2314
 
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
2315
 
                if not self.inventory.has_id(file_id):
2316
 
                    continue
2317
 
                text_hash = s.get("hash")
2318
 
                if text_hash == self.get_file_sha1(file_id):
2319
 
                    merge_hashes[file_id] = text_hash
2320
 
            return merge_hashes
2321
 
        finally:
2322
 
            hashfile.close()
2323
 
 
2324
 
    @needs_write_lock
2325
 
    def subsume(self, other_tree):
2326
 
        def add_children(inventory, entry):
2327
 
            for child_entry in entry.children.values():
2328
 
                inventory._byid[child_entry.file_id] = child_entry
2329
 
                if child_entry.kind == 'directory':
2330
 
                    add_children(inventory, child_entry)
2331
 
        if other_tree.get_root_id() == self.get_root_id():
2332
 
            raise errors.BadSubsumeSource(self, other_tree,
2333
 
                                          'Trees have the same root')
2334
 
        try:
2335
 
            other_tree_path = self.relpath(other_tree.basedir)
2336
 
        except errors.PathNotChild:
2337
 
            raise errors.BadSubsumeSource(self, other_tree,
2338
 
                'Tree is not contained by the other')
2339
 
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
2340
 
        if new_root_parent is None:
2341
 
            raise errors.BadSubsumeSource(self, other_tree,
2342
 
                'Parent directory is not versioned.')
2343
 
        # We need to ensure that the result of a fetch will have a
2344
 
        # versionedfile for the other_tree root, and only fetching into
2345
 
        # RepositoryKnit2 guarantees that.
2346
 
        if not self.branch.repository.supports_rich_root():
2347
 
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
2348
 
        other_tree.lock_tree_write()
2349
 
        try:
2350
 
            new_parents = other_tree.get_parent_ids()
2351
 
            other_root = other_tree.inventory.root
2352
 
            other_root.parent_id = new_root_parent
2353
 
            other_root.name = osutils.basename(other_tree_path)
2354
 
            self.inventory.add(other_root)
2355
 
            add_children(self.inventory, other_root)
2356
 
            self._write_inventory(self.inventory)
2357
 
            # normally we don't want to fetch whole repositories, but i think
2358
 
            # here we really do want to consolidate the whole thing.
2359
 
            for parent_id in other_tree.get_parent_ids():
2360
 
                self.branch.fetch(other_tree.branch, parent_id)
2361
 
                self.add_parent_tree_id(parent_id)
2362
 
        finally:
2363
 
            other_tree.unlock()
2364
 
        other_tree.bzrdir.retire_bzrdir()
2365
 
 
2366
 
    @needs_tree_write_lock
2367
 
    def extract(self, file_id, format=None):
2368
 
        """Extract a subtree from this tree.
2369
 
 
2370
 
        A new branch will be created, relative to the path for this tree.
2371
 
        """
2372
 
        self.flush()
2373
 
        def mkdirs(path):
2374
 
            segments = osutils.splitpath(path)
2375
 
            transport = self.branch.bzrdir.root_transport
2376
 
            for name in segments:
2377
 
                transport = transport.clone(name)
2378
 
                transport.ensure_base()
2379
 
            return transport
2380
 
 
2381
 
        sub_path = self.id2path(file_id)
2382
 
        branch_transport = mkdirs(sub_path)
2383
 
        if format is None:
2384
 
            format = self.bzrdir.cloning_metadir()
2385
 
        branch_transport.ensure_base()
2386
 
        branch_bzrdir = format.initialize_on_transport(branch_transport)
2387
 
        try:
2388
 
            repo = branch_bzrdir.find_repository()
2389
 
        except errors.NoRepositoryPresent:
2390
 
            repo = branch_bzrdir.create_repository()
2391
 
        if not repo.supports_rich_root():
2392
 
            raise errors.RootNotRich()
2393
 
        new_branch = branch_bzrdir.create_branch()
2394
 
        new_branch.pull(self.branch)
2395
 
        for parent_id in self.get_parent_ids():
2396
 
            new_branch.fetch(self.branch, parent_id)
2397
 
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
2398
 
        if tree_transport.base != branch_transport.base:
2399
 
            tree_bzrdir = format.initialize_on_transport(tree_transport)
2400
 
            branch.BranchReferenceFormat().initialize(tree_bzrdir,
2401
 
                target_branch=new_branch)
2402
 
        else:
2403
 
            tree_bzrdir = branch_bzrdir
2404
 
        wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
2405
 
        wt.set_parent_ids(self.get_parent_ids())
2406
 
        my_inv = self.inventory
2407
 
        child_inv = inventory.Inventory(root_id=None)
2408
 
        new_root = my_inv[file_id]
2409
 
        my_inv.remove_recursive_id(file_id)
2410
 
        new_root.parent_id = None
2411
 
        child_inv.add(new_root)
2412
 
        self._write_inventory(my_inv)
2413
 
        wt._write_inventory(child_inv)
2414
 
        return wt
2415
 
 
2416
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
2417
 
        """List all files as (path, class, kind, id, entry).
2418
 
 
2419
 
        Lists, but does not descend into unversioned directories.
2420
 
        This does not include files that have been deleted in this
2421
 
        tree. Skips the control directory.
2422
 
 
2423
 
        :param include_root: if True, return an entry for the root
2424
 
        :param from_dir: start from this directory or None for the root
2425
 
        :param recursive: whether to recurse into subdirectories or not
2426
 
        """
2427
 
        # list_files is an iterator, so @needs_read_lock doesn't work properly
2428
 
        # with it. So callers should be careful to always read_lock the tree.
2429
 
        if not self.is_locked():
2430
 
            raise errors.ObjectNotLocked(self)
2431
 
 
2432
 
        inv = self.inventory
2433
 
        if from_dir is None and include_root is True:
2434
 
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
2435
 
        # Convert these into local objects to save lookup times
2436
 
        pathjoin = osutils.pathjoin
2437
 
        file_kind = self._kind
2438
 
 
2439
 
        # transport.base ends in a slash, we want the piece
2440
 
        # between the last two slashes
2441
 
        transport_base_dir = self.bzrdir.transport.base.rsplit('/', 2)[1]
2442
 
 
2443
 
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
2444
 
 
2445
 
        # directory file_id, relative path, absolute path, reverse sorted children
2446
 
        if from_dir is not None:
2447
 
            from_dir_id = inv.path2id(from_dir)
2448
 
            if from_dir_id is None:
2449
 
                # Directory not versioned
2450
 
                return
2451
 
            from_dir_abspath = pathjoin(self.basedir, from_dir)
2452
 
        else:
2453
 
            from_dir_id = inv.root.file_id
2454
 
            from_dir_abspath = self.basedir
2455
 
        children = os.listdir(from_dir_abspath)
2456
 
        children.sort()
2457
 
        # jam 20060527 The kernel sized tree seems equivalent whether we
2458
 
        # use a deque and popleft to keep them sorted, or if we use a plain
2459
 
        # list and just reverse() them.
2460
 
        children = collections.deque(children)
2461
 
        stack = [(from_dir_id, u'', from_dir_abspath, children)]
2462
 
        while stack:
2463
 
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
2464
 
 
2465
 
            while children:
2466
 
                f = children.popleft()
2467
 
                ## TODO: If we find a subdirectory with its own .bzr
2468
 
                ## directory, then that is a separate tree and we
2469
 
                ## should exclude it.
2470
 
 
2471
 
                # the bzrdir for this tree
2472
 
                if transport_base_dir == f:
2473
 
                    continue
2474
 
 
2475
 
                # we know that from_dir_relpath and from_dir_abspath never end in a slash
2476
 
                # and 'f' doesn't begin with one, we can do a string op, rather
2477
 
                # than the checks of pathjoin(), all relative paths will have an extra slash
2478
 
                # at the beginning
2479
 
                fp = from_dir_relpath + '/' + f
2480
 
 
2481
 
                # absolute path
2482
 
                fap = from_dir_abspath + '/' + f
2483
 
 
2484
 
                dir_ie = inv[from_dir_id]
2485
 
                if dir_ie.kind == 'directory':
2486
 
                    f_ie = dir_ie.children.get(f)
2487
 
                else:
2488
 
                    f_ie = None
2489
 
                if f_ie:
2490
 
                    c = 'V'
2491
 
                elif self.is_ignored(fp[1:]):
2492
 
                    c = 'I'
2493
 
                else:
2494
 
                    # we may not have found this file, because of a unicode
2495
 
                    # issue, or because the directory was actually a symlink.
2496
 
                    f_norm, can_access = osutils.normalized_filename(f)
2497
 
                    if f == f_norm or not can_access:
2498
 
                        # No change, so treat this file normally
2499
 
                        c = '?'
2500
 
                    else:
2501
 
                        # this file can be accessed by a normalized path
2502
 
                        # check again if it is versioned
2503
 
                        # these lines are repeated here for performance
2504
 
                        f = f_norm
2505
 
                        fp = from_dir_relpath + '/' + f
2506
 
                        fap = from_dir_abspath + '/' + f
2507
 
                        f_ie = inv.get_child(from_dir_id, f)
2508
 
                        if f_ie:
2509
 
                            c = 'V'
2510
 
                        elif self.is_ignored(fp[1:]):
2511
 
                            c = 'I'
2512
 
                        else:
2513
 
                            c = '?'
2514
 
 
2515
 
                fk = file_kind(fap)
2516
 
 
2517
 
                # make a last minute entry
2518
 
                if f_ie:
2519
 
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
2520
 
                else:
2521
 
                    try:
2522
 
                        yield fp[1:], c, fk, None, fk_entries[fk]()
2523
 
                    except KeyError:
2524
 
                        yield fp[1:], c, fk, None, TreeEntry()
2525
 
                    continue
2526
 
 
2527
 
                if fk != 'directory':
2528
 
                    continue
2529
 
 
2530
 
                # But do this child first if recursing down
2531
 
                if recursive:
2532
 
                    new_children = os.listdir(fap)
2533
 
                    new_children.sort()
2534
 
                    new_children = collections.deque(new_children)
2535
 
                    stack.append((f_ie.file_id, fp, fap, new_children))
2536
 
                    # Break out of inner loop,
2537
 
                    # so that we start outer loop with child
2538
 
                    break
2539
 
            else:
2540
 
                # if we finished all children, pop it off the stack
2541
 
                stack.pop()
2542
 
 
2543
 
    @needs_tree_write_lock
2544
 
    def move(self, from_paths, to_dir=None, after=False):
2545
 
        """Rename files.
2546
 
 
2547
 
        to_dir must exist in the inventory.
2548
 
 
2549
 
        If to_dir exists and is a directory, the files are moved into
2550
 
        it, keeping their old names.
2551
 
 
2552
 
        Note that to_dir is only the last component of the new name;
2553
 
        this doesn't change the directory.
2554
 
 
2555
 
        For each entry in from_paths the move mode will be determined
2556
 
        independently.
2557
 
 
2558
 
        The first mode moves the file in the filesystem and updates the
2559
 
        inventory. The second mode only updates the inventory without
2560
 
        touching the file on the filesystem.
2561
 
 
2562
 
        move uses the second mode if 'after == True' and the target is
2563
 
        either not versioned or newly added, and present in the working tree.
2564
 
 
2565
 
        move uses the second mode if 'after == False' and the source is
2566
 
        versioned but no longer in the working tree, and the target is not
2567
 
        versioned but present in the working tree.
2568
 
 
2569
 
        move uses the first mode if 'after == False' and the source is
2570
 
        versioned and present in the working tree, and the target is not
2571
 
        versioned and not present in the working tree.
2572
 
 
2573
 
        Everything else results in an error.
2574
 
 
2575
 
        This returns a list of (from_path, to_path) pairs for each
2576
 
        entry that is moved.
2577
 
        """
2578
 
        rename_entries = []
2579
 
        rename_tuples = []
2580
 
 
2581
 
        # check for deprecated use of signature
2582
 
        if to_dir is None:
2583
 
            raise TypeError('You must supply a target directory')
2584
 
        # check destination directory
2585
 
        if isinstance(from_paths, basestring):
2586
 
            raise ValueError()
2587
 
        inv = self.inventory
2588
 
        to_abs = self.abspath(to_dir)
2589
 
        if not isdir(to_abs):
2590
 
            raise errors.BzrMoveFailedError('',to_dir,
2591
 
                errors.NotADirectory(to_abs))
2592
 
        if not self.has_filename(to_dir):
2593
 
            raise errors.BzrMoveFailedError('',to_dir,
2594
 
                errors.NotInWorkingDirectory(to_dir))
2595
 
        to_dir_id = inv.path2id(to_dir)
2596
 
        if to_dir_id is None:
2597
 
            raise errors.BzrMoveFailedError('',to_dir,
2598
 
                errors.NotVersionedError(path=to_dir))
2599
 
 
2600
 
        to_dir_ie = inv[to_dir_id]
2601
 
        if to_dir_ie.kind != 'directory':
2602
 
            raise errors.BzrMoveFailedError('',to_dir,
2603
 
                errors.NotADirectory(to_abs))
2604
 
 
2605
 
        # create rename entries and tuples
2606
 
        for from_rel in from_paths:
2607
 
            from_tail = splitpath(from_rel)[-1]
2608
 
            from_id = inv.path2id(from_rel)
2609
 
            if from_id is None:
2610
 
                raise errors.BzrMoveFailedError(from_rel,to_dir,
2611
 
                    errors.NotVersionedError(path=from_rel))
2612
 
 
2613
 
            from_entry = inv[from_id]
2614
 
            from_parent_id = from_entry.parent_id
2615
 
            to_rel = pathjoin(to_dir, from_tail)
2616
 
            rename_entry = InventoryWorkingTree._RenameEntry(
2617
 
                from_rel=from_rel,
2618
 
                from_id=from_id,
2619
 
                from_tail=from_tail,
2620
 
                from_parent_id=from_parent_id,
2621
 
                to_rel=to_rel, to_tail=from_tail,
2622
 
                to_parent_id=to_dir_id)
2623
 
            rename_entries.append(rename_entry)
2624
 
            rename_tuples.append((from_rel, to_rel))
2625
 
 
2626
 
        # determine which move mode to use. checks also for movability
2627
 
        rename_entries = self._determine_mv_mode(rename_entries, after)
2628
 
 
2629
 
        original_modified = self._inventory_is_modified
2630
 
        try:
2631
 
            if len(from_paths):
2632
 
                self._inventory_is_modified = True
2633
 
            self._move(rename_entries)
2634
 
        except:
2635
 
            # restore the inventory on error
2636
 
            self._inventory_is_modified = original_modified
2637
 
            raise
2638
 
        self._write_inventory(inv)
2639
 
        return rename_tuples
2640
 
 
2641
 
    @needs_tree_write_lock
2642
 
    def rename_one(self, from_rel, to_rel, after=False):
2643
 
        """Rename one file.
2644
 
 
2645
 
        This can change the directory or the filename or both.
2646
 
 
2647
 
        rename_one has several 'modes' to work. First, it can rename a physical
2648
 
        file and change the file_id. That is the normal mode. Second, it can
2649
 
        only change the file_id without touching any physical file.
2650
 
 
2651
 
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
2652
 
        versioned but present in the working tree.
2653
 
 
2654
 
        rename_one uses the second mode if 'after == False' and 'from_rel' is
2655
 
        versioned but no longer in the working tree, and 'to_rel' is not
2656
 
        versioned but present in the working tree.
2657
 
 
2658
 
        rename_one uses the first mode if 'after == False' and 'from_rel' is
2659
 
        versioned and present in the working tree, and 'to_rel' is not
2660
 
        versioned and not present in the working tree.
2661
 
 
2662
 
        Everything else results in an error.
2663
 
        """
2664
 
        inv = self.inventory
2665
 
        rename_entries = []
2666
 
 
2667
 
        # create rename entries and tuples
2668
 
        from_tail = splitpath(from_rel)[-1]
2669
 
        from_id = inv.path2id(from_rel)
2670
 
        if from_id is None:
2671
 
            # if file is missing in the inventory maybe it's in the basis_tree
2672
 
            basis_tree = self.branch.basis_tree()
2673
 
            from_id = basis_tree.path2id(from_rel)
2674
 
            if from_id is None:
2675
 
                raise errors.BzrRenameFailedError(from_rel,to_rel,
2676
 
                    errors.NotVersionedError(path=from_rel))
2677
 
            # put entry back in the inventory so we can rename it
2678
 
            from_entry = basis_tree.inventory[from_id].copy()
2679
 
            inv.add(from_entry)
2680
 
        else:
2681
 
            from_entry = inv[from_id]
2682
 
        from_parent_id = from_entry.parent_id
2683
 
        to_dir, to_tail = os.path.split(to_rel)
2684
 
        to_dir_id = inv.path2id(to_dir)
2685
 
        rename_entry = InventoryWorkingTree._RenameEntry(from_rel=from_rel,
2686
 
                                     from_id=from_id,
2687
 
                                     from_tail=from_tail,
2688
 
                                     from_parent_id=from_parent_id,
2689
 
                                     to_rel=to_rel, to_tail=to_tail,
2690
 
                                     to_parent_id=to_dir_id)
2691
 
        rename_entries.append(rename_entry)
2692
 
 
2693
 
        # determine which move mode to use. checks also for movability
2694
 
        rename_entries = self._determine_mv_mode(rename_entries, after)
2695
 
 
2696
 
        # check if the target changed directory and if the target directory is
2697
 
        # versioned
2698
 
        if to_dir_id is None:
2699
 
            raise errors.BzrMoveFailedError(from_rel,to_rel,
2700
 
                errors.NotVersionedError(path=to_dir))
2701
 
 
2702
 
        # all checks done. now we can continue with our actual work
2703
 
        mutter('rename_one:\n'
2704
 
               '  from_id   {%s}\n'
2705
 
               '  from_rel: %r\n'
2706
 
               '  to_rel:   %r\n'
2707
 
               '  to_dir    %r\n'
2708
 
               '  to_dir_id {%s}\n',
2709
 
               from_id, from_rel, to_rel, to_dir, to_dir_id)
2710
 
 
2711
 
        self._move(rename_entries)
2712
 
        self._write_inventory(inv)
2713
 
 
2714
 
    class _RenameEntry(object):
2715
 
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
2716
 
                     to_rel, to_tail, to_parent_id, only_change_inv=False,
2717
 
                     change_id=False):
2718
 
            self.from_rel = from_rel
2719
 
            self.from_id = from_id
2720
 
            self.from_tail = from_tail
2721
 
            self.from_parent_id = from_parent_id
2722
 
            self.to_rel = to_rel
2723
 
            self.to_tail = to_tail
2724
 
            self.to_parent_id = to_parent_id
2725
 
            self.change_id = change_id
2726
 
            self.only_change_inv = only_change_inv
2727
 
 
2728
 
    def _determine_mv_mode(self, rename_entries, after=False):
2729
 
        """Determines for each from-to pair if both inventory and working tree
2730
 
        or only the inventory has to be changed.
2731
 
 
2732
 
        Also does basic plausability tests.
2733
 
        """
2734
 
        inv = self.inventory
2735
 
 
2736
 
        for rename_entry in rename_entries:
2737
 
            # store to local variables for easier reference
2738
 
            from_rel = rename_entry.from_rel
2739
 
            from_id = rename_entry.from_id
2740
 
            to_rel = rename_entry.to_rel
2741
 
            to_id = inv.path2id(to_rel)
2742
 
            only_change_inv = False
2743
 
            change_id = False
2744
 
 
2745
 
            # check the inventory for source and destination
2746
 
            if from_id is None:
2747
 
                raise errors.BzrMoveFailedError(from_rel,to_rel,
2748
 
                    errors.NotVersionedError(path=from_rel))
2749
 
            if to_id is not None:
2750
 
                allowed = False
2751
 
                # allow it with --after but only if dest is newly added
2752
 
                if after:
2753
 
                    basis = self.basis_tree()
2754
 
                    basis.lock_read()
2755
 
                    try:
2756
 
                        if not basis.has_id(to_id):
2757
 
                            rename_entry.change_id = True
2758
 
                            allowed = True
2759
 
                    finally:
2760
 
                        basis.unlock()
2761
 
                if not allowed:
2762
 
                    raise errors.BzrMoveFailedError(from_rel,to_rel,
2763
 
                        errors.AlreadyVersionedError(path=to_rel))
2764
 
 
2765
 
            # try to determine the mode for rename (only change inv or change
2766
 
            # inv and file system)
2767
 
            if after:
2768
 
                if not self.has_filename(to_rel):
2769
 
                    raise errors.BzrMoveFailedError(from_id,to_rel,
2770
 
                        errors.NoSuchFile(path=to_rel,
2771
 
                        extra="New file has not been created yet"))
2772
 
                only_change_inv = True
2773
 
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
2774
 
                only_change_inv = True
2775
 
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
2776
 
                only_change_inv = False
2777
 
            elif (not self.case_sensitive
2778
 
                  and from_rel.lower() == to_rel.lower()
2779
 
                  and self.has_filename(from_rel)):
2780
 
                only_change_inv = False
2781
 
            else:
2782
 
                # something is wrong, so lets determine what exactly
2783
 
                if not self.has_filename(from_rel) and \
2784
 
                   not self.has_filename(to_rel):
2785
 
                    raise errors.BzrRenameFailedError(from_rel,to_rel,
2786
 
                        errors.PathsDoNotExist(paths=(str(from_rel),
2787
 
                        str(to_rel))))
2788
 
                else:
2789
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
2790
 
            rename_entry.only_change_inv = only_change_inv
2791
 
        return rename_entries
2792
 
 
2793
 
    def _move(self, rename_entries):
2794
 
        """Moves a list of files.
2795
 
 
2796
 
        Depending on the value of the flag 'only_change_inv', the
2797
 
        file will be moved on the file system or not.
2798
 
        """
2799
 
        inv = self.inventory
2800
 
        moved = []
2801
 
 
2802
 
        for entry in rename_entries:
2803
 
            try:
2804
 
                self._move_entry(entry)
2805
 
            except:
2806
 
                self._rollback_move(moved)
2807
 
                raise
2808
 
            moved.append(entry)
2809
 
 
2810
 
    def _rollback_move(self, moved):
2811
 
        """Try to rollback a previous move in case of an filesystem error."""
2812
 
        inv = self.inventory
2813
 
        for entry in moved:
2814
 
            try:
2815
 
                self._move_entry(WorkingTree._RenameEntry(
2816
 
                    entry.to_rel, entry.from_id,
2817
 
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
2818
 
                    entry.from_tail, entry.from_parent_id,
2819
 
                    entry.only_change_inv))
2820
 
            except errors.BzrMoveFailedError, e:
2821
 
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
2822
 
                        " The working tree is in an inconsistent state."
2823
 
                        " Please consider doing a 'bzr revert'."
2824
 
                        " Error message is: %s" % e)
2825
 
 
2826
 
    def _move_entry(self, entry):
2827
 
        inv = self.inventory
2828
 
        from_rel_abs = self.abspath(entry.from_rel)
2829
 
        to_rel_abs = self.abspath(entry.to_rel)
2830
 
        if from_rel_abs == to_rel_abs:
2831
 
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
2832
 
                "Source and target are identical.")
2833
 
 
2834
 
        if not entry.only_change_inv:
2835
 
            try:
2836
 
                osutils.rename(from_rel_abs, to_rel_abs)
2837
 
            except OSError, e:
2838
 
                raise errors.BzrMoveFailedError(entry.from_rel,
2839
 
                    entry.to_rel, e[1])
2840
 
        if entry.change_id:
2841
 
            to_id = inv.path2id(entry.to_rel)
2842
 
            inv.remove_recursive_id(to_id)
2843
 
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
2844
 
 
2845
 
    @needs_tree_write_lock
2846
 
    def unversion(self, file_ids):
2847
 
        """Remove the file ids in file_ids from the current versioned set.
2848
 
 
2849
 
        When a file_id is unversioned, all of its children are automatically
2850
 
        unversioned.
2851
 
 
2852
 
        :param file_ids: The file ids to stop versioning.
2853
 
        :raises: NoSuchId if any fileid is not currently versioned.
2854
 
        """
2855
 
        for file_id in file_ids:
2856
 
            if not self._inventory.has_id(file_id):
2857
 
                raise errors.NoSuchId(self, file_id)
2858
 
        for file_id in file_ids:
2859
 
            if self._inventory.has_id(file_id):
2860
 
                self._inventory.remove_recursive_id(file_id)
2861
 
        if len(file_ids):
2862
 
            # in the future this should just set a dirty bit to wait for the
2863
 
            # final unlock. However, until all methods of workingtree start
2864
 
            # with the current in -memory inventory rather than triggering
2865
 
            # a read, it is more complex - we need to teach read_inventory
2866
 
            # to know when to read, and when to not read first... and possibly
2867
 
            # to save first when the in memory one may be corrupted.
2868
 
            # so for now, we just only write it if it is indeed dirty.
2869
 
            # - RBC 20060907
2870
 
            self._write_inventory(self._inventory)
2871
 
 
2872
 
    def stored_kind(self, file_id):
2873
 
        """See Tree.stored_kind"""
2874
 
        return self.inventory[file_id].kind
2875
 
 
2876
 
    def extras(self):
2877
 
        """Yield all unversioned files in this WorkingTree.
2878
 
 
2879
 
        If there are any unversioned directories then only the directory is
2880
 
        returned, not all its children.  But if there are unversioned files
2881
 
        under a versioned subdirectory, they are returned.
2882
 
 
2883
 
        Currently returned depth-first, sorted by name within directories.
2884
 
        This is the same order used by 'osutils.walkdirs'.
2885
 
        """
2886
 
        ## TODO: Work from given directory downwards
2887
 
        for path, dir_entry in self.inventory.directories():
2888
 
            # mutter("search for unknowns in %r", path)
2889
 
            dirabs = self.abspath(path)
2890
 
            if not isdir(dirabs):
2891
 
                # e.g. directory deleted
2892
 
                continue
2893
 
 
2894
 
            fl = []
2895
 
            for subf in os.listdir(dirabs):
2896
 
                if self.bzrdir.is_control_filename(subf):
2897
 
                    continue
2898
 
                if subf not in dir_entry.children:
2899
 
                    try:
2900
 
                        (subf_norm,
2901
 
                         can_access) = osutils.normalized_filename(subf)
2902
 
                    except UnicodeDecodeError:
2903
 
                        path_os_enc = path.encode(osutils._fs_enc)
2904
 
                        relpath = path_os_enc + '/' + subf
2905
 
                        raise errors.BadFilenameEncoding(relpath,
2906
 
                                                         osutils._fs_enc)
2907
 
                    if subf_norm != subf and can_access:
2908
 
                        if subf_norm not in dir_entry.children:
2909
 
                            fl.append(subf_norm)
2910
 
                    else:
2911
 
                        fl.append(subf)
2912
 
 
2913
 
            fl.sort()
2914
 
            for subf in fl:
2915
 
                subp = pathjoin(path, subf)
2916
 
                yield subp
2917
 
 
2918
 
    def _walkdirs(self, prefix=""):
2919
 
        """Walk the directories of this tree.
2920
 
 
2921
 
        :param prefix: is used as the directrory to start with.
2922
 
        :returns: a generator which yields items in the form::
2923
 
 
2924
 
            ((curren_directory_path, fileid),
2925
 
             [(file1_path, file1_name, file1_kind, None, file1_id,
2926
 
               file1_kind), ... ])
2927
 
        """
2928
 
        _directory = 'directory'
2929
 
        # get the root in the inventory
2930
 
        inv = self.inventory
2931
 
        top_id = inv.path2id(prefix)
2932
 
        if top_id is None:
2933
 
            pending = []
2934
 
        else:
2935
 
            pending = [(prefix, '', _directory, None, top_id, None)]
2936
 
        while pending:
2937
 
            dirblock = []
2938
 
            currentdir = pending.pop()
2939
 
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
2940
 
            top_id = currentdir[4]
2941
 
            if currentdir[0]:
2942
 
                relroot = currentdir[0] + '/'
2943
 
            else:
2944
 
                relroot = ""
2945
 
            # FIXME: stash the node in pending
2946
 
            entry = inv[top_id]
2947
 
            if entry.kind == 'directory':
2948
 
                for name, child in entry.sorted_children():
2949
 
                    dirblock.append((relroot + name, name, child.kind, None,
2950
 
                        child.file_id, child.kind
2951
 
                        ))
2952
 
            yield (currentdir[0], entry.file_id), dirblock
2953
 
            # push the user specified dirs from dirblock
2954
 
            for dir in reversed(dirblock):
2955
 
                if dir[2] == _directory:
2956
 
                    pending.append(dir)
2957
 
 
2958
 
 
2959
 
class WorkingTreeFormatRegistry(controldir.ControlComponentFormatRegistry):
2960
 
    """Registry for working tree formats."""
2961
 
 
2962
 
    def __init__(self, other_registry=None):
2963
 
        super(WorkingTreeFormatRegistry, self).__init__(other_registry)
2964
 
        self._default_format = None
2965
 
        self._default_format_key = None
2966
 
 
2967
 
    def get_default(self):
2968
 
        """Return the current default format."""
2969
 
        if (self._default_format_key is not None and
2970
 
            self._default_format is None):
2971
 
            self._default_format = self.get(self._default_format_key)
2972
 
        return self._default_format
2973
 
 
2974
 
    def set_default(self, format):
2975
 
        """Set the default format."""
2976
 
        self._default_format = format
2977
 
        self._default_format_key = None
2978
 
 
2979
 
    def set_default_key(self, format_string):
2980
 
        """Set the default format by its format string."""
2981
 
        self._default_format_key = format_string
2982
 
        self._default_format = None
2983
 
 
2984
 
 
2985
 
format_registry = WorkingTreeFormatRegistry()
2986
 
 
2987
 
 
2988
 
class WorkingTreeFormat(controldir.ControlComponentFormat):
 
2658
    def unlock(self):
 
2659
        # do non-implementation specific cleanup
 
2660
        self._cleanup()
 
2661
        if self._control_files._lock_count == 1:
 
2662
            # _inventory_is_modified is always False during a read lock.
 
2663
            if self._inventory_is_modified:
 
2664
                self.flush()
 
2665
            self._write_hashcache_if_dirty()
 
2666
        # reverse order of locking.
 
2667
        try:
 
2668
            return self._control_files.unlock()
 
2669
        finally:
 
2670
            self.branch.unlock()
 
2671
 
 
2672
 
 
2673
def get_conflicted_stem(path):
 
2674
    for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
 
2675
        if path.endswith(suffix):
 
2676
            return path[:-len(suffix)]
 
2677
 
 
2678
 
 
2679
class WorkingTreeFormat(object):
2989
2680
    """An encapsulation of the initialization and open routines for a format.
2990
2681
 
2991
2682
    Formats provide three things:
3003
2694
    object will be created every time regardless.
3004
2695
    """
3005
2696
 
 
2697
    _default_format = None
 
2698
    """The default format used for new trees."""
 
2699
 
 
2700
    _formats = {}
 
2701
    """The known formats."""
 
2702
 
3006
2703
    requires_rich_root = False
3007
2704
 
3008
2705
    upgrade_recommended = False
3009
2706
 
3010
 
    requires_normalized_unicode_filenames = False
3011
 
 
3012
 
    case_sensitive_filename = "FoRMaT"
3013
 
 
3014
 
    missing_parent_conflicts = False
3015
 
    """If this format supports missing parent conflicts."""
3016
 
 
3017
 
    supports_versioned_directories = None
3018
 
 
3019
2707
    @classmethod
3020
 
    def find_format_string(klass, a_bzrdir):
3021
 
        """Return format name for the working tree object in a_bzrdir."""
 
2708
    def find_format(klass, a_bzrdir):
 
2709
        """Return the format for the working tree object in a_bzrdir."""
3022
2710
        try:
3023
2711
            transport = a_bzrdir.get_workingtree_transport(None)
3024
 
            return transport.get_bytes("format")
 
2712
            format_string = transport.get("format").read()
 
2713
            return klass._formats[format_string]
3025
2714
        except errors.NoSuchFile:
3026
2715
            raise errors.NoWorkingTree(base=transport.base)
3027
 
 
3028
 
    @classmethod
3029
 
    def find_format(klass, a_bzrdir):
3030
 
        """Return the format for the working tree object in a_bzrdir."""
3031
 
        try:
3032
 
            format_string = klass.find_format_string(a_bzrdir)
3033
 
            return format_registry.get(format_string)
3034
2716
        except KeyError:
3035
2717
            raise errors.UnknownFormatError(format=format_string,
3036
2718
                                            kind="working tree")
3037
2719
 
3038
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
3039
 
                   accelerator_tree=None, hardlink=False):
3040
 
        """Initialize a new working tree in a_bzrdir.
3041
 
 
3042
 
        :param a_bzrdir: BzrDir to initialize the working tree in.
3043
 
        :param revision_id: allows creating a working tree at a different
3044
 
            revision than the branch is at.
3045
 
        :param from_branch: Branch to checkout
3046
 
        :param accelerator_tree: A tree which can be used for retrieving file
3047
 
            contents more quickly than the revision tree, i.e. a workingtree.
3048
 
            The revision tree will be used for cases where accelerator_tree's
3049
 
            content is different.
3050
 
        :param hardlink: If true, hard-link files from accelerator_tree,
3051
 
            where possible.
3052
 
        """
3053
 
        raise NotImplementedError(self.initialize)
3054
 
 
3055
2720
    def __eq__(self, other):
3056
2721
        return self.__class__ is other.__class__
3057
2722
 
3059
2724
        return not (self == other)
3060
2725
 
3061
2726
    @classmethod
3062
 
    @symbol_versioning.deprecated_method(
3063
 
        symbol_versioning.deprecated_in((2, 4, 0)))
3064
2727
    def get_default_format(klass):
3065
2728
        """Return the current default format."""
3066
 
        return format_registry.get_default()
 
2729
        return klass._default_format
3067
2730
 
3068
2731
    def get_format_string(self):
3069
2732
        """Return the ASCII format string that identifies this format."""
3091
2754
        return False
3092
2755
 
3093
2756
    @classmethod
3094
 
    @symbol_versioning.deprecated_method(
3095
 
        symbol_versioning.deprecated_in((2, 4, 0)))
3096
2757
    def register_format(klass, format):
3097
 
        format_registry.register(format)
3098
 
 
3099
 
    @classmethod
3100
 
    @symbol_versioning.deprecated_method(
3101
 
        symbol_versioning.deprecated_in((2, 4, 0)))
3102
 
    def register_extra_format(klass, format):
3103
 
        format_registry.register_extra(format)
3104
 
 
3105
 
    @classmethod
3106
 
    @symbol_versioning.deprecated_method(
3107
 
        symbol_versioning.deprecated_in((2, 4, 0)))
3108
 
    def unregister_extra_format(klass, format):
3109
 
        format_registry.unregister_extra(format)
3110
 
 
3111
 
    @classmethod
3112
 
    @symbol_versioning.deprecated_method(
3113
 
        symbol_versioning.deprecated_in((2, 4, 0)))
3114
 
    def get_formats(klass):
3115
 
        return format_registry._get_all()
3116
 
 
3117
 
    @classmethod
3118
 
    @symbol_versioning.deprecated_method(
3119
 
        symbol_versioning.deprecated_in((2, 4, 0)))
 
2758
        klass._formats[format.get_format_string()] = format
 
2759
 
 
2760
    @classmethod
3120
2761
    def set_default_format(klass, format):
3121
 
        format_registry.set_default(format)
 
2762
        klass._default_format = format
3122
2763
 
3123
2764
    @classmethod
3124
 
    @symbol_versioning.deprecated_method(
3125
 
        symbol_versioning.deprecated_in((2, 4, 0)))
3126
2765
    def unregister_format(klass, format):
3127
 
        format_registry.remove(format)
3128
 
 
3129
 
 
3130
 
format_registry.register_lazy("Bazaar Working Tree Format 4 (bzr 0.15)\n",
3131
 
    "bzrlib.workingtree_4", "WorkingTreeFormat4")
3132
 
format_registry.register_lazy("Bazaar Working Tree Format 5 (bzr 1.11)\n",
3133
 
    "bzrlib.workingtree_4", "WorkingTreeFormat5")
3134
 
format_registry.register_lazy("Bazaar Working Tree Format 6 (bzr 1.14)\n",
3135
 
    "bzrlib.workingtree_4", "WorkingTreeFormat6")
3136
 
format_registry.register_lazy("Bazaar-NG Working Tree format 3",
3137
 
    "bzrlib.workingtree_3", "WorkingTreeFormat3")
3138
 
format_registry.set_default_key("Bazaar Working Tree Format 6 (bzr 1.14)\n")
 
2766
        del klass._formats[format.get_format_string()]
 
2767
 
 
2768
 
 
2769
class WorkingTreeFormat2(WorkingTreeFormat):
 
2770
    """The second working tree format.
 
2771
 
 
2772
    This format modified the hash cache from the format 1 hash cache.
 
2773
    """
 
2774
 
 
2775
    upgrade_recommended = True
 
2776
 
 
2777
    def get_format_description(self):
 
2778
        """See WorkingTreeFormat.get_format_description()."""
 
2779
        return "Working tree format 2"
 
2780
 
 
2781
    def _stub_initialize_on_transport(self, transport, file_mode):
 
2782
        """Workaround: create control files for a remote working tree.
 
2783
 
 
2784
        This ensures that it can later be updated and dealt with locally,
 
2785
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
 
2786
        no working tree.  (See bug #43064).
 
2787
        """
 
2788
        sio = StringIO()
 
2789
        inv = Inventory()
 
2790
        xml5.serializer_v5.write_inventory(inv, sio, working=True)
 
2791
        sio.seek(0)
 
2792
        transport.put_file('inventory', sio, file_mode)
 
2793
        transport.put_bytes('pending-merges', '', file_mode)
 
2794
 
 
2795
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
2796
                   accelerator_tree=None, hardlink=False):
 
2797
        """See WorkingTreeFormat.initialize()."""
 
2798
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2799
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2800
        if from_branch is not None:
 
2801
            branch = from_branch
 
2802
        else:
 
2803
            branch = a_bzrdir.open_branch()
 
2804
        if revision_id is None:
 
2805
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2806
        branch.lock_write()
 
2807
        try:
 
2808
            branch.generate_revision_history(revision_id)
 
2809
        finally:
 
2810
            branch.unlock()
 
2811
        inv = Inventory()
 
2812
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2813
                         branch,
 
2814
                         inv,
 
2815
                         _internal=True,
 
2816
                         _format=self,
 
2817
                         _bzrdir=a_bzrdir)
 
2818
        basis_tree = branch.repository.revision_tree(revision_id)
 
2819
        if basis_tree.inventory.root is not None:
 
2820
            wt.set_root_id(basis_tree.get_root_id())
 
2821
        # set the parent list and cache the basis tree.
 
2822
        if _mod_revision.is_null(revision_id):
 
2823
            parent_trees = []
 
2824
        else:
 
2825
            parent_trees = [(revision_id, basis_tree)]
 
2826
        wt.set_parent_trees(parent_trees)
 
2827
        transform.build_tree(basis_tree, wt)
 
2828
        return wt
 
2829
 
 
2830
    def __init__(self):
 
2831
        super(WorkingTreeFormat2, self).__init__()
 
2832
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
2833
 
 
2834
    def open(self, a_bzrdir, _found=False):
 
2835
        """Return the WorkingTree object for a_bzrdir
 
2836
 
 
2837
        _found is a private parameter, do not use it. It is used to indicate
 
2838
               if format probing has already been done.
 
2839
        """
 
2840
        if not _found:
 
2841
            # we are being called directly and must probe.
 
2842
            raise NotImplementedError
 
2843
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2844
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2845
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2846
                           _internal=True,
 
2847
                           _format=self,
 
2848
                           _bzrdir=a_bzrdir)
 
2849
        return wt
 
2850
 
 
2851
class WorkingTreeFormat3(WorkingTreeFormat):
 
2852
    """The second working tree format updated to record a format marker.
 
2853
 
 
2854
    This format:
 
2855
        - exists within a metadir controlling .bzr
 
2856
        - includes an explicit version marker for the workingtree control
 
2857
          files, separate from the BzrDir format
 
2858
        - modifies the hash cache format
 
2859
        - is new in bzr 0.8
 
2860
        - uses a LockDir to guard access for writes.
 
2861
    """
 
2862
 
 
2863
    upgrade_recommended = True
 
2864
 
 
2865
    def get_format_string(self):
 
2866
        """See WorkingTreeFormat.get_format_string()."""
 
2867
        return "Bazaar-NG Working Tree format 3"
 
2868
 
 
2869
    def get_format_description(self):
 
2870
        """See WorkingTreeFormat.get_format_description()."""
 
2871
        return "Working tree format 3"
 
2872
 
 
2873
    _lock_file_name = 'lock'
 
2874
    _lock_class = LockDir
 
2875
 
 
2876
    _tree_class = WorkingTree3
 
2877
 
 
2878
    def __get_matchingbzrdir(self):
 
2879
        return bzrdir.BzrDirMetaFormat1()
 
2880
 
 
2881
    _matchingbzrdir = property(__get_matchingbzrdir)
 
2882
 
 
2883
    def _open_control_files(self, a_bzrdir):
 
2884
        transport = a_bzrdir.get_workingtree_transport(None)
 
2885
        return LockableFiles(transport, self._lock_file_name,
 
2886
                             self._lock_class)
 
2887
 
 
2888
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
2889
                   accelerator_tree=None, hardlink=False):
 
2890
        """See WorkingTreeFormat.initialize().
 
2891
 
 
2892
        :param revision_id: if supplied, create a working tree at a different
 
2893
            revision than the branch is at.
 
2894
        :param accelerator_tree: A tree which can be used for retrieving file
 
2895
            contents more quickly than the revision tree, i.e. a workingtree.
 
2896
            The revision tree will be used for cases where accelerator_tree's
 
2897
            content is different.
 
2898
        :param hardlink: If true, hard-link files from accelerator_tree,
 
2899
            where possible.
 
2900
        """
 
2901
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2902
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2903
        transport = a_bzrdir.get_workingtree_transport(self)
 
2904
        control_files = self._open_control_files(a_bzrdir)
 
2905
        control_files.create_lock()
 
2906
        control_files.lock_write()
 
2907
        transport.put_bytes('format', self.get_format_string(),
 
2908
            mode=a_bzrdir._get_file_mode())
 
2909
        if from_branch is not None:
 
2910
            branch = from_branch
 
2911
        else:
 
2912
            branch = a_bzrdir.open_branch()
 
2913
        if revision_id is None:
 
2914
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2915
        # WorkingTree3 can handle an inventory which has a unique root id.
 
2916
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
 
2917
        # those trees. And because there isn't a format bump inbetween, we
 
2918
        # are maintaining compatibility with older clients.
 
2919
        # inv = Inventory(root_id=gen_root_id())
 
2920
        inv = self._initial_inventory()
 
2921
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2922
                         branch,
 
2923
                         inv,
 
2924
                         _internal=True,
 
2925
                         _format=self,
 
2926
                         _bzrdir=a_bzrdir,
 
2927
                         _control_files=control_files)
 
2928
        wt.lock_tree_write()
 
2929
        try:
 
2930
            basis_tree = branch.repository.revision_tree(revision_id)
 
2931
            # only set an explicit root id if there is one to set.
 
2932
            if basis_tree.inventory.root is not None:
 
2933
                wt.set_root_id(basis_tree.get_root_id())
 
2934
            if revision_id == NULL_REVISION:
 
2935
                wt.set_parent_trees([])
 
2936
            else:
 
2937
                wt.set_parent_trees([(revision_id, basis_tree)])
 
2938
            transform.build_tree(basis_tree, wt)
 
2939
        finally:
 
2940
            # Unlock in this order so that the unlock-triggers-flush in
 
2941
            # WorkingTree is given a chance to fire.
 
2942
            control_files.unlock()
 
2943
            wt.unlock()
 
2944
        return wt
 
2945
 
 
2946
    def _initial_inventory(self):
 
2947
        return Inventory()
 
2948
 
 
2949
    def __init__(self):
 
2950
        super(WorkingTreeFormat3, self).__init__()
 
2951
 
 
2952
    def open(self, a_bzrdir, _found=False):
 
2953
        """Return the WorkingTree object for a_bzrdir
 
2954
 
 
2955
        _found is a private parameter, do not use it. It is used to indicate
 
2956
               if format probing has already been done.
 
2957
        """
 
2958
        if not _found:
 
2959
            # we are being called directly and must probe.
 
2960
            raise NotImplementedError
 
2961
        if not isinstance(a_bzrdir.transport, LocalTransport):
 
2962
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
 
2963
        wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
2964
        return wt
 
2965
 
 
2966
    def _open(self, a_bzrdir, control_files):
 
2967
        """Open the tree itself.
 
2968
 
 
2969
        :param a_bzrdir: the dir for the tree.
 
2970
        :param control_files: the control files for the tree.
 
2971
        """
 
2972
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2973
                                _internal=True,
 
2974
                                _format=self,
 
2975
                                _bzrdir=a_bzrdir,
 
2976
                                _control_files=control_files)
 
2977
 
 
2978
    def __str__(self):
 
2979
        return self.get_format_string()
 
2980
 
 
2981
 
 
2982
__default_format = WorkingTreeFormat4()
 
2983
WorkingTreeFormat.register_format(__default_format)
 
2984
WorkingTreeFormat.register_format(WorkingTreeFormat5())
 
2985
WorkingTreeFormat.register_format(WorkingTreeFormat3())
 
2986
WorkingTreeFormat.set_default_format(__default_format)
 
2987
# formats which have no format string are not discoverable
 
2988
# and not independently creatable, so are not registered.
 
2989
_legacy_formats = [WorkingTreeFormat2(),
 
2990
                   ]