/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

First attempt to merge .dev and resolve the conflicts (but tests are 
failing)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 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
 
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
33
 
CONFLICT_HEADER_1 = "BZR conflict list format 1"
34
 
 
35
32
# TODO: Give the workingtree sole responsibility for the working inventory;
36
33
# remove the variable and references to it from the branch.  This may require
37
34
# updating the commit code so as to update the inventory within the working
39
36
# At the moment they may alias the inventory and have old copies of it in
40
37
# memory.  (Now done? -- mbp 20060309)
41
38
 
42
 
from binascii import hexlify
 
39
from cStringIO import StringIO
 
40
import os
 
41
import sys
 
42
 
 
43
from bzrlib.lazy_import import lazy_import
 
44
lazy_import(globals(), """
 
45
from bisect import bisect_left
43
46
import collections
44
 
from copy import deepcopy
45
 
from cStringIO import StringIO
46
47
import errno
47
 
import fnmatch
48
 
import os
49
 
import re
 
48
import itertools
 
49
import operator
50
50
import stat
51
51
from time import time
52
52
import warnings
 
53
import re
53
54
 
54
55
import bzrlib
55
 
from bzrlib import bzrdir, errors, ignores, osutils, urlutils
56
 
from bzrlib.atomicfile import AtomicFile
 
56
from bzrlib import (
 
57
    branch,
 
58
    bzrdir,
 
59
    conflicts as _mod_conflicts,
 
60
    dirstate,
 
61
    errors,
 
62
    generate_ids,
 
63
    globbing,
 
64
    hashcache,
 
65
    ignores,
 
66
    merge,
 
67
    revision as _mod_revision,
 
68
    revisiontree,
 
69
    repository,
 
70
    textui,
 
71
    trace,
 
72
    transform,
 
73
    ui,
 
74
    urlutils,
 
75
    xml5,
 
76
    xml6,
 
77
    xml7,
 
78
    )
57
79
import bzrlib.branch
58
 
from bzrlib.conflicts import Conflict, ConflictList, CONFLICT_SUFFIXES
 
80
from bzrlib.transport import get_transport
 
81
import bzrlib.ui
 
82
from bzrlib.workingtree_4 import WorkingTreeFormat4
 
83
""")
 
84
 
 
85
from bzrlib import symbol_versioning
59
86
from bzrlib.decorators import needs_read_lock, needs_write_lock
60
 
from bzrlib.errors import (BzrCheckError,
61
 
                           BzrError,
62
 
                           ConflictFormatError,
63
 
                           WeaveRevisionNotPresent,
64
 
                           NotBranchError,
65
 
                           NoSuchFile,
66
 
                           NotVersionedError,
67
 
                           MergeModifiedFormatError,
68
 
                           UnsupportedOperation,
69
 
                           )
70
 
from bzrlib.inventory import InventoryEntry, Inventory
 
87
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
71
88
from bzrlib.lockable_files import LockableFiles, TransportLock
72
89
from bzrlib.lockdir import LockDir
73
 
from bzrlib.merge import merge_inner, transform_tree
 
90
import bzrlib.mutabletree
 
91
from bzrlib.mutabletree import needs_tree_write_lock
 
92
from bzrlib import osutils
74
93
from bzrlib.osutils import (
75
 
                            abspath,
76
 
                            compact_date,
77
 
                            file_kind,
78
 
                            isdir,
79
 
                            getcwd,
80
 
                            pathjoin,
81
 
                            pumpfile,
82
 
                            safe_unicode,
83
 
                            splitpath,
84
 
                            rand_chars,
85
 
                            normpath,
86
 
                            realpath,
87
 
                            relpath,
88
 
                            rename,
89
 
                            supports_executable,
90
 
                            )
 
94
    compact_date,
 
95
    file_kind,
 
96
    isdir,
 
97
    normpath,
 
98
    pathjoin,
 
99
    rand_chars,
 
100
    realpath,
 
101
    safe_unicode,
 
102
    splitpath,
 
103
    supports_executable,
 
104
    )
 
105
from bzrlib.trace import mutter, note
 
106
from bzrlib.transport.local import LocalTransport
91
107
from bzrlib.progress import DummyProgress, ProgressPhase
92
 
from bzrlib.revision import NULL_REVISION
 
108
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
93
109
from bzrlib.rio import RioReader, rio_file, Stanza
94
110
from bzrlib.symbol_versioning import (deprecated_passed,
95
111
        deprecated_method,
96
112
        deprecated_function,
97
113
        DEPRECATED_PARAMETER,
98
 
        zero_eight,
99
 
        zero_eleven,
100
114
        )
101
 
from bzrlib.trace import mutter, note
102
 
from bzrlib.transform import build_tree
103
 
from bzrlib.transport import get_transport
104
 
from bzrlib.transport.local import LocalTransport
105
 
from bzrlib.textui import show_status
106
 
import bzrlib.tree
107
 
import bzrlib.ui
108
 
import bzrlib.xml5
109
 
 
110
 
 
111
 
# the regex removes any weird characters; we don't escape them 
112
 
# but rather just pull them out
113
 
_gen_file_id_re = re.compile(r'[^\w.]')
114
 
_gen_id_suffix = None
115
 
_gen_id_serial = 0
116
 
 
117
 
 
118
 
def _next_id_suffix():
119
 
    """Create a new file id suffix that is reasonably unique.
120
 
    
121
 
    On the first call we combine the current time with 64 bits of randomness
122
 
    to give a highly probably globally unique number. Then each call in the same
123
 
    process adds 1 to a serial number we append to that unique value.
124
 
    """
125
 
    # XXX TODO: change bzrlib.add.smart_add to call workingtree.add() rather 
126
 
    # than having to move the id randomness out of the inner loop like this.
127
 
    # XXX TODO: for the global randomness this uses we should add the thread-id
128
 
    # before the serial #.
129
 
    global _gen_id_suffix, _gen_id_serial
130
 
    if _gen_id_suffix is None:
131
 
        _gen_id_suffix = "-%s-%s-" % (compact_date(time()), rand_chars(16))
132
 
    _gen_id_serial += 1
133
 
    return _gen_id_suffix + str(_gen_id_serial)
134
 
 
135
 
 
136
 
def gen_file_id(name):
137
 
    """Return new file id for the basename 'name'.
138
 
 
139
 
    The uniqueness is supplied from _next_id_suffix.
140
 
    """
141
 
    # The real randomness is in the _next_id_suffix, the
142
 
    # rest of the identifier is just to be nice.
143
 
    # So we:
144
 
    # 1) Remove non-ascii word characters to keep the ids portable
145
 
    # 2) squash to lowercase, so the file id doesn't have to
146
 
    #    be escaped (case insensitive filesystems would bork for ids
147
 
    #    that only differred in case without escaping).
148
 
    # 3) truncate the filename to 20 chars. Long filenames also bork on some
149
 
    #    filesystems
150
 
    # 4) Removing starting '.' characters to prevent the file ids from
151
 
    #    being considered hidden.
152
 
    ascii_word_only = _gen_file_id_re.sub('', name.lower())
153
 
    short_no_dots = ascii_word_only.lstrip('.')[:20]
154
 
    return short_no_dots + _next_id_suffix()
155
 
 
156
 
 
157
 
def gen_root_id():
158
 
    """Return a new tree-root file id."""
159
 
    return gen_file_id('TREE_ROOT')
160
 
 
161
 
 
162
 
def needs_tree_write_lock(unbound):
163
 
    """Decorate unbound to take out and release a tree_write lock."""
164
 
    def tree_write_locked(self, *args, **kwargs):
165
 
        self.lock_tree_write()
166
 
        try:
167
 
            return unbound(self, *args, **kwargs)
168
 
        finally:
169
 
            self.unlock()
170
 
    tree_write_locked.__doc__ = unbound.__doc__
171
 
    tree_write_locked.__name__ = unbound.__name__
172
 
    return tree_write_locked
 
115
 
 
116
 
 
117
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
 
118
CONFLICT_HEADER_1 = "BZR conflict list format 1"
 
119
 
 
120
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
173
121
 
174
122
 
175
123
class TreeEntry(object):
227
175
        return ''
228
176
 
229
177
 
230
 
class WorkingTree(bzrlib.tree.Tree):
 
178
class WorkingTree(bzrlib.mutabletree.MutableTree):
231
179
    """Working copy tree.
232
180
 
233
181
    The inventory is held in the `Branch` working-inventory, and the
244
192
                 _internal=False,
245
193
                 _format=None,
246
194
                 _bzrdir=None):
247
 
        """Construct a WorkingTree for basedir.
 
195
        """Construct a WorkingTree instance. This is not a public API.
248
196
 
249
 
        If the branch is not supplied, it is opened automatically.
250
 
        If the branch is supplied, it must be the branch for this basedir.
251
 
        (branch.base is not cross checked, because for remote branches that
252
 
        would be meaningless).
 
197
        :param branch: A branch to override probing for the branch.
253
198
        """
254
199
        self._format = _format
255
200
        self.bzrdir = _bzrdir
256
201
        if not _internal:
257
 
            # not created via open etc.
258
 
            warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
259
 
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
260
 
                 DeprecationWarning,
261
 
                 stacklevel=2)
262
 
            wt = WorkingTree.open(basedir)
263
 
            self._branch = wt.branch
264
 
            self.basedir = wt.basedir
265
 
            self._control_files = wt._control_files
266
 
            self._hashcache = wt._hashcache
267
 
            self._set_inventory(wt._inventory)
268
 
            self._format = wt._format
269
 
            self.bzrdir = wt.bzrdir
270
 
        from bzrlib.hashcache import HashCache
271
 
        from bzrlib.trace import note, mutter
272
 
        assert isinstance(basedir, basestring), \
273
 
            "base directory %r is not a string" % basedir
 
202
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
 
203
                "WorkingTree.open() to obtain a WorkingTree.")
274
204
        basedir = safe_unicode(basedir)
275
205
        mutter("opening working tree %r", basedir)
276
206
        if deprecated_passed(branch):
277
 
            if not _internal:
278
 
                warnings.warn("WorkingTree(..., branch=XXX) is deprecated as of bzr 0.8."
279
 
                     " Please use bzrdir.open_workingtree() or"
280
 
                     " WorkingTree.open().",
281
 
                     DeprecationWarning,
282
 
                     stacklevel=2
283
 
                     )
284
207
            self._branch = branch
285
208
        else:
286
209
            self._branch = self.bzrdir.open_branch()
291
214
            self._control_files = self.branch.control_files
292
215
        else:
293
216
            # assume all other formats have their own control files.
294
 
            assert isinstance(_control_files, LockableFiles), \
295
 
                    "_control_files must be a LockableFiles, not %r" \
296
 
                    % _control_files
297
217
            self._control_files = _control_files
 
218
        self._transport = self._control_files._transport
298
219
        # update the whole cache up front and write to disk if anything changed;
299
220
        # in the future we might want to do this more selectively
300
221
        # two possible ways offer themselves : in self._unlock, write the cache
301
222
        # if needed, or, when the cache sees a change, append it to the hash
302
223
        # cache file, and have the parser take the most recent entry for a
303
224
        # given path only.
304
 
        cache_filename = self.bzrdir.get_workingtree_transport(None).local_abspath('stat-cache')
305
 
        hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
 
225
        wt_trans = self.bzrdir.get_workingtree_transport(None)
 
226
        cache_filename = wt_trans.local_abspath('stat-cache')
 
227
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
 
228
            self.bzrdir._get_file_mode())
 
229
        hc = self._hashcache
306
230
        hc.read()
307
231
        # is this scan needed ? it makes things kinda slow.
308
232
        #hc.scan()
312
236
            hc.write()
313
237
 
314
238
        if _inventory is None:
315
 
            self._set_inventory(self.read_working_inventory())
316
 
        else:
317
 
            self._set_inventory(_inventory)
 
239
            # This will be acquired on lock_read() or lock_write()
 
240
            self._inventory_is_modified = False
 
241
            self._inventory = None
 
242
        else:
 
243
            # the caller of __init__ has provided an inventory,
 
244
            # we assume they know what they are doing - as its only
 
245
            # the Format factory and creation methods that are
 
246
            # permitted to do this.
 
247
            self._set_inventory(_inventory, dirty=False)
 
248
        self._detect_case_handling()
 
249
        self._rules_searcher = None
 
250
 
 
251
    def _detect_case_handling(self):
 
252
        wt_trans = self.bzrdir.get_workingtree_transport(None)
 
253
        try:
 
254
            wt_trans.stat("FoRMaT")
 
255
        except errors.NoSuchFile:
 
256
            self.case_sensitive = True
 
257
        else:
 
258
            self.case_sensitive = False
 
259
 
 
260
        self._setup_directory_is_tree_reference()
318
261
 
