~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Aaron Bentley
  • Date: 2007-03-09 21:46:40 UTC
  • mto: (2323.6.9 0.15-integration)
  • mto: This revision was merged to the branch mainline in revision 2330.
  • Revision ID: abentley@panoramicfeedback.com-20070309214640-nnxk7g37bygoz50c
Add (set|get)_public_branch

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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
50
50
import stat
 
51
from time import time
 
52
import warnings
51
53
import re
52
54
 
53
55
import bzrlib
55
57
    branch,
56
58
    bzrdir,
57
59
    conflicts as _mod_conflicts,
 
60
    dirstate,
58
61
    errors,
59
62
    generate_ids,
60
63
    globbing,
61
 
    graph as _mod_graph,
62
64
    hashcache,
63
65
    ignores,
64
 
    inventory,
65
66
    merge,
66
 
    revision as _mod_revision,
 
67
    osutils,
67
68
    revisiontree,
 
69
    repository,
68
70
    textui,
69
 
    trace,
70
71
    transform,
71
 
    ui,
72
 
    views,
 
72
    urlutils,
73
73
    xml5,
 
74
    xml6,
74
75
    xml7,
75
76
    )
76
77
import bzrlib.branch
77
78
from bzrlib.transport import get_transport
78
 
from bzrlib.workingtree_4 import (
79
 
    WorkingTreeFormat4,
80
 
    WorkingTreeFormat5,
81
 
    WorkingTreeFormat6,
82
 
    )
 
79
import bzrlib.ui
 
80
from bzrlib.workingtree_4 import WorkingTreeFormat4
83
81
""")
84
82
 
85
83
from bzrlib import symbol_versioning
86
84
from bzrlib.decorators import needs_read_lock, needs_write_lock
87
 
from bzrlib.lockable_files import LockableFiles
 
85
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
 
86
from bzrlib.lockable_files import LockableFiles, TransportLock
88
87
from bzrlib.lockdir import LockDir
89
88
import bzrlib.mutabletree
90
89
from bzrlib.mutabletree import needs_tree_write_lock
91
 
from bzrlib import osutils
92
90
from bzrlib.osutils import (
 
91
    compact_date,
93
92
    file_kind,
94
93
    isdir,
95
94
    normpath,
96
95
    pathjoin,
 
96
    rand_chars,
97
97
    realpath,
98
98
    safe_unicode,
99
99
    splitpath,
100
100
    supports_executable,
101
101
    )
102
 
from bzrlib.filters import filtered_input_file
103
102
from bzrlib.trace import mutter, note
104
103
from bzrlib.transport.local import LocalTransport
105
104
from bzrlib.progress import DummyProgress, ProgressPhase
106
 
from bzrlib.revision import CURRENT_REVISION
 
105
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
107
106
from bzrlib.rio import RioReader, rio_file, Stanza
108
 
from bzrlib.symbol_versioning import (
109
 
    deprecated_passed,
110
 
    DEPRECATED_PARAMETER,
111
 
    )
 
107
from bzrlib.symbol_versioning import (deprecated_passed,
 
108
        deprecated_method,
 
109
        deprecated_function,
 
110
        DEPRECATED_PARAMETER,
 
111
        zero_eight,
 
112
        zero_eleven,
 
113
        zero_thirteen,
 
114
        )
112
115
 
113
116
 
114
117
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
115
118
CONFLICT_HEADER_1 = "BZR conflict list format 1"
116
119
 
117
 
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
 
120
 
 
121
@deprecated_function(zero_thirteen)
 
122
def gen_file_id(name):
 
123
    """Return new file id for the basename 'name'.
 
124
 
 
125
    Use bzrlib.generate_ids.gen_file_id() instead
 
126
    """
 
127
    return generate_ids.gen_file_id(name)
 
128
 
 
129
 
 
130
@deprecated_function(zero_thirteen)
 
131
def gen_root_id():
 
132
    """Return a new tree-root file id.
 
133
 
 
134
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
 
135
    """
 
136
    return generate_ids.gen_root_id()
118
137
 
119
138
 
120
139
class TreeEntry(object):
121
140
    """An entry that implements the minimum interface used by commands.
122
141
 
123
 
    This needs further inspection, it may be better to have
 
142
    This needs further inspection, it may be better to have 
124
143
    InventoryEntries without ids - though that seems wrong. For now,
125
144
    this is a parallel hierarchy to InventoryEntry, and needs to become
126
145
    one of several things: decorates to that hierarchy, children of, or
129
148
    no InventoryEntry available - i.e. for unversioned objects.
130
149
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
131
150
    """
132
 
 
 
151
 
133
152
    def __eq__(self, other):
134
153
        # yes, this us ugly, TODO: best practice __eq__ style.
135
154
        return (isinstance(other, TreeEntry)
136
155
                and other.__class__ == self.__class__)
137
 
 
 
156
 
138
157
    def kind_character(self):
139
158
        return "???"
140
159
 
182
201
    not listed in the Inventory and vice versa.
183
202
    """
184
203
 
185
 
    # override this to set the strategy for storing views
186
 
    def _make_views(self):
187
 
        return views.DisabledViews(self)
188
 
 
189
204
    def __init__(self, basedir='.',
190
205
                 branch=DEPRECATED_PARAMETER,
191
206
                 _inventory=None,
193
208
                 _internal=False,
194
209
                 _format=None,
195
210
                 _bzrdir=None):
196
 
        """Construct a WorkingTree instance. This is not a public API.
 
211
        """Construct a WorkingTree for basedir.
197
212
 
198
 
        :param branch: A branch to override probing for the branch.
 
213
        If the branch is not supplied, it is opened automatically.
 
214
        If the branch is supplied, it must be the branch for this basedir.
 
215
        (branch.base is not cross checked, because for remote branches that
 
216
        would be meaningless).
199
217
        """
200
218
        self._format = _format
201
219
        self.bzrdir = _bzrdir
202
220
        if not _internal:
203
 
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
204
 
                "WorkingTree.open() to obtain a WorkingTree.")
 
221
            # not created via open etc.
 
222
            warnings.warn("WorkingTree() is deprecated as of bzr version 0.8. "
 
223
                 "Please use bzrdir.open_workingtree or WorkingTree.open().",
 
224
                 DeprecationWarning,
 
225
                 stacklevel=2)
 
226
            wt = WorkingTree.open(basedir)
 
227
            self._branch = wt.branch
 
228
            self.basedir = wt.basedir
 
229
            self._control_files = wt._control_files
 
230
            self._hashcache = wt._hashcache
 
231
            self._set_inventory(wt._inventory, dirty=False)
 
232
            self._format = wt._format
 
233
            self.bzrdir = wt.bzrdir
 
234
        assert isinstance(basedir, basestring), \
 
235
            "base directory %r is not a string" % basedir
205
236
        basedir = safe_unicode(basedir)
206
237
        mutter("opening working tree %r", basedir)
207
238
        if deprecated_passed(branch):
 
239
            if not _internal:
 
240
                warnings.warn("WorkingTree(..., branch=XXX) is deprecated"
 
241
                     " as of bzr 0.8. Please use bzrdir.open_workingtree() or"
 
242
                     " WorkingTree.open().",
 
243
                     DeprecationWarning,
 
244
                     stacklevel=2
 
245
                     )
208
246
            self._branch = branch
209
247
        else:
210
248
            self._branch = self.bzrdir.open_branch()
215
253
            self._control_files = self.branch.control_files
216
254
        else:
217
255
            # assume all other formats have their own control files.
 
256
            assert isinstance(_control_files, LockableFiles), \
 
257
                    "_control_files must be a LockableFiles, not %r" \
 
258
                    % _control_files
218
259
            self._control_files = _control_files
219
 
        self._transport = self._control_files._transport
220
260
        # update the whole cache up front and write to disk if anything changed;
221
261
        # in the future we might want to do this more selectively
222
262
        # two possible ways offer themselves : in self._unlock, write the cache
226
266
        wt_trans = self.bzrdir.get_workingtree_transport(None)
227
267
        cache_filename = wt_trans.local_abspath('stat-cache')
228
268
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
229
 
            self.bzrdir._get_file_mode(),
230
 
            self._content_filter_stack_provider())
 
269
                                              self._control_files._file_mode)
231
270
        hc = self._hashcache
232
271
        hc.read()
233
272
        # is this scan needed ? it makes things kinda slow.
238
277
            hc.write()
239
278
 
240
279
        if _inventory is None:
241
 
            # This will be acquired on lock_read() or lock_write()
242
280
            self._inventory_is_modified = False
243
 
            self._inventory = None
 
281
            self.read_working_inventory()
244
282
        else:
245
283
            # the caller of __init__ has provided an inventory,
246
284
            # we assume they know what they are doing - as its only
247
285
            # the Format factory and creation methods that are
248
286
            # permitted to do this.
249
287
            self._set_inventory(_inventory, dirty=False)
250
 
        self._detect_case_handling()
251
 
        self._rules_searcher = None
252
 
        self.views = self._make_views()
253
 
 
254
 
    def _detect_case_handling(self):
255
 
        wt_trans = self.bzrdir.get_workingtree_transport(None)
256
 
        try:
257
 
            wt_trans.stat("FoRMaT")
258
 
        except errors.NoSuchFile:
259
 
            self.case_sensitive = True
260
 
        else:
261
 
            self.case_sensitive = False
262
 
 
263
 
        self._setup_directory_is_tree_reference()
264
288
 
265
289
    branch = property(
266
290
        fget=lambda self: self._branch,
281
305
        self._control_files.break_lock()
282
306
        self.branch.break_lock()
283
307
 
284
 
    def _get_check_refs(self):
285
 
        """Return the references needed to perform a check of this tree.
286
 
        
287
 
        The default implementation returns no refs, and is only suitable for
288
 
        trees that have no local caching and can commit on ghosts at any time.
289
 
 
290
 
        :seealso: bzrlib.check for details about check_refs.
291
 
        """
292
 
        return []
293
 
 
294
308
    def requires_rich_root(self):
295
309
        return self._format.requires_rich_root
296
310
 
297
311
    def supports_tree_reference(self):
298
312
        return False
299
313
 
300
 
    def supports_content_filtering(self):
301
 
        return self._format.supports_content_filtering()
302
 
 
303
 
    def supports_views(self):
304
 
        return self.views.supports_views()
305
 
 
306
314
    def _set_inventory(self, inv, dirty):
307
315
        """Set the internal cached inventory.
308
316
 
313
321
            False then the inventory is the same as that on disk and any
314
322
            serialisation would be unneeded overhead.
315
323
        """
 
324
        assert inv.root is not None
316
325
        self._inventory = inv
317
326
        self._inventory_is_modified = dirty
318
327
 
322
331
 
323
332
        """
324
333
        if path is None:
325
 
            path = osutils.getcwd()
 
334
            path = os.path.getcwdu()
326
335
        control = bzrdir.BzrDir.open(path, _unsupported)
327
336
        return control.open_workingtree(_unsupported)
328
 
 
 
337
        
329
338
    @staticmethod
330
339
    def open_containing(path=None):
331
340
        """Open an existing working tree which has its root about path.
332
 
 
 
341
        
333
342
        This probes for a working tree at path and searches upwards from there.
334
343
 
335
344
        Basically we keep looking up until we find the control directory or
353
362
        """
354
363
        return WorkingTree.open(path, _unsupported=True)
355
364
 
356
 
    @staticmethod
357
 
    def find_trees(location):
358
 
        def list_current(transport):
359
 
            return [d for d in transport.list_dir('') if d != '.bzr']
360
 
        def evaluate(bzrdir):
361
 
            try:
362
 
                tree = bzrdir.open_workingtree()
363
 
            except errors.NoWorkingTree:
364
 
                return True, None
365
 
            else:
366
 
                return True, tree
367
 
        transport = get_transport(location)
368
 
        iterator = bzrdir.BzrDir.find_bzrdirs(transport, evaluate=evaluate,
369
 
                                              list_current=list_current)
370
 
        return [t for t in iterator if t is not None]
371
 
 
372
365
    # should be deprecated - this is slow and in any case treating them as a
373
366
    # container is (we now know) bad style -- mbp 20070302
374
367
    ## @deprecated_method(zero_fifteen)
383
376
            if osutils.lexists(self.abspath(path)):
384
377
                yield ie.file_id
385
378
 
386
 
    def all_file_ids(self):
387
 
        """See Tree.iter_all_file_ids"""
388
 
        return set(self.inventory)
389
 
 
390
379
    def __repr__(self):
391
380
        return "<%s of %s>" % (self.__class__.__name__,
392
381
                               getattr(self, 'basedir', None))
393
382
 
394
383
    def abspath(self, filename):
395
384
        return pathjoin(self.basedir, filename)
396
 
 
 
385
    
397
386
    def basis_tree(self):
398
387
        """Return RevisionTree for the current last revision.
399
 
 
 
388
        
400
389
        If the left most parent is a ghost then the returned tree will be an
401
 
        empty tree - one obtained by calling
402
 
        repository.revision_tree(NULL_REVISION).
 
390
        empty tree - one obtained by calling repository.revision_tree(None).
403
391
        """
404
392
        try:
405
393
            revision_id = self.get_parent_ids()[0]
407
395
            # no parents, return an empty revision tree.
408
396
            # in the future this should return the tree for
