~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""WorkingTree object and friends.
18
18
 
19
19
A WorkingTree represents the editable working copy of a branch.
20
 
Operations which represent the WorkingTree are also done here, 
21
 
such as renaming or adding files.  The WorkingTree has an inventory 
22
 
which is updated by these operations.  A commit produces a 
 
20
Operations which represent the WorkingTree are also done here,
 
21
such as renaming or adding files.  The WorkingTree has an inventory
 
22
which is updated by these operations.  A commit produces a
23
23
new revision based on the workingtree and its inventory.
24
24
 
25
25
At the moment every WorkingTree has its own branch.  Remote
38
38
 
39
39
from cStringIO import StringIO
40
40
import os
 
41
import sys
41
42
 
42
43
from bzrlib.lazy_import import lazy_import
43
44
lazy_import(globals(), """
44
45
from bisect import bisect_left
45
46
import collections
46
 
from copy import deepcopy
47
47
import errno
48
48
import itertools
49
49
import operator
64
64
    hashcache,
65
65
    ignores,
66
66
    merge,
67
 
    osutils,
 
67
    revision as _mod_revision,
68
68
    revisiontree,
69
69
    repository,
70
70
    textui,
72
72
    transform,
73
73
    ui,
74
74
    urlutils,
 
75
    views,
75
76
    xml5,
76
77
    xml6,
77
78
    xml7,
79
80
import bzrlib.branch
80
81
from bzrlib.transport import get_transport
81
82
import bzrlib.ui
82
 
from bzrlib.workingtree_4 import WorkingTreeFormat4
 
83
from bzrlib.workingtree_4 import (
 
84
    WorkingTreeFormat4,
 
85
    WorkingTreeFormat5,
 
86
    WorkingTreeFormat6,
 
87
    )
83
88
""")
84
89
 
85
90
from bzrlib import symbol_versioning
86
91
from bzrlib.decorators import needs_read_lock, needs_write_lock
87
92
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
88
 
from bzrlib.lockable_files import LockableFiles, TransportLock
 
93
from bzrlib.lockable_files import LockableFiles
89
94
from bzrlib.lockdir import LockDir
90
95
import bzrlib.mutabletree
91
96
from bzrlib.mutabletree import needs_tree_write_lock
 
97
from bzrlib import osutils
92
98
from bzrlib.osutils import (
93
99
    compact_date,
94
100
    file_kind,
101
107
    splitpath,
102
108
    supports_executable,
103
109
    )
 
110
from bzrlib.filters import filtered_input_file
104
111
from bzrlib.trace import mutter, note
105
112
from bzrlib.transport.local import LocalTransport
106
113
from bzrlib.progress import DummyProgress, ProgressPhase
110
117
        deprecated_method,
111
118
        deprecated_function,
112
119
        DEPRECATED_PARAMETER,
113
 
        zero_eight,
114
 
        zero_eleven,
115
 
        zero_thirteen,
116
120
        )
117
121
 
118
122
 
119
123
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
120
124
CONFLICT_HEADER_1 = "BZR conflict list format 1"
121
125
 
122
 
 
123
 
@deprecated_function(zero_thirteen)
124
 
def gen_file_id(name):
125
 
    """Return new file id for the basename 'name'.
126
 
 
127
 
    Use bzrlib.generate_ids.gen_file_id() instead
128
 
    """
129
 
    return generate_ids.gen_file_id(name)
130
 
 
131
 
 
132
 
@deprecated_function(zero_thirteen)
133
 
def gen_root_id():
134
 
    """Return a new tree-root file id.
135
 
 
136
 
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
137
 
    """
138
 
    return generate_ids.gen_root_id()
 
126
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
139
127
 
140
128
 
141
129
class TreeEntry(object):
142
130
    """An entry that implements the minimum interface used by commands.
143
131
 
144
 
    This needs further inspection, it may be better to have 
 
132
    This needs further inspection, it may be better to have
145
133
    InventoryEntries without ids - though that seems wrong. For now,
146
134
    this is a parallel hierarchy to InventoryEntry, and needs to become
147
135
    one of several things: decorates to that hierarchy, children of, or
150
138
    no InventoryEntry available - i.e. for unversioned objects.
151
139
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
152
140
    """
153
 
 
 
141
 
154
142
    def __eq__(self, other):
155
143
        # yes, this us ugly, TODO: best practice __eq__ style.
156
144
        return (isinstance(other, TreeEntry)
157
145
                and other.__class__ == self.__class__)
158
 
 
 
146
 
159
147
    def kind_character(self):
160
148
        return "???"
161
149
 
203
191
    not listed in the Inventory and vice versa.
204
192
    """
205
193
 
 
194
    # override this to set the strategy for storing views
 
195
    def _make_views(self):
 
196
        return views.DisabledViews(self)
 
197
 
206
198
    def __init__(self, basedir='.',
207
199
                 branch=DEPRECATED_PARAMETER,
208
200
                 _inventory=None,
219
211
        if not _internal:
220
212
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
221
213
                "WorkingTree.open() to obtain a WorkingTree.")
222
 
        assert isinstance(basedir, basestring), \
223
 
            "base directory %r is not a string" % basedir
224
214
        basedir = safe_unicode(basedir)
225
215
        mutter("opening working tree %r", basedir)
226
216
        if deprecated_passed(branch):
234
224
            self._control_files = self.branch.control_files
235
225
        else:
236
226
            # assume all other formats have their own control files.
237
 
            assert isinstance(_control_files, LockableFiles), \
238
 
                    "_control_files must be a LockableFiles, not %r" \
239
 
                    % _control_files
240
227
            self._control_files = _control_files
 
228
        self._transport = self._control_files._transport
241
229
        # update the whole cache up front and write to disk if anything changed;
242
230
        # in the future we might want to do this more selectively
243
231
        # two possible ways offer themselves : in self._unlock, write the cache
247
235
        wt_trans = self.bzrdir.get_workingtree_transport(None)
248
236
        cache_filename = wt_trans.local_abspath('stat-cache')
249
237
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
250
 
                                              self._control_files._file_mode)
 
238
            self.bzrdir._get_file_mode(),
 
239
            self._content_filter_stack_provider())
251
240
        hc = self._hashcache
252
241
        hc.read()
253
242
        # is this scan needed ? it makes things kinda slow.
267
256
            # the Format factory and creation methods that are
268
257
            # permitted to do this.
269
258
            self._set_inventory(_inventory, dirty=False)
 
259
        self._detect_case_handling()
 
260
        self._rules_searcher = None
 
261
        self.views = self._make_views()
 
262
 
 
263
    def _detect_case_handling(self):
 
264
        wt_trans = self.bzrdir.get_workingtree_transport(None)
 
265
        try:
 
266
            wt_trans.stat("FoRMaT")
 
267
        except errors.NoSuchFile:
 
268
            self.case_sensitive = True
 
269
        else:
 
270
            self.case_sensitive = False
 
271
 
 
272
        self._setup_directory_is_tree_reference()
270
273
 
271
274
    branch = property(
272
275
        fget=lambda self: self._branch,
293
296
    def supports_tree_reference(self):
294
297
        return False
295
298
 
 
299
    def supports_content_filtering(self):
 
300
        return self._format.supports_content_filtering()
 
301
 
 
302
    def supports_views(self):
 
303
        return self.views.supports_views()
 
304
 
296
305
    def _set_inventory(self, inv, dirty):
297
306
        """Set the internal cached inventory.
298
307
 
303
312
            False then the inventory is the same as that on disk and any
304
313
            serialisation would be unneeded overhead.
305
314
        """
306
 
        assert inv.root is not None
307
315
        self._inventory = inv
308
316
        self._inventory_is_modified = dirty
309
317
 
313
321
 
314
322
        """
315
323
        if path is None:
316
 
            path = os.path.getcwdu()
 
324
            path = osutils.getcwd()
317
325
        control = bzrdir.BzrDir.open(path, _unsupported)
318
326
        return control.open_workingtree(_unsupported)
319
 
        
 
327
 
320
328
    @staticmethod
321
329
    def open_containing(path=None):
322
330
        """Open an existing working tree which has its root about path.
323
 
        
 
331
 
324
332
        This probes for a working tree at path and searches upwards from there.
325
333
 
326
334
        Basically we keep looking up until we find the control directory or
344
352
        """
345
353
        return WorkingTree.open(path, _unsupported=True)
346
354
 
 
355
    @staticmethod
 
356
    def find_trees(location):
 
357
        def list_current(transport):
 
358
            return [d for d in transport.list_dir('') if d != '.bzr']
 
359
        def evaluate(bzrdir):
 
360
            try:
 
361
                tree = bzrdir.open_workingtree()
 
362
            except errors.NoWorkingTree:
 
363
                return True, None
 
364
            else:
 
365
                return True, tree
 
366
        transport = get_transport(location)
 
367
        iterator = bzrdir.BzrDir.find_bzrdirs(transport, evaluate=evaluate,
 
368
                                              list_current=list_current)
 
369
        return [t for t in iterator if t is not None]
 
370
 
347
371
    # should be deprecated - this is slow and in any case treating them as a
348
372
    # container is (we now know) bad style -- mbp 20070302
349
373
    ## @deprecated_method(zero_fifteen)
358
382
            if osutils.lexists(self.abspath(path)):
359
383
                yield ie.file_id
360
384
 
 
385
    def all_file_ids(self):
 
386
        """See Tree.iter_all_file_ids"""
 
387
        return set(self.inventory)
 
388
 
361
389
    def __repr__(self):
362
390
        return "<%s of %s>" % (self.__class__.__name__,
363
391
                               getattr(self, 'basedir', None))
364
392
 
365
393
    def abspath(self, filename):
366
394
        return pathjoin(self.basedir, filename)
367
 
    
 
395
 
368
396
    def basis_tree(self):
369
397
        """Return RevisionTree for the current last revision.
370
 
        
 
398
 
371
399
        If the left most parent is a ghost then the returned tree will be an
372
 
        empty tree - one obtained by calling repository.revision_tree(None).
 
400
        empty tree - one obtained by calling
 
401
        repository.revision_tree(NULL_REVISION).
373
402
        """
374
403
        try:
375
404
            revision_id = self.get_parent_ids()[0]
377
406
            # no parents, return an empty revision tree.
378
407
            # in the future this should return the tree for
379
408
            # 'empty:' - the implicit root empty tree.
380
 
            return self.branch.repository.revision_tree(None)
 
409
            return self.branch.repository.revision_tree(
 
410
                       _mod_revision.NULL_REVISION)
381
411
        try:
382
412
            return self.revision_tree(revision_id)
383
413
        except errors.NoSuchRevision:
387
417
        # at this point ?
388
418
        try:
389
419
            return self.branch.repository.revision_tree(revision_id)
390
 
        except errors.RevisionNotPresent:
 
420
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
391
421
            # the basis tree *may* be a ghost or a low level error may have
392
 
            # occured. If the revision is present, its a problem, if its not
 
422
            # occurred. If the revision is present, its a problem, if its not
393
423
            # its a ghost.
394
424
            if self.branch.repository.has_revision(revision_id):
395
425
                raise
396
426
            # the basis tree is a ghost so return an empty tree.
397
 
            return self.branch.repository.revision_tree(None)
398
 
 
399
 
    @staticmethod
400
 
    @deprecated_method(zero_eight)
401
 
    def create(branch, directory):