319
262
    branch = property(
320
263
        fget=lambda self: self._branch,
335
278
        self._control_files.break_lock()
336
279
        self.branch.break_lock()
337
280
 
338
 
    def _set_inventory(self, inv):
339
 
        assert inv.root is not None
 
281
    def requires_rich_root(self):
 
282
        return self._format.requires_rich_root
 
283
 
 
284
    def supports_tree_reference(self):
 
285
        return False
 
286
 
 
287
    def _set_inventory(self, inv, dirty):
 
288
        """Set the internal cached inventory.
 
289
 
 
290
        :param inv: The inventory to set.
 
291
        :param dirty: A boolean indicating whether the inventory is the same
 
292
            logical inventory as whats on disk. If True the inventory is not
 
293
            the same and should be written to disk or data will be lost, if
 
294
            False then the inventory is the same as that on disk and any
 
295
            serialisation would be unneeded overhead.
 
296
        """
340
297
        self._inventory = inv
341
 
        self.path2id = self._inventory.path2id
342
 
 
343
 
    def is_control_filename(self, filename):
344
 
        """True if filename is the name of a control file in this tree.
345
 
        
346
 
        :param filename: A filename within the tree. This is a relative path
347
 
        from the root of this tree.
348
 
 
349
 
        This is true IF and ONLY IF the filename is part of the meta data
350
 
        that bzr controls in this tree. I.E. a random .bzr directory placed
351
 
        on disk will not be a control file for this tree.
352
 
        """
353
 
        return self.bzrdir.is_control_filename(filename)
 
298
        self._inventory_is_modified = dirty
354
299
 
355
300
    @staticmethod
356
301
    def open(path=None, _unsupported=False):
389
334
        """
390
335
        return WorkingTree.open(path, _unsupported=True)
391
336
 
 
337
    @staticmethod
 
338
    def find_trees(location):
 
339
        def list_current(transport):
 
340
            return [d for d in transport.list_dir('') if d != '.bzr']
 
341
        def evaluate(bzrdir):
 
342
            try:
 
343
                tree = bzrdir.open_workingtree()
 
344
            except errors.NoWorkingTree:
 
345
                return True, None
 
346
            else:
 
347
                return True, tree
 
348
        transport = get_transport(location)
 
349
        iterator = bzrdir.BzrDir.find_bzrdirs(transport, evaluate=evaluate,
 
350
                                              list_current=list_current)
 
351
        return [t for t in iterator if t is not None]
 
352
 
 
353
    # should be deprecated - this is slow and in any case treating them as a
 
354
    # container is (we now know) bad style -- mbp 20070302
 
355
    ## @deprecated_method(zero_fifteen)
392
356
    def __iter__(self):
393
357
        """Iterate through file_ids for this tree.
394
358
 
400
364
            if osutils.lexists(self.abspath(path)):
401
365
                yield ie.file_id
402
366
 
 
367
    def all_file_ids(self):
 
368
        """See Tree.iter_all_file_ids"""
 
369
        return set(self.inventory)
 
370
 
403
371
    def __repr__(self):
404
372
        return "<%s of %s>" % (self.__class__.__name__,
405
373
                               getattr(self, 'basedir', None))
406
374
 
407
375
    def abspath(self, filename):
408
376
        return pathjoin(self.basedir, filename)
409
 
    
 
377
 
410
378
    def basis_tree(self):
411
379
        """Return RevisionTree for the current last revision.
412
380
        
420
388
            # in the future this should return the tree for
421
389
            # 'empty:' - the implicit root empty tree.
422
390
            return self.branch.repository.revision_tree(None)
423
 
        else:
424
 
            try:
425
 
                xml = self.read_basis_inventory()
426
 
                inv = bzrlib.xml6.serializer_v6.read_inventory_from_string(xml)
427
 
                if inv is not None and inv.revision_id == revision_id:
428
 
                    return bzrlib.tree.RevisionTree(self.branch.repository, 
429
 
                                                    inv, revision_id)
430
 
            except (NoSuchFile, errors.BadInventoryFormat):
431
 
                pass
 
391
        try:
 
392
            return self.revision_tree(revision_id)
 
393
        except errors.NoSuchRevision:
 
394
            pass
432
395
        # No cached copy available, retrieve from the repository.
433
396
        # FIXME? RBC 20060403 should we cache the inventory locally
434
397
        # at this point ?
435
398
        try:
436
399
            return self.branch.repository.revision_tree(revision_id)
437
 
        except errors.RevisionNotPresent:
 
400
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
438
401
            # the basis tree *may* be a ghost or a low level error may have
439
402
            # occured. If the revision is present, its a problem, if its not
440
403
            # its a ghost.
443
406
            # the basis tree is a ghost so return an empty tree.
444
407
            return self.branch.repository.revision_tree(None)
445
408
 
446
 
    @staticmethod
447
 
    @deprecated_method(zero_eight)
448
 
    def create(branch, directory):
449
 
        """Create a workingtree for branch at directory.
450
 
 
451
 
        If existing_directory already exists it must have a .bzr directory.
452
 
        If it does not exist, it will be created.
453
 
 
454
 
        This returns a new WorkingTree object for the new checkout.
455
 
 
456
 
        TODO FIXME RBC 20060124 when we have checkout formats in place this
457
 
        should accept an optional revisionid to checkout [and reject this if
458
 
        checking out into the same dir as a pre-checkout-aware branch format.]
459
 
 
460
 
        XXX: When BzrDir is present, these should be created through that 
461
 
        interface instead.
462
 
        """
463
 
        warnings.warn('delete WorkingTree.create', stacklevel=3)
464
 
        transport = get_transport(directory)
465
 
        if branch.bzrdir.root_transport.base == transport.base:
466
 
            # same dir 
467
 
            return branch.bzrdir.create_workingtree()
468
 
        # different directory, 
469
 
        # create a branch reference
470
 
        # and now a working tree.
471
 
        raise NotImplementedError
472
 
 
473
 
    @staticmethod
474
 
    @deprecated_method(zero_eight)
475
 
    def create_standalone(directory):
476
 
        """Create a checkout and a branch and a repo at directory.
477
 
 
478
 
        Directory must exist and be empty.
479
 
 
480
 
        please use BzrDir.create_standalone_workingtree
481
 
        """
482
 
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
409
    def _cleanup(self):
 
410
        self._flush_ignore_list_cache()
483
411
 
484
412
    def relpath(self, path):
485
413
        """Return the local path portion from a given path.
487
415
        The path may be absolute or relative. If its a relative path it is 
488
416
        interpreted relative to the python current working directory.
489
417
        """
490
 
        return relpath(self.basedir, path)
 
418
        return osutils.relpath(self.basedir, path)
491
419
 
492
420
    def has_filename(self, filename):
493
421
        return osutils.lexists(self.abspath(filename))
494
422
 
495
 
    def get_file(self, file_id):
496
 
        return self.get_file_byname(self.id2path(file_id))
 
423
    def get_file(self, file_id, path=None):
 
424
        if path is None:
 
425
            path = self.id2path(file_id)
 
426
        return self.get_file_byname(path)
497
427
 
498
428
    def get_file_text(self, file_id):
499
429
        return self.get_file(file_id).read()
501
431
    def get_file_byname(self, filename):
502
432
        return file(self.abspath(filename), 'rb')
503
433
 
 
434
    @needs_read_lock
 
435
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
 
436
        """See Tree.annotate_iter
 
437
 
 
438
        This implementation will use the basis tree implementation if possible.
 
439
        Lines not in the basis are attributed to CURRENT_REVISION
 
440
 
 
441
        If there are pending merges, lines added by those merges will be
 
442
        incorrectly attributed to CURRENT_REVISION (but after committing, the
 
443
        attribution will be correct).
 
444
        """
 
445
        basis = self.basis_tree()
 
446
        basis.lock_read()
 
447
        try:
 
448
            changes = self.iter_changes(basis, True, [self.id2path(file_id)],
 
449
                require_versioned=True).next()
 
450
            changed_content, kind = changes[2], changes[6]
 
451
            if not changed_content:
 
452
                return basis.annotate_iter(file_id)
 
453
            if kind[1] is None:
 
454
                return None
 
455
            import annotate
 
456
            if kind[0] != 'file':
 
457
                old_lines = []
 
458
            else:
 
459
                old_lines = list(basis.annotate_iter(file_id))
 
460
            old = [old_lines]
 
461
            for tree in self.branch.repository.revision_trees(
 
462
                self.get_parent_ids()[1:]):
 
463
                if file_id not in tree:
 
464
                    continue
 
465
                old.append(list(tree.annotate_iter(file_id)))
 
466
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
467
                                       default_revision)
 
468
        finally:
 
469
            basis.unlock()
 
470
 
 
471
    def _get_ancestors(self, default_revision):
 
472
        ancestors = set([default_revision])
 
473
        for parent_id in self.get_parent_ids():
 
474
            ancestors.update(self.branch.repository.get_ancestry(
 
475
                             parent_id, topo_sorted=False))
 
476
        return ancestors
 
477
 
504
478
    def get_parent_ids(self):
505
479
        """See Tree.get_parent_ids.
506
480
        
507
481
        This implementation reads the pending merges list and last_revision
508
482
        value and uses that to decide what the parents list should be.
509
483
        """
510
 
        last_rev = self._last_revision()
511
 
        if last_rev is None:
 
484
        last_rev = _mod_revision.ensure_null(self._last_revision())
 
485
        if _mod_revision.NULL_REVISION == last_rev:
512
486
            parents = []
513
487
        else:
514
488
            parents = [last_rev]
515
489
        try:
516
 
            merges_file = self._control_files.get_utf8('pending-merges')
517
 
        except NoSuchFile:
 
490
            merges_file = self._transport.get('pending-merges')
 
491
        except errors.NoSuchFile:
518
492
            pass
519
493
        else:
520
494
            for l in merges_file.readlines():
521
 
                parents.append(l.rstrip('\n'))
 
495
                revision_id = l.rstrip('\n')
 
496
                parents.append(revision_id)
522
497
        return parents
523
498
 
 
499
    @needs_read_lock
524
500
    def get_root_id(self):
525
501
        """Return the id of this trees root"""
526
 
        inv = self.read_working_inventory()
527
 
        return inv.root.file_id
 
502
        return self._inventory.root.file_id
528
503
        
529
504
    def _get_store_filename(self, file_id):
530
505
        ## XXX: badly named; this is not in the store at all
531
506
        return self.abspath(self.id2path(file_id))
532
507
 
533
508
    @needs_read_lock
534
 
    def clone(self, to_bzrdir, revision_id=None, basis=None):
 
509
    def clone(self, to_bzrdir, revision_id=None):
535
510
        """Duplicate this working tree into to_bzr, including all state.
536
511
        
537
512
        Specifically modified files are kept as modified, but
543
518
            If not None, the cloned tree will have its last revision set to 
544
519
            revision, and and difference between the source trees last revision
545
520
            and this one merged in.
546
 
 
547
 
        basis
548
 
            If not None, a closer copy of a tree which may have some files in
549
 
            common, and which file content should be preferentially copied from.
550
521
        """
551
522
        # assumes the target bzr dir format is compatible.
552
523
        result = self._format.initialize(to_bzrdir)
556
527
    @needs_read_lock
557
528
    def copy_content_into(self, tree, revision_id=None):
558
529
        """Copy the current content and user files of this tree into tree."""
 
530
        tree.set_root_id(self.get_root_id())
559
531
        if revision_id is None:
560
 
            transform_tree(tree, self)
 
532
            merge.transform_tree(tree, self)
561
533
        else:
562
534
            # TODO now merge from tree.last_revision to revision (to preserve
563
535
            # user local changes)
564
 
            transform_tree(tree, self)
 
536
            merge.transform_tree(tree, self)
565
537
            tree.set_parent_ids([revision_id])
566
538
 
567
 
    @needs_write_lock
568
 
    def commit(self, message=None, revprops=None, *args, **kwargs):
569
 
        # avoid circular imports
570
 
        from bzrlib.commit import Commit
571
 
        if revprops is None:
572
 
            revprops = {}
573
 
        if not 'branch-nick' in revprops:
574
 
            revprops['branch-nick'] = self.branch.nick
575
 
        # args for wt.commit start at message from the Commit.commit method,
576
 
        # but with branch a kwarg now, passing in args as is results in the
577
 
        #message being used for the branch
578
 
        args = (DEPRECATED_PARAMETER, message, ) + args
579
 
        committed_id = Commit().commit( working_tree=self, revprops=revprops,
580
 
            *args, **kwargs)
581
 
        return committed_id
582
 
 
583
539
    def id2abspath(self, file_id):
584
540
        return self.abspath(self.id2path(file_id))
585
541
 
586
542
    def has_id(self, file_id):
587
543
        # files that have been deleted are excluded
588
 
        inv = self._inventory
 
544
        inv = self.inventory
589
545
        if not inv.has_id(file_id):
590
546
            return False
591
547
        path = inv.id2path(file_id)
599
555
    __contains__ = has_id
600
556
 
601
557
    def get_file_size(self, file_id):
602
 
        return os.path.getsize(self.id2abspath(file_id))
 
558
        """See Tree.get_file_size"""
 
559
        try:
 
560
            return os.path.getsize(self.id2abspath(file_id))
 
561
        except OSError, e:
 
562
            if e.errno != errno.ENOENT:
 
563
                raise
 
564
            else:
 
565
                return None
603
566
 
604
567
    @needs_read_lock
605
 
    def get_file_sha1(self, file_id, path=None):
 
568
    def get_file_sha1(self, file_id, path=None, stat_value=None):
606
569
        if not path:
607
570
            path = self._inventory.id2path(file_id)
608
 
        return self._hashcache.get_sha1(path)
 
571
        return self._hashcache.get_sha1(path, stat_value)
609
572
 
610
573
    def get_file_mtime(self, file_id, path=None):
611
574
        if not path:
612
 
            path = self._inventory.id2path(file_id)
 
575
            path = self.inventory.id2path(file_id)
613
576
        return os.lstat(self.abspath(path)).st_mtime
614
577
 
 
578
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
 
579
        file_id = self.path2id(path)
 
580
        return self._inventory[file_id].executable
 
581
 
 
582
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
583
        mode = stat_result.st_mode
 
584
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
585
 
615
586
    if not supports_executable():
616
587
        def is_executable(self, file_id, path=None):
617
588
            return self._inventory[file_id].executable
 
589
 
 
590
        _is_executable_from_path_and_stat = \
 
591
            _is_executable_from_path_and_stat_from_basis
618
592
    else:
619
593
        def is_executable(self, file_id, path=None):
620
594
            if not path:
621
 
                path = self._inventory.id2path(file_id)
 
595
                path = self.id2path(file_id)
622
596
            mode = os.lstat(self.abspath(path)).st_mode
623
597
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
624
598
 
 
599
        _is_executable_from_path_and_stat = \
 
600
            _is_executable_from_path_and_stat_from_stat
 
601
 
625
602
    @needs_tree_write_lock
626
 
    def add(self, files, ids=None):
627
 
        """Make files versioned.
628
 
 
629
 
        Note that the command line normally calls smart_add instead,
630
 
        which can automatically recurse.
631
 
 
632
 
        This adds the files to the inventory, so that they will be
633
 
        recorded by the next commit.
634
 
 
635
 
        files
636
 
            List of paths to add, relative to the base of the tree.
637
 
 
638
 
        ids
639
 
            If set, use these instead of automatically generated ids.
640
 
            Must be the same length as the list of files, but may
641
 
            contain None for ids that are to be autogenerated.
642
 
 
643
 
        TODO: Perhaps have an option to add the ids even if the files do
644
 
              not (yet) exist.
645
 
 
646
 
        TODO: Perhaps callback with the ids and paths as they're added.
647
 
        """
 
603
    def _add(self, files, ids, kinds):
 
604
        """See MutableTree._add."""
648
605
        # TODO: Re-adding a file that is removed in the working copy
649
606
        # should probably put it back with the previous ID.
650
 
        if isinstance(files, basestring):
651
 
            assert(ids is None or isinstance(ids, basestring))
652
 
            files = [files]
653
 
            if ids is not None:
654
 
                ids = [ids]
655
 
 
656
 
        if ids is None:
657
 
            ids = [None] * len(files)
658
 
        else:
659
 
            assert(len(ids) == len(files))
660
 
 
661
 
        inv = self.read_working_inventory()
662
 
        for f,file_id in zip(files, ids):
663
 
            if self.is_control_filename(f):
664
 
                raise errors.ForbiddenControlFileError(filename=f)
665
 
 
666
 
            fp = splitpath(f)
667
 
 
668
 
            if len(fp) == 0:
669
 
                raise BzrError("cannot add top-level %r" % f)
670
 
 
671
 
            fullpath = normpath(self.abspath(f))
672
 
            try:
673
 
                kind = file_kind(fullpath)
674
 
            except OSError, e:
675
 
                if e.errno == errno.ENOENT:
676
 
                    raise NoSuchFile(fullpath)
677
 
            if not InventoryEntry.versionable_kind(kind):
678
 
                raise errors.BadFileKindError(filename=f, kind=kind)
 
607
        # the read and write working inventory should not occur in this 
 
608
        # function - they should be part of lock_write and unlock.
 
609
        inv = self.inventory
 
610
        for f, file_id, kind in zip(files, ids, kinds):
679
611
            if file_id is None:
680
612
                inv.add_path(f, kind=kind)
681
613
            else:
682
614
                inv.add_path(f, kind=kind, file_id=file_id)
683
 
 
684
 
        self._write_inventory(inv)
 
615
            self._inventory_is_modified = True
685
616
 
686
617
    @needs_tree_write_lock
 
618
    def _gather_kinds(self, files, kinds):
 
619
        """See MutableTree._gather_kinds."""
 
620
        for pos, f in enumerate(files):
 
621
            if kinds[pos] is None:
 
622
                fullpath = normpath(self.abspath(f))
 
623
                try:
 
624
                    kinds[pos] = file_kind(fullpath)
 
625
                except OSError, e:
 
626
                    if e.errno == errno.ENOENT:
 
627
                        raise errors.NoSuchFile(fullpath)
 
628
 
 
629
    @needs_write_lock
687
630
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
688
631
        """Add revision_id as a parent.
689
632
 
696
639
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
697
640
        """
698
641
        parents = self.get_parent_ids() + [revision_id]
699
 
        self.set_parent_ids(parents,
700
 
            allow_leftmost_as_ghost=len(parents) > 1 or allow_leftmost_as_ghost)
 
642
        self.set_parent_ids(parents, allow_leftmost_as_ghost=len(parents) > 1
 
643
            or allow_leftmost_as_ghost)
701
644
 
702
645
    @needs_tree_write_lock
703
646
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
735
678
        if updated:
736
679
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
737
680
 
738
 
    @deprecated_method(zero_eleven)
739
 
    @needs_read_lock
740
 
    def pending_merges(self):
741
 
        """Return a list of pending merges.
742
 
 
743
 
        These are revisions that have been merged into the working
744
 
        directory but not yet committed.
745
 
 
746
 
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
747
 
        instead - which is available on all tree objects.
748
 
        """
749
 
        return self.get_parent_ids()[1:]
 
681
    def path_content_summary(self, path, _lstat=os.lstat,
 
682
        _mapper=osutils.file_kind_from_stat_mode):
 
683
        """See Tree.path_content_summary."""
 
684
        abspath = self.abspath(path)
 
685
        try:
 
686
            stat_result = _lstat(abspath)
 
687
        except OSError, e:
 
688
            if getattr(e, 'errno', None) == errno.ENOENT:
 
689
                # no file.
 
690
                return ('missing', None, None, None)
 
691
            # propagate other errors
 
692
            raise
 
693
        kind = _mapper(stat_result.st_mode)
 
694
        if kind == 'file':
 
695
            size = stat_result.st_size
 
696
            # try for a stat cache lookup
 
697
            executable = self._is_executable_from_path_and_stat(path, stat_result)
 
698
            return (kind, size, executable, self._sha_from_stat(
 
699
                path, stat_result))
 
700
        elif kind == 'directory':
 
701
            # perhaps it looks like a plain directory, but it's really a
 
702
            # reference.
 
703
            if self._directory_is_tree_reference(path):
 
704
                kind = 'tree-reference'
 
705
            return kind, None, None, None
 
706
        elif kind == 'symlink':
 
707
            return ('symlink', None, None, os.readlink(abspath))
 
708
        else:
 
709
            return (kind, None, None, None)
 
710
 
 
711
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
 
712
        """Common ghost checking functionality from set_parent_*.
 
713
 
 
714
        This checks that the left hand-parent exists if there are any
 
715
        revisions present.
 
716
        """
 
717
        if len(revision_ids) > 0:
 
718
            leftmost_id = revision_ids[0]
 
719
            if (not allow_leftmost_as_ghost and not
 
720
                self.branch.repository.has_revision(leftmost_id)):
 
721
                raise errors.GhostRevisionUnusableHere(leftmost_id)
 
722
 
 
723
    def _set_merges_from_parent_ids(self, parent_ids):
 
724
        merges = parent_ids[1:]
 
725
        self._transport.put_bytes('pending-merges', '\n'.join(merges),
 
726
            mode=self._control_files._file_mode)
 
727
 
 
728
    def _filter_parent_ids_by_ancestry(self, revision_ids):
 
729
        """Check that all merged revisions are proper 'heads'.
 
730
 
 
731
        This will always return the first revision_id, and any merged revisions
 
732
        which are 
 
733
        """
 
734
        if len(revision_ids) == 0:
 
735
            return revision_ids
 
736
        graph = self.branch.repository.get_graph()
 
737
        heads = graph.heads(revision_ids)
 
738
        new_revision_ids = revision_ids[:1]
 
739
        for revision_id in revision_ids[1:]:
 
740
            if revision_id in heads and revision_id not in new_revision_ids:
 
741
                new_revision_ids.append(revision_id)
 
742
        if new_revision_ids != revision_ids:
 
743
            trace.mutter('requested to set revision_ids = %s,'
 
744
                         ' but filtered to %s', revision_ids, new_revision_ids)
 
745
        return new_revision_ids
750
746
 
751
747
    @needs_tree_write_lock
752
748
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
761
757
        :param revision_ids: The revision_ids to set as the parent ids of this
762
758
            working tree. Any of these may be ghosts.
763
759
        """
 
760
        self._check_parents_for_ghosts(revision_ids,
 
761
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
762
        for revision_id in revision_ids:
 
763
            _mod_revision.check_not_reserved_id(revision_id)
 
764
 
 
765
        revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
 
766
 
764
767
        if len(revision_ids) > 0:
765
 
            leftmost_id = revision_ids[0]
766
 
            if (not allow_leftmost_as_ghost and not
767
 
                self.branch.repository.has_revision(leftmost_id)):
768
 
                raise errors.GhostRevisionUnusableHere(leftmost_id)
769
 
            self.set_last_revision(leftmost_id)
 
768
            self.set_last_revision(revision_ids[0])
770
769
        else:
771
 
            self.set_last_revision(None)
772
 
        merges = revision_ids[1:]
773
 
        self._control_files.put_utf8('pending-merges', '\n'.join(merges))
 
770
            self.set_last_revision(_mod_revision.NULL_REVISION)
 
771
 
 
772
        self._set_merges_from_parent_ids(revision_ids)
774
773
 
775
774
    @needs_tree_write_lock
776
775
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
777
 
        """Set the parents of the working tree.
 
776
        """See MutableTree.set_parent_trees."""
 
777
        parent_ids = [rev for (rev, tree) in parents_list]
 
778
        for revision_id in parent_ids:
 
779
            _mod_revision.check_not_reserved_id(revision_id)
778
780
 
779
 
        :param parents_list: A list of (revision_id, tree) tuples. 
780
 
            If tree is None, then that element is treated as an unreachable
781
 
            parent tree - i.e. a ghost.
782
 
        """
783
 
        # parent trees are not used in current format trees, delegate to
784
 
        # set_parent_ids
785
 
        self.set_parent_ids([rev for (rev, tree) in parents_list],
 
781
        self._check_parents_for_ghosts(parent_ids,
786
782
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
787
783
 
 
784
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
 
785
 
 
786
        if len(parent_ids) == 0:
 
787
            leftmost_parent_id = _mod_revision.NULL_REVISION
 
788
            leftmost_parent_tree = None
 
789
        else:
 
790
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
 
791
 
 
792
        if self._change_last_revision(leftmost_parent_id):
 
793
            if leftmost_parent_tree is None:
 
794
                # If we don't have a tree, fall back to reading the
 
795
                # parent tree from the repository.
 
796
                self._cache_basis_inventory(leftmost_parent_id)
 
797
            else:
 
798
                inv = leftmost_parent_tree.inventory
 
799
                xml = self._create_basis_xml_from_inventory(
 
800
                                        leftmost_parent_id, inv)
 
801
                self._write_basis_inventory(xml)
 
802
        self._set_merges_from_parent_ids(parent_ids)
 
803
 
788
804
    @needs_tree_write_lock
789
805
    def set_pending_merges(self, rev_list):
790
806
        parents = self.get_parent_ids()
796
812
    def set_merge_modified(self, modified_hashes):
797
813
        def iter_stanzas():
798
814
            for file_id, hash in modified_hashes.iteritems():
799
 
                yield Stanza(file_id=file_id, hash=hash)
 
815
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
800
816
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
801
817
 
802
 
    @needs_tree_write_lock
 
818
    def _sha_from_stat(self, path, stat_result):
 
819
        """Get a sha digest from the tree's stat cache.
 
820
 
 
821
        The default implementation assumes no stat cache is present.
 
822
 
 
823
        :param path: The path.
 
824
        :param stat_result: The stat result being looked up.
 
825
        """
 
826
        return None
 
827
 
803
828
    def _put_rio(self, filename, stanzas, header):
 
829
        self._must_be_locked()
804
830
        my_file = rio_file(stanzas, header)
805
 
        self._control_files.put(filename, my_file)
 
831
        self._transport.put_file(filename, my_file,
 
832
            mode=self._control_files._file_mode)
806
833
 
807
834
    @needs_write_lock # because merge pulls data into the branch.
808
 
    def merge_from_branch(self, branch, to_revision=None):
 
835
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
 
836
        merge_type=None):
809
837
        """Merge from a branch into this working tree.
810
838
 
811
839
        :param branch: The branch to merge from.
812
 
        :param to_revision: If non-None, the merge will merge to to_revision, but 
813
 
            not beyond it. to_revision does not need to be in the history of
814
 
            the branch when it is supplied. If None, to_revision defaults to
 
840
        :param to_revision: If non-None, the merge will merge to to_revision,
 
841
            but not beyond it. to_revision does not need to be in the history
 
842
            of the branch when it is supplied. If None, to_revision defaults to
815
843
            branch.last_revision().
816
844
        """
817
845
        from bzrlib.merge import Merger, Merge3Merger
824
852
            # local alterations
825
853
            merger.check_basis(check_clean=True, require_commits=False)
826
854
            if to_revision is None:
827
 
                to_revision = branch.last_revision()
 
855
                to_revision = _mod_revision.ensure_null(branch.last_revision())
828
856
            merger.other_rev_id = to_revision
829
 
            if merger.other_rev_id is None:
830
 
                raise error.NoCommits(branch)
 
857
            if _mod_revision.is_null(merger.other_rev_id):
 
858
                raise errors.NoCommits(branch)
831
859
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
832
860
            merger.other_basis = merger.other_rev_id
833
861
            merger.other_tree = self.branch.repository.revision_tree(
834
862
                merger.other_rev_id)
 
863
            merger.other_branch = branch
835
864
            merger.pp.next_phase()
836
 
            merger.find_base()
 
865
            if from_revision is None:
 
866
                merger.find_base()
 
867
            else:
 
868
                merger.set_base_revision(from_revision, branch)
837
869
            if merger.base_rev_id == merger.other_rev_id:
838
870
                raise errors.PointlessMerge
839
871
            merger.backup_files = False
840
 
            merger.merge_type = Merge3Merger
 
872
            if merge_type is None:
 
873
                merger.merge_type = Merge3Merger
 
874
            else:
 
875
                merger.merge_type = merge_type
841
876
            merger.set_interesting_files(None)
842
877
            merger.show_base = False
843
878
            merger.reprocess = False
849
884
 
850
885
    @needs_read_lock
851
886
    def merge_modified(self):
 
887
        """Return a dictionary of files modified by a merge.
 
888
 
 
889
        The list is initialized by WorkingTree.set_merge_modified, which is 
 
890
        typically called after we make some automatic updates to the tree
 
891
        because of a merge.
 
892
 
 
893
        This returns a map of file_id->sha1, containing only files which are
 
894
        still in the working inventory and have that text hash.
 
895
        """
852
896
        try:
853
 
            hashfile = self._control_files.get('merge-hashes')
854
 
        except NoSuchFile:
 
897
            hashfile = self._transport.get('merge-hashes')
 
898
        except errors.NoSuchFile:
855
899
            return {}
856
900
        merge_hashes = {}
857
901
        try:
858
902
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
859
 
                raise MergeModifiedFormatError()
 
903
                raise errors.MergeModifiedFormatError()
860
904
        except StopIteration:
861
 
            raise MergeModifiedFormatError()
 
905
            raise errors.MergeModifiedFormatError()
862
906
        for s in RioReader(hashfile):
863
 
            file_id = s.get("file_id")
 
907
            # RioReader reads in Unicode, so convert file_ids back to utf8
 
908
            file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
864
909
            if file_id not in self.inventory:
865
910
                continue
866
 
            hash = s.get("hash")
867
 
            if hash == self.get_file_sha1(file_id):
868
 
                merge_hashes[file_id] = hash
 
911
            text_hash = s.get("hash")
 
912
            if text_hash == self.get_file_sha1(file_id):
 
913
                merge_hashes[file_id] = text_hash
869
914
        return merge_hashes
870
915
 
 
916
    @needs_write_lock
 
917
    def mkdir(self, path, file_id=None):
 
918
        """See MutableTree.mkdir()."""
 
919
        if file_id is None:
 
920
            file_id = generate_ids.gen_file_id(os.path.basename(path))
 
921
        os.mkdir(self.abspath(path))
 
922
        self.add(path, file_id, 'directory')
 
923
        return file_id
 
924
 
871
925
    def get_symlink_target(self, file_id):
872
926
        return os.readlink(self.id2abspath(file_id))
873
927
 
874
 
    def file_class(self, filename):
875
 
        if self.path2id(filename):
876
 
            return 'V'
877
 
        elif self.is_ignored(filename):
878
 
            return 'I'
879
 
        else:
880
 
            return '?'
881
 
 
882
 
    def list_files(self):
 
928
    @needs_write_lock
 
929
    def subsume(self, other_tree):
 
930
        def add_children(inventory, entry):
 
931
            for child_entry in entry.children.values():
 
932
                inventory._byid[child_entry.file_id] = child_entry
 
933
                if child_entry.kind == 'directory':
 
934
                    add_children(inventory, child_entry)
 
935
        if other_tree.get_root_id() == self.get_root_id():
 
936
            raise errors.BadSubsumeSource(self, other_tree,
 
937
                                          'Trees have the same root')
 
938
        try:
 
939
            other_tree_path = self.relpath(other_tree.basedir)
 
940
        except errors.PathNotChild:
 
941
            raise errors.BadSubsumeSource(self, other_tree,
 
942
                'Tree is not contained by the other')
 
943
        new_root_parent = self.path2id(osutils.dirname(other_tree_path))
 
944
        if new_root_parent is None:
 
945
            raise errors.BadSubsumeSource(self, other_tree,
 
946
                'Parent directory is not versioned.')
 
947
        # We need to ensure that the result of a fetch will have a
 
948
        # versionedfile for the other_tree root, and only fetching into
 
949
        # RepositoryKnit2 guarantees that.
 
950
        if not self.branch.repository.supports_rich_root():
 
951
            raise errors.SubsumeTargetNeedsUpgrade(other_tree)
 
952
        other_tree.lock_tree_write()
 
953
        try:
 
954
            new_parents = other_tree.get_parent_ids()
 
955
            other_root = other_tree.inventory.root
 
956
            other_root.parent_id = new_root_parent
 
957
            other_root.name = osutils.basename(other_tree_path)
 
958
            self.inventory.add(other_root)
 
959
            add_children(self.inventory, other_root)
 
960
            self._write_inventory(self.inventory)
 
961
            # normally we don't want to fetch whole repositories, but i think
 
962
            # here we really do want to consolidate the whole thing.
 
963
            for parent_id in other_tree.get_parent_ids():
 
964
                self.branch.fetch(other_tree.branch, parent_id)
 
965
                self.add_parent_tree_id(parent_id)
 
966
        finally:
 
967
            other_tree.unlock()
 
968
        other_tree.bzrdir.retire_bzrdir()
 
969
 
 
970
    def _setup_directory_is_tree_reference(self):
 
971
        if self._branch.repository._format.supports_tree_reference:
 
972
            self._directory_is_tree_reference = \
 
973
                self._directory_may_be_tree_reference
 
974
        else:
 
975
            self._directory_is_tree_reference = \
 
976
                self._directory_is_never_tree_reference
 
977
 
 
978
    def _directory_is_never_tree_reference(self, relpath):
 
979
        return False
 
980
 
 
981
    def _directory_may_be_tree_reference(self, relpath):
 
982
        # as a special case, if a directory contains control files then 
 
983
        # it's a tree reference, except that the root of the tree is not
 
984
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
 
985
        # TODO: We could ask all the control formats whether they
 
986
        # recognize this directory, but at the moment there's no cheap api
 
987
        # to do that.  Since we probably can only nest bzr checkouts and
 
988
        # they always use this name it's ok for now.  -- mbp 20060306
 
989
        #
 
990
        # FIXME: There is an unhandled case here of a subdirectory
 
991
        # containing .bzr but not a branch; that will probably blow up
 
992
        # when you try to commit it.  It might happen if there is a
 
993
        # checkout in a subdirectory.  This can be avoided by not adding
 
994
        # it.  mbp 20070306
 
995
 
 
996
    @needs_tree_write_lock
 
997
    def extract(self, file_id, format=None):
 
998
        """Extract a subtree from this tree.
 
999
        
 
1000
        A new branch will be created, relative to the path for this tree.
 
1001
        """
 
1002
        self.flush()
 
1003
        def mkdirs(path):
 
1004
            segments = osutils.splitpath(path)
 
1005
            transport = self.branch.bzrdir.root_transport
 
1006
            for name in segments:
 
1007
                transport = transport.clone(name)
 
1008
                transport.ensure_base()
 
1009
            return transport
 
1010
            
 
1011
        sub_path = self.id2path(file_id)
 
1012
        branch_transport = mkdirs(sub_path)
 
1013
        if format is None:
 
1014
            format = self.bzrdir.cloning_metadir()
 
1015
        branch_transport.ensure_base()
 
1016
        branch_bzrdir = format.initialize_on_transport(branch_transport)
 
1017
        try:
 
1018
            repo = branch_bzrdir.find_repository()
 
1019
        except errors.NoRepositoryPresent:
 
1020
            repo = branch_bzrdir.create_repository()
 
1021
        if not repo.supports_rich_root():
 
1022
            raise errors.RootNotRich()
 
1023
        new_branch = branch_bzrdir.create_branch()
 
1024
        new_branch.pull(self.branch)
 
1025
        for parent_id in self.get_parent_ids():
 
1026
            new_branch.fetch(self.branch, parent_id)
 
1027
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
 
1028
        if tree_transport.base != branch_transport.base:
 
1029
            tree_bzrdir = format.initialize_on_transport(tree_transport)
 
1030
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
 
1031
        else:
 
1032
            tree_bzrdir = branch_bzrdir
 
1033
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
 
1034
        wt.set_parent_ids(self.get_parent_ids())
 
1035
        my_inv = self.inventory
 
1036
        child_inv = Inventory(root_id=None)
 
1037
        new_root = my_inv[file_id]
 
1038
        my_inv.remove_recursive_id(file_id)
 
1039
        new_root.parent_id = None
 
1040
        child_inv.add(new_root)
 
1041
        self._write_inventory(my_inv)
 
1042
        wt._write_inventory(child_inv)
 
1043
        return wt
 
1044
 
 
1045
    def _serialize(self, inventory, out_file):
 
1046
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
 
1047
            working=True)
 
1048
 
 
1049
    def _deserialize(selt, in_file):
 
1050
        return xml5.serializer_v5.read_inventory(in_file)
 
1051
 
 
1052
    def flush(self):
 
1053
        """Write the in memory inventory to disk."""
 
1054
        # TODO: Maybe this should only write on dirty ?
 
1055
        if self._control_files._lock_mode != 'w':
 
1056
            raise errors.NotWriteLocked(self)
 
1057
        sio = StringIO()
 
1058
        self._serialize(self._inventory, sio)
 
1059
        sio.seek(0)
 
1060
        self._transport.put_file('inventory', sio,
 
1061
            mode=self._control_files._file_mode)
 
1062
        self._inventory_is_modified = False
 
1063
 
 
1064
    def _kind(self, relpath):
 
1065
        return osutils.file_kind(self.abspath(relpath))
 
1066
 
 
1067
    def list_files(self, include_root=False):
883
1068
        """Recursively list all files as (path, class, kind, id, entry).
884
1069
 
885
1070
        Lists, but does not descend into unversioned directories.
889
1074
 
890
1075
        Skips the control directory.
891
1076
        """
892
 
        inv = self._inventory
 
1077
        # list_files is an iterator, so @needs_read_lock doesn't work properly
 
1078
        # with it. So callers should be careful to always read_lock the tree.
 
1079
        if not self.is_locked():
 
1080
            raise errors.ObjectNotLocked(self)
 
1081
 
 
1082
        inv = self.inventory
 
1083
        if include_root is True:
 
1084
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
893
1085
        # Convert these into local objects to save lookup times
894
1086
        pathjoin = osutils.pathjoin
895
 
        file_kind = osutils.file_kind
 
1087
        file_kind = self._kind
896
1088
 
897
1089
        # transport.base ends in a slash, we want the piece
898
1090
        # between the last two slashes
958
1150
 
959
1151
                fk = file_kind(fap)
960
1152
 
961
 
                if f_ie:
962
 
                    if f_ie.kind != fk:
963
 
                        raise BzrCheckError("file %r entered as kind %r id %r, "
964
 
                                            "now of kind %r"
965
 
                                            % (fap, f_ie.kind, f_ie.file_id, fk))
966
 
 
967
1153
                # make a last minute entry
968
1154
                if f_ie:
969
1155
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
982
1168
                new_children.sort()
983
1169
                new_children = collections.deque(new_children)
984
1170
                stack.append((f_ie.file_id, fp, fap, new_children))
985
 
                # Break out of inner loop, so that we start outer loop with child
 
1171
                # Break out of inner loop,
 
1172
                # so that we start outer loop with child
986
1173
                break
987
1174
            else:
988
1175
                # if we finished all children, pop it off the stack
989
1176
                stack.pop()
990
1177
 
991
1178
    @needs_tree_write_lock
992
 
    def move(self, from_paths, to_name):
 
1179
    def move(self, from_paths, to_dir=None, after=False, **kwargs):
993
1180
        """Rename files.
994
1181
 
995
 
        to_name must exist in the inventory.
 
1182
        to_dir must exist in the inventory.
996
1183
 
997
 
        If to_name exists and is a directory, the files are moved into
 
1184
        If to_dir exists and is a directory, the files are moved into
998
1185
        it, keeping their old names.  
999
1186
 
1000
 
        Note that to_name is only the last component of the new name;
 
1187
        Note that to_dir is only the last component of the new name;
1001
1188
        this doesn't change the directory.
1002
1189
 
 
1190
        For each entry in from_paths the move mode will be determined
 
1191
        independently.
 
1192
 
 
1193
        The first mode moves the file in the filesystem and updates the
 
1194
        inventory. The second mode only updates the inventory without
 
1195
        touching the file on the filesystem. This is the new mode introduced
 
1196
        in version 0.15.
 
1197
 
 
1198
        move uses the second mode if 'after == True' and the target is not
 
1199
        versioned but present in the working tree.
 
1200
 
 
1201
        move uses the second mode if 'after == False' and the source is
 
1202
        versioned but no longer in the working tree, and the target is not
 
1203
        versioned but present in the working tree.
 
1204
 
 
1205
        move uses the first mode if 'after == False' and the source is
 
1206
        versioned and present in the working tree, and the target is not
 
1207
        versioned and not present in the working tree.
 
1208
 
 
1209
        Everything else results in an error.
 
1210
 
1003
1211
        This returns a list of (from_path, to_path) pairs for each
1004
1212
        entry that is moved.
1005
1213
        """
1006
 
        result = []
1007
 
        ## TODO: Option to move IDs only
1008
 
        assert not isinstance(from_paths, basestring)
 
1214
        rename_entries = []
 
1215
        rename_tuples = []
 
1216
 
 
1217
        # check for deprecated use of signature
 
1218
        if to_dir is None:
 
1219
            to_dir = kwargs.get('to_name', None)
 
1220
            if to_dir is None:
 
1221
                raise TypeError('You must supply a target directory')
 
1222
            else:
 
1223
                symbol_versioning.warn('The parameter to_name was deprecated'
 
1224
                                       ' in version 0.13. Use to_dir instead',
 
1225
                                       DeprecationWarning)
 
1226
 
 
1227
        # check destination directory
 
1228
        if isinstance(from_paths, basestring):
 
1229
            raise ValueError()
1009
1230
        inv = self.inventory
1010
 
        to_abs = self.abspath(to_name)
 
1231
        to_abs = self.abspath(to_dir)
1011
1232
        if not isdir(to_abs):
1012
 
            raise BzrError("destination %r is not a directory" % to_abs)
1013
 
        if not self.has_filename(to_name):
1014
 
            raise BzrError("destination %r not in working directory" % to_abs)
1015
 
        to_dir_id = inv.path2id(to_name)
1016
 
        if to_dir_id is None and to_name != '':
1017
 
            raise BzrError("destination %r is not a versioned directory" % to_name)
 
1233
            raise errors.BzrMoveFailedError('',to_dir,
 
1234
                errors.NotADirectory(to_abs))
 
1235
        if not self.has_filename(to_dir):
 
1236
            raise errors.BzrMoveFailedError('',to_dir,
 
1237
                errors.NotInWorkingDirectory(to_dir))
 
1238
        to_dir_id = inv.path2id(to_dir)
 
1239
        if to_dir_id is None:
 
1240
            raise errors.BzrMoveFailedError('',to_dir,
 
1241
                errors.NotVersionedError(path=str(to_dir)))
 
1242
 
1018
1243
        to_dir_ie = inv[to_dir_id]
1019
1244
        if to_dir_ie.kind != 'directory':
1020
 
            raise BzrError("destination %r is not a directory" % to_abs)
1021
 
 
1022
 
        to_idpath = inv.get_idpath(to_dir_id)
1023
 
 
1024
 
        for f in from_paths:
1025
 
            if not self.has_filename(f):
1026
 
                raise BzrError("%r does not exist in working tree" % f)
1027
 
            f_id = inv.path2id(f)
1028
 
            if f_id is None:
1029
 
                raise BzrError("%r is not versioned" % f)
1030
 
            name_tail = splitpath(f)[-1]
1031
 
            dest_path = pathjoin(to_name, name_tail)
1032
 
            if self.has_filename(dest_path):
1033
 
                raise BzrError("destination %r already exists" % dest_path)
1034
 
            if f_id in to_idpath:
1035
 
                raise BzrError("can't move %r to a subdirectory of itself" % f)
1036
 
 
1037
 
        # OK, so there's a race here, it's possible that someone will
1038
 
        # create a file in this interval and then the rename might be
1039
 
        # left half-done.  But we should have caught most problems.
1040
 
        orig_inv = deepcopy(self.inventory)
 
1245
            raise errors.BzrMoveFailedError('',to_dir,
 
1246
                errors.NotADirectory(to_abs))
 
1247
 
 
1248
        # create rename entries and tuples
 
1249
        for from_rel in from_paths:
 
1250
            from_tail = splitpath(from_rel)[-1]
 
1251
            from_id = inv.path2id(from_rel)
 
1252
            if from_id is None:
 
1253
                raise errors.BzrMoveFailedError(from_rel,to_dir,
 
1254
                    errors.NotVersionedError(path=str(from_rel)))
 
1255
 
 
1256
            from_entry = inv[from_id]
 
1257
            from_parent_id = from_entry.parent_id
 
1258
            to_rel = pathjoin(to_dir, from_tail)
 
1259
            rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
 
1260
                                         from_id=from_id,
 
1261
                                         from_tail=from_tail,
 
1262
                                         from_parent_id=from_parent_id,
 
1263
                                         to_rel=to_rel, to_tail=from_tail,
 
1264
                                         to_parent_id=to_dir_id)
 
1265
            rename_entries.append(rename_entry)
 
1266
            rename_tuples.append((from_rel, to_rel))
 
1267
 
 
1268
        # determine which move mode to use. checks also for movability
 
1269
        rename_entries = self._determine_mv_mode(rename_entries, after)
 
1270
 
 
1271
        original_modified = self._inventory_is_modified
1041
1272
        try:
1042
 
            for f in from_paths:
1043
 
                name_tail = splitpath(f)[-1]
1044
 
                dest_path = pathjoin(to_name, name_tail)
1045
 
                result.append((f, dest_path))
1046
 
                inv.rename(inv.path2id(f), to_dir_id, name_tail)
1047
 
                try:
1048
 
                    rename(self.abspath(f), self.abspath(dest_path))
1049
 
                except OSError, e:
1050
 
                    raise BzrError("failed to rename %r to %r: %s" %
1051
 
                                   (f, dest_path, e[1]),
1052
 
                            ["rename rolled back"])
 
1273
            if len(from_paths):
 
1274
                self._inventory_is_modified = True
 
1275
            self._move(rename_entries)
1053
1276
        except:
1054
1277
            # restore the inventory on error
1055
 
            self._set_inventory(orig_inv)
 
1278
            self._inventory_is_modified = original_modified
1056
1279
            raise
1057
1280
        self._write_inventory(inv)
1058
 
        return result
 
1281
        return rename_tuples
 
1282
 
 
1283
    def _determine_mv_mode(self, rename_entries, after=False):
 
1284
        """Determines for each from-to pair if both inventory and working tree
 
1285
        or only the inventory has to be changed.
 
1286
 
 
1287
        Also does basic plausability tests.
 
1288
        """
 
1289
        inv = self.inventory
 
1290
 
 
1291
        for rename_entry in rename_entries:
 
1292
            # store to local variables for easier reference
 
1293
            from_rel = rename_entry.from_rel
 
1294
            from_id = rename_entry.from_id
 
1295
            to_rel = rename_entry.to_rel
 
1296
            to_id = inv.path2id(to_rel)
 
1297
            only_change_inv = False
 
1298
 
 
1299
            # check the inventory for source and destination
 
1300
            if from_id is None:
 
1301
                raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1302
                    errors.NotVersionedError(path=str(from_rel)))
 