409
397
            # 'empty:' - the implicit root empty tree.
410
 
            return self.branch.repository.revision_tree(
411
 
                       _mod_revision.NULL_REVISION)
 
398
            return self.branch.repository.revision_tree(None)
412
399
        try:
413
400
            return self.revision_tree(revision_id)
414
401
        except errors.NoSuchRevision:
418
405
        # at this point ?
419
406
        try:
420
407
            return self.branch.repository.revision_tree(revision_id)
421
 
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
 
408
        except errors.RevisionNotPresent:
422
409
            # the basis tree *may* be a ghost or a low level error may have
423
 
            # occurred. If the revision is present, its a problem, if its not
 
410
            # occured. If the revision is present, its a problem, if its not
424
411
            # its a ghost.
425
412
            if self.branch.repository.has_revision(revision_id):
426
413
                raise
427
414
            # the basis tree is a ghost so return an empty tree.
428
 
            return self.branch.repository.revision_tree(
429
 
                       _mod_revision.NULL_REVISION)
430
 
 
431
 
    def _cleanup(self):
432
 
        self._flush_ignore_list_cache()
 
415
            return self.branch.repository.revision_tree(None)
 
416
 
 
417
    @staticmethod
 
418
    @deprecated_method(zero_eight)
 
419
    def create(branch, directory):
 
420
        """Create a workingtree for branch at directory.
 
421
 
 
422
        If existing_directory already exists it must have a .bzr directory.
 
423
        If it does not exist, it will be created.
 
424
 
 
425
        This returns a new WorkingTree object for the new checkout.
 
426
 
 
427
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
428
        should accept an optional revisionid to checkout [and reject this if
 
429
        checking out into the same dir as a pre-checkout-aware branch format.]
 
430
 
 
431
        XXX: When BzrDir is present, these should be created through that 
 
432
        interface instead.
 
433
        """
 
434
        warnings.warn('delete WorkingTree.create', stacklevel=3)
 
435
        transport = get_transport(directory)
 
436
        if branch.bzrdir.root_transport.base == transport.base:
 
437
            # same dir 
 
438
            return branch.bzrdir.create_workingtree()
 
439
        # different directory, 
 
440
        # create a branch reference
 
441
        # and now a working tree.
 
442
        raise NotImplementedError
 
443
 
 
444
    @staticmethod
 
445
    @deprecated_method(zero_eight)
 
446
    def create_standalone(directory):
 
447
        """Create a checkout and a branch and a repo at directory.
 
448
 
 
449
        Directory must exist and be empty.
 
450
 
 
451
        please use BzrDir.create_standalone_workingtree
 
452
        """
 
453
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
433
454
 
434
455
    def relpath(self, path):
435
456
        """Return the local path portion from a given path.
436
 
 
437
 
        The path may be absolute or relative. If its a relative path it is
 
457
        
 
458
        The path may be absolute or relative. If its a relative path it is 
438
459
        interpreted relative to the python current working directory.
439
460
        """
440
461
        return osutils.relpath(self.basedir, path)
442
463
    def has_filename(self, filename):
443
464
        return osutils.lexists(self.abspath(filename))
444
465
 
445
 
    def get_file(self, file_id, path=None, filtered=True):
446
 
        return self.get_file_with_stat(file_id, path, filtered=filtered)[0]
447
 
 
448
 
    def get_file_with_stat(self, file_id, path=None, filtered=True,
449
 
        _fstat=os.fstat):
450
 
        """See Tree.get_file_with_stat."""
451
 
        if path is None:
452
 
            path = self.id2path(file_id)
453
 
        file_obj = self.get_file_byname(path, filtered=False)
454
 
        stat_value = _fstat(file_obj.fileno())
455
 
        if filtered and self.supports_content_filtering():
456
 
            filters = self._content_filter_stack(path)
457
 
            file_obj = filtered_input_file(file_obj, filters)
458
 
        return (file_obj, stat_value)
459
 
 
460
 
    def get_file_text(self, file_id, path=None, filtered=True):
461
 
        return self.get_file(file_id, path=path, filtered=filtered).read()
462
 
 
463
 
    def get_file_byname(self, filename, filtered=True):
464
 
        path = self.abspath(filename)
465
 
        f = file(path, 'rb')
466
 
        if filtered and self.supports_content_filtering():
467
 
            filters = self._content_filter_stack(filename)
468
 
            return filtered_input_file(f, filters)
469
 
        else:
470
 
            return f
471
 
 
472
 
    def get_file_lines(self, file_id, path=None, filtered=True):
473
 
        """See Tree.get_file_lines()"""
474
 
        file = self.get_file(file_id, path, filtered=filtered)
475
 
        try:
476
 
            return file.readlines()
477
 
        finally:
478
 
            file.close()
 
466
    def get_file(self, file_id):
 
467
        file_id = osutils.safe_file_id(file_id)
 
468
        return self.get_file_byname(self.id2path(file_id))
 
469
 
 
470
    def get_file_text(self, file_id):
 
471
        file_id = osutils.safe_file_id(file_id)
 
472
        return self.get_file(file_id).read()
 
473
 
 
474
    def get_file_byname(self, filename):
 
475
        return file(self.abspath(filename), 'rb')
479
476
 
480
477
    @needs_read_lock
481
 
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
 
478
    def annotate_iter(self, file_id):
482
479
        """See Tree.annotate_iter
483
480
 
484
481
        This implementation will use the basis tree implementation if possible.
488
485
        incorrectly attributed to CURRENT_REVISION (but after committing, the
489
486
        attribution will be correct).
490
487
        """
491
 
        maybe_file_parent_keys = []
492
 
        for parent_id in self.get_parent_ids():
493
 
            try:
494
 
                parent_tree = self.revision_tree(parent_id)
495
 
            except errors.NoSuchRevisionInTree:
496
 
                parent_tree = self.branch.repository.revision_tree(parent_id)
497
 
            parent_tree.lock_read()
498
 
            try:
499
 
                if file_id not in parent_tree:
500
 
                    continue
501
 
                ie = parent_tree.inventory[file_id]
502
 
                if ie.kind != 'file':
503
 
                    # Note: this is slightly unnecessary, because symlinks and
504
 
                    # directories have a "text" which is the empty text, and we
505
 
                    # know that won't mess up annotations. But it seems cleaner
506
 
                    continue
507
 
                parent_text_key = (file_id, ie.revision)
508
 
                if parent_text_key not in maybe_file_parent_keys:
509
 
                    maybe_file_parent_keys.append(parent_text_key)
510
 
            finally:
511
 
                parent_tree.unlock()
512
 
        graph = _mod_graph.Graph(self.branch.repository.texts)
513
 
        heads = graph.heads(maybe_file_parent_keys)
514
 
        file_parent_keys = []
515
 
        for key in maybe_file_parent_keys:
516
 
            if key in heads:
517
 
                file_parent_keys.append(key)
518
 
 
519
 
        # Now we have the parents of this content
520
 
        annotator = self.branch.repository.texts.get_annotator()
521
 
        text = self.get_file(file_id).read()
522
 
        this_key =(file_id, default_revision)
523
 
        annotator.add_special_text(this_key, file_parent_keys, text)
524
 
        annotations = [(key[-1], line)
525
 
                       for key, line in annotator.annotate_flat(this_key)]
526
 
        return annotations
527
 
 
528
 
    def _get_ancestors(self, default_revision):
529
 
        ancestors = set([default_revision])
530
 
        for parent_id in self.get_parent_ids():
531
 
            ancestors.update(self.branch.repository.get_ancestry(
532
 
                             parent_id, topo_sorted=False))
533
 
        return ancestors
 
488
        file_id = osutils.safe_file_id(file_id)
 
489
        basis = self.basis_tree()
 
490
        basis.lock_read()
 
491
        try:
 
492
            changes = self._iter_changes(basis, True, [self.id2path(file_id)],
 
493
                require_versioned=True).next()
 
494
            changed_content, kind = changes[2], changes[6]
 
495
            if not changed_content:
 
496
                return basis.annotate_iter(file_id)
 
497
            if kind[1] is None:
 
498
                return None
 
499
            import annotate
 
500
            if kind[0] != 'file':
 
501
                old_lines = []
 
502
            else:
 
503
                old_lines = list(basis.annotate_iter(file_id))
 
504
            old = [old_lines]
 
505
            for tree in self.branch.repository.revision_trees(
 
506
                self.get_parent_ids()[1:]):
 
507
                if file_id not in tree:
 
508
                    continue
 
509
                old.append(list(tree.annotate_iter(file_id)))
 
510
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
511
                                       CURRENT_REVISION)
 
512
        finally:
 
513
            basis.unlock()
534
514
 
535
515
    def get_parent_ids(self):
536
516
        """See Tree.get_parent_ids.
537
 
 
 
517
        
538
518
        This implementation reads the pending merges list and last_revision
539
519
        value and uses that to decide what the parents list should be.
540
520
        """
541
 
        last_rev = _mod_revision.ensure_null(self._last_revision())
542
 
        if _mod_revision.NULL_REVISION == last_rev:
 
521
        last_rev = self._last_revision()
 
522
        if last_rev is None:
543
523
            parents = []
544
524
        else:
545
525
            parents = [last_rev]
546
526
        try:
547
 
            merges_file = self._transport.get('pending-merges')
 
527
            merges_file = self._control_files.get('pending-merges')
548
528
        except errors.NoSuchFile:
549
529
            pass
550
530
        else:
551
531
            for l in merges_file.readlines():
552
 
                revision_id = l.rstrip('\n')
 
532
                revision_id = osutils.safe_revision_id(l.rstrip('\n'))
553
533
                parents.append(revision_id)
554
534
        return parents
555
535
 
557
537
    def get_root_id(self):
558
538
        """Return the id of this trees root"""
559
539
        return self._inventory.root.file_id
560
 
 
 
540
        
561
541
    def _get_store_filename(self, file_id):
562
542
        ## XXX: badly named; this is not in the store at all
 
543
        file_id = osutils.safe_file_id(file_id)
563
544
        return self.abspath(self.id2path(file_id))
564
545
 
565
546
    @needs_read_lock
566
 
    def clone(self, to_bzrdir, revision_id=None):
 
547
    def clone(self, to_bzrdir, revision_id=None, basis=None):
567
548
        """Duplicate this working tree into to_bzr, including all state.
568
 
 
 
549
        
569
550
        Specifically modified files are kept as modified, but
570
551
        ignored and unknown files are discarded.
571
552
 
572
553
        If you want to make a new line of development, see bzrdir.sprout()
573
554
 
574
555
        revision
575
 
            If not None, the cloned tree will have its last revision set to
576
 
            revision, and difference between the source trees last revision
 
556
            If not None, the cloned tree will have its last revision set to 
 
557
            revision, and and difference between the source trees last revision
577
558
            and this one merged in.
 
559
 
 
560
        basis
 
561
            If not None, a closer copy of a tree which may have some files in
 
562
            common, and which file content should be preferentially copied from.
578
563
        """
579
564
        # assumes the target bzr dir format is compatible.
580
 
        result = to_bzrdir.create_workingtree()
 
565
        result = self._format.initialize(to_bzrdir)
581
566
        self.copy_content_into(result, revision_id)
582
567
        return result
583
568
 
594
579
            tree.set_parent_ids([revision_id])
595
580
 
596
581
    def id2abspath(self, file_id):
 
582
        file_id = osutils.safe_file_id(file_id)
597
583
        return self.abspath(self.id2path(file_id))
598
584
 
599
585
    def has_id(self, file_id):
600
586
        # files that have been deleted are excluded
 
587
        file_id = osutils.safe_file_id(file_id)
601
588
        inv = self.inventory
602
589
        if not inv.has_id(file_id):
603
590
            return False
605
592
        return osutils.lexists(self.abspath(path))
606
593
 
607
594
    def has_or_had_id(self, file_id):
 
595
        file_id = osutils.safe_file_id(file_id)
608
596
        if file_id == self.inventory.root.file_id:
609
597
            return True
610
598
        return self.inventory.has_id(file_id)
612
600
    __contains__ = has_id
613
601
 
614
602
    def get_file_size(self, file_id):
615
 
        """See Tree.get_file_size"""
616
 
        try:
617
 
            return os.path.getsize(self.id2abspath(file_id))
618
 
        except OSError, e:
619
 
            if e.errno != errno.ENOENT:
620
 
                raise
621
 
            else:
622
 
                return None
 
603
        file_id = osutils.safe_file_id(file_id)
 
604
        return os.path.getsize(self.id2abspath(file_id))
623
605
 
624
606
    @needs_read_lock
625
607
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
608
        file_id = osutils.safe_file_id(file_id)
626
609
        if not path:
627
610
            path = self._inventory.id2path(file_id)
628
611
        return self._hashcache.get_sha1(path, stat_value)
629
612
 
630
613
    def get_file_mtime(self, file_id, path=None):
 
614
        file_id = osutils.safe_file_id(file_id)
631
615
        if not path:
632
616
            path = self.inventory.id2path(file_id)
633
617
        return os.lstat(self.abspath(path)).st_mtime
634
618
 
635
 
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
636
 
        file_id = self.path2id(path)
637
 
        return self._inventory[file_id].executable
638
 
 
639
 
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
640
 
        mode = stat_result.st_mode