402
 
        """Create a workingtree for branch at directory.
403
 
 
404
 
        If existing_directory already exists it must have a .bzr directory.
405
 
        If it does not exist, it will be created.
406
 
 
407
 
        This returns a new WorkingTree object for the new checkout.
408
 
 
409
 
        TODO FIXME RBC 20060124 when we have checkout formats in place this
410
 
        should accept an optional revisionid to checkout [and reject this if
411
 
        checking out into the same dir as a pre-checkout-aware branch format.]
412
 
 
413
 
        XXX: When BzrDir is present, these should be created through that 
414
 
        interface instead.
415
 
        """
416
 
        warnings.warn('delete WorkingTree.create', stacklevel=3)
417
 
        transport = get_transport(directory)
418
 
        if branch.bzrdir.root_transport.base == transport.base:
419
 
            # same dir 
420
 
            return branch.bzrdir.create_workingtree()
421
 
        # different directory, 
422
 
        # create a branch reference
423
 
        # and now a working tree.
424
 
        raise NotImplementedError
425
 
 
426
 
    @staticmethod
427
 
    @deprecated_method(zero_eight)
428
 
    def create_standalone(directory):
429
 
        """Create a checkout and a branch and a repo at directory.
430
 
 
431
 
        Directory must exist and be empty.
432
 
 
433
 
        please use BzrDir.create_standalone_workingtree
434
 
        """
435
 
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
 
427
            return self.branch.repository.revision_tree(
 
428
                       _mod_revision.NULL_REVISION)
 
429
 
 
430
    def _cleanup(self):
 
431
        self._flush_ignore_list_cache()
436
432
 
437
433
    def relpath(self, path):
438
434
        """Return the local path portion from a given path.
439
 
        
440
 
        The path may be absolute or relative. If its a relative path it is 
 
435
 
 
436
        The path may be absolute or relative. If its a relative path it is
441
437
        interpreted relative to the python current working directory.
442
438
        """
443
439
        return osutils.relpath(self.basedir, path)
445
441
    def has_filename(self, filename):
446
442
        return osutils.lexists(self.abspath(filename))
447
443
 
448
 
    def get_file(self, file_id):
449
 
        file_id = osutils.safe_file_id(file_id)
450
 
        return self.get_file_byname(self.id2path(file_id))
451
 
 
452
 
    def get_file_text(self, file_id):
453
 
        file_id = osutils.safe_file_id(file_id)
454
 
        return self.get_file(file_id).read()
455
 
 
456
 
    def get_file_byname(self, filename):
457
 
        return file(self.abspath(filename), 'rb')
 
444
    def get_file(self, file_id, path=None, filtered=True):
 
445
        return self.get_file_with_stat(file_id, path, filtered=filtered)[0]
 
446
 
 
447
    def get_file_with_stat(self, file_id, path=None, filtered=True,
 
448
        _fstat=os.fstat):
 
449
        """See MutableTree.get_file_with_stat."""
 
450
        if path is None:
 
451
            path = self.id2path(file_id)
 
452
        file_obj = self.get_file_byname(path, filtered=False)
 
453
        stat_value = _fstat(file_obj.fileno())
 
454
        if self.supports_content_filtering() and filtered:
 
455
            filters = self._content_filter_stack(path)
 
456
            file_obj = filtered_input_file(file_obj, filters)
 
457
        return (file_obj, stat_value)
 
458
 
 
459
    def get_file_text(self, file_id, path=None, filtered=True):
 
460
        return self.get_file(file_id, path=path, filtered=filtered).read()
 
461
 
 
462
    def get_file_byname(self, filename, filtered=True):
 
463
        path = self.abspath(filename)
 
464
        f = file(path, 'rb')
 
465
        if self.supports_content_filtering() and filtered:
 
466
            filters = self._content_filter_stack(filename)
 
467
            return filtered_input_file(f, filters)
 
468
        else:
 
469
            return f
 
470
 
 
471
    def get_file_lines(self, file_id, path=None, filtered=True):
 
472
        """See Tree.get_file_lines()"""
 
473
        file = self.get_file(file_id, path, filtered=filtered)
 
474
        try:
 
475
            return file.readlines()
 
476
        finally:
 
477
            file.close()
458
478
 
459
479
    @needs_read_lock
460
 
    def annotate_iter(self, file_id):
 
480
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
461
481
        """See Tree.annotate_iter
462
482
 
463
483
        This implementation will use the basis tree implementation if possible.
467
487
        incorrectly attributed to CURRENT_REVISION (but after committing, the
468
488
        attribution will be correct).
469
489
        """
470
 
        file_id = osutils.safe_file_id(file_id)
471
490
        basis = self.basis_tree()
472
491
        basis.lock_read()
473
492
        try:
474
 
            changes = self._iter_changes(basis, True, [self.id2path(file_id)],
 
493
            changes = self.iter_changes(basis, True, [self.id2path(file_id)],
475
494
                require_versioned=True).next()
476
495
            changed_content, kind = changes[2], changes[6]
477
496
            if not changed_content:
490
509
                    continue
491
510
                old.append(list(tree.annotate_iter(file_id)))
492
511
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
493
 
                                       CURRENT_REVISION)
 
512
                                       default_revision)
494
513
        finally:
495
514
            basis.unlock()
496
515
 
 
516
    def _get_ancestors(self, default_revision):
 
517
        ancestors = set([default_revision])
 
518
        for parent_id in self.get_parent_ids():
 
519
            ancestors.update(self.branch.repository.get_ancestry(
 
520
                             parent_id, topo_sorted=False))
 
521
        return ancestors
 
522
 
497
523
    def get_parent_ids(self):
498
524
        """See Tree.get_parent_ids.
499
 
        
 
525
 
500
526
        This implementation reads the pending merges list and last_revision
501
527
        value and uses that to decide what the parents list should be.
502
528
        """
503
 
        last_rev = self._last_revision()
504
 
        if last_rev is None:
 
529
        last_rev = _mod_revision.ensure_null(self._last_revision())
 
530
        if _mod_revision.NULL_REVISION == last_rev:
505
531
            parents = []
506
532
        else:
507
533
            parents = [last_rev]
508
534
        try:
509
 
            merges_file = self._control_files.get('pending-merges')
 
535
            merges_file = self._transport.get('pending-merges')
510
536
        except errors.NoSuchFile:
511
537
            pass
512
538
        else:
513
539
            for l in merges_file.readlines():
514
 
                revision_id = osutils.safe_revision_id(l.rstrip('\n'))
 
540
                revision_id = l.rstrip('\n')
515
541
                parents.append(revision_id)
516
542
        return parents
517
543
 
519
545
    def get_root_id(self):
520
546
        """Return the id of this trees root"""
521
547
        return self._inventory.root.file_id
522
 
        
 
548
 
523
549
    def _get_store_filename(self, file_id):
524
550
        ## XXX: badly named; this is not in the store at all
525
 
        file_id = osutils.safe_file_id(file_id)
526
551
        return self.abspath(self.id2path(file_id))
527
552
 
528
553
    @needs_read_lock
529
554
    def clone(self, to_bzrdir, revision_id=None):
530
555
        """Duplicate this working tree into to_bzr, including all state.
531
 
        
 
556
 
532
557
        Specifically modified files are kept as modified, but
533
558
        ignored and unknown files are discarded.
534
559
 
535
560
        If you want to make a new line of development, see bzrdir.sprout()
536
561
 
537
562
        revision
538
 
            If not None, the cloned tree will have its last revision set to 
539
 
            revision, and and difference between the source trees last revision
 
563
            If not None, the cloned tree will have its last revision set to
 
564
            revision, and difference between the source trees last revision
540
565
            and this one merged in.
541
566
        """
542
567
        # assumes the target bzr dir format is compatible.
543
 
        result = self._format.initialize(to_bzrdir)
 
568
        result = to_bzrdir.create_workingtree()
544
569
        self.copy_content_into(result, revision_id)
545
570
        return result
546
571
 
557
582
            tree.set_parent_ids([revision_id])
558
583
 
559
584
    def id2abspath(self, file_id):
560
 
        file_id = osutils.safe_file_id(file_id)
561
585
        return self.abspath(self.id2path(file_id))
562
586
 
563
587
    def has_id(self, file_id):
564
588
        # files that have been deleted are excluded
565
 
        file_id = osutils.safe_file_id(file_id)
566
589
        inv = self.inventory
567
590
        if not inv.has_id(file_id):
568
591
            return False
570
593
        return osutils.lexists(self.abspath(path))
571
594
 
572
595
    def has_or_had_id(self, file_id):
573
 
        file_id = osutils.safe_file_id(file_id)
574
596
        if file_id == self.inventory.root.file_id:
575
597
            return True
576
598
        return self.inventory.has_id(file_id)
578
600
    __contains__ = has_id
579
601
 
580
602
    def get_file_size(self, file_id):
581
 
        file_id = osutils.safe_file_id(file_id)
582
 
        return os.path.getsize(self.id2abspath(file_id))
 
603
        """See Tree.get_file_size"""
 
604
        try:
 
605
            return os.path.getsize(self.id2abspath(file_id))
 
606
        except OSError, e:
 
607
            if e.errno != errno.ENOENT:
 
608
                raise
 
609
            else:
 
610
                return None
583
611
 
584
612
    @needs_read_lock
585
613
    def get_file_sha1(self, file_id, path=None, stat_value=None):
586
 
        file_id = osutils.safe_file_id(file_id)
587
614
        if not path:
588
615
            path = self._inventory.id2path(file_id)
589
616
        return self._hashcache.get_sha1(path, stat_value)
590
617
 
591
618
    def get_file_mtime(self, file_id, path=None):
592
 
        file_id = osutils.safe_file_id(file_id)
593
619
        if not path:
594
620
            path = self.inventory.id2path(file_id)
595
621
        return os.lstat(self.abspath(path)).st_mtime
596
622
 
 
623
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
 
624
        file_id = self.path2id(path)
 
625
        return self._inventory[file_id].executable
 
626
 
 
627
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
 
628
        mode = stat_result.st_mode
 
629
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
 
630
 
597
631
    if not supports_executable():
598
632
        def is_executable(self, file_id, path=None):
599
 
            file_id = osutils.safe_file_id(file_id)
600
633
            return self._inventory[file_id].executable
 
634
 
 
635
        _is_executable_from_path_and_stat = \
 
636
            _is_executable_from_path_and_stat_from_basis
601
637
    else:
602
638
        def is_executable(self, file_id, path=None):
603
639
            if not path:
604
 
                file_id = osutils.safe_file_id(file_id)
605
640
                path = self.id2path(file_id)
606
641
            mode = os.lstat(self.abspath(path)).st_mode
607
642
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
608
643
 
 
644
        _is_executable_from_path_and_stat = \
 
645
            _is_executable_from_path_and_stat_from_stat
 
646
 
609
647
    @needs_tree_write_lock
610
648
    def _add(self, files, ids, kinds):
611
649
        """See MutableTree._add."""
612
650
        # TODO: Re-adding a file that is removed in the working copy
613
651
        # should probably put it back with the previous ID.
614
 
        # the read and write working inventory should not occur in this 
 
652
        # the read and write working inventory should not occur in this
615
653
        # function - they should be part of lock_write and unlock.
616
 
        inv = self.read_working_inventory()
 
654
        inv = self.inventory
617
655
        for f, file_id, kind in zip(files, ids, kinds):