1303
            if to_id is not None:
 
1304
                raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1305
                    errors.AlreadyVersionedError(path=str(to_rel)))
 
1306
 
 
1307
            # try to determine the mode for rename (only change inv or change
 
1308
            # inv and file system)
 
1309
            if after:
 
1310
                if not self.has_filename(to_rel):
 
1311
                    raise errors.BzrMoveFailedError(from_id,to_rel,
 
1312
                        errors.NoSuchFile(path=str(to_rel),
 
1313
                        extra="New file has not been created yet"))
 
1314
                only_change_inv = True
 
1315
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
 
1316
                only_change_inv = True
 
1317
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
 
1318
                only_change_inv = False
 
1319
            elif (sys.platform == 'win32'
 
1320
                and from_rel.lower() == to_rel.lower()
 
1321
                and self.has_filename(from_rel)):
 
1322
                only_change_inv = False
 
1323
            else:
 
1324
                # something is wrong, so lets determine what exactly
 
1325
                if not self.has_filename(from_rel) and \
 
1326
                   not self.has_filename(to_rel):
 
1327
                    raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1328
                        errors.PathsDoNotExist(paths=(str(from_rel),
 
1329
                        str(to_rel))))
 
1330
                else:
 
1331
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
 
1332
            rename_entry.only_change_inv = only_change_inv
 