641
 
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
642
 
 
643
619
    if not supports_executable():
644
620
        def is_executable(self, file_id, path=None):
 
621
            file_id = osutils.safe_file_id(file_id)
645
622
            return self._inventory[file_id].executable
646
 
 
647
 
        _is_executable_from_path_and_stat = \
648
 
            _is_executable_from_path_and_stat_from_basis
649
623
    else:
650
624
        def is_executable(self, file_id, path=None):
651
625
            if not path:
 
626
                file_id = osutils.safe_file_id(file_id)
652
627
                path = self.id2path(file_id)
653
628
            mode = os.lstat(self.abspath(path)).st_mode
654
629
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
655
630
 
656
 
        _is_executable_from_path_and_stat = \
657
 
            _is_executable_from_path_and_stat_from_stat
658
 
 
659
631
    @needs_tree_write_lock
660
632
    def _add(self, files, ids, kinds):
661
633
        """See MutableTree._add."""
662
634
        # TODO: Re-adding a file that is removed in the working copy
663
635
        # should probably put it back with the previous ID.
664
 
        # the read and write working inventory should not occur in this
 
636
        # the read and write working inventory should not occur in this 
665
637
        # function - they should be part of lock_write and unlock.
666
 
        inv = self.inventory
 
638
        inv = self.read_working_inventory()
667
639
        for f, file_id, kind in zip(files, ids, kinds):
 
640
            assert kind is not None
668
641
            if file_id is None:
669
642
                inv.add_path(f, kind=kind)
670
643
            else:
 
644
                file_id = osutils.safe_file_id(file_id)
671
645
                inv.add_path(f, kind=kind, file_id=file_id)
672
 
            self._inventory_is_modified = True
 
646
        self._write_inventory(inv)
673
647
 
674
648
    @needs_tree_write_lock
675
649
    def _gather_kinds(self, files, kinds):
735
709
        if updated:
736
710
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
737
711
 
738
 
    def path_content_summary(self, path, _lstat=os.lstat,
739
 
        _mapper=osutils.file_kind_from_stat_mode):
740
 
        """See Tree.path_content_summary."""
741
 
        abspath = self.abspath(path)
742
 
        try:
743
 
            stat_result = _lstat(abspath)
744
 
        except OSError, e:
745
 
            if getattr(e, 'errno', None) == errno.ENOENT:
746
 
                # no file.
747
 
                return ('missing', None, None, None)
748
 
            # propagate other errors
749
 
            raise
750
 
        kind = _mapper(stat_result.st_mode)
751
 
        if kind == 'file':
752
 
            size = stat_result.st_size
753
 
            # try for a stat cache lookup
754
 
            executable = self._is_executable_from_path_and_stat(path, stat_result)
755
 
            return (kind, size, executable, self._sha_from_stat(
756
 
                path, stat_result))
757
 
        elif kind == 'directory':
758
 
            # perhaps it looks like a plain directory, but it's really a
759
 
            # reference.
760
 
            if self._directory_is_tree_reference(path):
761
 
                kind = 'tree-reference'
762
 
            return kind, None, None, None
763
 
        elif kind == 'symlink':
764
 
            target = osutils.readlink(abspath)
765
 
            return ('symlink', None, None, target)
766
 
        else:
767
 
            return (kind, None, None, None)
 
712
    @deprecated_method(zero_eleven)
 
713
    @needs_read_lock
 
714
    def pending_merges(self):
 
715
        """Return a list of pending merges.
 
716
 
 
717
        These are revisions that have been merged into the working
 
718
        directory but not yet committed.
 
719
 
 
720
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
 
721
        instead - which is available on all tree objects.
 
722
        """
 
723
        return self.get_parent_ids()[1:]
768
724
 
769
725
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
770
726
        """Common ghost checking functionality from set_parent_*.
780
736
 
781
737
    def _set_merges_from_parent_ids(self, parent_ids):
782
738
        merges = parent_ids[1:]
783
 
        self._transport.put_bytes('pending-merges', '\n'.join(merges),
784
 
            mode=self.bzrdir._get_file_mode())
785
 
 
786
 
    def _filter_parent_ids_by_ancestry(self, revision_ids):
787
 
        """Check that all merged revisions are proper 'heads'.
788
 
 
789
 
        This will always return the first revision_id, and any merged revisions
790
 
        which are
791
 
        """
792
 
        if len(revision_ids) == 0:
793
 
            return revision_ids
794
 
        graph = self.branch.repository.get_graph()
795
 
        heads = graph.heads(revision_ids)
796
 
        new_revision_ids = revision_ids[:1]
797
 
        for revision_id in revision_ids[1:]:
798
 
            if revision_id in heads and revision_id not in new_revision_ids:
799
 
                new_revision_ids.append(revision_id)
800
 
        if new_revision_ids != revision_ids:
801
 
            trace.mutter('requested to set revision_ids = %s,'
802
 
                         ' but filtered to %s', revision_ids, new_revision_ids)
803
 
        return new_revision_ids
 
739
        self._control_files.put_bytes('pending-merges', '\n'.join(merges))
804
740
 
805
741
    @needs_tree_write_lock
806
742
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
807
743
        """Set the parent ids to revision_ids.
808
 
 
 
744
        
809
745
        See also set_parent_trees. This api will try to retrieve the tree data
810
746
        for each element of revision_ids from the trees repository. If you have
811
747
        tree data already available, it is more efficient to use
815
751
        :param revision_ids: The revision_ids to set as the parent ids of this
816
752
            working tree. Any of these may be ghosts.
817
753
        """
 
754
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
818
755
        self._check_parents_for_ghosts(revision_ids,
819
756
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
820
 
        for revision_id in revision_ids:
821
 
            _mod_revision.check_not_reserved_id(revision_id)
822
 
 
823
 
        revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
824
757
 
825
758
        if len(revision_ids) > 0:
826
759
            self.set_last_revision(revision_ids[0])
827
760
        else:
828
 
            self.set_last_revision(_mod_revision.NULL_REVISION)
 
761
            self.set_last_revision(None)
829
762
 
830
763
        self._set_merges_from_parent_ids(revision_ids)
831
764
 
832
765
    @needs_tree_write_lock
833
766
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
834
767
        """See MutableTree.set_parent_trees."""
835
 
        parent_ids = [rev for (rev, tree) in parents_list]
836
 
        for revision_id in parent_ids:
837
 
            _mod_revision.check_not_reserved_id(revision_id)
 
768
        parent_ids = [osutils.safe_revision_id(rev) for (rev, tree) in parents_list]
838
769
 
839
770
        self._check_parents_for_ghosts(parent_ids,
840
771
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
841
772
 
842
 
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
843
 
 
844
773
        if len(parent_ids) == 0:
845
 
            leftmost_parent_id = _mod_revision.NULL_REVISION
 
774
            leftmost_parent_id = None
846
775
            leftmost_parent_tree = None
847
776
        else:
848
777
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
873
802
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
874
803
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
875
804
 
876
 
    def _sha_from_stat(self, path, stat_result):
877
 
        """Get a sha digest from the tree's stat cache.
878
 
 
879
 
        The default implementation assumes no stat cache is present.
880
 
 
881
 
        :param path: The path.
882
 
        :param stat_result: The stat result being looked up.
883
 
        """
884
 
        return None
885
 
 
886
805
    def _put_rio(self, filename, stanzas, header):
887
806
        self._must_be_locked()
888
807
        my_file = rio_file(stanzas, header)
889
 
        self._transport.put_file(filename, my_file,
890
 
            mode=self.bzrdir._get_file_mode())
 
808
        self._control_files.put(filename, my_file)
891
809
 
892
810
    @needs_write_lock # because merge pulls data into the branch.
893
 
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
894
 
        merge_type=None):
 
811
    def merge_from_branch(self, branch, to_revision=None):
895
812
        """Merge from a branch into this working tree.
896
813
 
897
814
        :param branch: The branch to merge from.
901
818
            branch.last_revision().
902
819
        """
903
820
        from bzrlib.merge import Merger, Merge3Merger
904
 
        pb = ui.ui_factory.nested_progress_bar()
 
821
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
905
822
        try:
906
823
            merger = Merger(self.branch, this_tree=self, pb=pb)
907
824
            merger.pp = ProgressPhase("Merge phase", 5, pb)
910
827
            # local alterations
911
828
            merger.check_basis(check_clean=True, require_commits=False)
912
829
            if to_revision is None:
913
 
                to_revision = _mod_revision.ensure_null(branch.last_revision())
 
830
                to_revision = branch.last_revision()
 
831
            else:
 
832
                to_revision = osutils.safe_revision_id(to_revision)
914
833
            merger.other_rev_id = to_revision
915
 
            if _mod_revision.is_null(merger.other_rev_id):
916
 
                raise errors.NoCommits(branch)
 
834
            if merger.other_rev_id is None:
 
835
                raise error.NoCommits(branch)
917
836
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
918
837
            merger.other_basis = merger.other_rev_id
919
838
            merger.other_tree = self.branch.repository.revision_tree(
920
839
                merger.other_rev_id)
921
840
            merger.other_branch = branch
922
841
            merger.pp.next_phase()
923
 
            if from_revision is None:
924
 
                merger.find_base()
925
 
            else:
926
 
                merger.set_base_revision(from_revision, branch)
 
842
            merger.find_base()
927
843
            if merger.base_rev_id == merger.other_rev_id:
928
844
                raise errors.PointlessMerge
929
845
            merger.backup_files = False
930
 
            if merge_type is None:
931
 
                merger.merge_type = Merge3Merger
932
 
            else:
933
 
                merger.merge_type = merge_type
 
846
            merger.merge_type = Merge3Merger
934
847
            merger.set_interesting_files(None)
935
848
            merger.show_base = False
936
849
            merger.reprocess = False
944
857
    def merge_modified(self):
945
858
        """Return a dictionary of files modified by a merge.
946
859
 
947
 
        The list is initialized by WorkingTree.set_merge_modified, which is
 
860
        The list is initialized by WorkingTree.set_merge_modified, which is 
948
861
        typically called after we make some automatic updates to the tree
949
862
        because of a merge.
950
863
 
952
865
        still in the working inventory and have that text hash.
953
866
        """
954
867
        try:
955
 
            hashfile = self._transport.get('merge-hashes')
 
868
            hashfile = self._control_files.get('merge-hashes')
956
869
        except errors.NoSuchFile:
957
870
            return {}
 
871
        merge_hashes = {}
958
872
        try:
959
 
            merge_hashes = {}
960
 
            try:
961
 
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
962
 
                    raise errors.MergeModifiedFormatError()
963
 
            except StopIteration:
 
873
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
964
874
                raise errors.MergeModifiedFormatError()
965
 
            for s in RioReader(hashfile):
966
 
                # RioReader reads in Unicode, so convert file_ids back to utf8
967
 
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
968
 
                if file_id not in self.inventory:
969
 
                    continue
970
 
                text_hash = s.get("hash")
971
 
                if text_hash == self.get_file_sha1(file_id):
972
 
                    merge_hashes[file_id] = text_hash
973
 
            return merge_hashes
974
 
        finally:
975
 
            hashfile.close()
 
875
        except StopIteration:
 
876
            raise errors.MergeModifiedFormatError()
 
877
        for s in RioReader(hashfile):
 
878
            # RioReader reads in Unicode, so convert file_ids back to utf8
 
879
            file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
 
880
            if file_id not in self.inventory:
 
881
                continue
 
882
            text_hash = s.get("hash")
 
883
            if text_hash == self.get_file_sha1(file_id):
 
884
                merge_hashes[file_id] = text_hash
 
885
        return merge_hashes
976
886
 
977
887
    @needs_write_lock
978
888
    def mkdir(self, path, file_id=None):
984
894
        return file_id
985
895
 
986
896
    def get_symlink_target(self, file_id):
987
 
        abspath = self.id2abspath(file_id)
988
 
        target = osutils.readlink(abspath)
989
 
        return target
 
897
        file_id = osutils.safe_file_id(file_id)
 
898
        return os.readlink(self.id2abspath(file_id))
990
899
 
991
900
    @needs_write_lock
992
901
    def subsume(self, other_tree):
1030
939
            other_tree.unlock()
1031
940
        other_tree.bzrdir.retire_bzrdir()
1032
941
 
1033
 
    def _setup_directory_is_tree_reference(self):
1034
 
        if self._branch.repository._format.supports_tree_reference:
1035
 
            self._directory_is_tree_reference = \
1036
 
                self._directory_may_be_tree_reference
1037
 
        else:
1038
 
            self._directory_is_tree_reference = \
1039
 
                self._directory_is_never_tree_reference
1040
 
 
1041
 
    def _directory_is_never_tree_reference(self, relpath):
1042
 
        return False
1043
 
 
1044
 
    def _directory_may_be_tree_reference(self, relpath):
1045
 
        # as a special case, if a directory contains control files then
1046
 
        # it's a tree reference, except that the root of the tree is not
1047
 
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
1048
 
        # TODO: We could ask all the control formats whether they
1049
 
        # recognize this directory, but at the moment there's no cheap api
1050
 
        # to do that.  Since we probably can only nest bzr checkouts and
1051
 
        # they always use this name it's ok for now.  -- mbp 20060306
1052
 
        #
1053
 
        # FIXME: There is an unhandled case here of a subdirectory
1054
 
        # containing .bzr but not a branch; that will probably blow up
1055
 
        # when you try to commit it.  It might happen if there is a
1056
 
        # checkout in a subdirectory.  This can be avoided by not adding
1057
 
        # it.  mbp 20070306
1058
 
 
1059
942
    @needs_tree_write_lock
1060
943
    def extract(self, file_id, format=None):
1061
944
        """Extract a subtree from this tree.