618
 
            assert kind is not None
619
656
            if file_id is None:
620
657
                inv.add_path(f, kind=kind)
621
658
            else:
622
 
                file_id = osutils.safe_file_id(file_id)
623
659
                inv.add_path(f, kind=kind, file_id=file_id)
624
 
        self._write_inventory(inv)
 
660
            self._inventory_is_modified = True
625
661
 
626
662
    @needs_tree_write_lock
627
663
    def _gather_kinds(self, files, kinds):
687
723
        if updated:
688
724
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
689
725
 
690
 
    @deprecated_method(zero_eleven)
691
 
    @needs_read_lock
692
 
    def pending_merges(self):
693
 
        """Return a list of pending merges.
694
 
 
695
 
        These are revisions that have been merged into the working
696
 
        directory but not yet committed.
697
 
 
698
 
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
699
 
        instead - which is available on all tree objects.
700
 
        """
701
 
        return self.get_parent_ids()[1:]
 
726
    def path_content_summary(self, path, _lstat=os.lstat,
 
727
        _mapper=osutils.file_kind_from_stat_mode):
 
728
        """See Tree.path_content_summary."""
 
729
        abspath = self.abspath(path)
 
730
        try:
 
731
            stat_result = _lstat(abspath)
 
732
        except OSError, e:
 
733
            if getattr(e, 'errno', None) == errno.ENOENT:
 
734
                # no file.
 
735
                return ('missing', None, None, None)
 
736
            # propagate other errors
 
737
            raise
 
738
        kind = _mapper(stat_result.st_mode)
 
739
        if kind == 'file':
 
740
            size = stat_result.st_size
 
741
            # try for a stat cache lookup
 
742
            executable = self._is_executable_from_path_and_stat(path, stat_result)
 
743
            return (kind, size, executable, self._sha_from_stat(
 
744
                path, stat_result))
 
745
        elif kind == 'directory':
 
746
            # perhaps it looks like a plain directory, but it's really a
 
747
            # reference.
 
748
            if self._directory_is_tree_reference(path):
 
749
                kind = 'tree-reference'
 
750
            return kind, None, None, None
 
751
        elif kind == 'symlink':
 
752
            return ('symlink', None, None,
 
753
                    os.readlink(abspath.encode(osutils._fs_enc)
 
754
                                ).decode(osutils._fs_enc))
 
755
        else:
 
756
            return (kind, None, None, None)
702
757
 
703
758
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
704
759
        """Common ghost checking functionality from set_parent_*.
714
769
 
715
770
    def _set_merges_from_parent_ids(self, parent_ids):
716
771
        merges = parent_ids[1:]
717
 
        self._control_files.put_bytes('pending-merges', '\n'.join(merges))
 
772
        self._transport.put_bytes('pending-merges', '\n'.join(merges),
 
773
            mode=self.bzrdir._get_file_mode())
 
774
 
 
775
    def _filter_parent_ids_by_ancestry(self, revision_ids):
 
776
        """Check that all merged revisions are proper 'heads'.
 
777
 
 
778
        This will always return the first revision_id, and any merged revisions
 
779
        which are
 
780
        """
 
781
        if len(revision_ids) == 0:
 
782
            return revision_ids
 
783
        graph = self.branch.repository.get_graph()
 
784
        heads = graph.heads(revision_ids)
 
785
        new_revision_ids = revision_ids[:1]
 
786
        for revision_id in revision_ids[1:]:
 
787
            if revision_id in heads and revision_id not in new_revision_ids:
 
788
                new_revision_ids.append(revision_id)
 
789
        if new_revision_ids != revision_ids:
 
790
            trace.mutter('requested to set revision_ids = %s,'
 
791
                         ' but filtered to %s', revision_ids, new_revision_ids)
 
792
        return new_revision_ids
718
793
 
719
794
    @needs_tree_write_lock
720
795
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
721
796
        """Set the parent ids to revision_ids.
722
 
        
 
797
 
723
798
        See also set_parent_trees. This api will try to retrieve the tree data
724
799
        for each element of revision_ids from the trees repository. If you have
725
800
        tree data already available, it is more efficient to use
729
804
        :param revision_ids: The revision_ids to set as the parent ids of this
730
805
            working tree. Any of these may be ghosts.
731
806
        """
732
 
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
733
807
        self._check_parents_for_ghosts(revision_ids,
734
808
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
809
        for revision_id in revision_ids:
 
810
            _mod_revision.check_not_reserved_id(revision_id)
 
811
 
 
812
        revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
735
813
 
736
814
        if len(revision_ids) > 0:
737
815
            self.set_last_revision(revision_ids[0])
738
816
        else:
739
 
            self.set_last_revision(None)
 
817
            self.set_last_revision(_mod_revision.NULL_REVISION)
740
818
 
741
819
        self._set_merges_from_parent_ids(revision_ids)
742
820
 
743
821
    @needs_tree_write_lock
744
822
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
745
823
        """See MutableTree.set_parent_trees."""
746
 
        parent_ids = [osutils.safe_revision_id(rev) for (rev, tree) in parents_list]
 
824
        parent_ids = [rev for (rev, tree) in parents_list]
 
825
        for revision_id in parent_ids:
 
826
            _mod_revision.check_not_reserved_id(revision_id)
747
827
 
748
828
        self._check_parents_for_ghosts(parent_ids,
749
829
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
750
830
 
 
831
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
 
832
 
751
833
        if len(parent_ids) == 0:
752
 
            leftmost_parent_id = None
 
834
            leftmost_parent_id = _mod_revision.NULL_REVISION
753
835
            leftmost_parent_tree = None
754
836
        else:
755
837
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
780
862
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
781
863
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
782
864
 
 
865
    def _sha_from_stat(self, path, stat_result):
 
866
        """Get a sha digest from the tree's stat cache.
 
867
 
 
868
        The default implementation assumes no stat cache is present.
 
869
 
 
870
        :param path: The path.
 
871
        :param stat_result: The stat result being looked up.
 
872
        """
 
873
        return None
 
874
 
783
875
    def _put_rio(self, filename, stanzas, header):
784
876
        self._must_be_locked()
785
877
        my_file = rio_file(stanzas, header)
786
 
        self._control_files.put(filename, my_file)
 
878
        self._transport.put_file(filename, my_file,
 
879
            mode=self.bzrdir._get_file_mode())
787
880
 
788
881
    @needs_write_lock # because merge pulls data into the branch.
789
 
    def merge_from_branch(self, branch, to_revision=None):
 
882
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
 
883
        merge_type=None):
790
884
        """Merge from a branch into this working tree.
791
885
 
792
886
        :param branch: The branch to merge from.
805
899
            # local alterations
806
900
            merger.check_basis(check_clean=True, require_commits=False)
807
901
            if to_revision is None:
808
 
                to_revision = branch.last_revision()
809
 
            else:
810
 
                to_revision = osutils.safe_revision_id(to_revision)
 
902
                to_revision = _mod_revision.ensure_null(branch.last_revision())
811
903
            merger.other_rev_id = to_revision
812
 
            if merger.other_rev_id is None:
813
 
                raise error.NoCommits(branch)
 
904
            if _mod_revision.is_null(merger.other_rev_id):
 
905
                raise errors.NoCommits(branch)
814
906
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
815
907
            merger.other_basis = merger.other_rev_id
816
908
            merger.other_tree = self.branch.repository.revision_tree(
817
909
                merger.other_rev_id)
818
910
            merger.other_branch = branch
819
911
            merger.pp.next_phase()
820
 
            merger.find_base()
 
912
            if from_revision is None:
 
913
                merger.find_base()
 
914
            else:
 
915
                merger.set_base_revision(from_revision, branch)
821
916
            if merger.base_rev_id == merger.other_rev_id:
822
917
                raise errors.PointlessMerge
823
918
            merger.backup_files = False
824
 
            merger.merge_type = Merge3Merger
 
919
            if merge_type is None:
 
920
                merger.merge_type = Merge3Merger
 
921
            else:
 
922
                merger.merge_type = merge_type
825
923
            merger.set_interesting_files(None)
826
924
            merger.show_base = False
827
925
            merger.reprocess = False
835
933
    def merge_modified(self):
836
934
        """Return a dictionary of files modified by a merge.
837
935
 
838
 
        The list is initialized by WorkingTree.set_merge_modified, which is 
 
936
        The list is initialized by WorkingTree.set_merge_modified, which is
839
937
        typically called after we make some automatic updates to the tree
840
938
        because of a merge.
841
939
 
843
941
        still in the working inventory and have that text hash.
844
942
        """
845
943
        try:
846
 
            hashfile = self._control_files.get('merge-hashes')
 
944
            hashfile = self._transport.get('merge-hashes')
847
945
        except errors.NoSuchFile:
848
946
            return {}
849
 
        merge_hashes = {}
850
947
        try:
851
 
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
 
948
            merge_hashes = {}
 
949
            try:
 
950
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
 
951
                    raise errors.MergeModifiedFormatError()
 
952
            except StopIteration:
852
953
                raise errors.MergeModifiedFormatError()
853
 
        except StopIteration:
854
 
            raise errors.MergeModifiedFormatError()
855
 
        for s in RioReader(hashfile):
856
 
            # RioReader reads in Unicode, so convert file_ids back to utf8
857
 
            file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
858
 
            if file_id not in self.inventory:
859
 
                continue
860
 
            text_hash = s.get("hash")
861
 
            if text_hash == self.get_file_sha1(file_id):
862
 
                merge_hashes[file_id] = text_hash
863
 
        return merge_hashes
 
954
            for s in RioReader(hashfile):
 
955
                # RioReader reads in Unicode, so convert file_ids back to utf8
 
956
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
 
957
                if file_id not in self.inventory:
 
958
                    continue
 
959
                text_hash = s.get("hash")
 
960
                if text_hash == self.get_file_sha1(file_id):
 
961
                    merge_hashes[file_id] = text_hash
 
962
            return merge_hashes
 
963
        finally:
 
964
            hashfile.close()
864
965
 
865
966
    @needs_write_lock
866
967
    def mkdir(self, path, file_id=None):
872
973
        return file_id
873
974
 
874
975
    def get_symlink_target(self, file_id):
875
 
        file_id = osutils.safe_file_id(file_id)
876
 
        return os.readlink(self.id2abspath(file_id))
 
976
        return os.readlink(self.id2abspath(file_id).encode(osutils._fs_enc)
 
977
            ).decode(osutils._fs_enc)
877
978
 
878
979
    @needs_write_lock
879
980
    def subsume(self, other_tree):
917
1018
            other_tree.unlock()
918
1019
        other_tree.bzrdir.retire_bzrdir()
919
1020
 
 
1021
    def _setup_directory_is_tree_reference(self):
 
1022
        if self._branch.repository._format.supports_tree_reference:
 
1023
            self._directory_is_tree_reference = \
 
1024
                self._directory_may_be_tree_reference
 
1025
        else:
 
1026
            self._directory_is_tree_reference = \
 
1027
                self._directory_is_never_tree_reference
 
1028
 
 
1029
    def _directory_is_never_tree_reference(self, relpath):
 
1030
        return False
 
1031
 
 
1032
    def _directory_may_be_tree_reference(self, relpath):
 
1033
        # as a special case, if a directory contains control files then
 
1034
        # it's a tree reference, except that the root of the tree is not
 