1333
        return rename_entries
 
1334
 
 
1335
    def _move(self, rename_entries):
 
1336
        """Moves a list of files.
 
1337
 
 
1338
        Depending on the value of the flag 'only_change_inv', the
 
1339
        file will be moved on the file system or not.
 
1340
        """
 
1341
        inv = self.inventory
 
1342
        moved = []
 
1343
 
 
1344
        for entry in rename_entries:
 
1345
            try:
 
1346
                self._move_entry(entry)
 
1347
            except:
 
1348
                self._rollback_move(moved)
 
1349
                raise
 
1350
            moved.append(entry)
 
1351
 
 
1352
    def _rollback_move(self, moved):
 
1353
        """Try to rollback a previous move in case of an filesystem error."""
 
1354
        inv = self.inventory
 
1355
        for entry in moved:
 
1356
            try:
 
1357
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
 
1358
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
 
1359
                    entry.from_tail, entry.from_parent_id,
 
1360
                    entry.only_change_inv))
 
1361
            except errors.BzrMoveFailedError, e:
 
1362
                raise errors.BzrMoveFailedError( '', '', "Rollback failed."
 
1363
                        " The working tree is in an inconsistent state."
 
1364
                        " Please consider doing a 'bzr revert'."
 
1365
                        " Error message is: %s" % e)
 
1366
 
 
1367
    def _move_entry(self, entry):
 
1368
        inv = self.inventory
 
1369
        from_rel_abs = self.abspath(entry.from_rel)
 
1370
        to_rel_abs = self.abspath(entry.to_rel)
 
1371
        if from_rel_abs == to_rel_abs:
 
1372
            raise errors.BzrMoveFailedError(entry.from_rel, entry.to_rel,
 
1373
                "Source and target are identical.")
 
1374
 
 
1375
        if not entry.only_change_inv:
 
1376
            try:
 
1377
                osutils.rename(from_rel_abs, to_rel_abs)
 
1378
            except OSError, e:
 
1379
                raise errors.BzrMoveFailedError(entry.from_rel,
 
1380
                    entry.to_rel, e[1])
 
1381
        inv.rename(entry.from_id, entry.to_parent_id, entry.to_tail)
1059
1382
 
1060
1383
    @needs_tree_write_lock
1061
 
    def rename_one(self, from_rel, to_rel):
 
1384
    def rename_one(self, from_rel, to_rel, after=False):
1062
1385
        """Rename one file.
1063
1386
 
1064
1387
        This can change the directory or the filename or both.
 
1388
 
 
1389
        rename_one has several 'modes' to work. First, it can rename a physical
 
1390
        file and change the file_id. That is the normal mode. Second, it can
 
1391
        only change the file_id without touching any physical file. This is
 
1392
        the new mode introduced in version 0.15.
 
1393
 
 
1394
        rename_one uses the second mode if 'after == True' and 'to_rel' is not
 
1395
        versioned but present in the working tree.
 
1396
 
 
1397
        rename_one uses the second mode if 'after == False' and 'from_rel' is
 
1398
        versioned but no longer in the working tree, and 'to_rel' is not
 
1399
        versioned but present in the working tree.
 
1400
 
 
1401
        rename_one uses the first mode if 'after == False' and 'from_rel' is
 
1402
        versioned and present in the working tree, and 'to_rel' is not
 
1403
        versioned and not present in the working tree.
 
1404
 
 
1405
        Everything else results in an error.
1065
1406
        """
1066
1407
        inv = self.inventory
1067
 
        if not self.has_filename(from_rel):
1068
 
            raise BzrError("can't rename: old working file %r does not exist" % from_rel)
1069
 
        if self.has_filename(to_rel):
1070
 
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
1071
 
 
1072
 
        file_id = inv.path2id(from_rel)
1073
 
        if file_id is None:
1074
 
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1075
 
 
1076
 
        entry = inv[file_id]
1077
 
        from_parent = entry.parent_id
1078
 
        from_name = entry.name
1079
 
        
1080
 
        if inv.path2id(to_rel):
1081
 
            raise BzrError("can't rename: new name %r is already versioned" % to_rel)
1082
 
 
 
1408
        rename_entries = []
 
1409
 
 
1410
        # create rename entries and tuples
 
1411
        from_tail = splitpath(from_rel)[-1]
 
1412
        from_id = inv.path2id(from_rel)
 
1413
        if from_id is None:
 
1414
            raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1415
                errors.NotVersionedError(path=str(from_rel)))
 
1416
        from_entry = inv[from_id]
 
1417
        from_parent_id = from_entry.parent_id
1083
1418
        to_dir, to_tail = os.path.split(to_rel)
1084
1419
        to_dir_id = inv.path2id(to_dir)
1085
 
        if to_dir_id is None and to_dir != '':
1086
 
            raise BzrError("can't determine destination directory id for %r" % to_dir)
1087
 
 
1088
 
        mutter("rename_one:")
1089
 
        mutter("  file_id    {%s}" % file_id)
1090
 
        mutter("  from_rel   %r" % from_rel)
1091
 
        mutter("  to_rel     %r" % to_rel)
1092
 
        mutter("  to_dir     %r" % to_dir)
1093
 
        mutter("  to_dir_id  {%s}" % to_dir_id)
1094
 
 
1095
 
        inv.rename(file_id, to_dir_id, to_tail)
1096
 
 
1097
 
        from_abs = self.abspath(from_rel)
1098
 
        to_abs = self.abspath(to_rel)
1099
 
        try:
1100
 
            rename(from_abs, to_abs)
1101
 
        except OSError, e:
1102
 
            inv.rename(file_id, from_parent, from_name)
1103
 
            raise BzrError("failed to rename %r to %r: %s"
1104
 
                    % (from_abs, to_abs, e[1]),
1105
 
                    ["rename rolled back"])
 
1420
        rename_entry = WorkingTree._RenameEntry(from_rel=from_rel,
 
1421
                                     from_id=from_id,
 
1422
                                     from_tail=from_tail,
 
1423
                                     from_parent_id=from_parent_id,
 
1424
                                     to_rel=to_rel, to_tail=to_tail,
 
1425
                                     to_parent_id=to_dir_id)
 
1426
        rename_entries.append(rename_entry)
 
1427
 
 
1428
        # determine which move mode to use. checks also for movability
 
1429
        rename_entries = self._determine_mv_mode(rename_entries, after)
 
1430
 
 
1431
        # check if the target changed directory and if the target directory is
 
1432
        # versioned
 
1433
        if to_dir_id is None:
 
1434
            raise errors.BzrMoveFailedError(from_rel,to_rel,
 
1435
                errors.NotVersionedError(path=str(to_dir)))
 
1436
 
 
1437
        # all checks done. now we can continue with our actual work
 
1438
        mutter('rename_one:\n'
 
1439
               '  from_id   {%s}\n'
 
1440
               '  from_rel: %r\n'
 
1441
               '  to_rel:   %r\n'
 
1442
               '  to_dir    %r\n'
 
1443
               '  to_dir_id {%s}\n',
 
1444
               from_id, from_rel, to_rel, to_dir, to_dir_id)
 
1445
 
 
1446
        self._move(rename_entries)
1106
1447
        self._write_inventory(inv)
1107
1448
 
 
1449
    class _RenameEntry(object):
 
1450
        def __init__(self, from_rel, from_id, from_tail, from_parent_id,
 
1451
                     to_rel, to_tail, to_parent_id, only_change_inv=False):
 
1452
            self.from_rel = from_rel
 
1453
            self.from_id = from_id
 
1454
            self.from_tail = from_tail
 
1455
            self.from_parent_id = from_parent_id
 
1456
            self.to_rel = to_rel
 
1457
            self.to_tail = to_tail
 
1458
            self.to_parent_id = to_parent_id
 
1459
            self.only_change_inv = only_change_inv
 
1460
 
1108
1461
    @needs_read_lock
1109
1462
    def unknowns(self):
1110
1463
        """Return all unknown files.
1112
1465
        These are files in the working directory that are not versioned or
1113
1466
        control files or ignored.
1114
1467
        """
1115
 
        for subp in self.extras():
1116
 
            if not self.is_ignored(subp):
1117
 
                yield subp
1118
 
    
 
1468
        # force the extras method to be fully executed before returning, to 
 
1469
        # prevent race conditions with the lock
 
1470
        return iter(
 
1471
            [subp for subp in self.extras() if not self.is_ignored(subp)])
 
1472
 
1119
1473
    @needs_tree_write_lock
1120
1474
    def unversion(self, file_ids):
1121
1475
        """Remove the file ids in file_ids from the current versioned set.
1142
1496
            # - RBC 20060907
1143
1497
            self._write_inventory(self._inventory)
1144
1498
    
1145
 
    @deprecated_method(zero_eight)
1146
 
    def iter_conflicts(self):
1147
 
        """List all files in the tree that have text or content conflicts.