1062
 
 
 
945
        
1063
946
        A new branch will be created, relative to the path for this tree.
1064
947
        """
1065
948
        self.flush()
1068
951
            transport = self.branch.bzrdir.root_transport
1069
952
            for name in segments:
1070
953
                transport = transport.clone(name)
1071
 
                transport.ensure_base()
 
954
                try:
 
955
                    transport.mkdir('.')
 
956
                except errors.FileExists:
 
957
                    pass
1072
958
            return transport
1073
 
 
 
959
            
1074
960
        sub_path = self.id2path(file_id)
1075
961
        branch_transport = mkdirs(sub_path)
1076
962
        if format is None:
1077
 
            format = self.bzrdir.cloning_metadir()
1078
 
        branch_transport.ensure_base()
 
963
            format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
 
964
        try:
 
965
            branch_transport.mkdir('.')
 
966
        except errors.FileExists:
 
967
            pass
1079
968
        branch_bzrdir = format.initialize_on_transport(branch_transport)
1080
969
        try:
1081
970
            repo = branch_bzrdir.find_repository()
1082
971
        except errors.NoRepositoryPresent:
1083
972
            repo = branch_bzrdir.create_repository()
1084
 
        if not repo.supports_rich_root():
1085
 
            raise errors.RootNotRich()
 
973
            assert repo.supports_rich_root()
 
974
        else:
 
975
            if not repo.supports_rich_root():
 
976
                raise errors.RootNotRich()
1086
977
        new_branch = branch_bzrdir.create_branch()
1087
978
        new_branch.pull(self.branch)
1088
979
        for parent_id in self.get_parent_ids():
1093
984
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
1094
985
        else:
1095
986
            tree_bzrdir = branch_bzrdir
1096
 
        wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
 
987
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
1097
988
        wt.set_parent_ids(self.get_parent_ids())
1098
989
        my_inv = self.inventory
1099
 
        child_inv = inventory.Inventory(root_id=None)
 
990
        child_inv = Inventory(root_id=None)
1100
991
        new_root = my_inv[file_id]
1101
992
        my_inv.remove_recursive_id(file_id)
1102
993
        new_root.parent_id = None
1106
997
        return wt
1107
998
 
1108
999
    def _serialize(self, inventory, out_file):
1109
 
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
1110
 
            working=True)
 
1000
        xml5.serializer_v5.write_inventory(self._inventory, out_file)
1111
1001
 
1112
1002
    def _deserialize(selt, in_file):
1113
1003
        return xml5.serializer_v5.read_inventory(in_file)
1120
1010
        sio = StringIO()
1121
1011
        self._serialize(self._inventory, sio)
1122
1012
        sio.seek(0)
1123
 
        self._transport.put_file('inventory', sio,
1124
 
            mode=self.bzrdir._get_file_mode())
 
1013
        self._control_files.put('inventory', sio)
1125
1014
        self._inventory_is_modified = False
1126
1015
 
1127
 
    def _kind(self, relpath):
1128
 
        return osutils.file_kind(self.abspath(relpath))
1129
 
 
1130
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1131
 
        """List all files as (path, class, kind, id, entry).
 
1016
    def list_files(self, include_root=False):
 
1017
        """Recursively list all files as (path, class, kind, id, entry).
1132
1018
 
1133
1019
        Lists, but does not descend into unversioned directories.
 
1020
 
1134
1021
        This does not include files that have been deleted in this
1135
 
        tree. Skips the control directory.
 
1022
        tree.
1136
1023
 
1137
 
        :param include_root: if True, do not return an entry for the root
1138
 
        :param from_dir: start from this directory or None for the root
1139
 
        :param recursive: whether to recurse into subdirectories or not
 
1024
        Skips the control directory.
1140
1025
        """
1141
1026
        # list_files is an iterator, so @needs_read_lock doesn't work properly
1142
1027
        # with it. So callers should be careful to always read_lock the tree.
1144
1029
            raise errors.ObjectNotLocked(self)
1145
1030
 
1146
1031
        inv = self.inventory
1147
 
        if from_dir is None and include_root is True:
 
1032
        if include_root is True:
1148
1033
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1149
1034
        # Convert these into local objects to save lookup times
1150
1035
        pathjoin = osutils.pathjoin
1151
 
        file_kind = self._kind
 
1036
        file_kind = osutils.file_kind
1152
1037
 
1153
1038
        # transport.base ends in a slash, we want the piece
1154
1039
        # between the last two slashes
1157
1042
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1158
1043
 
1159
1044
        # directory file_id, relative path, absolute path, reverse sorted children
1160
 
        if from_dir is not None:
1161
 
            from_dir_id = inv.path2id(from_dir)
1162
 
            if from_dir_id is None:
1163
 
                # Directory not versioned
1164
 
                return
1165
 
            from_dir_abspath = pathjoin(self.basedir, from_dir)
1166
 
        else:
1167
 
            from_dir_id = inv.root.file_id
1168
 
            from_dir_abspath = self.basedir
1169
 
        children = os.listdir(from_dir_abspath)
 
1045
        children = os.listdir(self.basedir)
1170
1046
        children.sort()
1171
 
        # jam 20060527 The kernel sized tree seems equivalent whether we
 
1047
        # jam 20060527 The kernel sized tree seems equivalent whether we 
1172
1048
        # use a deque and popleft to keep them sorted, or if we use a plain
1173
1049
        # list and just reverse() them.
1174
1050
        children = collections.deque(children)
1175
 
        stack = [(from_dir_id, u'', from_dir_abspath, children)]
 
1051
        stack = [(inv.root.file_id, u'', self.basedir, children)]
1176
1052
        while stack:
1177
1053
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1178
1054
 
1194
1070
 
1195
1071
                # absolute path
1196
1072
                fap = from_dir_abspath + '/' + f
1197
 
 
 
1073
                
1198
1074
                f_ie = inv.get_child(from_dir_id, f)
1199
1075
                if f_ie:
1200
1076
                    c = 'V'
1223
1099
 
1224
1100
                fk = file_kind(fap)
1225
1101
 
 
1102
                if f_ie:
 
1103
                    if f_ie.kind != fk:
 
1104
                        raise errors.BzrCheckError(
 
1105
                            "file %r entered as kind %r id %r, now of kind %r"
 
1106
                            % (fap, f_ie.kind, f_ie.file_id, fk))
 
1107
 
1226
1108
                # make a last minute entry
1227
1109
                if f_ie:
1228
1110
                    yield fp[1:], c, fk, f_ie.file_id, f_ie
1232
1114
                    except KeyError:
1233
1115
                        yield fp[1:], c, fk, None, TreeEntry()
1234
1116
                    continue
1235
 
 
 
1117
                
1236
1118
                if fk != 'directory':
1237
1119
                    continue
1238
1120
 
1239
 
                # But do this child first if recursing down
1240
 
                if recursive:
1241
 
                    new_children = os.listdir(fap)
1242
 
                    new_children.sort()
1243
 
                    new_children = collections.deque(new_children)
1244
 
                    stack.append((f_ie.file_id, fp, fap, new_children))
1245
 
                    # Break out of inner loop,
1246
 
                    # so that we start outer loop with child
1247
 
                    break
 
1121
                # But do this child first
 
1122
                new_children = os.listdir(fap)
 
1123
                new_children.sort()
 
1124
                new_children = collections.deque(new_children)
 
1125
                stack.append((f_ie.file_id, fp, fap, new_children))
 
1126
                # Break out of inner loop,
 
1127
                # so that we start outer loop with child
 
1128
                break
1248
1129
            else:
1249
1130
                # if we finished all children, pop it off the stack
1250
1131
                stack.pop()
1256
1137
        to_dir must exist in the inventory.
1257
1138
 
1258
1139
        If to_dir exists and is a directory, the files are moved into
1259
 
        it, keeping their old names.
 
1140
        it, keeping their old names.  
1260
1141
 
1261
1142
        Note that to_dir is only the last component of the new name;
1262
1143
        this doesn't change the directory.
1299
1180
                                       DeprecationWarning)
1300
1181
 
1301
1182
        # check destination directory
1302
 
        if isinstance(from_paths, basestring):
1303
 
            raise ValueError()
 
1183
        assert not isinstance(from_paths, basestring)
1304
1184
        inv = self.inventory
1305
1185
        to_abs = self.abspath(to_dir)
1306
1186
        if not isdir(to_abs):
1390
1270
                only_change_inv = True
1391
1271
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1392
1272
                only_change_inv = False
1393
 
            elif (not self.case_sensitive
1394
 
                  and from_rel.lower() == to_rel.lower()
1395
 
                  and self.has_filename(from_rel)):
1396
 
                only_change_inv = False
1397
1273
            else:
1398
1274
                # something is wrong, so lets determine what exactly
1399
1275
                if not self.has_filename(from_rel) and \
1402
1278
                        errors.PathsDoNotExist(paths=(str(from_rel),
1403
1279
                        str(to_rel))))
1404
1280
                else:
1405
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
 
1281
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
 
1282
                        extra="(Use --after to update the Bazaar id)")
1406
1283
            rename_entry.only_change_inv = only_change_inv
1407
1284
        return rename_entries
1408
1285
 
1428
1305
        inv = self.inventory
1429
1306
        for entry in moved:
1430
1307
            try:
1431
 
                self._move_entry(WorkingTree._RenameEntry(
1432
 
                    entry.to_rel, entry.from_id,
 
1308
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1433
1309
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
1434
1310
                    entry.from_tail, entry.from_parent_id,
1435
1311
                    entry.only_change_inv))
1486
1362
        from_tail = splitpath(from_rel)[-1]
1487
1363
        from_id = inv.path2id(from_rel)
1488
1364
        if from_id is None:
1489
 
            # if file is missing in the inventory maybe it's in the basis_tree
1490
 
            basis_tree = self.branch.basis_tree()
1491
 
            from_id = basis_tree.path2id(from_rel)
1492
 
            if from_id is None:
1493
 
                raise errors.BzrRenameFailedError(from_rel,to_rel,
1494
 
                    errors.NotVersionedError(path=str(from_rel)))
1495
 
            # put entry back in the inventory so we can rename it
1496
 
            from_entry = basis_tree.inventory[from_id].copy()
1497
 
            inv.add(from_entry)
1498
 
        else:
1499
 
            from_entry = inv[from_id]
 
1365
            raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1366
                errors.NotVersionedError(path=str(from_rel)))
 
1367
        from_entry = inv[from_id]
1500
1368
        from_parent_id = from_entry.parent_id
1501
1369
        to_dir, to_tail = os.path.split(to_rel)
1502
1370
        to_dir_id = inv.path2id(to_dir)
1548
1416
        These are files in the working directory that are not versioned or
1549
1417
        control files or ignored.
1550
1418
        """
1551
 
        # force the extras method to be fully executed before returning, to
 
1419
        # force the extras method to be fully executed before returning, to 
1552
1420
        # prevent race conditions with the lock
1553
1421
        return iter(
1554
1422
            [subp for subp in self.extras() if not self.is_ignored(subp)])
1555
 
 
 
1423
    
1556
1424
    @needs_tree_write_lock
1557
1425
    def unversion(self, file_ids):
1558
1426
        """Remove the file ids in file_ids from the current versioned set.
1564
1432
        :raises: NoSuchId if any fileid is not currently versioned.
1565
1433
        """
1566
1434
        for file_id in file_ids:
1567
 
            if file_id not in self._inventory:
1568
 
                raise errors.NoSuchId(self, file_id)
1569
 
        for file_id in file_ids:
 
1435
            file_id = osutils.safe_file_id(file_id)
1570
1436
            if self._inventory.has_id(file_id):
1571
1437
                self._inventory.remove_recursive_id(file_id)
 
1438
            else:
 
1439
                raise errors.NoSuchId(self, file_id)
1572
1440
        if len(file_ids):
1573
 
            # in the future this should just set a dirty bit to wait for the
 
1441
            # in the future this should just set a dirty bit to wait for the 
1574
1442
            # final unlock. However, until all methods of workingtree start
1575
 
            # with the current in -memory inventory rather than triggering
 
1443
            # with the current in -memory inventory rather than triggering 
1576
1444
            # a read, it is more complex - we need to teach read_inventory
1577
1445
            # to know when to read, and when to not read first... and possibly
1578
1446
            # to save first when the in memory one may be corrupted.
1579
1447
            # so for now, we just only write it if it is indeed dirty.
1580
1448
            # - RBC 20060907
1581
1449
            self._write_inventory(self._inventory)
 
1450
    
 
1451
    @deprecated_method(zero_eight)
 
1452
    def iter_conflicts(self):
 
1453
        """List all files in the tree that have text or content conflicts.
 