1035
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
 
1036
        # TODO: We could ask all the control formats whether they
 
1037
        # recognize this directory, but at the moment there's no cheap api
 
1038
        # to do that.  Since we probably can only nest bzr checkouts and
 
1039
        # they always use this name it's ok for now.  -- mbp 20060306
 
1040
        #
 
1041
        # FIXME: There is an unhandled case here of a subdirectory
 
1042
        # containing .bzr but not a branch; that will probably blow up
 
1043
        # when you try to commit it.  It might happen if there is a
 
1044
        # checkout in a subdirectory.  This can be avoided by not adding
 
1045
        # it.  mbp 20070306
 
1046
 
920
1047
    @needs_tree_write_lock
921
1048
    def extract(self, file_id, format=None):
922
1049
        """Extract a subtree from this tree.
923
 
        
 
1050
 
924
1051
        A new branch will be created, relative to the path for this tree.
925
1052
        """
926
1053
        self.flush()
929
1056
            transport = self.branch.bzrdir.root_transport
930
1057
            for name in segments:
931
1058
                transport = transport.clone(name)
932
 
                try:
933
 
                    transport.mkdir('.')
934
 
                except errors.FileExists:
935
 
                    pass
 
1059
                transport.ensure_base()
936
1060
            return transport
937
 
            
 
1061
 
938
1062
        sub_path = self.id2path(file_id)
939
1063
        branch_transport = mkdirs(sub_path)
940
1064
        if format is None:
941
 
            format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
942
 
        try:
943
 
            branch_transport.mkdir('.')
944
 
        except errors.FileExists:
945
 
            pass
 
1065
            format = self.bzrdir.cloning_metadir()
 
1066
        branch_transport.ensure_base()
946
1067
        branch_bzrdir = format.initialize_on_transport(branch_transport)
947
1068
        try:
948
1069
            repo = branch_bzrdir.find_repository()
949
1070
        except errors.NoRepositoryPresent:
950
1071
            repo = branch_bzrdir.create_repository()
951
 
            assert repo.supports_rich_root()
952
 
        else:
953
 
            if not repo.supports_rich_root():
954
 
                raise errors.RootNotRich()
 
1072
        if not repo.supports_rich_root():
 
1073
            raise errors.RootNotRich()
955
1074
        new_branch = branch_bzrdir.create_branch()
956
1075
        new_branch.pull(self.branch)
957
1076
        for parent_id in self.get_parent_ids():
975
1094
        return wt
976
1095
 
977
1096
    def _serialize(self, inventory, out_file):
978
 
        xml5.serializer_v5.write_inventory(self._inventory, out_file)
 
1097
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
 
1098
            working=True)
979
1099
 
980
1100
    def _deserialize(selt, in_file):
981
1101
        return xml5.serializer_v5.read_inventory(in_file)
988
1108
        sio = StringIO()
989
1109
        self._serialize(self._inventory, sio)
990
1110
        sio.seek(0)
991
 
        self._control_files.put('inventory', sio)
 
1111
        self._transport.put_file('inventory', sio,
 
1112
            mode=self.bzrdir._get_file_mode())
992
1113
        self._inventory_is_modified = False
993
1114
 
994
1115
    def _kind(self, relpath):
1025
1146
        # directory file_id, relative path, absolute path, reverse sorted children
1026
1147
        children = os.listdir(self.basedir)
1027
1148
        children.sort()
1028
 
        # jam 20060527 The kernel sized tree seems equivalent whether we 
 
1149
        # jam 20060527 The kernel sized tree seems equivalent whether we
1029
1150
        # use a deque and popleft to keep them sorted, or if we use a plain
1030
1151
        # list and just reverse() them.
1031
1152
        children = collections.deque(children)
1051
1172
 
1052
1173
                # absolute path
1053
1174
                fap = from_dir_abspath + '/' + f
1054
 
                
 
1175
 
1055
1176
                f_ie = inv.get_child(from_dir_id, f)
1056
1177
                if f_ie:
1057
1178
                    c = 'V'
1089
1210
                    except KeyError:
1090
1211
                        yield fp[1:], c, fk, None, TreeEntry()
1091
1212
                    continue
1092
 
                
 
1213
 
1093
1214
                if fk != 'directory':
1094
1215
                    continue
1095
1216
 
1112
1233
        to_dir must exist in the inventory.
1113
1234
 
1114
1235
        If to_dir exists and is a directory, the files are moved into
1115
 
        it, keeping their old names.  
 
1236
        it, keeping their old names.
1116
1237
 
1117
1238
        Note that to_dir is only the last component of the new name;
1118
1239
        this doesn't change the directory.
1155
1276
                                       DeprecationWarning)
1156
1277
 
1157
1278
        # check destination directory
1158
 
        assert not isinstance(from_paths, basestring)
 
1279
        if isinstance(from_paths, basestring):
 
1280
            raise ValueError()
1159
1281
        inv = self.inventory
1160
1282
        to_abs = self.abspath(to_dir)
1161
1283
        if not isdir(to_abs):
1245
1367
                only_change_inv = True
1246
1368
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1247
1369
                only_change_inv = False
 
1370
            elif (not self.case_sensitive
 
1371
                  and from_rel.lower() == to_rel.lower()
 
1372
                  and self.has_filename(from_rel)):
 
1373
                only_change_inv = False
1248
1374
            else:
1249
1375
                # something is wrong, so lets determine what exactly
1250
1376
                if not self.has_filename(from_rel) and \
1253
1379
                        errors.PathsDoNotExist(paths=(str(from_rel),
1254
1380
                        str(to_rel))))
1255
1381
                else:
1256
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
1257
 
                        extra="(Use --after to update the Bazaar id)")
 
1382
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
1258
1383
            rename_entry.only_change_inv = only_change_inv
1259
1384
        return rename_entries
1260
1385
 
1391
1516
        These are files in the working directory that are not versioned or
1392
1517
        control files or ignored.
1393
1518
        """
1394
 
        # force the extras method to be fully executed before returning, to 
 
1519
        # force the extras method to be fully executed before returning, to
1395
1520
        # prevent race conditions with the lock
1396
1521
        return iter(
1397
1522
            [subp for subp in self.extras() if not self.is_ignored(subp)])
1407
1532
        :raises: NoSuchId if any fileid is not currently versioned.
1408
1533
        """
1409
1534
        for file_id in file_ids:
1410
 
            file_id = osutils.safe_file_id(file_id)
 
1535
            if file_id not in self._inventory:
 
1536
                raise errors.NoSuchId(self, file_id)
 
1537
        for file_id in file_ids:
1411
1538
            if self._inventory.has_id(file_id):
1412
1539
                self._inventory.remove_recursive_id(file_id)
1413
 
            else:
1414
 
                raise errors.NoSuchId(self, file_id)
1415
1540
        if len(file_ids):
1416
 
            # in the future this should just set a dirty bit to wait for the 
 
1541
            # in the future this should just set a dirty bit to wait for the
1417
1542
            # final unlock. However, until all methods of workingtree start
1418
 
            # with the current in -memory inventory rather than triggering 
 
1543
            # with the current in -memory inventory rather than triggering
1419
1544
            # a read, it is more complex - we need to teach read_inventory
1420
1545
            # to know when to read, and when to not read first... and possibly
1421
1546
            # to save first when the in memory one may be corrupted.
1422
1547
            # so for now, we just only write it if it is indeed dirty.
1423
1548
            # - RBC 20060907
1424
1549
            self._write_inventory(self._inventory)
1425
 
    
1426
 
    @deprecated_method(zero_eight)
1427
 
    def iter_conflicts(self):
1428
 
        """List all files in the tree that have text or content conflicts.
1429
 
        DEPRECATED.  Use conflicts instead."""
1430
 
        return self._iter_conflicts()
1431
1550
 
1432
1551
    def _iter_conflicts(self):
1433
1552
        conflicted = set()
1442
1561
 
1443
1562
    @needs_write_lock
1444
1563
    def pull(self, source, overwrite=False, stop_revision=None,
1445
 
             change_reporter=None):
 
1564
             change_reporter=None, possible_transports=None):
1446
1565
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1447
1566
        source.lock_read()
1448
1567
        try:
1450
1569
            pp.next_phase()
1451
1570
            old_revision_info = self.branch.last_revision_info()
1452
1571
            basis_tree = self.basis_tree()
1453
 
            count = self.branch.pull(source, overwrite, stop_revision)
 
1572
            count = self.branch.pull(source, overwrite, stop_revision,
 
1573
                                     possible_transports=possible_transports)
1454
1574
            new_revision_info = self.branch.last_revision_info()
1455
1575
            if new_revision_info != old_revision_info:
1456
1576
                pp.next_phase()
1468
1588
                                change_reporter=change_reporter)
1469
1589
                    if (basis_tree.inventory.root is None and
1470
1590
                        new_basis_tree.inventory.root is not None):
1471
 
                        self.set_root_id(new_basis_tree.inventory.root.file_id)
 
1591
                        self.set_root_id(new_basis_tree.get_root_id())
1472
1592
                finally:
1473
1593
                    pb.finished()
1474
1594
                    basis_tree.unlock()
1476
1596
                # reuse the revisiontree we merged against to set the new
1477
1597
                # tree data.
1478
1598
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1479
 
                # we have to pull the merge trees out again, because 
1480
 
                # merge_inner has set the ids. - this corner is not yet 
 
1599
                # we have to pull the merge trees out again, because
 
1600
                # merge_inner has set the ids. - this corner is not yet
1481
1601
                # layered well enough to prevent double handling.
1482
1602
                # XXX TODO: Fix the double handling: telling the tree about
1483
1603
                # the already known parent data is wasteful.
1494
1614
    @needs_write_lock
1495
1615
    def put_file_bytes_non_atomic(self, file_id, bytes):
1496
1616
        """See MutableTree.put_file_bytes_non_atomic."""
1497
 
        file_id = osutils.safe_file_id(file_id)
1498
1617
        stream = file(self.id2abspath(file_id), 'wb')
1499
1618
        try:
1500
1619
            stream.write(bytes)
1525
1644
                if subf == '.bzr':
1526
1645
                    continue
1527
1646
                if subf not in dir_entry.children:
1528
 
                    subf_norm, can_access = osutils.normalized_filename(subf)
 
1647
                    try:
 
1648
                        (subf_norm,
 
1649
                         can_access) = osutils.normalized_filename(subf)
 
1650
                    except UnicodeDecodeError:
 
1651
                        path_os_enc = path.encode(osutils._fs_enc)
 
1652
                        relpath = path_os_enc + '/' + subf
 
1653
                        raise errors.BadFilenameEncoding(relpath,
 
1654
                                                         osutils._fs_enc)
1529
1655
                    if subf_norm != subf and can_access:
1530
1656
                        if subf_norm not in dir_entry.children:
1531
1657
                            fl.append(subf_norm)
1532
1658
                    else:
1533
1659
                        fl.append(subf)
1534
 
            
 
1660
 
1535
1661
            fl.sort()
1536
1662
            for subf in fl:
1537
1663
                subp = pathjoin(path, subf)
1553
1679
        if ignoreset is not None:
1554
1680
            return ignoreset
1555
1681
 
1556
 
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
 
1682
        ignore_globs = set()
1557
1683
        ignore_globs.update(ignores.get_runtime_ignores())
1558
1684
        ignore_globs.update(ignores.get_user_ignores())