1148
 
        DEPRECATED.  Use conflicts instead."""
1149
 
        return self._iter_conflicts()
1150
 
 
1151
1499
    def _iter_conflicts(self):
1152
1500
        conflicted = set()
1153
1501
        for info in self.list_files():
1160
1508
                yield stem
1161
1509
 
1162
1510
    @needs_write_lock
1163
 
    def pull(self, source, overwrite=False, stop_revision=None):
 
1511
    def pull(self, source, overwrite=False, stop_revision=None,
 
1512
             change_reporter=None, possible_transports=None):
1164
1513
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1165
1514
        source.lock_read()
1166
1515
        try:
1167
1516
            pp = ProgressPhase("Pull phase", 2, top_pb)
1168
1517
            pp.next_phase()
1169
 
            old_revision_history = self.branch.revision_history()
 
1518
            old_revision_info = self.branch.last_revision_info()
1170
1519
            basis_tree = self.basis_tree()
1171
 
            count = self.branch.pull(source, overwrite, stop_revision)
1172
 
            new_revision_history = self.branch.revision_history()
1173
 
            if new_revision_history != old_revision_history:
 
1520
            count = self.branch.pull(source, overwrite, stop_revision,
 
1521
                                     possible_transports=possible_transports)
 
1522
            new_revision_info = self.branch.last_revision_info()
 
1523
            if new_revision_info != old_revision_info:
1174
1524
                pp.next_phase()
1175
 
                if len(old_revision_history):
1176
 
                    other_revision = old_revision_history[-1]
1177
 
                else:
1178
 
                    other_revision = None
1179
1525
                repository = self.branch.repository
1180
1526
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
1527
                basis_tree.lock_read()
1181
1528
                try:
1182
1529
                    new_basis_tree = self.branch.basis_tree()
1183
 
                    merge_inner(self.branch,
 
1530
                    merge.merge_inner(
 
1531
                                self.branch,
1184
1532
                                new_basis_tree,
1185
1533
                                basis_tree,
1186
1534
                                this_tree=self,
1187
 
                                pb=pb)
 
1535
                                pb=pb,
 
1536
                                change_reporter=change_reporter)
 
1537
                    if (basis_tree.inventory.root is None and
 
1538
                        new_basis_tree.inventory.root is not None):
 
1539
                        self.set_root_id(new_basis_tree.get_root_id())
1188
1540
                finally:
1189
1541
                    pb.finished()
 
1542
                    basis_tree.unlock()
1190
1543
                # TODO - dedup parents list with things merged by pull ?
1191
1544
                # reuse the revisiontree we merged against to set the new
1192
1545
                # tree data.
1194
1547
                # we have to pull the merge trees out again, because 
1195
1548
                # merge_inner has set the ids. - this corner is not yet 
1196
1549
                # layered well enough to prevent double handling.
 
1550
                # XXX TODO: Fix the double handling: telling the tree about
 
1551
                # the already known parent data is wasteful.
1197
1552
                merges = self.get_parent_ids()[1:]
1198
1553
                parent_trees.extend([
1199
1554
                    (parent, repository.revision_tree(parent)) for
1204
1559
            source.unlock()
1205
1560
            top_pb.finished()
1206
1561
 
 
1562
    @needs_write_lock
 
1563
    def put_file_bytes_non_atomic(self, file_id, bytes):
 
1564
        """See MutableTree.put_file_bytes_non_atomic."""
 
1565
        stream = file(self.id2abspath(file_id), 'wb')
 
1566
        try:
 
1567
            stream.write(bytes)
 
1568
        finally:
 
1569
            stream.close()
 
1570
        # TODO: update the hashcache here ?
 
1571
 
1207
1572
    def extras(self):
1208
 
        """Yield all unknown files in this WorkingTree.
 
1573
        """Yield all unversioned files in this WorkingTree.
1209
1574
 
1210
 
        If there are any unknown directories then only the directory is
1211
 
        returned, not all its children.  But if there are unknown files
 
1575
        If there are any unversioned directories then only the directory is
 
1576
        returned, not all its children.  But if there are unversioned files
1212
1577
        under a versioned subdirectory, they are returned.
1213
1578
 
1214
1579
        Currently returned depth-first, sorted by name within directories.
 
1580
        This is the same order used by 'osutils.walkdirs'.
1215
1581
        """
1216
1582
        ## TODO: Work from given directory downwards
1217
1583
        for path, dir_entry in self.inventory.directories():
1226
1592
                if subf == '.bzr':
1227
1593
                    continue
1228
1594
                if subf not in dir_entry.children:
1229
 
                    subf_norm, can_access = osutils.normalized_filename(subf)
 
1595
                    try:
 
1596
                        (subf_norm,
 
1597
                         can_access) = osutils.normalized_filename(subf)
 
1598
                    except UnicodeDecodeError:
 
1599
                        path_os_enc = path.encode(osutils._fs_enc)
 
1600
                        relpath = path_os_enc + '/' + subf
 
1601
                        raise errors.BadFilenameEncoding(relpath,
 
1602
                                                         osutils._fs_enc)
1230
1603
                    if subf_norm != subf and can_access:
1231
1604
                        if subf_norm not in dir_entry.children:
1232
1605
                            fl.append(subf_norm)
1238
1611
                subp = pathjoin(path, subf)
1239
1612
                yield subp
1240
1613
 
1241
 
    def _translate_ignore_rule(self, rule):
1242
 
        """Translate a single ignore rule to a regex.
1243
 
 
1244
 
        There are two types of ignore rules.  Those that do not contain a / are
1245
 
        matched against the tail of the filename (that is, they do not care
1246
 
        what directory the file is in.)  Rules which do contain a slash must
1247
 
        match the entire path.  As a special case, './' at the start of the
1248
 
        string counts as a slash in the string but is removed before matching
1249
 
        (e.g. ./foo.c, ./src/foo.c)
1250
 
 
1251
 
        :return: The translated regex.
1252
 
        """
1253
 
        if rule[:2] in ('./', '.\\'):
1254
 
            # rootdir rule
1255
 
            result = fnmatch.translate(rule[2:])
1256
 
        elif '/' in rule or '\\' in rule:
1257
 
            # path prefix 
1258
 
            result = fnmatch.translate(rule)
1259
 
        else:
1260
 
            # default rule style.
1261
 
            result = "(?:.*/)?(?!.*/)" + fnmatch.translate(rule)
1262
 
        assert result[-1] == '$', "fnmatch.translate did not add the expected $"
1263
 
        return "(" + result + ")"
1264
 
 
1265
 
    def _combine_ignore_rules(self, rules):
1266
 
        """Combine a list of ignore rules into a single regex object.
1267
 
 
1268
 
        Each individual rule is combined with | to form a big regex, which then
1269
 
        has $ added to it to form something like ()|()|()$. The group index for
1270
 
        each subregex's outermost group is placed in a dictionary mapping back 
1271
 
        to the rule. This allows quick identification of the matching rule that
1272
 
        triggered a match.
1273
 
        :return: a list of the compiled regex and the matching-group index 
1274
 
        dictionaries. We return a list because python complains if you try to 
1275
 
        combine more than 100 regexes.
1276
 
        """
1277
 
        result = []
1278
 
        groups = {}
1279
 
        next_group = 0
1280
 
        translated_rules = []
1281
 
        for rule in rules:
1282
 
            translated_rule = self._translate_ignore_rule(rule)
1283
 
            compiled_rule = re.compile(translated_rule)
1284
 
            groups[next_group] = rule
1285
 
            next_group += compiled_rule.groups
1286
 
            translated_rules.append(translated_rule)
1287
 
            if next_group == 99:
1288
 
                result.append((re.compile("|".join(translated_rules)), groups))
1289
 
                groups = {}
1290
 
                next_group = 0
1291
 
                translated_rules = []
1292
 
        if len(translated_rules):
1293
 
            result.append((re.compile("|".join(translated_rules)), groups))
1294
 
        return result
1295
 
 
1296
1614
    def ignored_files(self):
1297
1615
        """Yield list of PATH, IGNORE_PATTERN"""
1298
1616
        for subp in self.extras():
1309
1627
        if ignoreset is not None:
1310
1628
            return ignoreset
1311
1629
 
1312
 
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
 
1630
        ignore_globs = set()
1313
1631
        ignore_globs.update(ignores.get_runtime_ignores())
1314
 
 
1315
1632
        ignore_globs.update(ignores.get_user_ignores())
1316
 
 
1317
1633
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1318
1634
            f = self.get_file_byname(bzrlib.IGNORE_FILENAME)
1319
1635
            try:
1320
1636
                ignore_globs.update(ignores.parse_ignore_file(f))
1321
1637
            finally:
1322
1638
                f.close()
1323
 
 
1324
1639
        self._ignoreset = ignore_globs
1325
 
        self._ignore_regex = self._combine_ignore_rules(ignore_globs)
1326
1640
        return ignore_globs
1327
1641
 
1328
 
    def _get_ignore_rules_as_regex(self):
1329
 
        """Return a regex of the ignore rules and a mapping dict.
1330
 
 
1331
 
        :return: (ignore rules compiled regex, dictionary mapping rule group 
1332
 
        indices to original rule.)
1333
 
        """
1334
 
        if getattr(self, '_ignoreset', None) is None:
1335
 
            self.get_ignore_list()
1336
 
        return self._ignore_regex
 
1642
    def _flush_ignore_list_cache(self):
 
1643
        """Resets the cached ignore list to force a cache rebuild."""
 
1644
        self._ignoreset = None
 
1645
        self._ignoreglobster = None
1337
1646
 
1338
1647
    def is_ignored(self, filename):
1339
1648
        r"""Check whether the filename matches an ignore pattern.
1344
1653
        If the file is ignored, returns the pattern which caused it to
1345
1654
        be ignored, otherwise None.  So this can simply be used as a
1346
1655
        boolean if desired."""
1347
 
 
1348
 
        # TODO: Use '**' to match directories, and other extended
1349
 
        # globbing stuff from cvs/rsync.
1350
 
 
1351
 
        # XXX: fnmatch is actually not quite what we want: it's only
1352
 
        # approximately the same as real Unix fnmatch, and doesn't
1353
 
        # treat dotfiles correctly and allows * to match /.
1354
 
        # Eventually it should be replaced with something more
1355
 
        # accurate.
1356
 
    
1357
 
        rules = self._get_ignore_rules_as_regex()
1358
 
        for regex, mapping in rules:
1359
 
            match = regex.match(filename)
1360
 
            if match is not None:
1361
 
                # one or more of the groups in mapping will have a non-None
1362
 
                # group match.
1363
 
                groups = match.groups()
1364
 
                rules = [mapping[group] for group in 
1365
 
                    mapping if groups[group] is not None]
1366
 
                return rules[0]
1367
 
        return None
 
1656
        if getattr(self, '_ignoreglobster', None) is None:
 
1657
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
 
1658
        return self._ignoreglobster.match(filename)
1368
1659
 
1369
1660
    def kind(self, file_id):
1370
1661
        return file_kind(self.id2abspath(file_id))
1371
1662
 
 
1663
    def stored_kind(self, file_id):
 
1664
        """See Tree.stored_kind"""
 
1665
        return self.inventory[file_id].kind
 
1666
 
 
1667
    def _comparison_data(self, entry, path):
 
1668
        abspath = self.abspath(path)
 
1669
        try:
 
1670
            stat_value = os.lstat(abspath)
 
1671
        except OSError, e:
 
1672
            if getattr(e, 'errno', None) == errno.ENOENT:
 
1673
                stat_value = None
 
1674
                kind = None
 
1675
                executable = False
 
1676
            else:
 
1677
                raise
 
1678
        else:
 
1679
            mode = stat_value.st_mode
 
1680
            kind = osutils.file_kind_from_stat_mode(mode)
 
1681
            if not supports_executable():
 
1682
                executable = entry is not None and entry.executable
 
1683
            else:
 
1684
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
1685
        return kind, executable, stat_value
 
1686
 
 
1687
    def _file_size(self, entry, stat_value):
 
1688
        return stat_value.st_size
 
1689
 
1372
1690
    def last_revision(self):
1373
 
        """Return the last revision id of this working tree.
1374
 
 
1375
 
        In early branch formats this was the same as the branch last_revision,
1376
 
        but that cannot be relied upon - for working tree operations,
1377
 
        always use tree.last_revision(). This returns the left most parent id,
1378
 
        or None if there are no parents.
1379
 
 
1380
 
        This was deprecated as of 0.11. Please use get_parent_ids instead.
 
1691
        """Return the last revision of the branch for this tree.
 
1692
 
 
1693
        This format tree does not support a separate marker for last-revision
 
1694
        compared to the branch.
 
1695
 
 
1696
        See MutableTree.last_revision
1381
1697
        """
1382
1698
        return self._last_revision()
1383
1699
 
1384
1700
    @needs_read_lock
1385
1701
    def _last_revision(self):
1386
1702
        """helper for get_parent_ids."""
1387
 
        return self.branch.last_revision()
 
1703
        return _mod_revision.ensure_null(self.branch.last_revision())
1388
1704
 
1389
1705
    def is_locked(self):
1390
1706
        return self._control_files.is_locked()
1391
1707
 
 
1708
    def _must_be_locked(self):
 
1709
        if not self.is_locked():
 
1710
            raise errors.ObjectNotLocked(self)
 
1711
 
1392
1712
    def lock_read(self):
1393
1713
        """See Branch.lock_read, and WorkingTree.unlock."""
 
1714
        if not self.is_locked():
 
1715
            self._reset_data()
1394
1716
        self.branch.lock_read()
1395
1717
        try:
1396
1718
            return self._control_files.lock_read()
1399
1721
            raise
1400
1722
 
1401
1723
    def lock_tree_write(self):
1402
 
        """Lock the working tree for write, and the branch for read.
1403
 
 
1404
 
        This is useful for operations which only need to mutate the working
1405
 
        tree. Taking out branch write locks is a relatively expensive process
1406
 
        and may fail if the branch is on read only media. So branch write locks
1407
 
        should only be taken out when we are modifying branch data - such as in
1408
 
        operations like commit, pull, uncommit and update.
1409
 
        """
 
1724
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
 
1725
        if not self.is_locked():
 
1726
            self._reset_data()
1410
1727
        self.branch.lock_read()
1411
1728
        try:
1412
1729
            return self._control_files.lock_write()
1415
1732
            raise
1416
1733
 
1417
1734
    def lock_write(self):
1418
 
        """See Branch.lock_write, and WorkingTree.unlock."""
 
1735
        """See MutableTree.lock_write, and WorkingTree.unlock."""
 
1736
        if not self.is_locked():
 
1737
            self._reset_data()
1419
1738
        self.branch.lock_write()
1420
1739
        try:
1421
1740
            return self._control_files.lock_write()
1429
1748
    def _basis_inventory_name(self):
1430
1749
        return 'basis-inventory-cache'
1431
1750
 
 
1751
    def _reset_data(self):
 
1752
        """Reset transient data that cannot be revalidated."""
 
1753
        self._inventory_is_modified = False
 
1754
        result = self._deserialize(self._transport.get('inventory'))
 
1755
        self._set_inventory(result, dirty=False)
 
1756
 
1432
1757
    @needs_tree_write_lock
1433
1758
    def set_last_revision(self, new_revision):
1434
1759
        """Change the last revision in the working tree."""
1441
1766
        This is used to allow WorkingTree3 instances to not affect branch
1442
1767
        when their last revision is set.
1443
1768
        """
1444
 
        if new_revision is None:
 
1769
        if _mod_revision.is_null(new_revision):
1445
1770
            self.branch.set_revision_history([])
1446
1771
            return False
1447
1772
        try:
1451
1776
            self.branch.set_revision_history([new_revision])
1452
1777
        return True
1453
1778
 
 
1779
    def _write_basis_inventory(self, xml):
 
1780
        """Write the basis inventory XML to the basis-inventory file"""
 
1781
        path = self._basis_inventory_name()
 
1782
        sio = StringIO(xml)
 
1783
        self._transport.put_file(path, sio,
 
1784
            mode=self._control_files._file_mode)
 
1785
 
 
1786
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
 
1787
        """Create the text that will be saved in basis-inventory"""
 
1788
        inventory.revision_id = revision_id
 
1789
        return xml7.serializer_v7.write_inventory_to_string(inventory)
 
1790
 
1454
1791
    def _cache_basis_inventory(self, new_revision):
1455
1792
        """Cache new_revision as the basis inventory."""
1456
1793
        # TODO: this should allow the ready-to-use inventory to be passed in,
1470
1807
            xml = self.branch.repository.get_inventory_xml(new_revision)
1471
1808
            firstline = xml.split('\n', 1)[0]
1472
1809
            if (not 'revision_id="' in firstline or 
1473
 
                'format="6"' not in firstline):
 
1810
                'format="7"' not in firstline):
1474
1811
                inv = self.branch.repository.deserialise_inventory(
1475
1812
                    new_revision, xml)
1476
 
                inv.revision_id = new_revision
1477
 
                xml = bzrlib.xml6.serializer_v6.write_inventory_to_string(inv)
1478
 
            assert isinstance(xml, str), 'serialised xml must be bytestring.'
1479
 
            path = self._basis_inventory_name()
1480
 
            sio = StringIO(xml)
1481
 
            self._control_files.put(path, sio)
 
1813
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
 
1814
            self._write_basis_inventory(xml)
1482
1815
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1483
1816
            pass
1484
1817
 
1485
1818
    def read_basis_inventory(self):
1486
1819
        """Read the cached basis inventory."""
1487
1820
        path = self._basis_inventory_name()
1488
 
        return self._control_files.get(path).read()
 
1821
        return self._transport.get_bytes(path)
1489
1822
        
1490
1823
    @needs_read_lock
1491
1824
    def read_working_inventory(self):
1492
 
        """Read the working inventory."""
 