1454
        DEPRECATED.  Use conflicts instead."""
 
1455
        return self._iter_conflicts()
1582
1456
 
1583
1457
    def _iter_conflicts(self):
1584
1458
        conflicted = set()
1593
1467
 
1594
1468
    @needs_write_lock
1595
1469
    def pull(self, source, overwrite=False, stop_revision=None,
1596
 
             change_reporter=None, possible_transports=None, local=False):
1597
 
        top_pb = ui.ui_factory.nested_progress_bar()
 
1470
             change_reporter=None):
 
1471
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1598
1472
        source.lock_read()
1599
1473
        try:
1600
1474
            pp = ProgressPhase("Pull phase", 2, top_pb)
1601
1475
            pp.next_phase()
1602
1476
            old_revision_info = self.branch.last_revision_info()
1603
1477
            basis_tree = self.basis_tree()
1604
 
            count = self.branch.pull(source, overwrite, stop_revision,
1605
 
                                     possible_transports=possible_transports,
1606
 
                                     local=local)
 
1478
            count = self.branch.pull(source, overwrite, stop_revision)
1607
1479
            new_revision_info = self.branch.last_revision_info()
1608
1480
            if new_revision_info != old_revision_info:
1609
1481
                pp.next_phase()
1610
1482
                repository = self.branch.repository
1611
 
                pb = ui.ui_factory.nested_progress_bar()
 
1483
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1612
1484
                basis_tree.lock_read()
1613
1485
                try:
1614
1486
                    new_basis_tree = self.branch.basis_tree()
1621
1493
                                change_reporter=change_reporter)
1622
1494
                    if (basis_tree.inventory.root is None and
1623
1495
                        new_basis_tree.inventory.root is not None):
1624
 
                        self.set_root_id(new_basis_tree.get_root_id())
 
1496
                        self.set_root_id(new_basis_tree.inventory.root.file_id)
1625
1497
                finally:
1626
1498
                    pb.finished()
1627
1499
                    basis_tree.unlock()
1629
1501
                # reuse the revisiontree we merged against to set the new
1630
1502
                # tree data.
1631
1503
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1632
 
                # we have to pull the merge trees out again, because
1633
 
                # merge_inner has set the ids. - this corner is not yet
 
1504
                # we have to pull the merge trees out again, because 
 
1505
                # merge_inner has set the ids. - this corner is not yet 
1634
1506
                # layered well enough to prevent double handling.
1635
1507
                # XXX TODO: Fix the double handling: telling the tree about
1636
1508
                # the already known parent data is wasteful.
1647
1519
    @needs_write_lock
1648
1520
    def put_file_bytes_non_atomic(self, file_id, bytes):
1649
1521
        """See MutableTree.put_file_bytes_non_atomic."""
 
1522
        file_id = osutils.safe_file_id(file_id)
1650
1523
        stream = file(self.id2abspath(file_id), 'wb')
1651
1524
        try:
1652
1525
            stream.write(bytes)
1674
1547
 
1675
1548
            fl = []
1676
1549
            for subf in os.listdir(dirabs):
1677
 
                if self.bzrdir.is_control_filename(subf):
 
1550
                if subf == '.bzr':
1678
1551
                    continue
1679
1552
                if subf not in dir_entry.children:
1680
 
                    try:
1681
 
                        (subf_norm,
1682
 
                         can_access) = osutils.normalized_filename(subf)
1683
 
                    except UnicodeDecodeError:
1684
 
                        path_os_enc = path.encode(osutils._fs_enc)
1685
 
                        relpath = path_os_enc + '/' + subf
1686
 
                        raise errors.BadFilenameEncoding(relpath,
1687
 
                                                         osutils._fs_enc)
 
1553
                    subf_norm, can_access = osutils.normalized_filename(subf)
1688
1554
                    if subf_norm != subf and can_access:
1689
1555
                        if subf_norm not in dir_entry.children:
1690
1556
                            fl.append(subf_norm)
1691
1557
                    else:
1692
1558
                        fl.append(subf)
1693
 
 
 
1559
            
1694
1560
            fl.sort()
1695
1561
            for subf in fl:
1696
1562
                subp = pathjoin(path, subf)
1712
1578
        if ignoreset is not None:
1713
1579
            return ignoreset
1714
1580
 
1715
 
        ignore_globs = set()
 
1581
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1716
1582
        ignore_globs.update(ignores.get_runtime_ignores())
1717
1583
        ignore_globs.update(ignores.get_user_ignores())
1718
1584
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1745
1611
    def kind(self, file_id):
1746
1612
        return file_kind(self.id2abspath(file_id))
1747
1613
 
1748
 
    def stored_kind(self, file_id):
1749
 
        """See Tree.stored_kind"""
1750
 
        return self.inventory[file_id].kind
1751
 
 
1752
1614
    def _comparison_data(self, entry, path):
1753
1615
        abspath = self.abspath(path)
1754
1616
        try:
1764
1626
            mode = stat_value.st_mode
1765
1627
            kind = osutils.file_kind_from_stat_mode(mode)
1766
1628
            if not supports_executable():
1767
 
                executable = entry is not None and entry.executable
 
1629
                executable = entry.executable
1768
1630
            else:
1769
1631
                executable = bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
1770
1632
        return kind, executable, stat_value
1785
1647
    @needs_read_lock
1786
1648
    def _last_revision(self):
1787
1649
        """helper for get_parent_ids."""
1788
 
        return _mod_revision.ensure_null(self.branch.last_revision())
 
1650
        return self.branch.last_revision()
1789
1651
 
1790
1652
    def is_locked(self):
1791
1653
        return self._control_files.is_locked()
1836
1698
    def _reset_data(self):
1837
1699
        """Reset transient data that cannot be revalidated."""
1838
1700
        self._inventory_is_modified = False
1839
 
        result = self._deserialize(self._transport.get('inventory'))
 
1701
        result = self._deserialize(self._control_files.get('inventory'))
1840
1702
        self._set_inventory(result, dirty=False)
1841
1703
 
1842
1704
    @needs_tree_write_lock
1843
1705
    def set_last_revision(self, new_revision):
1844
1706
        """Change the last revision in the working tree."""
 
1707
        new_revision = osutils.safe_revision_id(new_revision)
1845
1708
        if self._change_last_revision(new_revision):
1846
1709
            self._cache_basis_inventory(new_revision)
1847
1710
 
1848
1711
    def _change_last_revision(self, new_revision):
1849
1712
        """Template method part of set_last_revision to perform the change.
1850
 
 
 
1713
        
1851
1714
        This is used to allow WorkingTree3 instances to not affect branch
1852
1715
        when their last revision is set.
1853
1716
        """
1854
 
        if _mod_revision.is_null(new_revision):
 
1717
        if new_revision is None:
1855
1718
            self.branch.set_revision_history([])
1856
1719
            return False
1857
1720
        try:
1863
1726
 
1864
1727
    def _write_basis_inventory(self, xml):
1865
1728
        """Write the basis inventory XML to the basis-inventory file"""
 
1729
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
1866
1730
        path = self._basis_inventory_name()
1867
1731
        sio = StringIO(xml)
1868
 
        self._transport.put_file(path, sio,
1869
 
            mode=self.bzrdir._get_file_mode())
 
1732
        self._control_files.put(path, sio)
1870
1733
 
1871
1734
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
1872
1735
        """Create the text that will be saved in basis-inventory"""
1873
 
        inventory.revision_id = revision_id
 
1736
        # TODO: jam 20070209 This should be redundant, as the revision_id
 
1737
        #       as all callers should have already converted the revision_id to
 
1738
        #       utf8
 
1739
        inventory.revision_id = osutils.safe_revision_id(revision_id)
1874
1740
        return xml7.serializer_v7.write_inventory_to_string(inventory)
1875
1741
 
1876
1742
    def _cache_basis_inventory(self, new_revision):
1879
1745
        # as commit already has that ready-to-use [while the format is the
1880
1746
        # same, that is].
1881
1747
        try:
1882
 
            # this double handles the inventory - unpack and repack -
 
1748
            # this double handles the inventory - unpack and repack - 
1883
1749
            # but is easier to understand. We can/should put a conditional
1884
1750
            # in here based on whether the inventory is in the latest format
1885
1751
            # - perhaps we should repack all inventories on a repository
1886
1752
            # upgrade ?
1887
1753
            # the fast path is to copy the raw xml from the repository. If the
1888
 
            # xml contains 'revision_id="', then we assume the right
 
1754
            # xml contains 'revision_id="', then we assume the right 
1889
1755
            # revision_id is set. We must check for this full string, because a
1890
1756
            # root node id can legitimately look like 'revision_id' but cannot
1891
1757
            # contain a '"'.
1892
1758
            xml = self.branch.repository.get_inventory_xml(new_revision)
1893
1759
            firstline = xml.split('\n', 1)[0]
1894
 
            if (not 'revision_id="' in firstline or
 
1760
            if (not 'revision_id="' in firstline or 
1895
1761
                'format="7"' not in firstline):
1896
 
                inv = self.branch.repository._serializer.read_inventory_from_string(
1897
 
                    xml, new_revision)
 
1762
                inv = self.branch.repository.deserialise_inventory(
 
1763
                    new_revision, xml)
1898
1764
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
1899
1765
            self._write_basis_inventory(xml)
1900
1766
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1903
1769
    def read_basis_inventory(self):
1904
1770
        """Read the cached basis inventory."""
1905
1771
        path = self._basis_inventory_name()
1906
 
        return self._transport.get_bytes(path)
1907
 
 
 
1772
        return self._control_files.get(path).read()
 
1773
        
1908
1774
    @needs_read_lock
1909
1775
    def read_working_inventory(self):
1910
1776
        """Read the working inventory.
1911
 
 
 
1777
        
1912
1778
        :raises errors.InventoryModified: read_working_inventory will fail
1913
1779
            when the current in memory inventory has been modified.
1914
1780
        """
1915
 
        # conceptually this should be an implementation detail of the tree.
 
1781
        # conceptually this should be an implementation detail of the tree. 
1916
1782
        # XXX: Deprecate this.
1917
1783
        # ElementTree does its own conversion from UTF-8, so open in
1918
1784
        # binary.
1919
1785
        if self._inventory_is_modified:
1920
1786
            raise errors.InventoryModified(self)
1921
 
        result = self._deserialize(self._transport.get('inventory'))
 
1787
        result = self._deserialize(self._control_files.get('inventory'))
1922
1788
        self._set_inventory(result, dirty=False)
1923
1789
        return result
1924
1790
 
1925
1791
    @needs_tree_write_lock
1926
 
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
1927
 
        force=False):
1928
 
        """Remove nominated files from the working inventory.
1929
 
 
1930
 
        :files: File paths relative to the basedir.
1931
 
        :keep_files: If true, the files will also be kept.
1932
 
        :force: Delete files and directories, even if they are changed and
1933
 
            even if the directories are not empty.
 
1792
    def remove(self, files, verbose=False, to_file=None):
 
1793
        """Remove nominated files from the working inventory..
 
1794
 
 
1795
        This does not remove their text.  This does not run on XXX on what? RBC
 
1796
 
 
1797
        TODO: Refuse to remove modified files unless --force is given?
 
1798
 
 
1799
        TODO: Do something useful with directories.
 
1800
 
 
1801
        TODO: Should this remove the text or not?  Tough call; not
 
1802
        removing may be useful and the user can just use use rm, and
 
1803
        is the opposite of add.  Removing it is consistent with most
 
1804
        other tools.  Maybe an option.
1934
1805
        """
 
1806
        ## TODO: Normalize names
 
1807
        ## TODO: Remove nested loops; better scalability
1935
1808
        if isinstance(files, basestring):
1936
1809
            files = [files]
1937
1810
 
1938
 
        inv_delta = []
1939
 
 
1940
 
        new_files=set()
1941
 
        unknown_nested_files=set()
1942
 
 
1943
 
        def recurse_directory_to_add_files(directory):
1944
 
            # Recurse directory and add all files
1945
 
            # so we can check if they have changed.
1946
 
            for parent_info, file_infos in\
1947
 
                self.walkdirs(directory):
1948
 
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
1949
 
                    # Is it versioned or ignored?
1950
 
                    if self.path2id(relpath) or self.is_ignored(relpath):
1951
 
                        # Add nested content for deletion.
1952
 
                        new_files.add(relpath)
1953
 
                    else:
1954
 
                        # Files which are not versioned and not ignored
1955
 
                        # should be treated as unknown.
1956
 
                        unknown_nested_files.add((relpath, None, kind))
1957
 
 
1958
 
        for filename in files:
1959
 
            # Get file name into canonical form.
1960
 
            abspath = self.abspath(filename)
1961
 
            filename = self.relpath(abspath)
1962
 
            if len(filename) > 0:
1963
 
                new_files.add(filename)
1964
 
                recurse_directory_to_add_files(filename)
1965
 
 
1966
 
        files = list(new_files)
1967
 
 
1968
 
        if len(files) == 0:
1969
 
            return # nothing to do
1970
 
 
1971
 
        # Sort needed to first handle directory content before the directory
1972
 
        files.sort(reverse=True)
1973
 
 
1974
 
        # Bail out if we are going to delete files we shouldn't
1975
 
        if not keep_files and not force:
1976
 
            has_changed_files = len(unknown_nested_files) > 0
1977
 
            if not has_changed_files:
1978
 
                for (file_id, path, content_change, versioned, parent_id, name,
1979
 
                     kind, executable) in self.iter_changes(self.basis_tree(),
1980
 
                         include_unchanged=True, require_versioned=False,
1981
 
                         want_unversioned=True, specific_files=files):