1559
1685
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1586
1712
    def kind(self, file_id):
1587
1713
        return file_kind(self.id2abspath(file_id))
1588
1714
 
 
1715
    def stored_kind(self, file_id):
 
1716
        """See Tree.stored_kind"""
 
1717
        return self.inventory[file_id].kind
 
1718
 
1589
1719
    def _comparison_data(self, entry, path):
1590
1720
        abspath = self.abspath(path)
1591
1721
        try:
1622
1752
    @needs_read_lock
1623
1753
    def _last_revision(self):
1624
1754
        """helper for get_parent_ids."""
1625
 
        return self.branch.last_revision()
 
1755
        return _mod_revision.ensure_null(self.branch.last_revision())
1626
1756
 
1627
1757
    def is_locked(self):
1628
1758
        return self._control_files.is_locked()
1673
1803
    def _reset_data(self):
1674
1804
        """Reset transient data that cannot be revalidated."""
1675
1805
        self._inventory_is_modified = False
1676
 
        result = self._deserialize(self._control_files.get('inventory'))
 
1806
        result = self._deserialize(self._transport.get('inventory'))
1677
1807
        self._set_inventory(result, dirty=False)
1678
1808
 
1679
1809
    @needs_tree_write_lock
1680
1810
    def set_last_revision(self, new_revision):
1681
1811
        """Change the last revision in the working tree."""
1682
 
        new_revision = osutils.safe_revision_id(new_revision)
1683
1812
        if self._change_last_revision(new_revision):
1684
1813
            self._cache_basis_inventory(new_revision)
1685
1814
 
1686
1815
    def _change_last_revision(self, new_revision):
1687
1816
        """Template method part of set_last_revision to perform the change.
1688
 
        
 
1817
 
1689
1818
        This is used to allow WorkingTree3 instances to not affect branch
1690
1819
        when their last revision is set.
1691
1820
        """
1692
 
        if new_revision is None:
 
1821
        if _mod_revision.is_null(new_revision):
1693
1822
            self.branch.set_revision_history([])
1694
1823
            return False
1695
1824
        try:
1701
1830
 
1702
1831
    def _write_basis_inventory(self, xml):
1703
1832
        """Write the basis inventory XML to the basis-inventory file"""
1704
 
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
1705
1833
        path = self._basis_inventory_name()
1706
1834
        sio = StringIO(xml)
1707
 
        self._control_files.put(path, sio)
 
1835
        self._transport.put_file(path, sio,
 
1836
            mode=self.bzrdir._get_file_mode())
1708
1837
 
1709
1838
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
1710
1839
        """Create the text that will be saved in basis-inventory"""
1711
 
        # TODO: jam 20070209 This should be redundant, as the revision_id
1712
 
        #       as all callers should have already converted the revision_id to
1713
 
        #       utf8
1714
 
        inventory.revision_id = osutils.safe_revision_id(revision_id)
 
1840
        inventory.revision_id = revision_id
1715
1841
        return xml7.serializer_v7.write_inventory_to_string(inventory)
1716
1842
 
1717
1843
    def _cache_basis_inventory(self, new_revision):
1720
1846
        # as commit already has that ready-to-use [while the format is the
1721
1847
        # same, that is].
1722
1848
        try:
1723
 
            # this double handles the inventory - unpack and repack - 
 
1849
            # this double handles the inventory - unpack and repack -
1724
1850
            # but is easier to understand. We can/should put a conditional
1725
1851
            # in here based on whether the inventory is in the latest format
1726
1852
            # - perhaps we should repack all inventories on a repository
1727
1853
            # upgrade ?
1728
1854
            # the fast path is to copy the raw xml from the repository. If the
1729
 
            # xml contains 'revision_id="', then we assume the right 
 
1855
            # xml contains 'revision_id="', then we assume the right
1730
1856
            # revision_id is set. We must check for this full string, because a
1731
1857
            # root node id can legitimately look like 'revision_id' but cannot
1732
1858
            # contain a '"'.
1733
1859
            xml = self.branch.repository.get_inventory_xml(new_revision)
1734
1860
            firstline = xml.split('\n', 1)[0]