1825
        """Read the working inventory.
 
1826
        
 
1827
        :raises errors.InventoryModified: read_working_inventory will fail
 
1828
            when the current in memory inventory has been modified.
 
1829
        """
 
1830
        # conceptually this should be an implementation detail of the tree. 
 
1831
        # XXX: Deprecate this.
1493
1832
        # ElementTree does its own conversion from UTF-8, so open in
1494
1833
        # binary.
1495
 
        result = bzrlib.xml5.serializer_v5.read_inventory(
1496
 
            self._control_files.get('inventory'))
1497
 
        self._set_inventory(result)
 
1834
        if self._inventory_is_modified:
 
1835
            raise errors.InventoryModified(self)
 
1836
        result = self._deserialize(self._transport.get('inventory'))
 
1837
        self._set_inventory(result, dirty=False)
1498
1838
        return result
1499
1839
 
1500
1840
    @needs_tree_write_lock
1501
 
    def remove(self, files, verbose=False, to_file=None):
1502
 
        """Remove nominated files from the working inventory..
1503
 
 
1504
 
        This does not remove their text.  This does not run on XXX on what? RBC
1505
 
 
1506
 
        TODO: Refuse to remove modified files unless --force is given?
1507
 
 
1508
 
        TODO: Do something useful with directories.
1509
 
 
1510
 
        TODO: Should this remove the text or not?  Tough call; not
1511
 
        removing may be useful and the user can just use use rm, and
1512
 
        is the opposite of add.  Removing it is consistent with most
1513
 
        other tools.  Maybe an option.
 
1841
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
 
1842
        force=False):
 
1843
        """Remove nominated files from the working inventory.
 
1844
 
 
1845
        :files: File paths relative to the basedir.
 
1846
        :keep_files: If true, the files will also be kept.
 
1847
        :force: Delete files and directories, even if they are changed and
 
1848
            even if the directories are not empty.
1514
1849
        """
1515
 
        ## TODO: Normalize names
1516
 
        ## TODO: Remove nested loops; better scalability
1517
1850
        if isinstance(files, basestring):
1518
1851
            files = [files]
1519
1852
 
1520
 
        inv = self.inventory
1521
 
 
1522
 
        # do this before any modifications
 
1853
        inv_delta = []
 
1854
 
 
1855
        new_files=set()
 
1856
        unknown_nested_files=set()
 
1857
 
 
1858
        def recurse_directory_to_add_files(directory):
 
1859
            # Recurse directory and add all files
 
1860
            # so we can check if they have changed.
 
1861
            for parent_info, file_infos in\
 
1862
                self.walkdirs(directory):
 
1863
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
 
1864
                    # Is it versioned or ignored?
 
1865
                    if self.path2id(relpath) or self.is_ignored(relpath):
 
1866
                        # Add nested content for deletion.
 
1867
                        new_files.add(relpath)
 
1868
                    else:
 
1869
                        # Files which are not versioned and not ignored
 
1870
                        # should be treated as unknown.
 
1871
                        unknown_nested_files.add((relpath, None, kind))
 
1872
 
 
1873
        for filename in files:
 
1874
            # Get file name into canonical form.
 
1875
            abspath = self.abspath(filename)
 
1876
            filename = self.relpath(abspath)
 
1877
            if len(filename) > 0:
 
1878
                new_files.add(filename)
 
1879
                recurse_directory_to_add_files(filename)
 
1880
 
 
1881
        files = list(new_files)
 
1882
 
 
1883
        if len(files) == 0:
 
1884
            return # nothing to do
 
1885
 
 
1886
        # Sort needed to first handle directory content before the directory
 
1887
        files.sort(reverse=True)
 
1888
 
 
1889
        # Bail out if we are going to delete files we shouldn't
 
1890
        if not keep_files and not force:
 
1891
            has_changed_files = len(unknown_nested_files) > 0
 
1892
            if not has_changed_files:
 
1893
                for (file_id, path, content_change, versioned, parent_id, name,
 
1894
                     kind, executable) in self.iter_changes(self.basis_tree(),
 
1895
                         include_unchanged=True, require_versioned=False,
 
1896
                         want_unversioned=True, specific_files=files):
 
1897
                    if versioned == (False, False):
 
1898
                        # The record is unknown ...
 
1899
                        if not self.is_ignored(path[1]):
 
1900
                            # ... but not ignored
 
1901
                            has_changed_files = True
 
1902
                            break
 
1903
                    elif content_change and (kind[1] is not None):
 
1904
                        # Versioned and changed, but not deleted
 
1905
                        has_changed_files = True
 
1906
                        break
 
1907
 
 
1908
            if has_changed_files:
 
1909
                # Make delta show ALL applicable changes in error message.
 
1910
                tree_delta = self.changes_from(self.basis_tree(),
 
1911
                    require_versioned=False, want_unversioned=True,
 
1912
                    specific_files=files)
 
1913
                for unknown_file in unknown_nested_files:
 
1914
                    if unknown_file not in tree_delta.unversioned:
 
1915
                        tree_delta.unversioned.extend((unknown_file,))
 
1916
                raise errors.BzrRemoveChangedFilesError(tree_delta)
 
1917
 
 
1918
        # Build inv_delta and delete files where applicaple,
 
1919
        # do this before any modifications to inventory.
1523
1920
        for f in files:
1524
 
            fid = inv.path2id(f)
 
1921
            fid = self.path2id(f)
 
1922
            message = None
1525
1923
            if not fid:
1526
 
                # TODO: Perhaps make this just a warning, and continue?
1527
 
                # This tends to happen when 
1528
 
                raise NotVersionedError(path=f)
1529
 
            if verbose:
1530
 
                # having remove it, it must be either ignored or unknown
1531
 
                if self.is_ignored(f):
1532
 
                    new_status = 'I'
1533
 
                else:
1534
 
                    new_status = '?'
1535
 
                show_status(new_status, inv[fid].kind, f, to_file=to_file)
1536
 
            del inv[fid]
1537
 
 
1538
 
        self._write_inventory(inv)
 
1924
                message = "%s is not versioned." % (f,)
 
1925
            else:
 
1926
                if verbose:
 
1927
                    # having removed it, it must be either ignored or unknown
 
1928
                    if self.is_ignored(f):
 
1929
                        new_status = 'I'
 
1930
                    else:
 
1931
                        new_status = '?'
 
1932
                    textui.show_status(new_status, self.kind(fid), f,
 
1933
                                       to_file=to_file)
 
1934
                # Unversion file
 
1935
                inv_delta.append((f, None, fid, None))
 
1936
                message = "removed %s" % (f,)
 
1937
 
 
1938
            if not keep_files:
 
1939
                abs_path = self.abspath(f)
 
1940
                if osutils.lexists(abs_path):
 
1941
                    if (osutils.isdir(abs_path) and
 
1942
                        len(os.listdir(abs_path)) > 0):
 
1943
                        if force:
 
1944
                            osutils.rmtree(abs_path)
 
1945
                        else:
 
1946
                            message = "%s is not an empty directory "\
 
1947
                                "and won't be deleted." % (f,)
 
1948
                    else:
 
1949
                        osutils.delete_any(abs_path)
 
1950
                        message = "deleted %s" % (f,)
 
1951
                elif message is not None:
 
1952
                    # Only care if we haven't done anything yet.
 
1953
                    message = "%s does not exist." % (f,)
 
1954
 
 
1955
            # Print only one message (if any) per file.
 
1956
            if message is not None:
 
1957
                note(message)
 
1958
        self.apply_inventory_delta(inv_delta)
1539
1959
 
1540
1960
    @needs_tree_write_lock
1541
 
    def revert(self, filenames, old_tree=None, backups=True, 
1542
 
               pb=DummyProgress()):
1543
 
        from transform import revert
1544
 
        from conflicts import resolve
 
1961
    def revert(self, filenames=None, old_tree=None, backups=True,
 
1962
               pb=DummyProgress(), report_changes=False):
 
1963
        from bzrlib.conflicts import resolve
 
1964
        if filenames == []:
 
1965
            filenames = None
 
1966
            symbol_versioning.warn('Using [] to revert all files is deprecated'
 
1967
                ' as of bzr 0.91.  Please use None (the default) instead.',
 
1968
                DeprecationWarning, stacklevel=2)
1545
1969
        if old_tree is None:
1546
 
            old_tree = self.basis_tree()
1547
 
        conflicts = revert(self, old_tree, filenames, backups, pb)
1548
 
        if not len(filenames):
1549
 
            self.set_parent_ids(self.get_parent_ids()[:1])
1550
 
            resolve(self)
 
1970
            basis_tree = self.basis_tree()
 
1971
            basis_tree.lock_read()
 
1972
            old_tree = basis_tree
1551
1973
        else:
1552
 
            resolve(self, filenames, ignore_misses=True)
 
1974
            basis_tree = None
 
1975
        try:
 
1976
            conflicts = transform.revert(self, old_tree, filenames, backups, pb,
 
1977
                                         report_changes)
 
1978
            if filenames is None and len(self.get_parent_ids()) > 1:
 
1979
                parent_trees = []
 
1980
                last_revision = self.last_revision()
 
1981
                if last_revision != NULL_REVISION:
 
1982
                    if basis_tree is None:
 
1983
                        basis_tree = self.basis_tree()
 
1984
                        basis_tree.lock_read()
 
1985
                    parent_trees.append((last_revision, basis_tree))
 
1986
                self.set_parent_trees(parent_trees)
 
1987
                resolve(self)
 
1988
            else:
 
1989
                resolve(self, filenames, ignore_misses=True, recursive=True)
 
1990
        finally:
 
1991
            if basis_tree is not None:
 
1992
                basis_tree.unlock()
1553
1993
        return conflicts
1554
1994
 
 
1995
    def revision_tree(self, revision_id):
 
1996
        """See Tree.revision_tree.
 
1997
 
 
1998
        WorkingTree can supply revision_trees for the basis revision only
 
1999
        because there is only one cached inventory in the bzr directory.
 
2000
        """
 
2001
        if revision_id == self.last_revision():
 
2002
            try:
 
2003
                xml = self.read_basis_inventory()
 
2004
            except errors.NoSuchFile:
 
2005
                pass
 
2006
            else:
 
2007
                try:
 
2008
                    inv = xml7.serializer_v7.read_inventory_from_string(xml)
 
2009
                    # dont use the repository revision_tree api because we want
 
2010
                    # to supply the inventory.
 
2011
                    if inv.revision_id == revision_id:
 
2012
                        return revisiontree.RevisionTree(self.branch.repository,
 
2013
                            inv, revision_id)
 
2014
                except errors.BadInventoryFormat:
 
2015
                    pass
 
2016
        # raise if there was no inventory, or if we read the wrong inventory.
 
2017
        raise errors.NoSuchRevisionInTree(self, revision_id)
 
2018
 
1555
2019
    # XXX: This method should be deprecated in favour of taking in a proper
1556
2020
    # new Inventory object.
1557
2021
    @needs_tree_write_lock
1574
2038
            elif kind == 'symlink':
1575
2039
                inv.add(InventoryLink(file_id, name, parent))
1576
2040
            else:
1577
 
                raise BzrError("unknown kind %r" % kind)
 
2041
                raise errors.BzrError("unknown kind %r" % kind)
1578
2042
        self._write_inventory(inv)
1579
2043
 
1580
2044
    @needs_tree_write_lock
1581
2045
    def set_root_id(self, file_id):
1582
2046
        """Set the root id for this tree."""
1583
 
        inv = self.read_working_inventory()
 
2047
        # for compatability 
 
2048
        if file_id is None:
 
2049
            raise ValueError(
 
2050
                'WorkingTree.set_root_id with fileid=None')
 
2051
        file_id = osutils.safe_file_id(file_id)
 
2052
        self._set_root_id(file_id)
 
2053
 
 
2054
    def _set_root_id(self, file_id):
 
2055
        """Set the root id for this tree, in a format specific manner.
 
2056
 
 
2057
        :param file_id: The file id to assign to the root. It must not be 
 
2058
            present in the current inventory or an error will occur. It must
 
2059
            not be None, but rather a valid file id.
 
2060
        """
 
2061
        inv = self._inventory
1584
2062
        orig_root_id = inv.root.file_id
 
2063
        # TODO: it might be nice to exit early if there was nothing
 
2064
        # to do, saving us from trigger a sync on unlock.
 
2065
        self._inventory_is_modified = True
 
2066
        # we preserve the root inventory entry object, but
 
2067
        # unlinkit from the byid index
1585
2068
        del inv._byid[inv.root.file_id]
1586
2069
        inv.root.file_id = file_id
 
2070
        # and link it into the index with the new changed id.
1587
2071
        inv._byid[inv.root.file_id] = inv.root
 
2072
        # and finally update all children to reference the new id.
 
2073
        # XXX: this should be safe to just look at the root.children
 
2074
        # list, not the WHOLE INVENTORY.
1588
2075
        for fid in inv:
1589
2076
            entry = inv[fid]
1590
2077
            if entry.parent_id == orig_root_id:
1591
2078
                entry.parent_id = inv.root.file_id
1592
 
        self._write_inventory(inv)
1593
2079
 
1594
2080
    def unlock(self):
1595
2081
        """See Branch.unlock.
1604
2090
 
1605
2091
    _marker = object()
1606
2092
 
1607
 
    @needs_write_lock
1608
 
    def update(self, revision=None, old_tip=_marker):
 
2093
    def update(self, change_reporter=None, possible_transports=None,
 
2094
               revision=None, old_tip=_marker):
1609
2095
        """Update a working tree along its branch.
1610
2096
 
1611
2097
        This will update the branch if its bound too, which means we have
1612
2098
        multiple trees involved:
1613
 
        The new basis tree of the master.
1614
 
        The old basis tree of the branch.
1615
 
        The old basis tree of the working tree.
1616
 
        The current working tree state.
1617
 
        pathologically all three may be different, and non ancestors of each other.
1618
 
        Conceptually we want to:
1619
 
        Preserve the wt.basis->wt.state changes
1620
 
        Transform the wt.basis to the new master basis.
1621
 
        Apply a merge of the old branch basis to get any 'local' changes from
1622
 
        it into the tree.
1623
 
        Restore the wt.basis->wt.state changes.
 
2099
 
 
2100
        - The new basis tree of the master.
 
2101
        - The old basis tree of the branch.
 
2102
        - The old basis tree of the working tree.
 
2103
        - The current working tree state.
 
2104
 
 
2105
        Pathologically, all three may be different, and non-ancestors of each
 
2106
        other.  Conceptually we want to:
 
2107
 
 
2108
        - Preserve the wt.basis->wt.state changes
 
2109
        - Transform the wt.basis to the new master basis.
 
2110
        - Apply a merge of the old branch basis to get any 'local' changes from
 
2111
          it into the tree.
 
2112
        - Restore the wt.basis->wt.state changes.
1624
2113
 
1625
2114
        There isn't a single operation at the moment to do that, so we:
1626
 
        Merge current state -> basis tree of the master w.r.t. the old tree 
1627
 
        basis. Do a 'normal' merge of the old branch basis if it is relevant.
 
2115
        - Merge current state -> basis tree of the master w.r.t. the old tree
 
2116
          basis.
 
2117
        - Do a 'normal' merge of the old branch basis if it is relevant.
1628
2118
 
1629
2119
        :param revision: The target revision to update to. Must be in the
1630
2120
            revision history.
1632
2122
            returned (old tip of the branch or None). _marker is used
1633
2123
            otherwise.
1634
2124
        """
1635
 
        if old_tip == self._marker:
1636
 
            old_tip = self.branch.update()
 
2125
        if self.branch.get_bound_location() is not None:
 
2126
            self.lock_write()
 
2127
            update_branch = (old_tip == self._marker)
 
2128
        else:
 
2129
            self.lock_tree_write()
 
2130
            update_branch = False
 
2131
        try:
 
2132
            if update_branch:
 
2133
                old_tip = self.branch.update(possible_transports)
 
2134
            else:
 
2135
                old_tip = None
 
2136
            return self._update_tree(old_tip, change_reporter, revision)
 
2137
        finally:
 
2138
            self.unlock()
 
2139
 
 
2140
    @needs_tree_write_lock
 
2141
    def _update_tree(self, old_tip=None, change_reporter=None, revision=None):
 
2142
        """Update a tree to the master branch.
 
2143
 
 
2144
        :param old_tip: if supplied, the previous tip revision the branch,
 
2145
            before it was changed to the master branch's tip.
 
2146
        """
1637
2147
        # here if old_tip is not None, it is the old tip of the branch before
1638
2148
        # it was updated from the master branch. This should become a pending
1639
2149
        # merge in the working tree to preserve the user existing work.  we
1648
2158
        try:
1649
2159
            last_rev = self.get_parent_ids()[0]
1650
2160
        except IndexError:
1651
 
            last_rev = None
 
2161
            last_rev = _mod_revision.NULL_REVISION
1652
2162
        if revision is None:
1653
2163
            revision = self.branch.last_revision()
1654
2164
        else:
1655
2165
            if revision not in self.branch.revision_history():
1656
2166
                raise errors.NoSuchRevision(self.branch, revision)
1657
 
        if last_rev != revision:
1658
 
            # merge tree state up to new branch tip.
 
2167
        if last_rev != _mod_revision.ensure_null(revision):
 
2168
            # merge tree state up to specified revision.
1659
2169
            basis = self.basis_tree()
1660
 
            to_tree = self.branch.repository.revision_tree(revision)
1661
 
            result += merge_inner(self.branch,
1662
 
                                  to_tree,
1663
 
                                  basis,
1664
 
                                  this_tree=self)
1665
 
            self.set_last_revision(revision)
 