1982
 
                    if versioned == (False, False):
1983
 
                        # The record is unknown ...
1984
 
                        if not self.is_ignored(path[1]):
1985
 
                            # ... but not ignored
1986
 
                            has_changed_files = True
1987
 
                            break
1988
 
                    elif content_change and (kind[1] is not None):
1989
 
                        # Versioned and changed, but not deleted
1990
 
                        has_changed_files = True
1991
 
                        break
1992
 
 
1993
 
            if has_changed_files:
1994
 
                # Make delta show ALL applicable changes in error message.
1995
 
                tree_delta = self.changes_from(self.basis_tree(),
1996
 
                    require_versioned=False, want_unversioned=True,
1997
 
                    specific_files=files)
1998
 
                for unknown_file in unknown_nested_files:
1999
 
                    if unknown_file not in tree_delta.unversioned:
2000
 
                        tree_delta.unversioned.extend((unknown_file,))
2001
 
                raise errors.BzrRemoveChangedFilesError(tree_delta)
2002
 
 
2003
 
        # Build inv_delta and delete files where applicable,
2004
 
        # do this before any modifications to inventory.
 
1811
        inv = self.inventory
 
1812
 
 
1813
        # do this before any modifications
2005
1814
        for f in files:
2006
 
            fid = self.path2id(f)
2007
 
            message = None
 
1815
            fid = inv.path2id(f)
2008
1816
            if not fid:
2009
 
                message = "%s is not versioned." % (f,)
 
1817
                note("%s is not versioned."%f)
2010
1818
            else:
2011
1819
                if verbose:
2012
 
                    # having removed it, it must be either ignored or unknown
 
1820
                    # having remove it, it must be either ignored or unknown
2013
1821
                    if self.is_ignored(f):
2014
1822
                        new_status = 'I'
2015
1823
                    else:
2016
1824
                        new_status = '?'
2017
 
                    textui.show_status(new_status, self.kind(fid), f,
 
1825
                    textui.show_status(new_status, inv[fid].kind, f,
2018
1826
                                       to_file=to_file)
2019
 
                # Unversion file
2020
 
                inv_delta.append((f, None, fid, None))
2021
 
                message = "removed %s" % (f,)
2022
 
 
2023
 
            if not keep_files:
2024
 
                abs_path = self.abspath(f)
2025
 
                if osutils.lexists(abs_path):
2026
 
                    if (osutils.isdir(abs_path) and
2027
 
                        len(os.listdir(abs_path)) > 0):
2028
 
                        if force:
2029
 
                            osutils.rmtree(abs_path)
2030
 
                        else:
2031
 
                            message = "%s is not an empty directory "\
2032
 
                                "and won't be deleted." % (f,)
2033
 
                    else:
2034
 
                        osutils.delete_any(abs_path)
2035
 
                        message = "deleted %s" % (f,)
2036
 
                elif message is not None:
2037
 
                    # Only care if we haven't done anything yet.
2038
 
                    message = "%s does not exist." % (f,)
2039
 
 
2040
 
            # Print only one message (if any) per file.
2041
 
            if message is not None:
2042
 
                note(message)
2043
 
        self.apply_inventory_delta(inv_delta)
 
1827
                del inv[fid]
 
1828
 
 
1829
        self._write_inventory(inv)
2044
1830
 
2045
1831
    @needs_tree_write_lock
2046
 
    def revert(self, filenames=None, old_tree=None, backups=True,
 
1832
    def revert(self, filenames, old_tree=None, backups=True, 
2047
1833
               pb=DummyProgress(), report_changes=False):
2048
1834
        from bzrlib.conflicts import resolve
2049
 
        if filenames == []:
2050
 
            filenames = None
2051
 
            symbol_versioning.warn('Using [] to revert all files is deprecated'
2052
 
                ' as of bzr 0.91.  Please use None (the default) instead.',
2053
 
                DeprecationWarning, stacklevel=2)
2054
1835
        if old_tree is None:
2055
 
            basis_tree = self.basis_tree()
2056
 
            basis_tree.lock_read()
2057
 
            old_tree = basis_tree
 
1836
            old_tree = self.basis_tree()
 
1837
        conflicts = transform.revert(self, old_tree, filenames, backups, pb,
 
1838
                                     report_changes)
 
1839
        if not len(filenames):
 
1840
            self.set_parent_ids(self.get_parent_ids()[:1])
 
1841
            resolve(self)
2058
1842
        else:
2059
 
            basis_tree = None
2060
 
        try:
2061
 
            conflicts = transform.revert(self, old_tree, filenames, backups, pb,
2062
 
                                         report_changes)
2063
 
            if filenames is None and len(self.get_parent_ids()) > 1:
2064
 
                parent_trees = []
2065
 
                last_revision = self.last_revision()
2066
 
                if last_revision != _mod_revision.NULL_REVISION:
2067
 
                    if basis_tree is None:
2068
 
                        basis_tree = self.basis_tree()
2069
 
                        basis_tree.lock_read()
2070
 
                    parent_trees.append((last_revision, basis_tree))
2071
 
                self.set_parent_trees(parent_trees)
2072
 
                resolve(self)
2073
 
            else:
2074
 
                resolve(self, filenames, ignore_misses=True, recursive=True)
2075
 
        finally:
2076
 
            if basis_tree is not None:
2077
 
                basis_tree.unlock()
 
1843
            resolve(self, filenames, ignore_misses=True)
2078
1844
        return conflicts
2079
1845
 
2080
1846
    def revision_tree(self, revision_id):
2107
1873
    def set_inventory(self, new_inventory_list):
2108
1874
        from bzrlib.inventory import (Inventory,
2109
1875
                                      InventoryDirectory,
 
1876
                                      InventoryEntry,
2110
1877
                                      InventoryFile,
2111
1878
                                      InventoryLink)
2112
1879
        inv = Inventory(self.get_root_id())
2114
1881
            name = os.path.basename(path)
2115
1882
            if name == "":
2116
1883
                continue
2117
 
            # fixme, there should be a factory function inv,add_??
 
1884
            # fixme, there should be a factory function inv,add_?? 
2118
1885
            if kind == 'directory':
2119
1886
                inv.add(InventoryDirectory(file_id, name, parent))
2120
1887
            elif kind == 'file':
2128
1895
    @needs_tree_write_lock
2129
1896
    def set_root_id(self, file_id):
2130
1897
        """Set the root id for this tree."""
2131
 
        # for compatability
 
1898
        # for compatability 
2132
1899
        if file_id is None:
2133
 
            raise ValueError(
2134
 
                'WorkingTree.set_root_id with fileid=None')
2135
 
        file_id = osutils.safe_file_id(file_id)
 
1900
            symbol_versioning.warn(symbol_versioning.zero_twelve
 
1901
                % 'WorkingTree.set_root_id with fileid=None',
 
1902
                DeprecationWarning,
 
1903
                stacklevel=3)
 
1904
            file_id = ROOT_ID
 
1905
        else:
 
1906
            file_id = osutils.safe_file_id(file_id)
2136
1907
        self._set_root_id(file_id)
2137
1908
 
2138
1909
    def _set_root_id(self, file_id):
2139
1910
        """Set the root id for this tree, in a format specific manner.
2140
1911
 
2141
 
        :param file_id: The file id to assign to the root. It must not be
 
1912
        :param file_id: The file id to assign to the root. It must not be 
2142
1913
            present in the current inventory or an error will occur. It must
2143
1914
            not be None, but rather a valid file id.
2144
1915
        """
2163
1934
 
2164
1935
    def unlock(self):
2165
1936
        """See Branch.unlock.
2166
 
 
 
1937
        
2167
1938
        WorkingTree locking just uses the Branch locking facilities.
2168
1939
        This is current because all working trees have an embedded branch
2169
1940
        within them. IF in the future, we were to make branch data shareable
2170
 
        between multiple working trees, i.e. via shared storage, then we
 
1941
        between multiple working trees, i.e. via shared storage, then we 
2171
1942
        would probably want to lock both the local tree, and the branch.
2172
1943
        """
2173
1944
        raise NotImplementedError(self.unlock)
2174
1945
 
2175
 
    def update(self, change_reporter=None, possible_transports=None):
 
1946
    def update(self):
2176
1947
        """Update a working tree along its branch.
2177
1948
 
2178
1949
        This will update the branch if its bound too, which means we have
2197
1968
          basis.
2198
1969
        - Do a 'normal' merge of the old branch basis if it is relevant.
2199
1970
        """
2200
 
        if self.branch.get_bound_location() is not None:
 
1971
        if self.branch.get_master_branch() is not None:
2201
1972
            self.lock_write()
2202
1973
            update_branch = True
2203
1974
        else:
2205
1976
            update_branch = False
2206
1977
        try:
2207
1978
            if update_branch:
2208
 
                old_tip = self.branch.update(possible_transports)
 
1979
                old_tip = self.branch.update()
2209
1980
            else:
2210
1981
                old_tip = None
2211
 
            return self._update_tree(old_tip, change_reporter)
 
1982
            return self._update_tree(old_tip)
2212
1983
        finally:
2213
1984
            self.unlock()
2214
1985
 
2215
1986
    @needs_tree_write_lock
2216
 
    def _update_tree(self, old_tip=None, change_reporter=None):
 
1987
    def _update_tree(self, old_tip=None):
2217
1988
        """Update a tree to the master branch.
2218
1989
 
2219
1990
        :param old_tip: if supplied, the previous tip revision the branch,
2225
1996
        # cant set that until we update the working trees last revision to be
2226
1997
        # one from the new branch, because it will just get absorbed by the
2227
1998
        # parent de-duplication logic.
2228
 
        #
 
1999
        # 
2229
2000
        # We MUST save it even if an error occurs, because otherwise the users
2230
2001
        # local work is unreferenced and will appear to have been lost.
2231
 
        #
 
2002
        # 
2232
2003
        result = 0
2233
2004
        try:
2234
2005
            last_rev = self.get_parent_ids()[0]
2235
2006
        except IndexError:
2236
 
            last_rev = _mod_revision.NULL_REVISION
2237
 
        if last_rev != _mod_revision.ensure_null(self.branch.last_revision()):
 
2007
            last_rev = None
 
2008
        if last_rev != self.branch.last_revision():
2238
2009
            # merge tree state up to new branch tip.
2239
2010
            basis = self.basis_tree()
2240
2011
            basis.lock_read()
2241
2012
            try:
2242
2013
                to_tree = self.branch.basis_tree()
2243
2014
                if basis.inventory.root is None:
2244
 
                    self.set_root_id(to_tree.get_root_id())
 
2015
                    self.set_root_id(to_tree.inventory.root.file_id)
2245
2016
                    self.flush()
2246
2017
                result += merge.merge_inner(
2247
2018
                                      self.branch,
2248
2019
                                      to_tree,
2249
2020
                                      basis,
2250
 
                                      this_tree=self,
2251
 
                                      change_reporter=change_reporter)
 
2021
                                      this_tree=self)
2252
2022
            finally:
2253
2023
                basis.unlock()
2254
2024
            # TODO - dedup parents list with things merged by pull ?
2256
2026
            parent_trees = [(self.branch.last_revision(), to_tree)]
2257
2027
            merges = self.get_parent_ids()[1:]
2258
2028
            # Ideally we ask the tree for the trees here, that way the working
2259
 
            # tree can decide whether to give us the entire tree or give us a
 
2029
            # tree can decide whether to give us teh entire tree or give us a
2260
2030
            # lazy initialised tree. dirstate for instance will have the trees
2261
2031
            # in ram already, whereas a last-revision + basis-inventory tree
2262
2032
            # will not, but also does not need them when setting parents.
2263
2033
            for parent in merges:
2264
2034
                parent_trees.append(
2265
2035
                    (parent, self.branch.repository.revision_tree(parent)))
2266
 
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
 
2036
            if old_tip is not None:
2267
2037
                parent_trees.append(
2268
2038
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
2269
2039
            self.set_parent_trees(parent_trees)
2272
2042
            # the working tree had the same last-revision as the master
2273
2043
            # branch did. We may still have pivot local work from the local
2274
2044
            # branch into old_tip:
2275
 
            if (old_tip is not None and not _mod_revision.is_null(old_tip)):
 
2045
            if old_tip is not None:
2276
2046
                self.add_parent_tree_id(old_tip)
2277
 
        if (old_tip is not None and not _mod_revision.is_null(old_tip)
2278
 
            and old_tip != last_rev):
 
2047
        if old_tip and old_tip != last_rev:
2279
2048
            # our last revision was not the prior branch last revision
2280
2049
            # and we have converted that last revision to a pending merge.
2281
2050
            # base is somewhere between the branch tip now
2288
2057
            #       inventory and calls tree._write_inventory(). Ultimately we
2289
2058
            #       should be able to remove this extra flush.
2290
2059
            self.flush()
2291
 
            graph = self.branch.repository.get_graph()
2292
 
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
2293
 
                                                old_tip)
 
2060
            from bzrlib.revision import common_ancestor
 
2061
            try:
 
2062
                base_rev_id = common_ancestor(self.branch.last_revision(),
 
2063
                                              old_tip,
 
2064
                                              self.branch.repository)
 
2065
            except errors.NoCommonAncestor:
 
2066
                base_rev_id = None
2294
2067
            base_tree = self.branch.repository.revision_tree(base_rev_id)
2295
2068
            other_tree = self.branch.repository.revision_tree(old_tip)
2296
2069
            result += merge.merge_inner(
2297
2070
                                  self.branch,
2298
2071
                                  other_tree,
2299
2072
                                  base_tree,
2300
 
                                  this_tree=self,
2301
 
                                  change_reporter=change_reporter)
 
2073
                                  this_tree=self)
2302
2074
        return result
2303
2075
 
2304
2076
    def _write_hashcache_if_dirty(self):
2356
2128
    def walkdirs(self, prefix=""):
2357
2129
        """Walk the directories of this tree.
2358
2130
 
2359
 
        returns a generator which yields items in the form:
2360
 
                ((curren_directory_path, fileid),
2361
 
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
2362
 
                   file1_kind), ... ])
