~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

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