1735
 
            if (not 'revision_id="' in firstline or 
 
1861
            if (not 'revision_id="' in firstline or
1736
1862
                'format="7"' not in firstline):
1737
1863
                inv = self.branch.repository.deserialise_inventory(
1738
1864
                    new_revision, xml)
1744
1870
    def read_basis_inventory(self):
1745
1871
        """Read the cached basis inventory."""
1746
1872
        path = self._basis_inventory_name()
1747
 
        return self._control_files.get(path).read()
1748
 
        
 
1873
        return self._transport.get_bytes(path)
 
1874
 
1749
1875
    @needs_read_lock
1750
1876
    def read_working_inventory(self):
1751
1877
        """Read the working inventory.
1752
 
        
 
1878
 
1753
1879
        :raises errors.InventoryModified: read_working_inventory will fail
1754
1880
            when the current in memory inventory has been modified.
1755
1881
        """
1756
 
        # conceptually this should be an implementation detail of the tree. 
 
1882
        # conceptually this should be an implementation detail of the tree.
1757
1883
        # XXX: Deprecate this.
1758
1884
        # ElementTree does its own conversion from UTF-8, so open in
1759
1885
        # binary.
1760
1886
        if self._inventory_is_modified:
1761
1887
            raise errors.InventoryModified(self)
1762
 
        result = self._deserialize(self._control_files.get('inventory'))
 
1888
        result = self._deserialize(self._transport.get('inventory'))
1763
1889
        self._set_inventory(result, dirty=False)
1764
1890
        return result
1765
1891
 
1766
1892
    @needs_tree_write_lock
1767
 
    def remove(self, files, verbose=False, to_file=None):
1768
 
        """Remove nominated files from the working inventory..
1769
 
 
1770
 
        This does not remove their text.  This does not run on XXX on what? RBC
1771
 
 
1772
 
        TODO: Refuse to remove modified files unless --force is given?
1773
 
 
1774
 
        TODO: Do something useful with directories.
1775
 
 
1776
 
        TODO: Should this remove the text or not?  Tough call; not
1777
 
        removing may be useful and the user can just use use rm, and
1778
 
        is the opposite of add.  Removing it is consistent with most
1779
 
        other tools.  Maybe an option.
 
1893
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
 
1894
        force=False):
 
1895
        """Remove nominated files from the working inventory.
 
1896
 
 
1897
        :files: File paths relative to the basedir.
 
1898
        :keep_files: If true, the files will also be kept.
 
1899
        :force: Delete files and directories, even if they are changed and
 
1900
            even if the directories are not empty.
1780
1901
        """
1781
 
        ## TODO: Normalize names
1782
 
        ## TODO: Remove nested loops; better scalability
1783
1902
        if isinstance(files, basestring):
1784
1903
            files = [files]
1785
1904
 
1786
 
        inv = self.inventory
1787
 
 
1788
 
        # do this before any modifications
 
1905
        inv_delta = []
 
1906
 
 
1907
        new_files=set()
 
1908
        unknown_nested_files=set()
 
1909
 
 
1910
        def recurse_directory_to_add_files(directory):
 
1911
            # Recurse directory and add all files
 
1912
            # so we can check if they have changed.
 
1913
            for parent_info, file_infos in\
 
1914
                self.walkdirs(directory):
 
1915
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
 
1916
                    # Is it versioned or ignored?
 
1917
                    if self.path2id(relpath) or self.is_ignored(relpath):
 
1918
                        # Add nested content for deletion.
 
1919
                        new_files.add(relpath)
 
1920
                    else:
 
1921
                        # Files which are not versioned and not ignored
 
1922
                        # should be treated as unknown.
 
1923
                        unknown_nested_files.add((relpath, None, kind))
 
1924
 
 
1925
        for filename in files:
 
1926
            # Get file name into canonical form.
 
1927
            abspath = self.abspath(filename)
 
1928
            filename = self.relpath(abspath)
 
1929
            if len(filename) > 0:
 
1930
                new_files.add(filename)
 
1931
                recurse_directory_to_add_files(filename)
 
1932
 
 
1933
        files = list(new_files)
 
1934
 
 
1935
        if len(files) == 0:
 
1936
            return # nothing to do
 
1937
 
 
1938
        # Sort needed to first handle directory content before the directory
 
1939
        files.sort(reverse=True)
 
1940
 
 
1941
        # Bail out if we are going to delete files we shouldn't
 
1942
        if not keep_files and not force:
 
1943
            has_changed_files = len(unknown_nested_files) > 0
 
1944
            if not has_changed_files:
 
1945
                for (file_id, path, content_change, versioned, parent_id, name,
 
1946
                     kind, executable) in self.iter_changes(self.basis_tree(),
 
1947
                         include_unchanged=True, require_versioned=False,
 
1948
                         want_unversioned=True, specific_files=files):
 
1949
                    if versioned == (False, False):
 
1950
                        # The record is unknown ...
 
1951
                        if not self.is_ignored(path[1]):
 
1952
                            # ... but not ignored
 
1953
                            has_changed_files = True
 
1954
                            break
 
1955
                    elif content_change and (kind[1] is not None):
 
1956
                        # Versioned and changed, but not deleted
 
1957
                        has_changed_files = True
 
1958
                        break
 
1959
 
 
1960
            if has_changed_files:
 
1961
                # Make delta show ALL applicable changes in error message.
 
1962
                tree_delta = self.changes_from(self.basis_tree(),
 
1963
                    require_versioned=False, want_unversioned=True,
 
1964
                    specific_files=files)
 
1965
                for unknown_file in unknown_nested_files:
 
1966
                    if unknown_file not in tree_delta.unversioned:
 
1967
                        tree_delta.unversioned.extend((unknown_file,))
 
1968
                raise errors.BzrRemoveChangedFilesError(tree_delta)
 
1969
 
 
1970
        # Build inv_delta and delete files where applicable,
 
1971
        # do this before any modifications to inventory.
1789
1972
        for f in files:
1790
 
            fid = inv.path2id(f)
 
1973
            fid = self.path2id(f)
 
1974
            message = None
1791
1975
            if not fid:
1792
 
                note("%s is not versioned."%f)
 
1976
                message = "%s is not versioned." % (f,)
1793
1977
            else:
1794
1978
                if verbose:
1795
 
                    # having remove it, it must be either ignored or unknown
 
1979
                    # having removed it, it must be either ignored or unknown
1796
1980
                    if self.is_ignored(f):
1797
1981
                        new_status = 'I'
1798
1982
                    else:
1799
1983
                        new_status = '?'
1800
 
                    textui.show_status(new_status, inv[fid].kind, f,
 
1984
                    textui.show_status(new_status, self.kind(fid), f,
1801
1985
                                       to_file=to_file)
1802
 
                del inv[fid]
1803
 
 
1804
 
        self._write_inventory(inv)
 
1986
                # Unversion file
 
1987
                inv_delta.append((f, None, fid, None))
 
1988
                message = "removed %s" % (f,)
 
1989
 
 
1990
            if not keep_files:
 
1991
                abs_path = self.abspath(f)
 
1992
                if osutils.lexists(abs_path):
 
1993
                    if (osutils.isdir(abs_path) and
 
1994
                        len(os.listdir(abs_path)) > 0):
 
1995
                        if force:
 
1996
                            osutils.rmtree(abs_path)
 
1997
                        else:
 
1998
                            message = "%s is not an empty directory "\
 
1999
                                "and won't be deleted." % (f,)
 
2000
                    else:
 
2001
                        osutils.delete_any(abs_path)
 
2002
                        message = "deleted %s" % (f,)
 
2003
                elif message is not None:
 
2004
                    # Only care if we haven't done anything yet.
 
2005
                    message = "%s does not exist." % (f,)
 
2006
 
 
2007
            # Print only one message (if any) per file.
 
2008
            if message is not None:
 
2009
                note(message)
 
2010
        self.apply_inventory_delta(inv_delta)
1805
2011
 
1806
2012
    @needs_tree_write_lock
1807
 
    def revert(self, filenames, old_tree=None, backups=True, 
 
2013
    def revert(self, filenames=None, old_tree=None, backups=True,
1808
2014
               pb=DummyProgress(), report_changes=False):
1809
2015
        from bzrlib.conflicts import resolve
 
2016
        if filenames == []:
 
2017
            filenames = None
 
2018
            symbol_versioning.warn('Using [] to revert all files is deprecated'
 
2019
                ' as of bzr 0.91.  Please use None (the default) instead.',
 
2020
                DeprecationWarning, stacklevel=2)
1810
2021
        if old_tree is None:
1811
 
            old_tree = self.basis_tree()
1812
 
        conflicts = transform.revert(self, old_tree, filenames, backups, pb,
1813
 
                                     report_changes)
1814
 
        if not len(filenames):
1815
 
            self.set_parent_ids(self.get_parent_ids()[:1])
1816
 
            resolve(self)
 
2022
            basis_tree = self.basis_tree()
 
2023
            basis_tree.lock_read()
 
2024
            old_tree = basis_tree
1817
2025
        else:
1818
 
            resolve(self, filenames, ignore_misses=True)
 
2026
            basis_tree = None
 
2027
        try:
 
2028
            conflicts = transform.revert(self, old_tree, filenames, backups, pb,
 
2029
                                         report_changes)
 
2030
            if filenames is None and len(self.get_parent_ids()) > 1:
 
2031
                parent_trees = []
 
2032
                last_revision = self.last_revision()
 
2033
                if last_revision != NULL_REVISION:
 
2034
                    if basis_tree is None:
 
2035
                        basis_tree = self.basis_tree()
 
2036
                        basis_tree.lock_read()
 
2037
                    parent_trees.append((last_revision, basis_tree))
 
2038
                self.set_parent_trees(parent_trees)
 
2039
                resolve(self)
 
2040
            else:
 
2041
                resolve(self, filenames, ignore_misses=True, recursive=True)
 
2042
        finally:
 
2043
            if basis_tree is not None:
 
2044
                basis_tree.unlock()
1819
2045
        return conflicts
1820
2046
 
1821
2047
    def revision_tree(self, revision_id):
1856
2082
            name = os.path.basename(path)
1857
2083
            if name == "":
1858
2084
                continue
1859
 
            # fixme, there should be a factory function inv,add_?? 
 
2085
            # fixme, there should be a factory function inv,add_??
1860
2086
            if kind == 'directory':
1861
2087
                inv.add(InventoryDirectory(file_id, name, parent))
1862
2088
            elif kind == 'file':
1870
2096
    @needs_tree_write_lock
1871
2097
    def set_root_id(self, file_id):
1872
2098
        """Set the root id for this tree."""
1873
 
        # for compatability 
 
2099
        # for compatability
1874
2100
        if file_id is None:
1875
 
            symbol_versioning.warn(symbol_versioning.zero_twelve
1876
 
                % 'WorkingTree.set_root_id with fileid=None',
1877
 
                DeprecationWarning,
1878
 
                stacklevel=3)
1879
 
            file_id = ROOT_ID
1880
 
        else:
1881
 
            file_id = osutils.safe_file_id(file_id)
 
2101
            raise ValueError(
 
2102
                'WorkingTree.set_root_id with fileid=None')
 
2103
        file_id = osutils.safe_file_id(file_id)
1882
2104
        self._set_root_id(file_id)
1883
2105
 
1884
2106
    def _set_root_id(self, file_id):
1885
2107
        """Set the root id for this tree, in a format specific manner.
1886
2108
 
1887
 
        :param file_id: The file id to assign to the root. It must not be 
 
2109
        :param file_id: The file id to assign to the root. It must not be
1888
2110
            present in the current inventory or an error will occur. It must
1889
2111
            not be None, but rather a valid file id.
1890
2112
        """
1909
2131
 
1910
2132
    def unlock(self):
1911
2133
        """See Branch.unlock.
1912
 
        
 
2134
 
1913
2135
        WorkingTree locking just uses the Branch locking facilities.
1914
2136
        This is current because all working trees have an embedded branch
1915
2137
        within them. IF in the future, we were to make branch data shareable
1916
 
        between multiple working trees, i.e. via shared storage, then we 
 
2138
        between multiple working trees, i.e. via shared storage, then we
1917
2139
        would probably want to lock both the local tree, and the branch.
1918
2140
        """
1919
2141
        raise NotImplementedError(self.unlock)
1920
2142
 
1921
 
    def update(self):
 
2143
    def update(self, change_reporter=None, possible_transports=None):
1922
2144
        """Update a working tree along its branch.
1923
2145
 
1924
2146
        This will update the branch if its bound too, which means we have
1943
2165
          basis.
1944
2166
        - Do a 'normal' merge of the old branch basis if it is relevant.
1945
2167
        """
1946
 
        if self.branch.get_master_branch() is not None:
 
2168
        if self.branch.get_bound_location() is not None:
1947
2169
            self.lock_write()
1948
2170
            update_branch = True
1949
2171
        else:
1951
2173
            update_branch = False
1952
2174
        try:
1953
2175
            if update_branch:
1954
 
                old_tip = self.branch.update()
 
2176
                old_tip = self.branch.update(possible_transports)
1955
2177
            else:
1956
2178
                old_tip = None
1957
 
            return self._update_tree(old_tip)
 
2179
            return self._update_tree(old_tip, change_reporter)
1958
2180
        finally:
1959
2181
            self.unlock()
1960
2182
 
1961
2183
    @needs_tree_write_lock
1962
 
    def _update_tree(self, old_tip=None):
 
2184
    def _update_tree(self, old_tip=None, change_reporter=None):
1963
2185
        """Update a tree to the master branch.
1964
2186
 
1965
2187
        :param old_tip: if supplied, the previous tip revision the branch,
1971
2193
        # cant set that until we update the working trees last revision to be
1972
2194
        # one from the new branch, because it will just get absorbed by the
1973
2195
        # parent de-duplication logic.
1974
 
        # 
 
2196
        #
1975
2197
        # We MUST save it even if an error occurs, because otherwise the users
1976
2198
        # local work is unreferenced and will appear to have been lost.
1977
 
        # 
 
2199
        #
1978
2200
        result = 0
1979
2201
        try:
1980
2202
            last_rev = self.get_parent_ids()[0]
1981
2203
        except IndexError:
1982
 
            last_rev = None
1983
 
        if last_rev != self.branch.last_revision():
 
2204
            last_rev = _mod_revision.NULL_REVISION
 
2205
        if last_rev != _mod_revision.ensure_null(self.branch.last_revision()):
1984
2206
            # merge tree state up to new branch tip.
1985
2207
            basis = self.basis_tree()
1986
2208
            basis.lock_read()
1987
2209
            try:
1988
2210
                to_tree = self.branch.basis_tree()
1989
2211
                if basis.inventory.root is None:
1990
 
                    self.set_root_id(to_tree.inventory.root.file_id)
 
2212
                    self.set_root_id(to_tree.get_root_id())
1991
2213
                    self.flush()
1992
2214
                result += merge.merge_inner(
1993
2215
                                      self.branch,
1994
2216
                                      to_tree,
1995
2217
                                      basis,
1996
 
                                      this_tree=self)
 
2218
                                      this_tree=self,
 
2219
                                      change_reporter=change_reporter)
1997
2220
            finally:
1998
2221
                basis.unlock()
1999
2222
            # TODO - dedup parents list with things merged by pull ?
2001
2224
            parent_trees = [(self.branch.last_revision(), to_tree)]
2002
2225
            merges = self.get_parent_ids()[1:]
2003
2226
            # Ideally we ask the tree for the trees here, that way the working
2004
 
            # tree can decide whether to give us teh entire tree or give us a
 
2227
            # tree can decide whether to give us the entire tree or give us a
2005
2228
            # lazy initialised tree. dirstate for instance will have the trees
2006
2229
            # in ram already, whereas a last-revision + basis-inventory tree
2007
2230
            # will not, but also does not need them when setting parents.
2008
2231
            for parent in merges:
2009
2232
                parent_trees.append(
2010
2233
                    (parent, self.branch.repository.revision_tree(parent)))
2011
 
            if old_tip is not None:
 
2234
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
2012
2235
                parent_trees.append(
2013
2236
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
2014
2237
            self.set_parent_trees(parent_trees)
2017
2240
            # the working tree had the same last-revision as the master
2018
2241
            # branch did. We may still have pivot local work from the local
2019
2242
            # branch into old_tip:
2020
 
            if old_tip is not None:
 
2243
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
2021
2244
                self.add_parent_tree_id(old_tip)
2022
 
        if old_tip and old_tip != last_rev:
 
2245
        if (old_tip is not None and not _mod_revision.is_null(old_tip)
 
2246
            and old_tip != last_rev):
2023
2247
            # our last revision was not the prior branch last revision
2024
2248
            # and we have converted that last revision to a pending merge.
2025
2249
            # base is somewhere between the branch tip now
2032
2256
            #       inventory and calls tree._write_inventory(). Ultimately we
2033
2257
            #       should be able to remove this extra flush.
2034
2258
            self.flush()
2035
 
            from bzrlib.revision import common_ancestor
2036
 
            try:
2037
 
                base_rev_id = common_ancestor(self.branch.last_revision(),
2038
 
                                              old_tip,
2039
 
                                              self.branch.repository)
2040
 
            except errors.NoCommonAncestor:
2041
 
                base_rev_id = None
 
2259
            graph = self.branch.repository.get_graph()
 
2260
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
 
2261
                                                old_tip)
2042
2262
            base_tree = self.branch.repository.revision_tree(base_rev_id)
2043
2263
            other_tree = self.branch.repository.revision_tree(old_tip)
2044
2264
            result += merge.merge_inner(
2045
2265
                                  self.branch,
2046
2266
                                  other_tree,
2047
2267
                                  base_tree,
2048
 
                                  this_tree=self)
 
2268
                                  this_tree=self,
 
2269
                                  change_reporter=change_reporter)
2049
2270
        return result
2050
2271
 
2051
2272
    def _write_hashcache_if_dirty(self):
2103
2324
    def walkdirs(self, prefix=""):
2104
2325
        """Walk the directories of this tree.
2105
2326
 
 
2327
        returns a generator which yields items in the form:
 
2328
                ((curren_directory_path, fileid),
 
2329
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
 
2330
                   file1_kind), ... ])
 
2331
 
2106
2332
        This API returns a generator, which is only valid during the current
2107
2333
        tree transaction - within a single lock_read or lock_write duration.
2108
2334
 
2109
 
        If the tree is not locked, it may cause an error to be raised, depending
2110
 
        on the tree implementation.
 
2335
        If the tree is not locked, it may cause an error to be raised,
 
2336
        depending on the tree implementation.
2111
2337
        """