2363
 
 
2364
2131
        This API returns a generator, which is only valid during the current
2365
2132
        tree transaction - within a single lock_read or lock_write duration.
2366
2133
 
2367
 
        If the tree is not locked, it may cause an error to be raised,
2368
 
        depending on the tree implementation.
 
2134
        If the tree is not locked, it may cause an error to be raised, depending
 
2135
        on the tree implementation.
2369
2136
        """
2370
2137
        disk_top = self.abspath(prefix)
2371
2138
        if disk_top.endswith('/'):
2377
2144
            current_disk = disk_iterator.next()
2378
2145
            disk_finished = False
2379
2146
        except OSError, e:
2380
 
            if not (e.errno == errno.ENOENT or
2381
 
                (sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
 
2147
            if e.errno != errno.ENOENT:
2382
2148
                raise
2383
2149
            current_disk = None
2384
2150
            disk_finished = True
2389
2155
            current_inv = None
2390
2156
            inv_finished = True
2391
2157
        while not inv_finished or not disk_finished:
2392
 
            if current_disk:
2393
 
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2394
 
                    cur_disk_dir_content) = current_disk
2395
 
            else:
2396
 
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2397
 
                    cur_disk_dir_content) = ((None, None), None)
2398
2158
            if not disk_finished:
2399
2159
                # strip out .bzr dirs
2400
 
                if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
2401
 
                    len(cur_disk_dir_content) > 0):
2402
 
                    # osutils.walkdirs can be made nicer -
 
2160
                if current_disk[0][1][top_strip_len:] == '':
 
2161
                    # osutils.walkdirs can be made nicer - 
2403
2162
                    # yield the path-from-prefix rather than the pathjoined
2404
2163
                    # value.
2405
 
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
2406
 
                        ('.bzr', '.bzr'))
2407
 
                    if (bzrdir_loc < len(cur_disk_dir_content)
2408
 
                        and self.bzrdir.is_control_filename(
2409
 
                            cur_disk_dir_content[bzrdir_loc][0])):
 
2164
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
 
2165
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
2410
2166
                        # we dont yield the contents of, or, .bzr itself.
2411
 
                        del cur_disk_dir_content[bzrdir_loc]
 
2167
                        del current_disk[1][bzrdir_loc]
2412
2168
            if inv_finished:
2413
2169
                # everything is unknown
2414
2170
                direction = 1
2416
2172
                # everything is missing
2417
2173
                direction = -1
2418
2174
            else:
2419
 
                direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
 
2175
                direction = cmp(current_inv[0][0], current_disk[0][0])
2420
2176
            if direction > 0:
2421
2177
                # disk is before inventory - unknown
2422
2178
                dirblock = [(relpath, basename, kind, stat, None, None) for
2423
 
                    relpath, basename, kind, stat, top_path in
2424
 
                    cur_disk_dir_content]
2425
 
                yield (cur_disk_dir_relpath, None), dirblock
 
2179
                    relpath, basename, kind, stat, top_path in current_disk[1]]
 
2180
                yield (current_disk[0][0], None), dirblock
2426
2181
                try:
2427
2182
                    current_disk = disk_iterator.next()
2428
2183
                except StopIteration:
2430
2185
            elif direction < 0:
2431
2186
                # inventory is before disk - missing.
2432
2187
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2433
 
                    for relpath, basename, dkind, stat, fileid, kind in
 
2188
                    for relpath, basename, dkind, stat, fileid, kind in 
2434
2189
                    current_inv[1]]
2435
2190
                yield (current_inv[0][0], current_inv[0][1]), dirblock
2436
2191
                try:
2442
2197
                # merge the inventory and disk data together
2443
2198
                dirblock = []
2444
2199
                for relpath, subiterator in itertools.groupby(sorted(
2445
 
                    current_inv[1] + cur_disk_dir_content,
2446
 
                    key=operator.itemgetter(0)), operator.itemgetter(1)):
 
2200
                    current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
2447
2201
                    path_elements = list(subiterator)
2448
2202
                    if len(path_elements) == 2:
2449
2203
                        inv_row, disk_row = path_elements
2475
2229
                    disk_finished = True
2476
2230
 
2477
2231
    def _walkdirs(self, prefix=""):
2478
 
        """Walk the directories of this tree.
2479
 
 
2480
 
           :prefix: is used as the directrory to start with.
2481
 
           returns a generator which yields items in the form:
2482
 
                ((curren_directory_path, fileid),
2483
 
                 [(file1_path, file1_name, file1_kind, None, file1_id,
2484
 
                   file1_kind), ... ])
2485
 
        """
2486
2232
        _directory = 'directory'
2487
2233
        # get the root in the inventory
2488
2234
        inv = self.inventory
2502
2248
                relroot = ""
2503
2249
            # FIXME: stash the node in pending
2504
2250
            entry = inv[top_id]
2505
 
            if entry.kind == 'directory':
2506
 
                for name, child in entry.sorted_children():
2507
 
                    dirblock.append((relroot + name, name, child.kind, None,
2508
 
                        child.file_id, child.kind
2509
 
                        ))
 
2251
            for name, child in entry.sorted_children():
 
2252
                dirblock.append((relroot + name, name, child.kind, None,
 
2253
                    child.file_id, child.kind
 
2254
                    ))
2510
2255
            yield (currentdir[0], entry.file_id), dirblock
2511
2256
            # push the user specified dirs from dirblock
2512
2257
            for dir in reversed(dirblock):
2545
2290
        self.set_conflicts(un_resolved)
2546
2291
        return un_resolved, resolved
2547
2292
 
2548
 
    @needs_read_lock
2549
 
    def _check(self, references):
2550
 
        """Check the tree for consistency.
2551
 
 
2552
 
        :param references: A dict with keys matching the items returned by
2553
 
            self._get_check_refs(), and values from looking those keys up in
2554
 
            the repository.
2555
 
        """
2556
 
        tree_basis = self.basis_tree()
2557
 
        tree_basis.lock_read()
2558
 
        try:
2559
 
            repo_basis = references[('trees', self.last_revision())]
2560
 
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2561
 
                raise errors.BzrCheckError(
2562
 
                    "Mismatched basis inventory content.")
2563
 
            self._validate()
2564
 
        finally:
2565
 
            tree_basis.unlock()
2566
 
 
2567
 
    def _validate(self):
2568
 
        """Validate internal structures.
2569
 
 
2570
 
        This is meant mostly for the test suite. To give it a chance to detect
2571
 
        corruption after actions have occurred. The default implementation is a
2572
 
        just a no-op.
2573
 
 
2574
 
        :return: None. An exception should be raised if there is an error.
2575
 
        """
2576
 
        return
2577
 
 
2578
 
    @needs_read_lock
2579
 
    def _get_rules_searcher(self, default_searcher):
2580
 
        """See Tree._get_rules_searcher."""
2581
 
        if self._rules_searcher is None:
2582
 
            self._rules_searcher = super(WorkingTree,
2583
 
                self)._get_rules_searcher(default_searcher)
2584
 
        return self._rules_searcher
2585
 
 
2586
 
    def get_shelf_manager(self):
2587
 
        """Return the ShelfManager for this WorkingTree."""
2588
 
        from bzrlib.shelf import ShelfManager
2589
 
        return ShelfManager(self, self._transport)
2590
 
 
2591
2293
 
2592
2294
class WorkingTree2(WorkingTree):
2593
2295
    """This is the Format 2 working tree.
2594
2296
 
2595
 
    This was the first weave based working tree.
 
2297
    This was the first weave based working tree. 
2596
2298
     - uses os locks for locking.
2597
2299
     - uses the branch last-revision.
2598
2300
    """
2599
2301
 
2600
 
    def __init__(self, *args, **kwargs):
2601
 
        super(WorkingTree2, self).__init__(*args, **kwargs)
2602
 
        # WorkingTree2 has more of a constraint that self._inventory must
2603
 
        # exist. Because this is an older format, we don't mind the overhead
2604
 
        # caused by the extra computation here.
2605
 
 
2606
 
        # Newer WorkingTree's should only have self._inventory set when they
2607
 
        # have a read lock.
2608
 
        if self._inventory is None:
2609
 
            self.read_working_inventory()
2610
 
 
2611
 
    def _get_check_refs(self):
2612
 
        """Return the references needed to perform a check of this tree."""
2613
 
        return [('trees', self.last_revision())]
2614
 
 
2615
2302
    def lock_tree_write(self):
2616
2303
        """See WorkingTree.lock_tree_write().
2617
2304
 
2626
2313
            raise
2627
2314
 
2628
2315
    def unlock(self):
2629
 
        # do non-implementation specific cleanup
2630
 
        self._cleanup()
2631
 
 
2632
2316
        # we share control files:
2633
2317
        if self._control_files._lock_count == 3:
2634
2318
            # _inventory_is_modified is always False during a read lock.
2635
2319
            if self._inventory_is_modified:
2636
2320
                self.flush()
2637
2321
            self._write_hashcache_if_dirty()
2638
 
 
 
2322
                    
2639
2323
        # reverse order of locking.
2640
2324
        try:
2641
2325
            return self._control_files.unlock()
2657
2341
    def _last_revision(self):
2658
2342
        """See Mutable.last_revision."""
2659
2343
        try:
2660
 
            return self._transport.get_bytes('last-revision')
 
2344
            return osutils.safe_revision_id(
 
2345
                        self._control_files.get('last-revision').read())
2661
2346
        except errors.NoSuchFile:
2662
 
            return _mod_revision.NULL_REVISION
 
2347
            return None
2663
2348
 
2664
2349
    def _change_last_revision(self, revision_id):
2665
2350
        """See WorkingTree._change_last_revision."""
2666
 
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
2351
        if revision_id is None or revision_id == NULL_REVISION:
2667
2352
            try:
2668
 
                self._transport.delete('last-revision')
 
2353
                self._control_files._transport.delete('last-revision')
2669
2354
            except errors.NoSuchFile:
2670
2355
                pass
2671
2356
            return False
2672
2357
        else:
2673
 
            self._transport.put_bytes('last-revision', revision_id,
2674
 
                mode=self.bzrdir._get_file_mode())
 
2358
            self._control_files.put_bytes('last-revision', revision_id)
2675
2359
            return True
2676
2360
 
2677
 
    def _get_check_refs(self):
2678
 
        """Return the references needed to perform a check of this tree."""
2679
 
        return [('trees', self.last_revision())]
2680
 
 
2681
2361
    @needs_tree_write_lock
2682
2362
    def set_conflicts(self, conflicts):