2170
            basis.lock_read()
 
2171
            try:
 
2172
                to_tree = self.branch.repository.revision_tree(revision)
 
2173
                if basis.inventory.root is None:
 
2174
                    self.set_root_id(to_tree.get_root_id())
 
2175
                    self.flush()
 
2176
                result += merge.merge_inner(
 
2177
                                      self.branch,
 
2178
                                      to_tree,
 
2179
                                      basis,
 
2180
                                      this_tree=self,
 
2181
                                      change_reporter=change_reporter)
 
2182
                self.set_last_revision(revision)
 
2183
            finally:
 
2184
                basis.unlock()
1666
2185
            # TODO - dedup parents list with things merged by pull ?
1667
2186
            # reuse the tree we've updated to to set the basis:
1668
2187
            parent_trees = [(revision, to_tree)]
1675
2194
            for parent in merges:
1676
2195
                parent_trees.append(
1677
2196
                    (parent, self.branch.repository.revision_tree(parent)))
1678
 
            if old_tip is not None:
 
2197
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
1679
2198
                parent_trees.append(
1680
2199
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
1681
2200
            self.set_parent_trees(parent_trees)
1684
2203
            # the working tree had the same last-revision as the master
1685
2204
            # branch did. We may still have pivot local work from the local
1686
2205
            # branch into old_tip:
1687
 
            if old_tip is not None:
 
2206
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
1688
2207
                self.add_parent_tree_id(old_tip)
1689
 
        if old_tip and old_tip != last_rev:
 
2208
        if (old_tip is not None and not _mod_revision.is_null(old_tip)
 
2209
            and old_tip != last_rev):
1690
2210
            # our last revision was not the prior branch last revision
1691
2211
            # and we have converted that last revision to a pending merge.
1692
2212
            # base is somewhere between the branch tip now
1693
2213
            # and the now pending merge
1694
 
            from bzrlib.revision import common_ancestor
1695
 
            try:
1696
 
                base_rev_id = common_ancestor(revision,
1697
 
                                              old_tip,
1698
 
                                              self.branch.repository)
1699
 
            except errors.NoCommonAncestor:
1700
 
                base_rev_id = None
 
2214
 
 
2215
            # Since we just modified the working tree and inventory, flush out
 
2216
            # the current state, before we modify it again.
 
2217
            # TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
 
2218
            #       requires it only because TreeTransform directly munges the
 
2219
            #       inventory and calls tree._write_inventory(). Ultimately we
 
2220
            #       should be able to remove this extra flush.
 
2221
            self.flush()
 
2222
            graph = self.branch.repository.get_graph()
 
2223
            base_rev_id = graph.find_unique_lca(revision, old_tip)
1701
2224
            base_tree = self.branch.repository.revision_tree(base_rev_id)
1702
2225
            other_tree = self.branch.repository.revision_tree(old_tip)
1703
 
            result += merge_inner(self.branch,
 
2226
            result += merge.merge_inner(
 
2227
                                  self.branch,
1704
2228
                                  other_tree,
1705
2229
                                  base_tree,
1706
 
                                  this_tree=self)
 
2230
                                  this_tree=self,
 
2231
                                  change_reporter=change_reporter)
1707
2232
        return result
1708
2233
 
 
2234
    def _write_hashcache_if_dirty(self):
 
2235
        """Write out the hashcache if it is dirty."""
 
2236
        if self._hashcache.needs_write:
 
2237
            try:
 
2238
                self._hashcache.write()
 
2239
            except OSError, e:
 
2240
                if e.errno not in (errno.EPERM, errno.EACCES):
 
2241
                    raise
 
2242
                # TODO: jam 20061219 Should this be a warning? A single line
 
2243
                #       warning might be sufficient to let the user know what
 
2244
                #       is going on.
 
2245
                mutter('Could not write hashcache for %s\nError: %s',
 
2246
                       self._hashcache.cache_file_name(), e)
 
2247
 
1709
2248
    @needs_tree_write_lock
1710
2249
    def _write_inventory(self, inv):
1711
2250
        """Write inventory as the current inventory."""
1712
 
        sio = StringIO()
1713
 
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
1714
 
        sio.seek(0)
1715
 
        self._control_files.put('inventory', sio)
1716
 
        self._set_inventory(inv)
1717
 
        mutter('wrote working inventory')
 
2251
        self._set_inventory(inv, dirty=True)
 
2252
        self.flush()
1718
2253
 
1719
2254
    def set_conflicts(self, arg):
1720
 
        raise UnsupportedOperation(self.set_conflicts, self)
 
2255
        raise errors.UnsupportedOperation(self.set_conflicts, self)
1721
2256
 
1722
2257
    def add_conflicts(self, arg):
1723
 
        raise UnsupportedOperation(self.add_conflicts, self)
 
2258
        raise errors.UnsupportedOperation(self.add_conflicts, self)
1724
2259
 
1725
2260
    @needs_read_lock
1726
2261
    def conflicts(self):
1727
 
        conflicts = ConflictList()
 
2262
        conflicts = _mod_conflicts.ConflictList()
1728
2263
        for conflicted in self._iter_conflicts():
1729
2264
            text = True
1730
2265
            try:
1743
2278
                    if text == False:
1744
2279
                        break
1745
2280
            ctype = {True: 'text conflict', False: 'contents conflict'}[text]
1746
 
            conflicts.append(Conflict.factory(ctype, path=conflicted,
 
2281
            conflicts.append(_mod_conflicts.Conflict.factory(ctype,
 
2282
                             path=conflicted,
1747
2283
                             file_id=self.path2id(conflicted)))
1748
2284
        return conflicts
1749
2285
 
 
2286
    def walkdirs(self, prefix=""):
 
2287
        """Walk the directories of this tree.
 
2288
 
 
2289
        returns a generator which yields items in the form:
 
2290
                ((curren_directory_path, fileid),
 
2291
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
 
2292
                   file1_kind), ... ])
 
2293
 
 
2294
        This API returns a generator, which is only valid during the current
 
2295
        tree transaction - within a single lock_read or lock_write duration.
 
2296
 
 
2297
        If the tree is not locked, it may cause an error to be raised,
 
2298
        depending on the tree implementation.
 
2299
        """
 
2300
        disk_top = self.abspath(prefix)
 
2301
        if disk_top.endswith('/'):
 
2302
            disk_top = disk_top[:-1]
 
2303
        top_strip_len = len(disk_top) + 1
 
2304
        inventory_iterator = self._walkdirs(prefix)
 
2305
        disk_iterator = osutils.walkdirs(disk_top, prefix)
 
2306
        try:
 
2307
            current_disk = disk_iterator.next()
 
2308
            disk_finished = False
 
2309
        except OSError, e:
 
2310
            if not (e.errno == errno.ENOENT or
 
2311
                (sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
 
2312
                raise
 
2313
            current_disk = None
 
2314
            disk_finished = True
 
2315
        try:
 
2316
            current_inv = inventory_iterator.next()
 
2317
            inv_finished = False
 
2318
        except StopIteration:
 
2319
            current_inv = None
 
2320
            inv_finished = True
 
2321
        while not inv_finished or not disk_finished:
 
2322
            if current_disk:
 
2323
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
 
2324
                    cur_disk_dir_content) = current_disk
 
2325
            else:
 
2326
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
 
2327
                    cur_disk_dir_content) = ((None, None), None)
 
2328
            if not disk_finished:
 
2329
                # strip out .bzr dirs
 
2330
                if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
 
2331
                    len(cur_disk_dir_content) > 0):
 
2332
                    # osutils.walkdirs can be made nicer -
 
2333
                    # yield the path-from-prefix rather than the pathjoined
 
2334
                    # value.
 
2335
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
 
2336
                        ('.bzr', '.bzr'))
 
2337
                    if cur_disk_dir_content[bzrdir_loc][0] == '.bzr':
 
2338
                        # we dont yield the contents of, or, .bzr itself.
 
2339
                        del cur_disk_dir_content[bzrdir_loc]
 
2340
            if inv_finished:
 
2341
                # everything is unknown
 
2342
                direction = 1
 
2343
            elif disk_finished:
 
2344
                # everything is missing
 
2345
                direction = -1
 
2346
            else:
 
2347
                direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
 
2348
            if direction > 0:
 
2349
                # disk is before inventory - unknown
 
2350
                dirblock = [(relpath, basename, kind, stat, None, None) for
 
2351
                    relpath, basename, kind, stat, top_path in
 
2352
                    cur_disk_dir_content]
 
2353
                yield (cur_disk_dir_relpath, None), dirblock
 
2354
                try:
 
2355
                    current_disk = disk_iterator.next()
 
2356
                except StopIteration:
 
2357
                    disk_finished = True
 
2358
            elif direction < 0:
 
2359
                # inventory is before disk - missing.
 
2360
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
 
2361
                    for relpath, basename, dkind, stat, fileid, kind in
 
2362
                    current_inv[1]]
 
2363
                yield (current_inv[0][0], current_inv[0][1]), dirblock
 
2364
                try:
 
2365
                    current_inv = inventory_iterator.next()
 
2366
                except StopIteration:
 
2367
                    inv_finished = True
 
2368
            else:
 
2369
                # versioned present directory
 
2370
                # merge the inventory and disk data together
 
2371
                dirblock = []
 
2372
                for relpath, subiterator in itertools.groupby(sorted(
 
2373
                    current_inv[1] + cur_disk_dir_content,
 
2374
                    key=operator.itemgetter(0)), operator.itemgetter(1)):
 
2375
                    path_elements = list(subiterator)
 
2376
                    if len(path_elements) == 2:
 
2377
                        inv_row, disk_row = path_elements
 
2378
                        # versioned, present file
 
2379
                        dirblock.append((inv_row[0],
 
2380
                            inv_row[1], disk_row[2],
 
2381
                            disk_row[3], inv_row[4],
 
2382
                            inv_row[5]))
 
2383
                    elif len(path_elements[0]) == 5:
 
2384
                        # unknown disk file
 
2385
                        dirblock.append((path_elements[0][0],
 
2386
                            path_elements[0][1], path_elements[0][2],
 
2387
                            path_elements[0][3], None, None))
 
2388
                    elif len(path_elements[0]) == 6:
 
2389
                        # versioned, absent file.
 
2390
                        dirblock.append((path_elements[0][0],
 
2391
                            path_elements[0][1], 'unknown', None,
 
2392
                            path_elements[0][4], path_elements[0][5]))
 
2393
                    else:
 
2394
                        raise NotImplementedError('unreachable code')
 
2395
                yield current_inv[0], dirblock
 
2396
                try:
 
2397
                    current_inv = inventory_iterator.next()
 
2398
                except StopIteration:
 
2399
                    inv_finished = True
 
2400
                try:
 
2401
                    current_disk = disk_iterator.next()
 
2402
                except StopIteration:
 
2403
                    disk_finished = True
 
2404
 
 
2405
    def _walkdirs(self, prefix=""):
 
2406
        """Walk the directories of this tree.
 
2407
 
 
2408
           :prefix: is used as the directrory to start with.
 
2409
           returns a generator which yields items in the form:
 
2410
                ((curren_directory_path, fileid),
 
2411
                 [(file1_path, file1_name, file1_kind, None, file1_id,
 
2412
                   file1_kind), ... ])
 
2413
        """
 
2414
        _directory = 'directory'
 
2415
        # get the root in the inventory
 
2416
        inv = self.inventory
 
2417
        top_id = inv.path2id(prefix)
 
2418
        if top_id is None:
 
2419
            pending = []
 
2420
        else:
 
2421
            pending = [(prefix, '', _directory, None, top_id, None)]
 
2422
        while pending:
 
2423
            dirblock = []
 
2424
            currentdir = pending.pop()
 
2425
            # 0 - relpath, 1- basename, 2- kind, 3- stat, 4-id, 5-kind
 
2426
            top_id = currentdir[4]
 
2427
            if currentdir[0]:
 
2428
                relroot = currentdir[0] + '/'
 
2429
            else:
 
2430
                relroot = ""
 
2431
            # FIXME: stash the node in pending
 
2432
            entry = inv[top_id]
 
2433
            if entry.kind == 'directory':
 
2434
                for name, child in entry.sorted_children():
 
2435
                    dirblock.append((relroot + name, name, child.kind, None,
 
2436
                        child.file_id, child.kind
 
2437
                        ))
 
2438
            yield (currentdir[0], entry.file_id), dirblock
 
2439
            # push the user specified dirs from dirblock
 
2440
            for dir in reversed(dirblock):
 
2441
                if dir[2] == _directory:
 
2442
                    pending.append(dir)
 
2443
 
 
2444
    @needs_tree_write_lock
 
2445
    def auto_resolve(self):
 
2446
        """Automatically resolve text conflicts according to contents.
 
2447
 
 
2448
        Only text conflicts are auto_resolvable. Files with no conflict markers
 
2449
        are considered 'resolved', because bzr always puts conflict markers
 
2450
        into files that have text conflicts.  The corresponding .THIS .BASE and
 
2451
        .OTHER files are deleted, as per 'resolve'.
 
2452
        :return: a tuple of ConflictLists: (un_resolved, resolved).
 
2453
        """
 
2454
        un_resolved = _mod_conflicts.ConflictList()
 
2455
        resolved = _mod_conflicts.ConflictList()
 
2456
        conflict_re = re.compile('^(<{7}|={7}|>{7})')
 
2457
        for conflict in self.conflicts():
 
2458
            if (conflict.typestring != 'text conflict' or
 
2459
                self.kind(conflict.file_id) != 'file'):
 
2460
                un_resolved.append(conflict)
 
2461
                continue
 
2462
            my_file = open(self.id2abspath(conflict.file_id), 'rb')
 
2463
            try:
 
2464
                for line in my_file:
 
2465
                    if conflict_re.search(line):
 
2466
                        un_resolved.append(conflict)
 
2467
                        break
 
2468
                else:
 
2469
                    resolved.append(conflict)
 
2470
            finally:
 
2471
                my_file.close()
 
2472
        resolved.remove_files(self)
 
2473
        self.set_conflicts(un_resolved)
 
2474
        return un_resolved, resolved
 
2475
 
 
2476
    @needs_read_lock
 
2477
    def _check(self):
 
2478
        tree_basis = self.basis_tree()
 
2479
        tree_basis.lock_read()
 
2480
        try:
 
2481
            repo_basis = self.branch.repository.revision_tree(
 
2482
                self.last_revision())
 
2483
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
 
2484
                raise errors.BzrCheckError(
 
2485
                    "Mismatched basis inventory content.")
 
2486
            self._validate()
 
2487
        finally:
 
2488
            tree_basis.unlock()
 
2489
 
 
2490
    def _validate(self):
 
2491
        """Validate internal structures.
 
2492
 
 
2493
        This is meant mostly for the test suite. To give it a chance to detect
 
2494
        corruption after actions have occurred. The default implementation is a
 
2495
        just a no-op.
 
2496
 
 
2497
        :return: None. An exception should be raised if there is an error.
 
2498
        """
 
2499
        return
 
2500
 
 
2501
    @needs_read_lock
 
2502
    def _get_rules_searcher(self, default_searcher):
 
2503
        """See Tree._get_rules_searcher."""
 
2504
        if self._rules_searcher is None:
 
2505
            self._rules_searcher = super(WorkingTree,
 
2506
                self)._get_rules_searcher(default_searcher)
 
2507
        return self._rules_searcher
 
2508
 
1750
2509
 
1751
2510
class WorkingTree2(WorkingTree):
1752
2511
    """This is the Format 2 working tree.
1756
2515
     - uses the branch last-revision.
1757
2516
    """
1758
2517
 
 
2518
    def __init__(self, *args, **kwargs):
 
2519
        super(WorkingTree2, self).__init__(*args, **kwargs)
 
2520
        # WorkingTree2 has more of a constraint that self._inventory must
 
2521
        # exist. Because this is an older format, we don't mind the overhead
 
2522
        # caused by the extra computation here.
 
2523
 
 
2524
        # Newer WorkingTree's should only have self._inventory set when they
 
2525
        # have a read lock.
 
2526
        if self._inventory is None:
 
2527
            self.read_working_inventory()
 
2528
 
1759
2529
    def lock_tree_write(self):