2112
2338
        disk_top = self.abspath(prefix)
2113
2339
        if disk_top.endswith('/'):
2119
2345
            current_disk = disk_iterator.next()
2120
2346
            disk_finished = False
2121
2347
        except OSError, e:
2122
 
            if e.errno != errno.ENOENT:
 
2348
            if not (e.errno == errno.ENOENT or
 
2349
                (sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
2123
2350
                raise
2124
2351
            current_disk = None
2125
2352
            disk_finished = True
2130
2357
            current_inv = None
2131
2358
            inv_finished = True
2132
2359
        while not inv_finished or not disk_finished:
 
2360
            if current_disk:
 
2361
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
 
2362
                    cur_disk_dir_content) = current_disk
 
2363
            else:
 
2364
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
 
2365
                    cur_disk_dir_content) = ((None, None), None)
2133
2366
            if not disk_finished:
2134
2367
                # strip out .bzr dirs
2135
 
                if current_disk[0][1][top_strip_len:] == '':
2136
 
                    # osutils.walkdirs can be made nicer - 
 
2368
                if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
 
2369
                    len(cur_disk_dir_content) > 0):
 
2370
                    # osutils.walkdirs can be made nicer -
2137
2371
                    # yield the path-from-prefix rather than the pathjoined
2138
2372
                    # value.
2139
 
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
2140
 
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
 
2373
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
 
2374
                        ('.bzr', '.bzr'))
 
2375
                    if (bzrdir_loc < len(cur_disk_dir_content)
 
2376
                        and cur_disk_dir_content[bzrdir_loc][0] == '.bzr'):
2141
2377
                        # we dont yield the contents of, or, .bzr itself.
2142
 
                        del current_disk[1][bzrdir_loc]
 
2378
                        del cur_disk_dir_content[bzrdir_loc]
2143
2379
            if inv_finished:
2144
2380
                # everything is unknown
2145
2381
                direction = 1
2147
2383
                # everything is missing
2148
2384
                direction = -1
2149
2385
            else:
2150
 
                direction = cmp(current_inv[0][0], current_disk[0][0])
 
2386
                direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
2151
2387
            if direction > 0:
2152
2388
                # disk is before inventory - unknown
2153
2389
                dirblock = [(relpath, basename, kind, stat, None, None) for
2154
 
                    relpath, basename, kind, stat, top_path in current_disk[1]]
2155
 
                yield (current_disk[0][0], None), dirblock
 
2390
                    relpath, basename, kind, stat, top_path in
 
2391
                    cur_disk_dir_content]
 
2392
                yield (cur_disk_dir_relpath, None), dirblock
2156
2393
                try:
2157
2394
                    current_disk = disk_iterator.next()
2158
2395
                except StopIteration:
2160
2397
            elif direction < 0:
2161
2398
                # inventory is before disk - missing.
2162
2399
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2163
 
                    for relpath, basename, dkind, stat, fileid, kind in 
 
2400
                    for relpath, basename, dkind, stat, fileid, kind in
2164
2401
                    current_inv[1]]
2165
2402
                yield (current_inv[0][0], current_inv[0][1]), dirblock
2166
2403
                try:
2172
2409
                # merge the inventory and disk data together
2173
2410
                dirblock = []
2174
2411
                for relpath, subiterator in itertools.groupby(sorted(
2175
 
                    current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
 
2412
                    current_inv[1] + cur_disk_dir_content,
 
2413
                    key=operator.itemgetter(0)), operator.itemgetter(1)):
2176
2414
                    path_elements = list(subiterator)
2177
2415
                    if len(path_elements) == 2:
2178
2416
                        inv_row, disk_row = path_elements
2204
2442
                    disk_finished = True
2205
2443
 
2206
2444
    def _walkdirs(self, prefix=""):
 
2445
        """Walk the directories of this tree.
 
2446
 
 
2447
           :prefix: is used as the directrory to start with.
 
2448
           returns a generator which yields items in the form:
 
2449
                ((curren_directory_path, fileid),
 
2450
                 [(file1_path, file1_name, file1_kind, None, file1_id,
 
2451
                   file1_kind), ... ])
 
2452
        """
2207
2453
        _directory = 'directory'
2208
2454
        # get the root in the inventory
2209
2455
        inv = self.inventory
2223
2469
                relroot = ""
2224
2470
            # FIXME: stash the node in pending
2225
2471
            entry = inv[top_id]
2226
 
            for name, child in entry.sorted_children():
2227
 
                dirblock.append((relroot + name, name, child.kind, None,
2228
 
                    child.file_id, child.kind
2229
 
                    ))
 
2472
            if entry.kind == 'directory':
 
2473
                for name, child in entry.sorted_children():
 
2474
                    dirblock.append((relroot + name, name, child.kind, None,
 
2475
                        child.file_id, child.kind
 
2476
                        ))
2230
2477
            yield (currentdir[0], entry.file_id), dirblock
2231
2478
            # push the user specified dirs from dirblock
2232
2479
            for dir in reversed(dirblock):
2265
2512
        self.set_conflicts(un_resolved)
2266
2513
        return un_resolved, resolved
2267
2514
 
 
2515
    @needs_read_lock
 
2516
    def _check(self):
 
2517
        tree_basis = self.basis_tree()
 
2518
        tree_basis.lock_read()
 
2519
        try:
 
2520
            repo_basis = self.branch.repository.revision_tree(
 
2521
                self.last_revision())
 
2522
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
 
2523
                raise errors.BzrCheckError(
 
2524
                    "Mismatched basis inventory content.")
 
2525
            self._validate()
 
2526
        finally:
 
2527
            tree_basis.unlock()
 
2528
 
2268
2529
    def _validate(self):
2269
2530
        """Validate internal structures.
2270
2531
 
2276
2537
        """
2277
2538
        return
2278
2539
 
 
2540
    @needs_read_lock
 
2541
    def _get_rules_searcher(self, default_searcher):
 
2542
        """See Tree._get_rules_searcher."""
 
2543
        if self._rules_searcher is None:
 
2544
            self._rules_searcher = super(WorkingTree,
 
2545
                self)._get_rules_searcher(default_searcher)
 
2546
        return self._rules_searcher
 
2547
 
 
2548
    def get_shelf_manager(self):
 
2549
        """Return the ShelfManager for this WorkingTree."""
 
2550
        from bzrlib.shelf import ShelfManager
 
2551
        return ShelfManager(self, self._transport)
 
2552
 
2279
2553
 
2280
2554
class WorkingTree2(WorkingTree):
2281
2555
    """This is the Format 2 working tree.
2282
2556
 
2283
 
    This was the first weave based working tree. 
 
2557
    This was the first weave based working tree.
2284
2558
     - uses os locks for locking.
2285
2559
     - uses the branch last-revision.
2286
2560
    """
2310
2584
            raise
2311
2585
 
2312
2586
    def unlock(self):
 
2587
        # do non-implementation specific cleanup
 
2588
        self._cleanup()
 
2589
 
2313
2590
        # we share control files:
2314
2591
        if self._control_files._lock_count == 3:
2315
2592
            # _inventory_is_modified is always False during a read lock.
2316
2593
            if self._inventory_is_modified:
2317
2594
                self.flush()
2318
2595
            self._write_hashcache_if_dirty()
2319
 
                    
 
2596
 
2320
2597
        # reverse order of locking.
2321
2598
        try:
2322
2599
            return self._control_files.unlock()
2338
2615
    def _last_revision(self):
2339
2616
        """See Mutable.last_revision."""
2340
2617
        try:
2341
 
            return osutils.safe_revision_id(
2342
 
                        self._control_files.get('last-revision').read())
 
2618
            return self._transport.get_bytes('last-revision')
2343
2619
        except errors.NoSuchFile:
2344
 
            return None
 
2620
            return _mod_revision.NULL_REVISION
2345
2621
 
2346
2622
    def _change_last_revision(self, revision_id):
2347
2623
        """See WorkingTree._change_last_revision."""
2348
2624
        if revision_id is None or revision_id == NULL_REVISION:
2349
2625
            try:
2350
 
                self._control_files._transport.delete('last-revision')
 
2626
                self._transport.delete('last-revision')
2351
2627
            except errors.NoSuchFile:
2352
2628
                pass
2353
2629
            return False
2354
2630
        else:
2355
 
            self._control_files.put_bytes('last-revision', revision_id)
 
2631
            self._transport.put_bytes('last-revision', revision_id,
 
2632
                mode=self.bzrdir._get_file_mode())
2356
2633
            return True
2357
2634
 
2358
2635
    @needs_tree_write_lock
2359
2636
    def set_conflicts(self, conflicts):