2683
 
        self._put_rio('conflicts', conflicts.to_stanzas(),
 
2363
        self._put_rio('conflicts', conflicts.to_stanzas(), 
2684
2364
                      CONFLICT_HEADER_1)
2685
2365
 
2686
2366
    @needs_tree_write_lock
2693
2373
    @needs_read_lock
2694
2374
    def conflicts(self):
2695
2375
        try:
2696
 
            confile = self._transport.get('conflicts')
 
2376
            confile = self._control_files.get('conflicts')
2697
2377
        except errors.NoSuchFile:
2698
2378
            return _mod_conflicts.ConflictList()
2699
2379
        try:
2700
 
            try:
2701
 
                if confile.next() != CONFLICT_HEADER_1 + '\n':
2702
 
                    raise errors.ConflictFormatError()
2703
 
            except StopIteration:
 
2380
            if confile.next() != CONFLICT_HEADER_1 + '\n':
2704
2381
                raise errors.ConflictFormatError()
2705
 
            return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2706
 
        finally:
2707
 
            confile.close()
 
2382
        except StopIteration:
 
2383
            raise errors.ConflictFormatError()
 
2384
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2708
2385
 
2709
2386
    def unlock(self):
2710
 
        # do non-implementation specific cleanup
2711
 
        self._cleanup()
2712
2387
        if self._control_files._lock_count == 1:
2713
2388
            # _inventory_is_modified is always False during a read lock.
2714
2389
            if self._inventory_is_modified:
2727
2402
            return path[:-len(suffix)]
2728
2403
 
2729
2404
 
 
2405
@deprecated_function(zero_eight)
 
2406
def is_control_file(filename):
 
2407
    """See WorkingTree.is_control_filename(filename)."""
 
2408
    ## FIXME: better check
 
2409
    filename = normpath(filename)
 
2410
    while filename != '':
 
2411
        head, tail = os.path.split(filename)
 
2412
        ## mutter('check %r for control file' % ((head, tail),))
 
2413
        if tail == '.bzr':
 
2414
            return True
 
2415
        if filename == head:
 
2416
            break
 
2417
        filename = head
 
2418
    return False
 
2419
 
 
2420
 
2730
2421
class WorkingTreeFormat(object):
2731
2422
    """An encapsulation of the initialization and open routines for a format.
2732
2423
 
2735
2426
     * a format string,
2736
2427
     * an open routine.
2737
2428
 
2738
 
    Formats are placed in an dict by their format string for reference
 
2429
    Formats are placed in an dict by their format string for reference 
2739
2430
    during workingtree opening. Its not required that these be instances, they
2740
 
    can be classes themselves with class methods - it simply depends on
 
2431
    can be classes themselves with class methods - it simply depends on 
2741
2432
    whether state is needed for a given format or not.
2742
2433
 
2743
2434
    Once a format is deprecated, just deprecate the initialize and open
2744
 
    methods on the format class. Do not deprecate the object, as the
 
2435
    methods on the format class. Do not deprecate the object, as the 
2745
2436
    object will be created every time regardless.
2746
2437
    """
2747
2438
 
2753
2444
 
2754
2445
    requires_rich_root = False
2755
2446
 
2756
 
    upgrade_recommended = False
2757
 
 
2758
2447
    @classmethod
2759
2448
    def find_format(klass, a_bzrdir):
2760
2449
        """Return the format for the working tree object in a_bzrdir."""
2765
2454
        except errors.NoSuchFile:
2766
2455
            raise errors.NoWorkingTree(base=transport.base)
2767
2456
        except KeyError:
2768
 
            raise errors.UnknownFormatError(format=format_string,
2769
 
                                            kind="working tree")
 
2457
            raise errors.UnknownFormatError(format=format_string)
2770
2458
 
2771
2459
    def __eq__(self, other):
2772
2460
        return self.__class__ is other.__class__
2791
2479
        """Is this format supported?
2792
2480
 
2793
2481
        Supported formats can be initialized and opened.
2794
 
        Unsupported formats may not support initialization or committing or
 
2482
        Unsupported formats may not support initialization or committing or 
2795
2483
        some other features depending on the reason for not being supported.
2796
2484
        """
2797
2485
        return True
2798
2486
 
2799
 
    def supports_content_filtering(self):
2800
 
        """True if this format supports content filtering."""
2801
 
        return False
2802
 
 
2803
 
    def supports_views(self):
2804
 
        """True if this format supports stored views."""
2805
 
        return False
2806
 
 
2807
2487
    @classmethod
2808
2488
    def register_format(klass, format):
2809
2489
        klass._formats[format.get_format_string()] = format
2814
2494
 
2815
2495
    @classmethod
2816
2496
    def unregister_format(klass, format):
 
2497
        assert klass._formats[format.get_format_string()] is format
2817
2498
        del klass._formats[format.get_format_string()]
2818
2499
 
2819
2500
 
 
2501
 
2820
2502
class WorkingTreeFormat2(WorkingTreeFormat):
2821
 
    """The second working tree format.
 
2503
    """The second working tree format. 
2822
2504
 
2823
2505
    This format modified the hash cache from the format 1 hash cache.
2824
2506
    """
2825
2507
 
2826
 
    upgrade_recommended = True
2827
 
 
2828
2508
    def get_format_description(self):
2829
2509
        """See WorkingTreeFormat.get_format_description()."""
2830
2510
        return "Working tree format 2"
2831
2511
 
2832
 
    def _stub_initialize_on_transport(self, transport, file_mode):
2833
 
        """Workaround: create control files for a remote working tree.
2834
 
 
 
2512
    def stub_initialize_remote(self, control_files):
 
2513
        """As a special workaround create critical control files for a remote working tree
 
2514
        
2835
2515
        This ensures that it can later be updated and dealt with locally,
2836
 
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
 
2516
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
2837
2517
        no working tree.  (See bug #43064).
2838
2518
        """
2839
2519
        sio = StringIO()
2840
 
        inv = inventory.Inventory()
2841
 
        xml5.serializer_v5.write_inventory(inv, sio, working=True)
 
2520
        inv = Inventory()
 
2521
        xml5.serializer_v5.write_inventory(inv, sio)
2842
2522
        sio.seek(0)
2843
 
        transport.put_file('inventory', sio, file_mode)
2844
 
        transport.put_bytes('pending-merges', '', file_mode)
2845
 
 
2846
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
2847
 
                   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):
2848
2529
        """See WorkingTreeFormat.initialize()."""
2849
2530
        if not isinstance(a_bzrdir.transport, LocalTransport):
2850
2531
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2851
 
        if from_branch is not None:
2852
 
            branch = from_branch
2853
 
        else:
2854
 
            branch = a_bzrdir.open_branch()
2855
 
        if revision_id is None:
2856
 
            revision_id = _mod_revision.ensure_null(branch.last_revision())
2857
 
        branch.lock_write()
2858
 
        try:
2859
 
            branch.generate_revision_history(revision_id)
2860
 
        finally:
2861
 
            branch.unlock()
2862
 
        inv = inventory.Inventory()
 
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()
 
2546
        inv = Inventory()
2863
2547
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2864
2548
                         branch,
2865
2549
                         inv,
2866
2550
                         _internal=True,
2867
2551
                         _format=self,
2868
2552
                         _bzrdir=a_bzrdir)
2869
 
        basis_tree = branch.repository.revision_tree(revision_id)
 
2553
        basis_tree = branch.repository.revision_tree(revision)
2870
2554
        if basis_tree.inventory.root is not None:
2871
 
            wt.set_root_id(basis_tree.get_root_id())
 
2555
            wt.set_root_id(basis_tree.inventory.root.file_id)
2872
2556
        # set the parent list and cache the basis tree.
2873
 
        if _mod_revision.is_null(revision_id):
2874
 
            parent_trees = []
2875
 
        else:
2876
 
            parent_trees = [(revision_id, basis_tree)]
2877
 
        wt.set_parent_trees(parent_trees)
 
2557
        wt.set_parent_trees([(revision, basis_tree)])
2878
2558
        transform.build_tree(basis_tree, wt)
2879
2559
        return wt
2880
2560
 
2893
2573
            raise NotImplementedError
2894
2574
        if not isinstance(a_bzrdir.transport, LocalTransport):
2895
2575
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2896
 
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
 
2576
        return WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
2897
2577
                           _internal=True,
2898
2578
                           _format=self,
2899
2579
                           _bzrdir=a_bzrdir)
2900
 
        return wt
 
2580
 
2901
2581
 
2902
2582
class WorkingTreeFormat3(WorkingTreeFormat):
2903
2583
    """The second working tree format updated to record a format marker.
2911
2591
        - uses a LockDir to guard access for writes.
2912
2592
    """
2913
2593
 
2914
 
    upgrade_recommended = True
2915
 
 
2916
2594
    def get_format_string(self):
2917
2595
        """See WorkingTreeFormat.get_format_string()."""
2918
2596
        return "Bazaar-NG Working Tree format 3"
2933
2611
 
2934
2612
    def _open_control_files(self, a_bzrdir):
2935
2613
        transport = a_bzrdir.get_workingtree_transport(None)
2936
 
        return LockableFiles(transport, self._lock_file_name,
 
2614
        return LockableFiles(transport, self._lock_file_name, 
2937
2615
                             self._lock_class)
2938
2616
 
2939
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
2940
 
                   accelerator_tree=None, hardlink=False):
 
2617
    def initialize(self, a_bzrdir, revision_id=None):
2941
2618
        """See WorkingTreeFormat.initialize().
2942
 
 
2943
 
        :param revision_id: if supplied, create a working tree at a different
2944
 
            revision than the branch is at.
2945
 
        :param accelerator_tree: A tree which can be used for retrieving file
2946
 
            contents more quickly than the revision tree, i.e. a workingtree.
2947
 
            The revision tree will be used for cases where accelerator_tree's
2948
 
            content is different.
2949
 
        :param hardlink: If true, hard-link files from accelerator_tree,
2950
 
            where possible.
 
2619
        
 
2620
        revision_id allows creating a working tree at a different
 
2621
        revision than the branch is at.
2951
2622
        """
2952
2623
        if not isinstance(a_bzrdir.transport, LocalTransport):
2953
2624
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
2955
2626
        control_files = self._open_control_files(a_bzrdir)
2956
2627
        control_files.create_lock()
2957
2628
        control_files.lock_write()
2958
 
        transport.put_bytes('format', self.get_format_string(),
2959
 
            mode=a_bzrdir._get_file_mode())
2960
 
        if from_branch is not None:
2961
 
            branch = from_branch
 
2629
        control_files.put_utf8('format', self.get_format_string())
 
2630
        branch = a_bzrdir.open_branch()
 
2631
        if revision_id is None:
 
2632
            revision_id = branch.last_revision()
2962
2633
        else:
2963
 
            branch = a_bzrdir.open_branch()
2964
 
        if revision_id is None:
2965
 
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2634
            revision_id = osutils.safe_revision_id(revision_id)
2966
2635
        # WorkingTree3 can handle an inventory which has a unique root id.
2967
2636
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
2968
2637
        # those trees. And because there isn't a format bump inbetween, we
2981
2650
            basis_tree = branch.repository.revision_tree(revision_id)
2982
2651
            # only set an explicit root id if there is one to set.
2983
2652
            if basis_tree.inventory.root is not None:
2984
 
                wt.set_root_id(basis_tree.get_root_id())
2985
 
            if revision_id == _mod_revision.NULL_REVISION:
 
2653
                wt.set_root_id(basis_tree.inventory.root.file_id)
 
2654
            if revision_id == NULL_REVISION:
2986
2655
                wt.set_parent_trees([])
2987
2656
            else:
2988
2657
                wt.set_parent_trees([(revision_id, basis_tree)])
2995
2664
        return wt
2996
2665
 
2997
2666
    def _initial_inventory(self):
2998
 
        return inventory.Inventory()
 
2667
        return Inventory()
2999
2668
 
3000
2669
    def __init__(self):
3001
2670
        super(WorkingTreeFormat3, self).__init__()
3011
2680
            raise NotImplementedError
3012
2681
        if not isinstance(a_bzrdir.transport, LocalTransport):
3013
2682
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
3014
 
        wt = self._open(a_bzrdir, self._open_control_files(a_bzrdir))
3015
 
        return wt
 
2683
        return self._open(a_bzrdir, self._open_control_files(a_bzrdir))
3016
2684
 
3017
2685
    def _open(self, a_bzrdir, control_files):
3018
2686
        """Open the tree itself.
3019
 
 
 
2687
        
3020
2688
        :param a_bzrdir: the dir for the tree.
3021
2689
        :param control_files: the control files for the tree.
3022
2690
        """
3030
2698
        return self.get_format_string()
3031
2699
 
3032
2700
 
3033
 
__default_format = WorkingTreeFormat6()
 
2701
__default_format = WorkingTreeFormat4()
3034
2702
WorkingTreeFormat.register_format(__default_format)
3035
 
WorkingTreeFormat.register_format(WorkingTreeFormat5())
3036
 
WorkingTreeFormat.register_format(WorkingTreeFormat4())
3037
2703
WorkingTreeFormat.register_format(WorkingTreeFormat3())
3038
2704
WorkingTreeFormat.set_default_format(__default_format)
3039
2705
# formats which have no format string are not discoverable
3040
2706
# and not independently creatable, so are not registered.
3041
2707
_legacy_formats = [WorkingTreeFormat2(),
3042
2708
                   ]
 
2709
 
 
2710
 
 
2711
class WorkingTreeTestProviderAdapter(object):
 
2712
    """A tool to generate a suite testing multiple workingtree formats at once.
 
2713
 
 
2714
    This is done by copying the test once for each transport and injecting
 
2715
    the transport_server, transport_readonly_server, and workingtree_format
 
2716
    classes into each copy. Each copy is also given a new id() to make it
 
2717
    easy to identify.
 
2718
    """
 
2719
 
 
2720
    def __init__(self, transport_server, transport_readonly_server, formats):
 
2721
        self._transport_server = transport_server
 
2722
        self._transport_readonly_server = transport_readonly_server
 
2723
        self._formats = formats
 
2724
    
 
2725
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
 
2726
        """Clone test for adaption."""
 
2727
        new_test = deepcopy(test)
 
2728
        new_test.transport_server = self._transport_server
 
2729
        new_test.transport_readonly_server = self._transport_readonly_server
 
2730
        new_test.bzrdir_format = bzrdir_format
 
2731
        new_test.workingtree_format = workingtree_format
 
2732
        def make_new_test_id():
 
2733
            new_id = "%s(%s)" % (test.id(), variation)
 
2734
            return lambda: new_id
 
2735
        new_test.id = make_new_test_id()
 
2736
        return new_test
 
2737
    
 
2738
    def adapt(self, test):
 
2739
        from bzrlib.tests import TestSuite
 
2740
        result = TestSuite()
 
2741
        for workingtree_format, bzrdir_format in self._formats:
 
2742
            new_test = self._clone_test(
 
2743
                test,
 
2744
                bzrdir_format,
 
2745
                workingtree_format, workingtree_format.__class__.__name__)
 
2746
            result.addTest(new_test)
 
2747
        return result