1760
2530
        """See WorkingTree.lock_tree_write().
1761
2531
 
1770
2540
            raise
1771
2541
 
1772
2542
    def unlock(self):
 
2543
        # do non-implementation specific cleanup
 
2544
        self._cleanup()
 
2545
 
1773
2546
        # we share control files:
1774
 
        if self._hashcache.needs_write and self._control_files._lock_count==3:
1775
 
            self._hashcache.write()
 
2547
        if self._control_files._lock_count == 3:
 
2548
            # _inventory_is_modified is always False during a read lock.
 
2549
            if self._inventory_is_modified:
 
2550
                self.flush()
 
2551
            self._write_hashcache_if_dirty()
 
2552
                    
1776
2553
        # reverse order of locking.
1777
2554
        try:
1778
2555
            return self._control_files.unlock()
1792
2569
 
1793
2570
    @needs_read_lock
1794
2571
    def _last_revision(self):
1795
 
        """See WorkingTree._last_revision."""
 
2572
        """See Mutable.last_revision."""
1796
2573
        try:
1797
 
            return self._control_files.get_utf8('last-revision').read()
1798
 
        except NoSuchFile:
1799
 
            return None
 
2574
            return self._transport.get_bytes('last-revision')
 
2575
        except errors.NoSuchFile:
 
2576
            return _mod_revision.NULL_REVISION
1800
2577
 
1801
2578
    def _change_last_revision(self, revision_id):
1802
2579
        """See WorkingTree._change_last_revision."""
1803
2580
        if revision_id is None or revision_id == NULL_REVISION:
1804
2581
            try:
1805
 
                self._control_files._transport.delete('last-revision')
 
2582
                self._transport.delete('last-revision')
1806
2583
            except errors.NoSuchFile:
1807
2584
                pass
1808
2585
            return False
1809
2586
        else:
1810
 
            self._control_files.put_utf8('last-revision', revision_id)
 
2587
            self._transport.put_bytes('last-revision', revision_id,
 
2588
                mode=self._control_files._file_mode)
1811
2589
            return True
1812
2590
 
1813
2591
    @needs_tree_write_lock
1819
2597
    def add_conflicts(self, new_conflicts):
1820
2598
        conflict_set = set(self.conflicts())
1821
2599
        conflict_set.update(set(list(new_conflicts)))
1822
 
        self.set_conflicts(ConflictList(sorted(conflict_set,
1823
 
                                               key=Conflict.sort_key)))
 
2600
        self.set_conflicts(_mod_conflicts.ConflictList(sorted(conflict_set,
 
2601
                                       key=_mod_conflicts.Conflict.sort_key)))
1824
2602
 
1825
2603
    @needs_read_lock
1826
2604
    def conflicts(self):
1827
2605
        try:
1828
 
            confile = self._control_files.get('conflicts')
1829
 
        except NoSuchFile:
1830
 
            return ConflictList()
 
2606
            confile = self._transport.get('conflicts')
 
2607
        except errors.NoSuchFile:
 
2608
            return _mod_conflicts.ConflictList()
1831
2609
        try:
1832
2610
            if confile.next() != CONFLICT_HEADER_1 + '\n':
1833
 
                raise ConflictFormatError()
 
2611
                raise errors.ConflictFormatError()
1834
2612
        except StopIteration:
1835
 
            raise ConflictFormatError()
1836
 
        return ConflictList.from_stanzas(RioReader(confile))
 
2613
            raise errors.ConflictFormatError()
 
2614
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
1837
2615
 
1838
2616
    def unlock(self):
1839
 
        if self._hashcache.needs_write and self._control_files._lock_count==1:
1840
 
            self._hashcache.write()
 
2617
        # do non-implementation specific cleanup
 
2618
        self._cleanup()
 
2619
        if self._control_files._lock_count == 1:
 
2620
            # _inventory_is_modified is always False during a read lock.
 
2621
            if self._inventory_is_modified:
 
2622
                self.flush()
 
2623
            self._write_hashcache_if_dirty()
1841
2624
        # reverse order of locking.
1842
2625
        try:
1843
2626
            return self._control_files.unlock()
1846
2629
 
1847
2630
 
1848
2631
def get_conflicted_stem(path):
1849
 
    for suffix in CONFLICT_SUFFIXES:
 
2632
    for suffix in _mod_conflicts.CONFLICT_SUFFIXES:
1850
2633
        if path.endswith(suffix):
1851
2634
            return path[:-len(suffix)]
1852
2635
 
1853
 
@deprecated_function(zero_eight)
1854
 
def is_control_file(filename):
1855
 
    """See WorkingTree.is_control_filename(filename)."""
1856
 
    ## FIXME: better check
1857
 
    filename = normpath(filename)
1858
 
    while filename != '':
1859
 
        head, tail = os.path.split(filename)
1860
 
        ## mutter('check %r for control file' % ((head, tail),))
1861
 
        if tail == '.bzr':
1862
 
            return True
1863
 
        if filename == head:
1864
 
            break
1865
 
        filename = head
1866
 
    return False
1867
 
 
1868
2636
 
1869
2637
class WorkingTreeFormat(object):
1870
2638
    """An encapsulation of the initialization and open routines for a format.
1890
2658
    _formats = {}
1891
2659
    """The known formats."""
1892
2660
 
 
2661
    requires_rich_root = False
 
2662
 
 
2663
    upgrade_recommended = False
 
2664
 
1893
2665
    @classmethod
1894
2666
    def find_format(klass, a_bzrdir):
1895
2667
        """Return the format for the working tree object in a_bzrdir."""
1897
2669
            transport = a_bzrdir.get_workingtree_transport(None)
1898
2670
            format_string = transport.get("format").read()
1899
2671
            return klass._formats[format_string]
1900
 
        except NoSuchFile:
 
2672
        except errors.NoSuchFile:
1901
2673
            raise errors.NoWorkingTree(base=transport.base)
1902
2674
        except KeyError:
1903
 
            raise errors.UnknownFormatError(format=format_string)
 
2675
            raise errors.UnknownFormatError(format=format_string,
 
2676
                                            kind="working tree")
 
2677
 
 
2678
    def __eq__(self, other):
 
2679
        return self.__class__ is other.__class__
 
2680
 
 
2681
    def __ne__(self, other):
 
2682
        return not (self == other)
1904
2683
 
1905
2684
    @classmethod
1906
2685
    def get_default_format(klass):
1934
2713
 
1935
2714
    @classmethod
1936
2715
    def unregister_format(klass, format):
1937
 
        assert klass._formats[format.get_format_string()] is format
1938
2716
        del klass._formats[format.get_format_string()]
1939
2717
 
1940
2718
 
1941
 
 
1942
2719
class WorkingTreeFormat2(WorkingTreeFormat):
1943
2720
    """The second working tree format. 
1944
2721
 
1945
2722
    This format modified the hash cache from the format 1 hash cache.
1946
2723
    """
1947
2724
 
 
2725
    upgrade_recommended = True
 
2726
 
1948
2727
    def get_format_description(self):
1949
2728
        """See WorkingTreeFormat.get_format_description()."""
1950
2729
        return "Working tree format 2"
1951
2730
 
1952
 
    def stub_initialize_remote(self, control_files):
1953
 
        """As a special workaround create critical control files for a remote working tree
 
2731
    def _stub_initialize_remote(self, branch):
 
2732
        """As a special workaround create critical control files for a remote working tree.
1954
2733
        
1955
2734
        This ensures that it can later be updated and dealt with locally,
1956
2735
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
1958
2737
        """
1959
2738
        sio = StringIO()
1960
2739
        inv = Inventory()
1961
 
        bzrlib.xml5.serializer_v5.write_inventory(inv, sio)
 
2740
        xml5.serializer_v5.write_inventory(inv, sio, working=True)
1962
2741
        sio.seek(0)
1963
 
        control_files.put('inventory', sio)
1964
 
 
1965
 
        control_files.put_utf8('pending-merges', '')
 
2742
        branch._transport.put_file('inventory', sio,
 
2743
            mode=branch.control_files._file_mode)
 
2744
        branch._transport.put_bytes('pending-merges', '',
 
2745
            mode=branch.control_files._file_mode)
1966
2746
        
1967
2747
 
1968
 
    def initialize(self, a_bzrdir, revision_id=None):
 
2748
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
2749
                   accelerator_tree=None, hardlink=False):
1969
2750
        """See WorkingTreeFormat.initialize()."""
1970
2751
        if not isinstance(a_bzrdir.transport, LocalTransport):
1971
2752
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1972
 
        branch = a_bzrdir.open_branch()
1973
 
        if revision_id is not None:
1974
 
            branch.lock_write()
1975
 
            try:
1976
 
                revision_history = branch.revision_history()
1977
 
                try:
1978
 
                    position = revision_history.index(revision_id)
1979
 
                except ValueError:
1980
 
                    raise errors.NoSuchRevision(branch, revision_id)
1981
 
                branch.set_revision_history(revision_history[:position + 1])
1982
 
            finally:
1983
 
                branch.unlock()
1984
 
        revision = branch.last_revision()
 
2753
        if from_branch is not None:
 
2754
            branch = from_branch
 
2755
        else:
 
2756
            branch = a_bzrdir.open_branch()
 
2757
        if revision_id is None:
 
2758
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2759
        branch.lock_write()
 
2760
        try:
 
2761
            branch.generate_revision_history(revision_id)
 
2762
        finally:
 
2763
            branch.unlock()
1985
2764
        inv = Inventory()
1986
2765
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1987
2766
                         branch,
1989
2768
                         _internal=True,
1990
2769
                         _format=self,
1991
2770
                         _bzrdir=a_bzrdir)
1992
 
        wt._write_inventory(inv)
1993
 
        wt.set_root_id(inv.root.file_id)
1994
 
        basis_tree = branch.repository.revision_tree(revision)
1995
 
        wt.set_parent_trees([(revision, basis_tree)])
1996
 
        build_tree(basis_tree, wt)
 
2771
        basis_tree = branch.repository.revision_tree(revision_id)
 
2772
        if basis_tree.inventory.root is not None:
 
2773
            wt.set_root_id(basis_tree.get_root_id())
 
2774
        # set the parent list and cache the basis tree.
 
2775
        if _mod_revision.is_null(revision_id):
 
2776
            parent_trees = []
 
2777
        else:
 
2778
            parent_trees = [(revision_id, basis_tree)]
 
2779
        wt.set_parent_trees(parent_trees)
 
2780
        transform.build_tree(basis_tree, wt)
1997
2781
        return wt
1998
2782
 
1999
2783
    def __init__(self):
2011
2795
            raise NotImplementedError
2012
2796
        if not isinstance(a_bzrdir.transport, LocalTransport):
2013
2797
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2014
 
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2798
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2015
2799
                           _internal=True,
2016
2800
                           _format=self,
2017
2801
                           _bzrdir=a_bzrdir)
2018
 
 
 
2802
        return wt
2019
2803
 
2020
2804
class WorkingTreeFormat3(WorkingTreeFormat):
2021
2805
    """The second working tree format updated to record a format marker.
2028
2812
        - is new in bzr 0.8
2029
2813
        - uses a LockDir to guard access for writes.
2030
2814
    """
 
2815
    
 
2816
    upgrade_recommended = True
2031
2817
 
2032
2818
    def get_format_string(self):
2033
2819
        """See WorkingTreeFormat.get_format_string()."""
2040
2826
    _lock_file_name = 'lock'
2041
2827
    _lock_class = LockDir
2042
2828
 
 
2829
    _tree_class = WorkingTree3
 
2830
 
 
2831
    def __get_matchingbzrdir(self):
 
2832
        return bzrdir.BzrDirMetaFormat1()
 
2833
 
 
2834
    _matchingbzrdir = property(__get_matchingbzrdir)
 
2835
 
2043
2836
    def _open_control_files(self, a_bzrdir):
2044
2837
        transport = a_bzrdir.get_workingtree_transport(None)
2045
2838
        return LockableFiles(transport, self._lock_file_name, 
2046
2839
                             self._lock_class)
2047
2840
 
2048
 
    def initialize(self, a_bzrdir, revision_id=None):
 
2841
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
2842
                   accelerator_tree=None, hardlink=False):
2049
2843
        """See WorkingTreeFormat.initialize().
2050
2844
        
2051
 
        revision_id allows creating a working tree at a different
2052
 
        revision than the branch is at.
 
2845
        :param revision_id: if supplied, create a working tree at a different
 
2846
            revision than the branch is at.
 
2847
        :param accelerator_tree: A tree which can be used for retrieving file
 
2848
            contents more quickly than the revision tree, i.e. a workingtree.
 
2849
            The revision tree will be used for cases where accelerator_tree's
 
2850
            content is different.
 
2851
        :param hardlink: If true, hard-link files from accelerator_tree,
 
2852
            where possible.
2053
2853
        """
2054
2854
        if not isinstance(a_bzrdir.transport, LocalTransport):
2055
2855
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2057
2857
        control_files = self._open_control_files(a_bzrdir)
2058
2858
        control_files.create_lock()
2059
2859
        control_files.lock_write()
2060
 
        control_files.put_utf8('format', self.get_format_string())
2061
 
        branch = a_bzrdir.open_branch()
 
2860
        transport.put_bytes('format', self.get_format_string(),
 
2861
            mode=control_files._file_mode)
 
2862
        if from_branch is not None:
 
2863
            branch = from_branch
 
2864
        else:
 
2865
            branch = a_bzrdir.open_branch()
2062
2866
        if revision_id is None:
2063
 
            revision_id = branch.last_revision()
2064
 
        inv = Inventory() 
2065
 
        wt = WorkingTree3(a_bzrdir.root_transport.local_abspath('.'),
 
2867
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2868
        # WorkingTree3 can handle an inventory which has a unique root id.
 
2869
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
 
2870
        # those trees. And because there isn't a format bump inbetween, we
 
2871
        # are maintaining compatibility with older clients.
 
2872
        # inv = Inventory(root_id=gen_root_id())
 
2873
        inv = self._initial_inventory()
 
2874
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
2066
2875
                         branch,
2067
2876
                         inv,
2068
2877
                         _internal=True,
2071
2880
                         _control_files=control_files)
2072
2881
        wt.lock_tree_write()
2073
2882
        try:
2074
 
            wt._write_inventory(inv)
2075
 
            wt.set_root_id(inv.root.file_id)
2076
2883
            basis_tree = branch.repository.revision_tree(revision_id)
2077
 
            if revision_id == bzrlib.revision.NULL_REVISION:
 
2884
            # only set an explicit root id if there is one to set.
 
2885
            if basis_tree.inventory.root is not None:
 
2886
                wt.set_root_id(basis_tree.get_root_id())
 
2887
            if revision_id == NULL_REVISION:
2078
2888
                wt.set_parent_trees([])
2079
2889
            else:
2080
2890
                wt.set_parent_trees([(revision_id, basis_tree)])
2081
 
            build_tree(basis_tree, wt)
 
2891
            transform.build_tree(basis_tree, wt)
2082
2892
        finally:
 
2893
            # Unlock in this order so that the unlock-triggers-flush in
 
2894
            # WorkingTree is given a chance to fire.
 
2895
            control_files.unlock()
2083
2896
            wt.unlock()
2084
 
            control_files.unlock()
2085
2897
        return wt
2086
2898
 
 
2899
    def _initial_inventory(self):
 
2900
        return Inventory()
 
2901
 
2087
2902
    def __init__(self):
2088
2903
        super(WorkingTreeFormat3, self).__init__()
2089
 
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2090
2904
 
2091
2905
    def open(self, a_bzrdir, _found=False):
2092
2906
        """Return the WorkingTree object for a_bzrdir
2099
2913
            raise NotImplementedError
2100
2914
        if not isinstance(a_bzrdir.transport, LocalTransport):
2101
2915
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2102
 
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
2916
        wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
 
2917
        return wt
2103
2918
 
2104
2919
    def _open(self, a_bzrdir, control_files):
2105
2920
        """Open the tree itself.
2107
2922
        :param a_bzrdir: the dir for the tree.
2108
2923
        :param control_files: the control files for the tree.
2109
2924
        """
2110
 
        return WorkingTree3(a_bzrdir.root_transport.local_abspath('.'),
2111
 
                           _internal=True,
2112
 
                           _format=self,
2113
 
                           _bzrdir=a_bzrdir,
2114
 
                           _control_files=control_files)
 
2925
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
2926
                                _internal=True,
 
2927
                                _format=self,
 
2928
                                _bzrdir=a_bzrdir,
 
2929
                                _control_files=control_files)
2115
2930
 
2116
2931
    def __str__(self):
2117
2932
        return self.get_format_string()
2118
2933
 
2119
2934
 
 
2935
__default_format = WorkingTreeFormat4()
 
2936
WorkingTreeFormat.register_format(__default_format)
 
2937
WorkingTreeFormat.register_format(WorkingTreeFormat3())
 
2938
WorkingTreeFormat.set_default_format(__default_format)
2120
2939
# formats which have no format string are not discoverable
2121
2940
# and not independently creatable, so are not registered.
2122
 
__default_format = WorkingTreeFormat3()
2123
 
WorkingTreeFormat.register_format(__default_format)
2124
 
WorkingTreeFormat.set_default_format(__default_format)
2125
2941
_legacy_formats = [WorkingTreeFormat2(),
2126
2942
                   ]
2127
 
 
2128
 
 
2129
 
class WorkingTreeTestProviderAdapter(object):
2130
 
    """A tool to generate a suite testing multiple workingtree formats at once.
2131
 
 
2132
 
    This is done by copying the test once for each transport and injecting
2133
 
    the transport_server, transport_readonly_server, and workingtree_format
2134
 
    classes into each copy. Each copy is also given a new id() to make it
2135
 
    easy to identify.
2136
 
    """
2137
 
 
2138
 
    def __init__(self, transport_server, transport_readonly_server, formats):
2139
 
        self._transport_server = transport_server
2140
 
        self._transport_readonly_server = transport_readonly_server
2141
 
        self._formats = formats
2142
 
    
2143
 
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2144
 
        """Clone test for adaption."""
2145
 
        new_test = deepcopy(test)
2146
 
        new_test.transport_server = self._transport_server
2147
 
        new_test.transport_readonly_server = self._transport_readonly_server
2148
 
        new_test.bzrdir_format = bzrdir_format
2149
 
        new_test.workingtree_format = workingtree_format
2150
 
        def make_new_test_id():
2151
 
            new_id = "%s(%s)" % (test.id(), variation)
2152
 
            return lambda: new_id
2153
 
        new_test.id = make_new_test_id()
2154
 
        return new_test
2155
 
    
2156
 
    def adapt(self, test):
2157
 
        from bzrlib.tests import TestSuite
2158
 
        result = TestSuite()
2159
 
        for workingtree_format, bzrdir_format in self._formats:
2160
 
            new_test = self._clone_test(
2161
 
                test,
2162
 
                bzrdir_format,
2163
 
                workingtree_format, workingtree_format.__class__.__name__)
2164
 
            result.addTest(new_test)
2165
 
        return result