2360
 
        self._put_rio('conflicts', conflicts.to_stanzas(), 
 
2637
        self._put_rio('conflicts', conflicts.to_stanzas(),
2361
2638
                      CONFLICT_HEADER_1)
2362
2639
 
2363
2640
    @needs_tree_write_lock
2370
2647
    @needs_read_lock
2371
2648
    def conflicts(self):
2372
2649
        try:
2373
 
            confile = self._control_files.get('conflicts')
 
2650
            confile = self._transport.get('conflicts')
2374
2651
        except errors.NoSuchFile:
2375
2652
            return _mod_conflicts.ConflictList()
2376
2653
        try:
2377
 
            if confile.next() != CONFLICT_HEADER_1 + '\n':
 
2654
            try:
 
2655
                if confile.next() != CONFLICT_HEADER_1 + '\n':
 
2656
                    raise errors.ConflictFormatError()
 
2657
            except StopIteration:
2378
2658
                raise errors.ConflictFormatError()
2379
 
        except StopIteration:
2380
 
            raise errors.ConflictFormatError()
2381
 
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
 
2659
            return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
 
2660
        finally:
 
2661
            confile.close()
2382
2662
 
2383
2663
    def unlock(self):
 
2664
        # do non-implementation specific cleanup
 
2665
        self._cleanup()
2384
2666
        if self._control_files._lock_count == 1:
2385
2667
            # _inventory_is_modified is always False during a read lock.
2386
2668
            if self._inventory_is_modified:
2399
2681
            return path[:-len(suffix)]
2400
2682
 
2401
2683
 
2402
 
@deprecated_function(zero_eight)
2403
 
def is_control_file(filename):
2404
 
    """See WorkingTree.is_control_filename(filename)."""
2405
 
    ## FIXME: better check
2406
 
    filename = normpath(filename)
2407
 
    while filename != '':
2408
 
        head, tail = os.path.split(filename)
2409
 
        ## mutter('check %r for control file' % ((head, tail),))
2410
 
        if tail == '.bzr':
2411
 
            return True
2412
 
        if filename == head:
2413
 
            break
2414
 
        filename = head
2415
 
    return False
2416
 
 
2417
 
 
2418
2684
class WorkingTreeFormat(object):
2419
2685
    """An encapsulation of the initialization and open routines for a format.
2420
2686
 
2423
2689
     * a format string,
2424
2690
     * an open routine.
2425
2691
 
2426
 
    Formats are placed in an dict by their format string for reference 
 
2692
    Formats are placed in an dict by their format string for reference
2427
2693
    during workingtree opening. Its not required that these be instances, they
2428
 
    can be classes themselves with class methods - it simply depends on 
 
2694
    can be classes themselves with class methods - it simply depends on
2429
2695
    whether state is needed for a given format or not.
2430
2696
 
2431
2697
    Once a format is deprecated, just deprecate the initialize and open
2432
 
    methods on the format class. Do not deprecate the object, as the 
 
2698
    methods on the format class. Do not deprecate the object, as the
2433
2699
    object will be created every time regardless.
2434
2700
    """
2435
2701
 
2453
2719
        except errors.NoSuchFile:
2454
2720
            raise errors.NoWorkingTree(base=transport.base)
2455
2721
        except KeyError:
2456
 
            raise errors.UnknownFormatError(format=format_string)
 
2722
            raise errors.UnknownFormatError(format=format_string,
 
2723
                                            kind="working tree")
2457
2724
 
2458
2725
    def __eq__(self, other):
2459
2726
        return self.__class__ is other.__class__
2478
2745
        """Is this format supported?
2479
2746
 
2480
2747
        Supported formats can be initialized and opened.
2481
 
        Unsupported formats may not support initialization or committing or 
 
2748
        Unsupported formats may not support initialization or committing or
2482
2749
        some other features depending on the reason for not being supported.
2483
2750
        """
2484
2751
        return True
2485
2752
 
 
2753
    def supports_content_filtering(self):
 
2754
        """True if this format supports content filtering."""
 
2755
        return False
 
2756
 
 
2757
    def supports_views(self):
 
2758
        """True if this format supports stored views."""
 
2759
        return False
 
2760
 
2486
2761
    @classmethod
2487
2762
    def register_format(klass, format):
2488
2763
        klass._formats[format.get_format_string()] = format
2493
2768
 
2494
2769
    @classmethod
2495
2770
    def unregister_format(klass, format):
2496
 
        assert klass._formats[format.get_format_string()] is format
2497
2771
        del klass._formats[format.get_format_string()]
2498
2772
 
2499
2773
 
2500
2774
class WorkingTreeFormat2(WorkingTreeFormat):
2501
 
    """The second working tree format. 
 
2775
    """The second working tree format.
2502
2776
 
2503
2777
    This format modified the hash cache from the format 1 hash cache.
2504
2778
    """
2509
2783
        """See WorkingTreeFormat.get_format_description()."""
2510
2784
        return "Working tree format 2"
2511
2785
 
2512
 
    def stub_initialize_remote(self, control_files):
2513
 
        """As a special workaround create critical control files for a remote working tree
2514
 
        
 
2786
    def _stub_initialize_on_transport(self, transport, file_mode):
 
2787
        """Workaround: create control files for a remote working tree.
 
2788
 
2515
2789
        This ensures that it can later be updated and dealt with locally,
2516
 
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
 
2790
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
2517
2791
        no working tree.  (See bug #43064).
2518
2792
        """
2519
2793
        sio = StringIO()
2520
2794
        inv = Inventory()
2521
 
        xml5.serializer_v5.write_inventory(inv, sio)
 
2795
        xml5.serializer_v5.write_inventory(inv, sio, working=True)
2522
2796
        sio.seek(0)
2523
 
        control_files.put('inventory', sio)
2524
 
 
2525
 
        control_files.put_bytes('pending-merges', '')
2526
 
        
2527
 
 
2528
 
    def initialize(self, a_bzrdir, revision_id=None):
 
2797
        transport.put_file('inventory', sio, file_mode)
 
2798
        transport.put_bytes('pending-merges', '', file_mode)
 
2799
 
 
2800
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
2801
                   accelerator_tree=None, hardlink=False):
2529
2802
        """See WorkingTreeFormat.initialize()."""
2530
2803
        if not isinstance(a_bzrdir.transport, LocalTransport):
2531
2804
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2532
 
        branch = a_bzrdir.open_branch()
2533
 
        if revision_id is not None:
2534
 
            revision_id = osutils.safe_revision_id(revision_id)
2535
 
            branch.lock_write()
2536
 
            try:
2537
 
                revision_history = branch.revision_history()
2538
 
                try:
2539
 
                    position = revision_history.index(revision_id)
2540
 
                except ValueError:
2541
 
                    raise errors.NoSuchRevision(branch, revision_id)
2542
 
                branch.set_revision_history(revision_history[:position + 1])
2543
 
            finally:
2544
 
                branch.unlock()
2545
 
        revision = branch.last_revision()
 
2805
        if from_branch is not None:
 
2806
            branch = from_branch
 
2807
        else:
 
2808
            branch = a_bzrdir.open_branch()
 
2809
        if revision_id is None:
 
2810
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2811
        branch.lock_write()
 
2812
        try:
 
2813
            branch.generate_revision_history(revision_id)
 
2814
        finally:
 
2815
            branch.unlock()
2546
2816
        inv = Inventory()
2547
2817
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2548
2818
                         branch,
2550
2820
                         _internal=True,
2551
2821
                         _format=self,
2552
2822
                         _bzrdir=a_bzrdir)
2553
 
        basis_tree = branch.repository.revision_tree(revision)
 
2823
        basis_tree = branch.repository.revision_tree(revision_id)
2554
2824
        if basis_tree.inventory.root is not None:
2555
 
            wt.set_root_id(basis_tree.inventory.root.file_id)
 
2825
            wt.set_root_id(basis_tree.get_root_id())
2556
2826
        # set the parent list and cache the basis tree.
2557
 
        wt.set_parent_trees([(revision, basis_tree)])
 
2827
        if _mod_revision.is_null(revision_id):
 
2828
            parent_trees = []
 
2829
        else:
 
2830
            parent_trees = [(revision_id, basis_tree)]
 
2831
        wt.set_parent_trees(parent_trees)
2558
2832
        transform.build_tree(basis_tree, wt)
2559
2833
        return wt
2560
2834
 
2590
2864
        - is new in bzr 0.8
2591
2865
        - uses a LockDir to guard access for writes.
2592
2866
    """
2593
 
    
 
2867
 
2594
2868
    upgrade_recommended = True
2595
2869
 
2596
2870
    def get_format_string(self):
2613
2887
 
2614
2888
    def _open_control_files(self, a_bzrdir):
2615
2889
        transport = a_bzrdir.get_workingtree_transport(None)
2616
 
        return LockableFiles(transport, self._lock_file_name, 
 
2890
        return LockableFiles(transport, self._lock_file_name,
2617
2891
                             self._lock_class)
2618
2892
 
2619
 
    def initialize(self, a_bzrdir, revision_id=None):
 
2893
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
2894
                   accelerator_tree=None, hardlink=False):
2620
2895
        """See WorkingTreeFormat.initialize().
2621
 
        
2622
 
        revision_id allows creating a working tree at a different
2623
 
        revision than the branch is at.
 
2896
 
 
2897
        :param revision_id: if supplied, create a working tree at a different
 
2898
            revision than the branch is at.
 
2899
        :param accelerator_tree: A tree which can be used for retrieving file
 
2900
            contents more quickly than the revision tree, i.e. a workingtree.
 
2901
            The revision tree will be used for cases where accelerator_tree's
 
2902
            content is different.
 
2903
        :param hardlink: If true, hard-link files from accelerator_tree,
 
2904
            where possible.
2624
2905
        """
2625
2906
        if not isinstance(a_bzrdir.transport, LocalTransport):
2626
2907
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2628
2909
        control_files = self._open_control_files(a_bzrdir)
2629
2910
        control_files.create_lock()
2630
2911
        control_files.lock_write()
2631
 
        control_files.put_utf8('format', self.get_format_string())
2632
 
        branch = a_bzrdir.open_branch()
 
2912
        transport.put_bytes('format', self.get_format_string(),
 
2913
            mode=a_bzrdir._get_file_mode())
 
2914
        if from_branch is not None:
 
2915
            branch = from_branch
 
2916
        else:
 
2917
            branch = a_bzrdir.open_branch()
2633
2918
        if revision_id is None:
2634
 
            revision_id = branch.last_revision()
2635
 
        else:
2636
 
            revision_id = osutils.safe_revision_id(revision_id)
 
2919
            revision_id = _mod_revision.ensure_null(branch.last_revision())
2637
2920
        # WorkingTree3 can handle an inventory which has a unique root id.
2638
2921
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
2639
2922
        # those trees. And because there isn't a format bump inbetween, we
2652
2935
            basis_tree = branch.repository.revision_tree(revision_id)
2653
2936
            # only set an explicit root id if there is one to set.
2654
2937
            if basis_tree.inventory.root is not None:
2655
 
                wt.set_root_id(basis_tree.inventory.root.file_id)
 
2938
                wt.set_root_id(basis_tree.get_root_id())
2656
2939
            if revision_id == NULL_REVISION:
2657
2940
                wt.set_parent_trees([])
2658
2941
            else:
2687
2970
 
2688
2971
    def _open(self, a_bzrdir, control_files):
2689
2972
        """Open the tree itself.
2690
 
        
 
2973
 
2691
2974
        :param a_bzrdir: the dir for the tree.
2692
2975
        :param control_files: the control files for the tree.
2693
2976
        """
2703
2986
 
2704
2987
__default_format = WorkingTreeFormat4()
2705
2988
WorkingTreeFormat.register_format(__default_format)
 
2989
WorkingTreeFormat.register_format(WorkingTreeFormat6())
 
2990
WorkingTreeFormat.register_format(WorkingTreeFormat5())
2706
2991
WorkingTreeFormat.register_format(WorkingTreeFormat3())
2707
2992
WorkingTreeFormat.set_default_format(__default_format)
2708
2993
# formats which have no format string are not discoverable
2709
2994
# and not independently creatable, so are not registered.
2710
2995
_legacy_formats = [WorkingTreeFormat2(),
2711
2996
                   ]
2712
 
 
2713
 
 
2714
 
class WorkingTreeTestProviderAdapter(object):
2715
 
    """A tool to generate a suite testing multiple workingtree formats at once.
2716
 
 
2717
 
    This is done by copying the test once for each transport and injecting
2718
 
    the transport_server, transport_readonly_server, and workingtree_format
2719
 
    classes into each copy. Each copy is also given a new id() to make it
2720
 
    easy to identify.
2721
 
    """
2722
 
 
2723
 
    def __init__(self, transport_server, transport_readonly_server, formats):
2724
 
        self._transport_server = transport_server
2725
 
        self._transport_readonly_server = transport_readonly_server
2726
 
        self._formats = formats
2727
 
    
2728
 
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
2729
 
        """Clone test for adaption."""
2730
 
        new_test = deepcopy(test)
2731
 
        new_test.transport_server = self._transport_server
2732
 
        new_test.transport_readonly_server = self._transport_readonly_server
2733
 
        new_test.bzrdir_format = bzrdir_format
2734
 
        new_test.workingtree_format = workingtree_format
2735
 
        def make_new_test_id():
2736
 
            new_id = "%s(%s)" % (test.id(), variation)
2737
 
            return lambda: new_id
2738
 
        new_test.id = make_new_test_id()
2739
 
        return new_test
2740
 
    
2741
 
    def adapt(self, test):
2742
 
        from bzrlib.tests import TestSuite
2743
 
        result = TestSuite()
2744
 
        for workingtree_format, bzrdir_format in self._formats:
2745
 
            new_test = self._clone_test(
2746
 
                test,
2747
 
                bzrdir_format,
2748
 
                workingtree_format, workingtree_format.__class__.__name__)
2749
 
            result.addTest(new_test)
2750
 
        return result