~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
29
29
WorkingTree.open(dir).
30
30
"""
31
31
 
 
32
# TODO: Give the workingtree sole responsibility for the working inventory;
 
33
# remove the variable and references to it from the branch.  This may require
 
34
# updating the commit code so as to update the inventory within the working
 
35
# copy, and making sure there's only one WorkingTree for any directory on disk.
 
36
# At the moment they may alias the inventory and have old copies of it in
 
37
# memory.  (Now done? -- mbp 20060309)
32
38
 
33
39
from cStringIO import StringIO
34
40
import os
35
 
import sys
36
41
 
37
42
from bzrlib.lazy_import import lazy_import
38
43
lazy_import(globals(), """
39
44
from bisect import bisect_left
40
45
import collections
 
46
from copy import deepcopy
41
47
import errno
42
48
import itertools
43
49
import operator
44
50
import stat
 
51
from time import time
 
52
import warnings
45
53
import re
46
54
 
47
55
import bzrlib
49
57
    branch,
50
58
    bzrdir,
51
59
    conflicts as _mod_conflicts,
52
 
    controldir,
 
60
    dirstate,
53
61
    errors,
54
62
    generate_ids,
55
63
    globbing,
56
 
    graph as _mod_graph,
57
64
    hashcache,
58
65
    ignores,
59
 
    inventory,
60
66
    merge,
61
 
    revision as _mod_revision,
 
67
    osutils,
62
68
    revisiontree,
 
69
    repository,
 
70
    textui,
63
71
    trace,
64
72
    transform,
65
 
    transport,
66
73
    ui,
67
 
    views,
 
74
    urlutils,
68
75
    xml5,
 
76
    xml6,
69
77
    xml7,
70
78
    )
71
 
from bzrlib.workingtree_4 import (
72
 
    WorkingTreeFormat4,
73
 
    WorkingTreeFormat5,
74
 
    WorkingTreeFormat6,
75
 
    )
 
79
import bzrlib.branch
 
80
from bzrlib.transport import get_transport
 
81
import bzrlib.ui
 
82
from bzrlib.workingtree_4 import WorkingTreeFormat4
76
83
""")
77
84
 
78
85
from bzrlib import symbol_versioning
79
86
from bzrlib.decorators import needs_read_lock, needs_write_lock
80
 
from bzrlib.lock import LogicalLockResult
81
 
from bzrlib.lockable_files import LockableFiles
 
87
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, TreeReference
 
88
from bzrlib.lockable_files import LockableFiles, TransportLock
82
89
from bzrlib.lockdir import LockDir
83
90
import bzrlib.mutabletree
84
91
from bzrlib.mutabletree import needs_tree_write_lock
85
 
from bzrlib import osutils
86
92
from bzrlib.osutils import (
 
93
    compact_date,
87
94
    file_kind,
88
95
    isdir,
89
96
    normpath,
90
97
    pathjoin,
 
98
    rand_chars,
91
99
    realpath,
92
100
    safe_unicode,
93
101
    splitpath,
94
102
    supports_executable,
95
103
    )
96
 
from bzrlib.filters import filtered_input_file
97
104
from bzrlib.trace import mutter, note
98
105
from bzrlib.transport.local import LocalTransport
99
 
from bzrlib.revision import CURRENT_REVISION
 
106
from bzrlib.progress import DummyProgress, ProgressPhase
 
107
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
100
108
from bzrlib.rio import RioReader, rio_file, Stanza
101
 
from bzrlib.symbol_versioning import (
102
 
    deprecated_passed,
103
 
    DEPRECATED_PARAMETER,
104
 
    )
 
109
from bzrlib.symbol_versioning import (deprecated_passed,
 
110
        deprecated_method,
 
111
        deprecated_function,
 
112
        DEPRECATED_PARAMETER,
 
113
        zero_eight,
 
114
        zero_eleven,
 
115
        zero_thirteen,
 
116
        )
105
117
 
106
118
 
107
119
MERGE_MODIFIED_HEADER_1 = "BZR merge-modified list format 1"
108
 
# TODO: Modifying the conflict objects or their type is currently nearly
109
 
# impossible as there is no clear relationship between the working tree format
110
 
# and the conflict list file format.
111
120
CONFLICT_HEADER_1 = "BZR conflict list format 1"
112
121
 
113
 
ERROR_PATH_NOT_FOUND = 3    # WindowsError errno code, equivalent to ENOENT
 
122
 
 
123
@deprecated_function(zero_thirteen)
 
124
def gen_file_id(name):
 
125
    """Return new file id for the basename 'name'.
 
126
 
 
127
    Use bzrlib.generate_ids.gen_file_id() instead
 
128
    """
 
129
    return generate_ids.gen_file_id(name)
 
130
 
 
131
 
 
132
@deprecated_function(zero_thirteen)
 
133
def gen_root_id():
 
134
    """Return a new tree-root file id.
 
135
 
 
136
    This has been deprecated in favor of bzrlib.generate_ids.gen_root_id()
 
137
    """
 
138
    return generate_ids.gen_root_id()
114
139
 
115
140
 
116
141
class TreeEntry(object):
117
142
    """An entry that implements the minimum interface used by commands.
118
143
 
119
 
    This needs further inspection, it may be better to have
 
144
    This needs further inspection, it may be better to have 
120
145
    InventoryEntries without ids - though that seems wrong. For now,
121
146
    this is a parallel hierarchy to InventoryEntry, and needs to become
122
147
    one of several things: decorates to that hierarchy, children of, or
125
150
    no InventoryEntry available - i.e. for unversioned objects.
126
151
    Perhaps they should be UnversionedEntry et al. ? - RBC 20051003
127
152
    """
128
 
 
 
153
 
129
154
    def __eq__(self, other):
130
155
        # yes, this us ugly, TODO: best practice __eq__ style.
131
156
        return (isinstance(other, TreeEntry)
132
157
                and other.__class__ == self.__class__)
133
 
 
 
158
 
134
159
    def kind_character(self):
135
160
        return "???"
136
161
 
168
193
        return ''
169
194
 
170
195
 
171
 
class WorkingTree(bzrlib.mutabletree.MutableTree,
172
 
    controldir.ControlComponent):
 
196
class WorkingTree(bzrlib.mutabletree.MutableTree):
173
197
    """Working copy tree.
174
198
 
175
199
    The inventory is held in the `Branch` working-inventory, and the
177
201
 
178
202
    It is possible for a `WorkingTree` to have a filename which is
179
203
    not listed in the Inventory and vice versa.
180
 
 
181
 
    :ivar basedir: The root of the tree on disk. This is a unicode path object
182
 
        (as opposed to a URL).
183
204
    """
184
205
 
185
 
    # override this to set the strategy for storing views
186
 
    def _make_views(self):
187
 
        return views.DisabledViews(self)
188
 
 
189
206
    def __init__(self, basedir='.',
190
207
                 branch=DEPRECATED_PARAMETER,
191
208
                 _inventory=None,
202
219
        if not _internal:
203
220
            raise errors.BzrError("Please use bzrdir.open_workingtree or "
204
221
                "WorkingTree.open() to obtain a WorkingTree.")
 
222
        assert isinstance(basedir, basestring), \
 
223
            "base directory %r is not a string" % basedir
205
224
        basedir = safe_unicode(basedir)
206
225
        mutter("opening working tree %r", basedir)
207
226
        if deprecated_passed(branch):
209
228
        else:
210
229
            self._branch = self.bzrdir.open_branch()
211
230
        self.basedir = realpath(basedir)
212
 
        self._control_files = _control_files
213
 
        self._transport = self._control_files._transport
 
231
        # if branch is at our basedir and is a format 6 or less
 
232
        if isinstance(self._format, WorkingTreeFormat2):
 
233
            # share control object
 
234
            self._control_files = self.branch.control_files
 
235
        else:
 
236
            # assume all other formats have their own control files.
 
237
            assert isinstance(_control_files, LockableFiles), \
 
238
                    "_control_files must be a LockableFiles, not %r" \
 
239
                    % _control_files
 
240
            self._control_files = _control_files
214
241
        # update the whole cache up front and write to disk if anything changed;
215
242
        # in the future we might want to do this more selectively
216
243
        # two possible ways offer themselves : in self._unlock, write the cache
220
247
        wt_trans = self.bzrdir.get_workingtree_transport(None)
221
248
        cache_filename = wt_trans.local_abspath('stat-cache')
222
249
        self._hashcache = hashcache.HashCache(basedir, cache_filename,
223
 
            self.bzrdir._get_file_mode(),
224
 
            self._content_filter_stack_provider())
 
250
                                              self._control_files._file_mode)
225
251
        hc = self._hashcache
226
252
        hc.read()
227
253
        # is this scan needed ? it makes things kinda slow.
241
267
            # the Format factory and creation methods that are
242
268
            # permitted to do this.
243
269
            self._set_inventory(_inventory, dirty=False)
244
 
        self._detect_case_handling()
245
 
        self._rules_searcher = None
246
 
        self.views = self._make_views()
247
 
 
248
 
    @property
249
 
    def user_transport(self):
250
 
        return self.bzrdir.user_transport
251
 
 
252
 
    @property
253
 
    def control_transport(self):
254
 
        return self._transport
255
 
 
256
 
    def _detect_case_handling(self):
257
 
        wt_trans = self.bzrdir.get_workingtree_transport(None)
258
 
        try:
259
 
            wt_trans.stat(self._format.case_sensitive_filename)
260
 
        except errors.NoSuchFile:
261
 
            self.case_sensitive = True
262
 
        else:
263
 
            self.case_sensitive = False
264
 
 
265
 
        self._setup_directory_is_tree_reference()
266
270
 
267
271
    branch = property(
268
272
        fget=lambda self: self._branch,
283
287
        self._control_files.break_lock()
284
288
        self.branch.break_lock()
285
289
 
286
 
    def _get_check_refs(self):
287
 
        """Return the references needed to perform a check of this tree.
288
 
        
289
 
        The default implementation returns no refs, and is only suitable for
290
 
        trees that have no local caching and can commit on ghosts at any time.
291
 
 
292
 
        :seealso: bzrlib.check for details about check_refs.
293
 
        """
294
 
        return []
295
 
 
296
290
    def requires_rich_root(self):
297
291
        return self._format.requires_rich_root
298
292
 
299
293
    def supports_tree_reference(self):
300
294
        return False
301
295
 
302
 
    def supports_content_filtering(self):
303
 
        return self._format.supports_content_filtering()
304
 
 
305
 
    def supports_views(self):
306
 
        return self.views.supports_views()
307
 
 
308
296
    def _set_inventory(self, inv, dirty):
309
297
        """Set the internal cached inventory.
310
298
 
315
303
            False then the inventory is the same as that on disk and any
316
304
            serialisation would be unneeded overhead.
317
305
        """
 
306
        assert inv.root is not None
318
307
        self._inventory = inv
319
308
        self._inventory_is_modified = dirty
320
309
 
324
313
 
325
314
        """
326
315
        if path is None:
327
 
            path = osutils.getcwd()
 
316
            path = os.path.getcwdu()
328
317
        control = bzrdir.BzrDir.open(path, _unsupported)
329
318
        return control.open_workingtree(_unsupported)
330
 
 
 
319
        
331
320
    @staticmethod
332
321
    def open_containing(path=None):
333
322
        """Open an existing working tree which has its root about path.
334
 
 
 
323
        
335
324
        This probes for a working tree at path and searches upwards from there.
336
325
 
337
326
        Basically we keep looking up until we find the control directory or
344
333
        if path is None:
345
334
            path = osutils.getcwd()
346
335
        control, relpath = bzrdir.BzrDir.open_containing(path)
 
336
 
347
337
        return control.open_workingtree(), relpath
348
338
 
349
339
    @staticmethod
350
 
    def open_containing_paths(file_list, default_directory=None,
351
 
                              canonicalize=True, apply_view=True):
352
 
        """Open the WorkingTree that contains a set of paths.
353
 
 
354
 
        Fail if the paths given are not all in a single tree.
355
 
 
356
 
        This is used for the many command-line interfaces that take a list of
357
 
        any number of files and that require they all be in the same tree.
358
 
        """
359
 
        if default_directory is None:
360
 
            default_directory = u'.'
361
 
        # recommended replacement for builtins.internal_tree_files
362
 
        if file_list is None or len(file_list) == 0:
363
 
            tree = WorkingTree.open_containing(default_directory)[0]
364
 
            # XXX: doesn't really belong here, and seems to have the strange
365
 
            # side effect of making it return a bunch of files, not the whole
366
 
            # tree -- mbp 20100716
367
 
            if tree.supports_views() and apply_view:
368
 
                view_files = tree.views.lookup_view()
369
 
                if view_files:
370
 
                    file_list = view_files
371
 
                    view_str = views.view_display_str(view_files)
372
 
                    note("Ignoring files outside view. View is %s" % view_str)
373
 
            return tree, file_list
374
 
        if default_directory == u'.':
375
 
            seed = file_list[0]
376
 
        else:
377
 
            seed = default_directory
378
 
            file_list = [osutils.pathjoin(default_directory, f)
379
 
                         for f in file_list]
380
 
        tree = WorkingTree.open_containing(seed)[0]
381
 
        return tree, tree.safe_relpath_files(file_list, canonicalize,
382
 
                                             apply_view=apply_view)
383
 
 
384
 
    def safe_relpath_files(self, file_list, canonicalize=True, apply_view=True):
385
 
        """Convert file_list into a list of relpaths in tree.
386
 
 
387
 
        :param self: A tree to operate on.
388
 
        :param file_list: A list of user provided paths or None.
389
 
        :param apply_view: if True and a view is set, apply it or check that
390
 
            specified files are within it
391
 
        :return: A list of relative paths.
392
 
        :raises errors.PathNotChild: When a provided path is in a different self
393
 
            than self.
394
 
        """
395
 
        if file_list is None:
396
 
            return None
397
 
        if self.supports_views() and apply_view:
398
 
            view_files = self.views.lookup_view()
399
 
        else:
400
 
            view_files = []
401
 
        new_list = []
402
 
        # self.relpath exists as a "thunk" to osutils, but canonical_relpath
403
 
        # doesn't - fix that up here before we enter the loop.
404
 
        if canonicalize:
405
 
            fixer = lambda p: osutils.canonical_relpath(self.basedir, p)
406
 
        else:
407
 
            fixer = self.relpath
408
 
        for filename in file_list:
409
 
            relpath = fixer(osutils.dereference_path(filename))
410
 
            if view_files and not osutils.is_inside_any(view_files, relpath):
411
 
                raise errors.FileOutsideView(filename, view_files)
412
 
            new_list.append(relpath)
413
 
        return new_list
414
 
 
415
 
    @staticmethod
416
340
    def open_downlevel(path=None):
417
341
        """Open an unsupported working tree.
418
342
 
420
344
        """
421
345
        return WorkingTree.open(path, _unsupported=True)
422
346
 
423
 
    @staticmethod
424
 
    def find_trees(location):
425
 
        def list_current(transport):
426
 
            return [d for d in transport.list_dir('') if d != '.bzr']
427
 
        def evaluate(bzrdir):
428
 
            try:
429
 
                tree = bzrdir.open_workingtree()
430
 
            except errors.NoWorkingTree:
431
 
                return True, None
432
 
            else:
433
 
                return True, tree
434
 
        t = transport.get_transport(location)
435
 
        iterator = bzrdir.BzrDir.find_bzrdirs(t, evaluate=evaluate,
436
 
                                              list_current=list_current)
437
 
        return [tr for tr in iterator if tr is not None]
438
 
 
439
347
    # should be deprecated - this is slow and in any case treating them as a
440
348
    # container is (we now know) bad style -- mbp 20070302
441
349
    ## @deprecated_method(zero_fifteen)
450
358
            if osutils.lexists(self.abspath(path)):
451
359
                yield ie.file_id
452
360
 
453
 
    def all_file_ids(self):
454
 
        """See Tree.iter_all_file_ids"""
455
 
        return set(self.inventory)
456
 
 
457
361
    def __repr__(self):
458
362
        return "<%s of %s>" % (self.__class__.__name__,
459
363
                               getattr(self, 'basedir', None))
460
364
 
461
365
    def abspath(self, filename):
462
366
        return pathjoin(self.basedir, filename)
463
 
 
 
367
    
464
368
    def basis_tree(self):
465
369
        """Return RevisionTree for the current last revision.
466
 
 
 
370
        
467
371
        If the left most parent is a ghost then the returned tree will be an
468
 
        empty tree - one obtained by calling
469
 
        repository.revision_tree(NULL_REVISION).
 
372
        empty tree - one obtained by calling repository.revision_tree(None).
470
373
        """
471
374
        try:
472
375
            revision_id = self.get_parent_ids()[0]
474
377
            # no parents, return an empty revision tree.
475
378
            # in the future this should return the tree for
476
379
            # 'empty:' - the implicit root empty tree.
477
 
            return self.branch.repository.revision_tree(
478
 
                       _mod_revision.NULL_REVISION)
 
380
            return self.branch.repository.revision_tree(None)
479
381
        try:
480
382
            return self.revision_tree(revision_id)
481
383
        except errors.NoSuchRevision:
485
387
        # at this point ?
486
388
        try:
487
389
            return self.branch.repository.revision_tree(revision_id)
488
 
        except (errors.RevisionNotPresent, errors.NoSuchRevision):
 
390
        except errors.RevisionNotPresent:
489
391
            # the basis tree *may* be a ghost or a low level error may have
490
 
            # occurred. If the revision is present, its a problem, if its not
 
392
            # occured. If the revision is present, its a problem, if its not
491
393
            # its a ghost.
492
394
            if self.branch.repository.has_revision(revision_id):
493
395
                raise
494
396
            # the basis tree is a ghost so return an empty tree.
495
 
            return self.branch.repository.revision_tree(
496
 
                       _mod_revision.NULL_REVISION)
497
 
 
498
 
    def _cleanup(self):
499
 
        self._flush_ignore_list_cache()
 
397
            return self.branch.repository.revision_tree(None)
 
398
 
 
399
    @staticmethod
 
400
    @deprecated_method(zero_eight)
 
401
    def create(branch, directory):
 
402
        """Create a workingtree for branch at directory.
 
403
 
 
404
        If existing_directory already exists it must have a .bzr directory.
 
405
        If it does not exist, it will be created.
 
406
 
 
407
        This returns a new WorkingTree object for the new checkout.
 
408
 
 
409
        TODO FIXME RBC 20060124 when we have checkout formats in place this
 
410
        should accept an optional revisionid to checkout [and reject this if
 
411
        checking out into the same dir as a pre-checkout-aware branch format.]
 
412
 
 
413
        XXX: When BzrDir is present, these should be created through that 
 
414
        interface instead.
 
415
        """
 
416
        warnings.warn('delete WorkingTree.create', stacklevel=3)
 
417
        transport = get_transport(directory)
 
418
        if branch.bzrdir.root_transport.base == transport.base:
 
419
            # same dir 
 
420
            return branch.bzrdir.create_workingtree()
 
421
        # different directory, 
 
422
        # create a branch reference
 
423
        # and now a working tree.
 
424
        raise NotImplementedError
 
425
 
 
426
    @staticmethod
 
427
    @deprecated_method(zero_eight)
 
428
    def create_standalone(directory):
 
429
        """Create a checkout and a branch and a repo at directory.
 
430
 
 
431
        Directory must exist and be empty.
 
432
 
 
433
        please use BzrDir.create_standalone_workingtree
 
434
        """
 
435
        return bzrdir.BzrDir.create_standalone_workingtree(directory)
500
436
 
501
437
    def relpath(self, path):
502
438
        """Return the local path portion from a given path.
503
 
 
504
 
        The path may be absolute or relative. If its a relative path it is
 
439
        
 
440
        The path may be absolute or relative. If its a relative path it is 
505
441
        interpreted relative to the python current working directory.
506
442
        """
507
443
        return osutils.relpath(self.basedir, path)
509
445
    def has_filename(self, filename):
510
446
        return osutils.lexists(self.abspath(filename))
511
447
 
512
 
    def get_file(self, file_id, path=None, filtered=True):
513
 
        return self.get_file_with_stat(file_id, path, filtered=filtered)[0]
514
 
 
515
 
    def get_file_with_stat(self, file_id, path=None, filtered=True,
516
 
        _fstat=os.fstat):
517
 
        """See Tree.get_file_with_stat."""
518
 
        if path is None:
519
 
            path = self.id2path(file_id)
520
 
        file_obj = self.get_file_byname(path, filtered=False)
521
 
        stat_value = _fstat(file_obj.fileno())
522
 
        if filtered and self.supports_content_filtering():
523
 
            filters = self._content_filter_stack(path)
524
 
            file_obj = filtered_input_file(file_obj, filters)
525
 
        return (file_obj, stat_value)
526
 
 
527
 
    def get_file_text(self, file_id, path=None, filtered=True):
528
 
        my_file = self.get_file(file_id, path=path, filtered=filtered)
529
 
        try:
530
 
            return my_file.read()
531
 
        finally:
532
 
            my_file.close()
533
 
 
534
 
    def get_file_byname(self, filename, filtered=True):
535
 
        path = self.abspath(filename)
536
 
        f = file(path, 'rb')
537
 
        if filtered and self.supports_content_filtering():
538
 
            filters = self._content_filter_stack(filename)
539
 
            return filtered_input_file(f, filters)
540
 
        else:
541
 
            return f
542
 
 
543
 
    def get_file_lines(self, file_id, path=None, filtered=True):
544
 
        """See Tree.get_file_lines()"""
545
 
        file = self.get_file(file_id, path, filtered=filtered)
546
 
        try:
547
 
            return file.readlines()
548
 
        finally:
549
 
            file.close()
 
448
    def get_file(self, file_id):
 
449
        file_id = osutils.safe_file_id(file_id)
 
450
        return self.get_file_byname(self.id2path(file_id))
 
451
 
 
452
    def get_file_text(self, file_id):
 
453
        file_id = osutils.safe_file_id(file_id)
 
454
        return self.get_file(file_id).read()
 
455
 
 
456
    def get_file_byname(self, filename):
 
457
        return file(self.abspath(filename), 'rb')
550
458
 
551
459
    @needs_read_lock
552
 
    def annotate_iter(self, file_id, default_revision=CURRENT_REVISION):
 
460
    def annotate_iter(self, file_id):
553
461
        """See Tree.annotate_iter
554
462
 
555
463
        This implementation will use the basis tree implementation if possible.
559
467
        incorrectly attributed to CURRENT_REVISION (but after committing, the
560
468
        attribution will be correct).
561
469
        """
562
 
        maybe_file_parent_keys = []
563
 
        for parent_id in self.get_parent_ids():
564
 
            try:
565
 
                parent_tree = self.revision_tree(parent_id)
566
 
            except errors.NoSuchRevisionInTree:
567
 
                parent_tree = self.branch.repository.revision_tree(parent_id)
568
 
            parent_tree.lock_read()
569
 
            try:
570
 
                if file_id not in parent_tree:
571
 
                    continue
572
 
                ie = parent_tree.inventory[file_id]
573
 
                if ie.kind != 'file':
574
 
                    # Note: this is slightly unnecessary, because symlinks and
575
 
                    # directories have a "text" which is the empty text, and we
576
 
                    # know that won't mess up annotations. But it seems cleaner
577
 
                    continue
578
 
                parent_text_key = (file_id, ie.revision)
579
 
                if parent_text_key not in maybe_file_parent_keys:
580
 
                    maybe_file_parent_keys.append(parent_text_key)
581
 
            finally:
582
 
                parent_tree.unlock()
583
 
        graph = _mod_graph.Graph(self.branch.repository.texts)
584
 
        heads = graph.heads(maybe_file_parent_keys)
585
 
        file_parent_keys = []
586
 
        for key in maybe_file_parent_keys:
587
 
            if key in heads:
588
 
                file_parent_keys.append(key)
589
 
 
590
 
        # Now we have the parents of this content
591
 
        annotator = self.branch.repository.texts.get_annotator()
592
 
        text = self.get_file_text(file_id)
593
 
        this_key =(file_id, default_revision)
594
 
        annotator.add_special_text(this_key, file_parent_keys, text)
595
 
        annotations = [(key[-1], line)
596
 
                       for key, line in annotator.annotate_flat(this_key)]
597
 
        return annotations
598
 
 
599
 
    def _get_ancestors(self, default_revision):
600
 
        ancestors = set([default_revision])
601
 
        for parent_id in self.get_parent_ids():
602
 
            ancestors.update(self.branch.repository.get_ancestry(
603
 
                             parent_id, topo_sorted=False))
604
 
        return ancestors
 
470
        file_id = osutils.safe_file_id(file_id)
 
471
        basis = self.basis_tree()
 
472
        basis.lock_read()
 
473
        try:
 
474
            changes = self._iter_changes(basis, True, [self.id2path(file_id)],
 
475
                require_versioned=True).next()
 
476
            changed_content, kind = changes[2], changes[6]
 
477
            if not changed_content:
 
478
                return basis.annotate_iter(file_id)
 
479
            if kind[1] is None:
 
480
                return None
 
481
            import annotate
 
482
            if kind[0] != 'file':
 
483
                old_lines = []
 
484
            else:
 
485
                old_lines = list(basis.annotate_iter(file_id))
 
486
            old = [old_lines]
 
487
            for tree in self.branch.repository.revision_trees(
 
488
                self.get_parent_ids()[1:]):
 
489
                if file_id not in tree:
 
490
                    continue
 
491
                old.append(list(tree.annotate_iter(file_id)))
 
492
            return annotate.reannotate(old, self.get_file(file_id).readlines(),
 
493
                                       CURRENT_REVISION)
 
494
        finally:
 
495
            basis.unlock()
605
496
 
606
497
    def get_parent_ids(self):
607
498
        """See Tree.get_parent_ids.
608
 
 
 
499
        
609
500
        This implementation reads the pending merges list and last_revision
610
501
        value and uses that to decide what the parents list should be.
611
502
        """
612
 
        last_rev = _mod_revision.ensure_null(self._last_revision())
613
 
        if _mod_revision.NULL_REVISION == last_rev:
 
503
        last_rev = self._last_revision()
 
504
        if last_rev is None:
614
505
            parents = []
615
506
        else:
616
507
            parents = [last_rev]
617
508
        try:
618
 
            merges_bytes = self._transport.get_bytes('pending-merges')
 
509
            merges_file = self._control_files.get('pending-merges')
619
510
        except errors.NoSuchFile:
620
511
            pass
621
512
        else:
622
 
            for l in osutils.split_lines(merges_bytes):
623
 
                revision_id = l.rstrip('\n')
 
513
            for l in merges_file.readlines():
 
514
                revision_id = osutils.safe_revision_id(l.rstrip('\n'))
624
515
                parents.append(revision_id)
625
516
        return parents
626
517
 
628
519
    def get_root_id(self):
629
520
        """Return the id of this trees root"""
630
521
        return self._inventory.root.file_id
631
 
 
 
522
        
632
523
    def _get_store_filename(self, file_id):
633
524
        ## XXX: badly named; this is not in the store at all
 
525
        file_id = osutils.safe_file_id(file_id)
634
526
        return self.abspath(self.id2path(file_id))
635
527
 
636
528
    @needs_read_lock
637
529
    def clone(self, to_bzrdir, revision_id=None):
638
530
        """Duplicate this working tree into to_bzr, including all state.
639
 
 
 
531
        
640
532
        Specifically modified files are kept as modified, but
641
533
        ignored and unknown files are discarded.
642
534
 
643
535
        If you want to make a new line of development, see bzrdir.sprout()
644
536
 
645
537
        revision
646
 
            If not None, the cloned tree will have its last revision set to
647
 
            revision, and difference between the source trees last revision
 
538
            If not None, the cloned tree will have its last revision set to 
 
539
            revision, and and difference between the source trees last revision
648
540
            and this one merged in.
649
541
        """
650
542
        # assumes the target bzr dir format is compatible.
651
 
        result = to_bzrdir.create_workingtree()
 
543
        result = self._format.initialize(to_bzrdir)
652
544
        self.copy_content_into(result, revision_id)
653
545
        return result
654
546
 
665
557
            tree.set_parent_ids([revision_id])
666
558
 
667
559
    def id2abspath(self, file_id):
 
560
        file_id = osutils.safe_file_id(file_id)
668
561
        return self.abspath(self.id2path(file_id))
669
562
 
670
563
    def has_id(self, file_id):
671
564
        # files that have been deleted are excluded
 
565
        file_id = osutils.safe_file_id(file_id)
672
566
        inv = self.inventory
673
567
        if not inv.has_id(file_id):
674
568
            return False
676
570
        return osutils.lexists(self.abspath(path))
677
571
 
678
572
    def has_or_had_id(self, file_id):
 
573
        file_id = osutils.safe_file_id(file_id)
679
574
        if file_id == self.inventory.root.file_id:
680
575
            return True
681
576
        return self.inventory.has_id(file_id)
683
578
    __contains__ = has_id
684
579
 
685
580
    def get_file_size(self, file_id):
686
 
        """See Tree.get_file_size"""
687
 
        # XXX: this returns the on-disk size; it should probably return the
688
 
        # canonical size
689
 
        try:
690
 
            return os.path.getsize(self.id2abspath(file_id))
691
 
        except OSError, e:
692
 
            if e.errno != errno.ENOENT:
693
 
                raise
694
 
            else:
695
 
                return None
 
581
        file_id = osutils.safe_file_id(file_id)
 
582
        return os.path.getsize(self.id2abspath(file_id))
696
583
 
697
584
    @needs_read_lock
698
585
    def get_file_sha1(self, file_id, path=None, stat_value=None):
 
586
        file_id = osutils.safe_file_id(file_id)
699
587
        if not path:
700
588
            path = self._inventory.id2path(file_id)
701
589
        return self._hashcache.get_sha1(path, stat_value)
702
590
 
703
591
    def get_file_mtime(self, file_id, path=None):
 
592
        file_id = osutils.safe_file_id(file_id)
704
593
        if not path:
705
594
            path = self.inventory.id2path(file_id)
706
595
        return os.lstat(self.abspath(path)).st_mtime
707
596
 
708
 
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
709
 
        file_id = self.path2id(path)
710
 
        if file_id is None:
711
 
            # For unversioned files on win32, we just assume they are not
712
 
            # executable
713
 
            return False
714
 
        return self._inventory[file_id].executable
715
 
 
716
 
    def _is_executable_from_path_and_stat_from_stat(self, path, stat_result):
717
 
        mode = stat_result.st_mode
718
 
        return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
719
 
 
720
597
    if not supports_executable():
721
598
        def is_executable(self, file_id, path=None):
 
599
            file_id = osutils.safe_file_id(file_id)
722
600
            return self._inventory[file_id].executable
723
 
 
724
 
        _is_executable_from_path_and_stat = \
725
 
            _is_executable_from_path_and_stat_from_basis
726
601
    else:
727
602
        def is_executable(self, file_id, path=None):
728
603
            if not path:
 
604
                file_id = osutils.safe_file_id(file_id)
729
605
                path = self.id2path(file_id)
730
606
            mode = os.lstat(self.abspath(path)).st_mode
731
607
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
732
608
 
733
 
        _is_executable_from_path_and_stat = \
734
 
            _is_executable_from_path_and_stat_from_stat
735
 
 
736
609
    @needs_tree_write_lock
737
610
    def _add(self, files, ids, kinds):
738
611
        """See MutableTree._add."""
739
612
        # TODO: Re-adding a file that is removed in the working copy
740
613
        # should probably put it back with the previous ID.
741
 
        # the read and write working inventory should not occur in this
 
614
        # the read and write working inventory should not occur in this 
742
615
        # function - they should be part of lock_write and unlock.
743
 
        inv = self.inventory
 
616
        inv = self.read_working_inventory()
744
617
        for f, file_id, kind in zip(files, ids, kinds):
 
618
            assert kind is not None
745
619
            if file_id is None:
746
620
                inv.add_path(f, kind=kind)
747
621
            else:
 
622
                file_id = osutils.safe_file_id(file_id)
748
623
                inv.add_path(f, kind=kind, file_id=file_id)
749
 
            self._inventory_is_modified = True
 
624
        self._write_inventory(inv)
750
625
 
751
626
    @needs_tree_write_lock
752
627
    def _gather_kinds(self, files, kinds):
812
687
        if updated:
813
688
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
814
689
 
815
 
    def path_content_summary(self, path, _lstat=os.lstat,
816
 
        _mapper=osutils.file_kind_from_stat_mode):
817
 
        """See Tree.path_content_summary."""
818
 
        abspath = self.abspath(path)
819
 
        try:
820
 
            stat_result = _lstat(abspath)
821
 
        except OSError, e:
822
 
            if getattr(e, 'errno', None) == errno.ENOENT:
823
 
                # no file.
824
 
                return ('missing', None, None, None)
825
 
            # propagate other errors
826
 
            raise
827
 
        kind = _mapper(stat_result.st_mode)
828
 
        if kind == 'file':
829
 
            return self._file_content_summary(path, stat_result)
830
 
        elif kind == 'directory':
831
 
            # perhaps it looks like a plain directory, but it's really a
832
 
            # reference.
833
 
            if self._directory_is_tree_reference(path):
834
 
                kind = 'tree-reference'
835
 
            return kind, None, None, None
836
 
        elif kind == 'symlink':
837
 
            target = osutils.readlink(abspath)
838
 
            return ('symlink', None, None, target)
839
 
        else:
840
 
            return (kind, None, None, None)
841
 
 
842
 
    def _file_content_summary(self, path, stat_result):
843
 
        size = stat_result.st_size
844
 
        executable = self._is_executable_from_path_and_stat(path, stat_result)
845
 
        # try for a stat cache lookup
846
 
        return ('file', size, executable, self._sha_from_stat(
847
 
            path, stat_result))
 
690
    @deprecated_method(zero_eleven)
 
691
    @needs_read_lock
 
692
    def pending_merges(self):
 
693
        """Return a list of pending merges.
 
694
 
 
695
        These are revisions that have been merged into the working
 
696
        directory but not yet committed.
 
697
 
 
698
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
 
699
        instead - which is available on all tree objects.
 
700
        """
 
701
        return self.get_parent_ids()[1:]
848
702
 
849
703
    def _check_parents_for_ghosts(self, revision_ids, allow_leftmost_as_ghost):
850
704
        """Common ghost checking functionality from set_parent_*.
860
714
 
861
715
    def _set_merges_from_parent_ids(self, parent_ids):
862
716
        merges = parent_ids[1:]
863
 
        self._transport.put_bytes('pending-merges', '\n'.join(merges),
864
 
            mode=self.bzrdir._get_file_mode())
865
 
 
866
 
    def _filter_parent_ids_by_ancestry(self, revision_ids):
867
 
        """Check that all merged revisions are proper 'heads'.
868
 
 
869
 
        This will always return the first revision_id, and any merged revisions
870
 
        which are
871
 
        """
872
 
        if len(revision_ids) == 0:
873
 
            return revision_ids
874
 
        graph = self.branch.repository.get_graph()
875
 
        heads = graph.heads(revision_ids)
876
 
        new_revision_ids = revision_ids[:1]
877
 
        for revision_id in revision_ids[1:]:
878
 
            if revision_id in heads and revision_id not in new_revision_ids:
879
 
                new_revision_ids.append(revision_id)
880
 
        if new_revision_ids != revision_ids:
881
 
            trace.mutter('requested to set revision_ids = %s,'
882
 
                         ' but filtered to %s', revision_ids, new_revision_ids)
883
 
        return new_revision_ids
 
717
        self._control_files.put_bytes('pending-merges', '\n'.join(merges))
884
718
 
885
719
    @needs_tree_write_lock
886
720
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
887
721
        """Set the parent ids to revision_ids.
888
 
 
 
722
        
889
723
        See also set_parent_trees. This api will try to retrieve the tree data
890
724
        for each element of revision_ids from the trees repository. If you have
891
725
        tree data already available, it is more efficient to use
895
729
        :param revision_ids: The revision_ids to set as the parent ids of this
896
730
            working tree. Any of these may be ghosts.
897
731
        """
 
732
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
898
733
        self._check_parents_for_ghosts(revision_ids,
899
734
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
900
 
        for revision_id in revision_ids:
901
 
            _mod_revision.check_not_reserved_id(revision_id)
902
 
 
903
 
        revision_ids = self._filter_parent_ids_by_ancestry(revision_ids)
904
735
 
905
736
        if len(revision_ids) > 0:
906
737
            self.set_last_revision(revision_ids[0])
907
738
        else:
908
 
            self.set_last_revision(_mod_revision.NULL_REVISION)
 
739
            self.set_last_revision(None)
909
740
 
910
741
        self._set_merges_from_parent_ids(revision_ids)
911
742
 
912
743
    @needs_tree_write_lock
913
744
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
914
745
        """See MutableTree.set_parent_trees."""
915
 
        parent_ids = [rev for (rev, tree) in parents_list]
916
 
        for revision_id in parent_ids:
917
 
            _mod_revision.check_not_reserved_id(revision_id)
 
746
        parent_ids = [osutils.safe_revision_id(rev) for (rev, tree) in parents_list]
918
747
 
919
748
        self._check_parents_for_ghosts(parent_ids,
920
749
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
921
750
 
922
 
        parent_ids = self._filter_parent_ids_by_ancestry(parent_ids)
923
 
 
924
751
        if len(parent_ids) == 0:
925
 
            leftmost_parent_id = _mod_revision.NULL_REVISION
 
752
            leftmost_parent_id = None
926
753
            leftmost_parent_tree = None
927
754
        else:
928
755
            leftmost_parent_id, leftmost_parent_tree = parents_list[0]
953
780
                yield Stanza(file_id=file_id.decode('utf8'), hash=hash)
954
781
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
955
782
 
956
 
    def _sha_from_stat(self, path, stat_result):
957
 
        """Get a sha digest from the tree's stat cache.
958
 
 
959
 
        The default implementation assumes no stat cache is present.
960
 
 
961
 
        :param path: The path.
962
 
        :param stat_result: The stat result being looked up.
963
 
        """
964
 
        return None
965
 
 
966
783
    def _put_rio(self, filename, stanzas, header):
967
784
        self._must_be_locked()
968
785
        my_file = rio_file(stanzas, header)
969
 
        self._transport.put_file(filename, my_file,
970
 
            mode=self.bzrdir._get_file_mode())
 
786
        self._control_files.put(filename, my_file)
971
787
 
972
788
    @needs_write_lock # because merge pulls data into the branch.
973
 
    def merge_from_branch(self, branch, to_revision=None, from_revision=None,
974
 
                          merge_type=None, force=False):
 
789
    def merge_from_branch(self, branch, to_revision=None):
975
790
        """Merge from a branch into this working tree.
976
791
 
977
792
        :param branch: The branch to merge from.
981
796
            branch.last_revision().
982
797
        """
983
798
        from bzrlib.merge import Merger, Merge3Merger
984
 
        merger = Merger(self.branch, this_tree=self)
985
 
        # check that there are no local alterations
986
 
        if not force and self.has_changes():
987
 
            raise errors.UncommittedChanges(self)
988
 
        if to_revision is None:
989
 
            to_revision = _mod_revision.ensure_null(branch.last_revision())
990
 
        merger.other_rev_id = to_revision
991
 
        if _mod_revision.is_null(merger.other_rev_id):
992
 
            raise errors.NoCommits(branch)
993
 
        self.branch.fetch(branch, last_revision=merger.other_rev_id)
994
 
        merger.other_basis = merger.other_rev_id
995
 
        merger.other_tree = self.branch.repository.revision_tree(
996
 
            merger.other_rev_id)
997
 
        merger.other_branch = branch
998
 
        if from_revision is None:
 
799
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
 
800
        try:
 
801
            merger = Merger(self.branch, this_tree=self, pb=pb)
 
802
            merger.pp = ProgressPhase("Merge phase", 5, pb)
 
803
            merger.pp.next_phase()
 
804
            # check that there are no
 
805
            # local alterations
 
806
            merger.check_basis(check_clean=True, require_commits=False)
 
807
            if to_revision is None:
 
808
                to_revision = branch.last_revision()
 
809
            else:
 
810
                to_revision = osutils.safe_revision_id(to_revision)
 
811
            merger.other_rev_id = to_revision
 
812
            if merger.other_rev_id is None:
 
813
                raise error.NoCommits(branch)
 
814
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
 
815
            merger.other_basis = merger.other_rev_id
 
816
            merger.other_tree = self.branch.repository.revision_tree(
 
817
                merger.other_rev_id)
 
818
            merger.other_branch = branch
 
819
            merger.pp.next_phase()
999
820
            merger.find_base()
1000
 
        else:
1001
 
            merger.set_base_revision(from_revision, branch)
1002
 
        if merger.base_rev_id == merger.other_rev_id:
1003
 
            raise errors.PointlessMerge
1004
 
        merger.backup_files = False
1005
 
        if merge_type is None:
 
821
            if merger.base_rev_id == merger.other_rev_id:
 
822
                raise errors.PointlessMerge
 
823
            merger.backup_files = False
1006
824
            merger.merge_type = Merge3Merger
1007
 
        else:
1008
 
            merger.merge_type = merge_type
1009
 
        merger.set_interesting_files(None)
1010
 
        merger.show_base = False
1011
 
        merger.reprocess = False
1012
 
        conflicts = merger.do_merge()
1013
 
        merger.set_pending()
 
825
            merger.set_interesting_files(None)
 
826
            merger.show_base = False
 
827
            merger.reprocess = False
 
828
            conflicts = merger.do_merge()
 
829
            merger.set_pending()
 
830
        finally:
 
831
            pb.finished()
1014
832
        return conflicts
1015
833
 
1016
834
    @needs_read_lock
1017
835
    def merge_modified(self):
1018
836
        """Return a dictionary of files modified by a merge.
1019
837
 
1020
 
        The list is initialized by WorkingTree.set_merge_modified, which is
 
838
        The list is initialized by WorkingTree.set_merge_modified, which is 
1021
839
        typically called after we make some automatic updates to the tree
1022
840
        because of a merge.
1023
841
 
1025
843
        still in the working inventory and have that text hash.
1026
844
        """
1027
845
        try:
1028
 
            hashfile = self._transport.get('merge-hashes')
 
846
            hashfile = self._control_files.get('merge-hashes')
1029
847
        except errors.NoSuchFile:
1030
848
            return {}
 
849
        merge_hashes = {}
1031
850
        try:
1032
 
            merge_hashes = {}
1033
 
            try:
1034
 
                if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
1035
 
                    raise errors.MergeModifiedFormatError()
1036
 
            except StopIteration:
 
851
            if hashfile.next() != MERGE_MODIFIED_HEADER_1 + '\n':
1037
852
                raise errors.MergeModifiedFormatError()
1038
 
            for s in RioReader(hashfile):
1039
 
                # RioReader reads in Unicode, so convert file_ids back to utf8
1040
 
                file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
1041
 
                if file_id not in self.inventory:
1042
 
                    continue
1043
 
                text_hash = s.get("hash")
1044
 
                if text_hash == self.get_file_sha1(file_id):
1045
 
                    merge_hashes[file_id] = text_hash
1046
 
            return merge_hashes
1047
 
        finally:
1048
 
            hashfile.close()
 
853
        except StopIteration:
 
854
            raise errors.MergeModifiedFormatError()
 
855
        for s in RioReader(hashfile):
 
856
            # RioReader reads in Unicode, so convert file_ids back to utf8
 
857
            file_id = osutils.safe_file_id(s.get("file_id"), warn=False)
 
858
            if file_id not in self.inventory:
 
859
                continue
 
860
            text_hash = s.get("hash")
 
861
            if text_hash == self.get_file_sha1(file_id):
 
862
                merge_hashes[file_id] = text_hash
 
863
        return merge_hashes
1049
864
 
1050
865
    @needs_write_lock
1051
866
    def mkdir(self, path, file_id=None):
1057
872
        return file_id
1058
873
 
1059
874
    def get_symlink_target(self, file_id):
1060
 
        abspath = self.id2abspath(file_id)
1061
 
        target = osutils.readlink(abspath)
1062
 
        return target
 
875
        file_id = osutils.safe_file_id(file_id)
 
876
        return os.readlink(self.id2abspath(file_id))
1063
877
 
1064
878
    @needs_write_lock
1065
879
    def subsume(self, other_tree):
1103
917
            other_tree.unlock()
1104
918
        other_tree.bzrdir.retire_bzrdir()
1105
919
 
1106
 
    def _setup_directory_is_tree_reference(self):
1107
 
        if self._branch.repository._format.supports_tree_reference:
1108
 
            self._directory_is_tree_reference = \
1109
 
                self._directory_may_be_tree_reference
1110
 
        else:
1111
 
            self._directory_is_tree_reference = \
1112
 
                self._directory_is_never_tree_reference
1113
 
 
1114
 
    def _directory_is_never_tree_reference(self, relpath):
1115
 
        return False
1116
 
 
1117
 
    def _directory_may_be_tree_reference(self, relpath):
1118
 
        # as a special case, if a directory contains control files then
1119
 
        # it's a tree reference, except that the root of the tree is not
1120
 
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
1121
 
        # TODO: We could ask all the control formats whether they
1122
 
        # recognize this directory, but at the moment there's no cheap api
1123
 
        # to do that.  Since we probably can only nest bzr checkouts and
1124
 
        # they always use this name it's ok for now.  -- mbp 20060306
1125
 
        #
1126
 
        # FIXME: There is an unhandled case here of a subdirectory
1127
 
        # containing .bzr but not a branch; that will probably blow up
1128
 
        # when you try to commit it.  It might happen if there is a
1129
 
        # checkout in a subdirectory.  This can be avoided by not adding
1130
 
        # it.  mbp 20070306
1131
 
 
1132
920
    @needs_tree_write_lock
1133
921
    def extract(self, file_id, format=None):
1134
922
        """Extract a subtree from this tree.
1135
 
 
 
923
        
1136
924
        A new branch will be created, relative to the path for this tree.
1137
925
        """
1138
926
        self.flush()
1141
929
            transport = self.branch.bzrdir.root_transport
1142
930
            for name in segments:
1143
931
                transport = transport.clone(name)
1144
 
                transport.ensure_base()
 
932
                try:
 
933
                    transport.mkdir('.')
 
934
                except errors.FileExists:
 
935
                    pass
1145
936
            return transport
1146
 
 
 
937
            
1147
938
        sub_path = self.id2path(file_id)
1148
939
        branch_transport = mkdirs(sub_path)
1149
940
        if format is None:
1150
 
            format = self.bzrdir.cloning_metadir()
1151
 
        branch_transport.ensure_base()
 
941
            format = bzrdir.format_registry.make_bzrdir('dirstate-with-subtree')
 
942
        try:
 
943
            branch_transport.mkdir('.')
 
944
        except errors.FileExists:
 
945
            pass
1152
946
        branch_bzrdir = format.initialize_on_transport(branch_transport)
1153
947
        try:
1154
948
            repo = branch_bzrdir.find_repository()
1155
949
        except errors.NoRepositoryPresent:
1156
950
            repo = branch_bzrdir.create_repository()
1157
 
        if not repo.supports_rich_root():
1158
 
            raise errors.RootNotRich()
 
951
            assert repo.supports_rich_root()
 
952
        else:
 
953
            if not repo.supports_rich_root():
 
954
                raise errors.RootNotRich()
1159
955
        new_branch = branch_bzrdir.create_branch()
1160
956
        new_branch.pull(self.branch)
1161
957
        for parent_id in self.get_parent_ids():
1163
959
        tree_transport = self.bzrdir.root_transport.clone(sub_path)
1164
960
        if tree_transport.base != branch_transport.base:
1165
961
            tree_bzrdir = format.initialize_on_transport(tree_transport)
1166
 
            branch.BranchReferenceFormat().initialize(tree_bzrdir,
1167
 
                target_branch=new_branch)
 
962
            branch.BranchReferenceFormat().initialize(tree_bzrdir, new_branch)
1168
963
        else:
1169
964
            tree_bzrdir = branch_bzrdir
1170
 
        wt = tree_bzrdir.create_workingtree(_mod_revision.NULL_REVISION)
 
965
        wt = tree_bzrdir.create_workingtree(NULL_REVISION)
1171
966
        wt.set_parent_ids(self.get_parent_ids())
1172
967
        my_inv = self.inventory
1173
 
        child_inv = inventory.Inventory(root_id=None)
 
968
        child_inv = Inventory(root_id=None)
1174
969
        new_root = my_inv[file_id]
1175
970
        my_inv.remove_recursive_id(file_id)
1176
971
        new_root.parent_id = None
1180
975
        return wt
1181
976
 
1182
977
    def _serialize(self, inventory, out_file):
1183
 
        xml5.serializer_v5.write_inventory(self._inventory, out_file,
1184
 
            working=True)
 
978
        xml5.serializer_v5.write_inventory(self._inventory, out_file)
1185
979
 
1186
980
    def _deserialize(selt, in_file):
1187
981
        return xml5.serializer_v5.read_inventory(in_file)
1194
988
        sio = StringIO()
1195
989
        self._serialize(self._inventory, sio)
1196
990
        sio.seek(0)
1197
 
        self._transport.put_file('inventory', sio,
1198
 
            mode=self.bzrdir._get_file_mode())
 
991
        self._control_files.put('inventory', sio)
1199
992
        self._inventory_is_modified = False
1200
993
 
1201
994
    def _kind(self, relpath):
1202
995
        return osutils.file_kind(self.abspath(relpath))
1203
996
 
1204
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
1205
 
        """List all files as (path, class, kind, id, entry).
 
997
    def list_files(self, include_root=False):
 
998
        """Recursively list all files as (path, class, kind, id, entry).
1206
999
 
1207
1000
        Lists, but does not descend into unversioned directories.
 
1001
 
1208
1002
        This does not include files that have been deleted in this
1209
 
        tree. Skips the control directory.
 
1003
        tree.
1210
1004
 
1211
 
        :param include_root: if True, return an entry for the root
1212
 
        :param from_dir: start from this directory or None for the root
1213
 
        :param recursive: whether to recurse into subdirectories or not
 
1005
        Skips the control directory.
1214
1006
        """
1215
1007
        # list_files is an iterator, so @needs_read_lock doesn't work properly
1216
1008
        # with it. So callers should be careful to always read_lock the tree.
1218
1010
            raise errors.ObjectNotLocked(self)
1219
1011
 
1220
1012
        inv = self.inventory
1221
 
        if from_dir is None and include_root is True:
 
1013
        if include_root is True:
1222
1014
            yield ('', 'V', 'directory', inv.root.file_id, inv.root)
1223
1015
        # Convert these into local objects to save lookup times
1224
1016
        pathjoin = osutils.pathjoin
1231
1023
        fk_entries = {'directory':TreeDirectory, 'file':TreeFile, 'symlink':TreeLink}
1232
1024
 
1233
1025
        # directory file_id, relative path, absolute path, reverse sorted children
1234
 
        if from_dir is not None:
1235
 
            from_dir_id = inv.path2id(from_dir)
1236
 
            if from_dir_id is None:
1237
 
                # Directory not versioned
1238
 
                return
1239
 
            from_dir_abspath = pathjoin(self.basedir, from_dir)
1240
 
        else:
1241
 
            from_dir_id = inv.root.file_id
1242
 
            from_dir_abspath = self.basedir
1243
 
        children = os.listdir(from_dir_abspath)
 
1026
        children = os.listdir(self.basedir)
1244
1027
        children.sort()
1245
 
        # jam 20060527 The kernel sized tree seems equivalent whether we
 
1028
        # jam 20060527 The kernel sized tree seems equivalent whether we 
1246
1029
        # use a deque and popleft to keep them sorted, or if we use a plain
1247
1030
        # list and just reverse() them.
1248
1031
        children = collections.deque(children)
1249
 
        stack = [(from_dir_id, u'', from_dir_abspath, children)]
 
1032
        stack = [(inv.root.file_id, u'', self.basedir, children)]
1250
1033
        while stack:
1251
1034
            from_dir_id, from_dir_relpath, from_dir_abspath, children = stack[-1]
1252
1035
 
1268
1051
 
1269
1052
                # absolute path
1270
1053
                fap = from_dir_abspath + '/' + f
1271
 
 
1272
 
                dir_ie = inv[from_dir_id]
1273
 
                if dir_ie.kind == 'directory':
1274
 
                    f_ie = dir_ie.children.get(f)
1275
 
                else:
1276
 
                    f_ie = None
 
1054
                
 
1055
                f_ie = inv.get_child(from_dir_id, f)
1277
1056
                if f_ie:
1278
1057
                    c = 'V'
1279
1058
                elif self.is_ignored(fp[1:]):
1280
1059
                    c = 'I'
1281
1060
                else:
1282
 
                    # we may not have found this file, because of a unicode
1283
 
                    # issue, or because the directory was actually a symlink.
 
1061
                    # we may not have found this file, because of a unicode issue
1284
1062
                    f_norm, can_access = osutils.normalized_filename(f)
1285
1063
                    if f == f_norm or not can_access:
1286
1064
                        # No change, so treat this file normally
1311
1089
                    except KeyError:
1312
1090
                        yield fp[1:], c, fk, None, TreeEntry()
1313
1091
                    continue
1314
 
 
 
1092
                
1315
1093
                if fk != 'directory':
1316
1094
                    continue
1317
1095
 
1318
 
                # But do this child first if recursing down
1319
 
                if recursive:
1320
 
                    new_children = os.listdir(fap)
1321
 
                    new_children.sort()
1322
 
                    new_children = collections.deque(new_children)
1323
 
                    stack.append((f_ie.file_id, fp, fap, new_children))
1324
 
                    # Break out of inner loop,
1325
 
                    # so that we start outer loop with child
1326
 
                    break
 
1096
                # But do this child first
 
1097
                new_children = os.listdir(fap)
 
1098
                new_children.sort()
 
1099
                new_children = collections.deque(new_children)
 
1100
                stack.append((f_ie.file_id, fp, fap, new_children))
 
1101
                # Break out of inner loop,
 
1102
                # so that we start outer loop with child
 
1103
                break
1327
1104
            else:
1328
1105
                # if we finished all children, pop it off the stack
1329
1106
                stack.pop()
1330
1107
 
1331
1108
    @needs_tree_write_lock
1332
 
    def move(self, from_paths, to_dir=None, after=False):
 
1109
    def move(self, from_paths, to_dir=None, after=False, **kwargs):
1333
1110
        """Rename files.
1334
1111
 
1335
1112
        to_dir must exist in the inventory.
1336
1113
 
1337
1114
        If to_dir exists and is a directory, the files are moved into
1338
 
        it, keeping their old names.
 
1115
        it, keeping their old names.  
1339
1116
 
1340
1117
        Note that to_dir is only the last component of the new name;
1341
1118
        this doesn't change the directory.
1369
1146
 
1370
1147
        # check for deprecated use of signature
1371
1148
        if to_dir is None:
1372
 
            raise TypeError('You must supply a target directory')
 
1149
            to_dir = kwargs.get('to_name', None)
 
1150
            if to_dir is None:
 
1151
                raise TypeError('You must supply a target directory')
 
1152
            else:
 
1153
                symbol_versioning.warn('The parameter to_name was deprecated'
 
1154
                                       ' in version 0.13. Use to_dir instead',
 
1155
                                       DeprecationWarning)
 
1156
 
1373
1157
        # check destination directory
1374
 
        if isinstance(from_paths, basestring):
1375
 
            raise ValueError()
 
1158
        assert not isinstance(from_paths, basestring)
1376
1159
        inv = self.inventory
1377
1160
        to_abs = self.abspath(to_dir)
1378
1161
        if not isdir(to_abs):
1384
1167
        to_dir_id = inv.path2id(to_dir)
1385
1168
        if to_dir_id is None:
1386
1169
            raise errors.BzrMoveFailedError('',to_dir,
1387
 
                errors.NotVersionedError(path=to_dir))
 
1170
                errors.NotVersionedError(path=str(to_dir)))
1388
1171
 
1389
1172
        to_dir_ie = inv[to_dir_id]
1390
1173
        if to_dir_ie.kind != 'directory':
1397
1180
            from_id = inv.path2id(from_rel)
1398
1181
            if from_id is None:
1399
1182
                raise errors.BzrMoveFailedError(from_rel,to_dir,
1400
 
                    errors.NotVersionedError(path=from_rel))
 
1183
                    errors.NotVersionedError(path=str(from_rel)))
1401
1184
 
1402
1185
            from_entry = inv[from_id]
1403
1186
            from_parent_id = from_entry.parent_id
1445
1228
            # check the inventory for source and destination
1446
1229
            if from_id is None:
1447
1230
                raise errors.BzrMoveFailedError(from_rel,to_rel,
1448
 
                    errors.NotVersionedError(path=from_rel))
 
1231
                    errors.NotVersionedError(path=str(from_rel)))
1449
1232
            if to_id is not None:
1450
1233
                raise errors.BzrMoveFailedError(from_rel,to_rel,
1451
 
                    errors.AlreadyVersionedError(path=to_rel))
 
1234
                    errors.AlreadyVersionedError(path=str(to_rel)))
1452
1235
 
1453
1236
            # try to determine the mode for rename (only change inv or change
1454
1237
            # inv and file system)
1455
1238
            if after:
1456
1239
                if not self.has_filename(to_rel):
1457
1240
                    raise errors.BzrMoveFailedError(from_id,to_rel,
1458
 
                        errors.NoSuchFile(path=to_rel,
 
1241
                        errors.NoSuchFile(path=str(to_rel),
1459
1242
                        extra="New file has not been created yet"))
1460
1243
                only_change_inv = True
1461
1244
            elif not self.has_filename(from_rel) and self.has_filename(to_rel):
1462
1245
                only_change_inv = True
1463
1246
            elif self.has_filename(from_rel) and not self.has_filename(to_rel):
1464
1247
                only_change_inv = False
1465
 
            elif (not self.case_sensitive
1466
 
                  and from_rel.lower() == to_rel.lower()
1467
 
                  and self.has_filename(from_rel)):
1468
 
                only_change_inv = False
1469
1248
            else:
1470
1249
                # something is wrong, so lets determine what exactly
1471
1250
                if not self.has_filename(from_rel) and \
1474
1253
                        errors.PathsDoNotExist(paths=(str(from_rel),
1475
1254
                        str(to_rel))))
1476
1255
                else:
1477
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
 
1256
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
 
1257
                        extra="(Use --after to update the Bazaar id)")
1478
1258
            rename_entry.only_change_inv = only_change_inv
1479
1259
        return rename_entries
1480
1260
 
1500
1280
        inv = self.inventory
1501
1281
        for entry in moved:
1502
1282
            try:
1503
 
                self._move_entry(WorkingTree._RenameEntry(
1504
 
                    entry.to_rel, entry.from_id,
 
1283
                self._move_entry(_RenameEntry(entry.to_rel, entry.from_id,
1505
1284
                    entry.to_tail, entry.to_parent_id, entry.from_rel,
1506
1285
                    entry.from_tail, entry.from_parent_id,
1507
1286
                    entry.only_change_inv))
1558
1337
        from_tail = splitpath(from_rel)[-1]
1559
1338
        from_id = inv.path2id(from_rel)
1560
1339
        if from_id is None:
1561
 
            # if file is missing in the inventory maybe it's in the basis_tree
1562
 
            basis_tree = self.branch.basis_tree()
1563
 
            from_id = basis_tree.path2id(from_rel)
1564
 
            if from_id is None:
1565
 
                raise errors.BzrRenameFailedError(from_rel,to_rel,
1566
 
                    errors.NotVersionedError(path=from_rel))
1567
 
            # put entry back in the inventory so we can rename it
1568
 
            from_entry = basis_tree.inventory[from_id].copy()
1569
 
            inv.add(from_entry)
1570
 
        else:
1571
 
            from_entry = inv[from_id]
 
1340
            raise errors.BzrRenameFailedError(from_rel,to_rel,
 
1341
                errors.NotVersionedError(path=str(from_rel)))
 
1342
        from_entry = inv[from_id]
1572
1343
        from_parent_id = from_entry.parent_id
1573
1344
        to_dir, to_tail = os.path.split(to_rel)
1574
1345
        to_dir_id = inv.path2id(to_dir)
1587
1358
        # versioned
1588
1359
        if to_dir_id is None:
1589
1360
            raise errors.BzrMoveFailedError(from_rel,to_rel,
1590
 
                errors.NotVersionedError(path=to_dir))
 
1361
                errors.NotVersionedError(path=str(to_dir)))
1591
1362
 
1592
1363
        # all checks done. now we can continue with our actual work
1593
1364
        mutter('rename_one:\n'
1620
1391
        These are files in the working directory that are not versioned or
1621
1392
        control files or ignored.
1622
1393
        """
1623
 
        # force the extras method to be fully executed before returning, to
 
1394
        # force the extras method to be fully executed before returning, to 
1624
1395
        # prevent race conditions with the lock
1625
1396
        return iter(
1626
1397
            [subp for subp in self.extras() if not self.is_ignored(subp)])
1636
1407
        :raises: NoSuchId if any fileid is not currently versioned.
1637
1408
        """
1638
1409
        for file_id in file_ids:
1639
 
            if file_id not in self._inventory:
1640
 
                raise errors.NoSuchId(self, file_id)
1641
 
        for file_id in file_ids:
 
1410
            file_id = osutils.safe_file_id(file_id)
1642
1411
            if self._inventory.has_id(file_id):
1643
1412
                self._inventory.remove_recursive_id(file_id)
 
1413
            else:
 
1414
                raise errors.NoSuchId(self, file_id)
1644
1415
        if len(file_ids):
1645
 
            # in the future this should just set a dirty bit to wait for the
 
1416
            # in the future this should just set a dirty bit to wait for the 
1646
1417
            # final unlock. However, until all methods of workingtree start
1647
 
            # with the current in -memory inventory rather than triggering
 
1418
            # with the current in -memory inventory rather than triggering 
1648
1419
            # a read, it is more complex - we need to teach read_inventory
1649
1420
            # to know when to read, and when to not read first... and possibly
1650
1421
            # to save first when the in memory one may be corrupted.
1651
1422
            # so for now, we just only write it if it is indeed dirty.
1652
1423
            # - RBC 20060907
1653
1424
            self._write_inventory(self._inventory)
 
1425
    
 
1426
    @deprecated_method(zero_eight)
 
1427
    def iter_conflicts(self):
 
1428
        """List all files in the tree that have text or content conflicts.
 
1429
        DEPRECATED.  Use conflicts instead."""
 
1430
        return self._iter_conflicts()
1654
1431
 
1655
1432
    def _iter_conflicts(self):
1656
1433
        conflicted = set()
1665
1442
 
1666
1443
    @needs_write_lock
1667
1444
    def pull(self, source, overwrite=False, stop_revision=None,
1668
 
             change_reporter=None, possible_transports=None, local=False,
1669
 
             show_base=False):
 
1445
             change_reporter=None):
 
1446
        top_pb = bzrlib.ui.ui_factory.nested_progress_bar()
1670
1447
        source.lock_read()
1671
1448
        try:
 
1449
            pp = ProgressPhase("Pull phase", 2, top_pb)
 
1450
            pp.next_phase()
1672
1451
            old_revision_info = self.branch.last_revision_info()
1673
1452
            basis_tree = self.basis_tree()
1674
 
            count = self.branch.pull(source, overwrite, stop_revision,
1675
 
                                     possible_transports=possible_transports,
1676
 
                                     local=local)
 
1453
            count = self.branch.pull(source, overwrite, stop_revision)
1677
1454
            new_revision_info = self.branch.last_revision_info()
1678
1455
            if new_revision_info != old_revision_info:
 
1456
                pp.next_phase()
1679
1457
                repository = self.branch.repository
 
1458
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1680
1459
                basis_tree.lock_read()
1681
1460
                try:
1682
1461
                    new_basis_tree = self.branch.basis_tree()
1685
1464
                                new_basis_tree,
1686
1465
                                basis_tree,
1687
1466
                                this_tree=self,
1688
 
                                pb=None,
1689
 
                                change_reporter=change_reporter,
1690
 
                                show_base=show_base)
1691
 
                    basis_root_id = basis_tree.get_root_id()
1692
 
                    new_root_id = new_basis_tree.get_root_id()
1693
 
                    if basis_root_id != new_root_id:
1694
 
                        self.set_root_id(new_root_id)
 
1467
                                pb=pb,
 
1468
                                change_reporter=change_reporter)
 
1469
                    if (basis_tree.inventory.root is None and
 
1470
                        new_basis_tree.inventory.root is not None):
 
1471
                        self.set_root_id(new_basis_tree.inventory.root.file_id)
1695
1472
                finally:
 
1473
                    pb.finished()
1696
1474
                    basis_tree.unlock()
1697
1475
                # TODO - dedup parents list with things merged by pull ?
1698
1476
                # reuse the revisiontree we merged against to set the new
1699
1477
                # tree data.
1700
1478
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1701
 
                # we have to pull the merge trees out again, because
1702
 
                # merge_inner has set the ids. - this corner is not yet
 
1479
                # we have to pull the merge trees out again, because 
 
1480
                # merge_inner has set the ids. - this corner is not yet 
1703
1481
                # layered well enough to prevent double handling.
1704
1482
                # XXX TODO: Fix the double handling: telling the tree about
1705
1483
                # the already known parent data is wasteful.
1711
1489
            return count
1712
1490
        finally:
1713
1491
            source.unlock()
 
1492
            top_pb.finished()
1714
1493
 
1715
1494
    @needs_write_lock
1716
1495
    def put_file_bytes_non_atomic(self, file_id, bytes):
1717
1496
        """See MutableTree.put_file_bytes_non_atomic."""
 
1497
        file_id = osutils.safe_file_id(file_id)
1718
1498
        stream = file(self.id2abspath(file_id), 'wb')
1719
1499
        try:
1720
1500
            stream.write(bytes)
1742
1522
 
1743
1523
            fl = []
1744
1524
            for subf in os.listdir(dirabs):
1745
 
                if self.bzrdir.is_control_filename(subf):
 
1525
                if subf == '.bzr':
1746
1526
                    continue
1747
1527
                if subf not in dir_entry.children:
1748
 
                    try:
1749
 
                        (subf_norm,
1750
 
                         can_access) = osutils.normalized_filename(subf)
1751
 
                    except UnicodeDecodeError:
1752
 
                        path_os_enc = path.encode(osutils._fs_enc)
1753
 
                        relpath = path_os_enc + '/' + subf
1754
 
                        raise errors.BadFilenameEncoding(relpath,
1755
 
                                                         osutils._fs_enc)
 
1528
                    subf_norm, can_access = osutils.normalized_filename(subf)
1756
1529
                    if subf_norm != subf and can_access:
1757
1530
                        if subf_norm not in dir_entry.children:
1758
1531
                            fl.append(subf_norm)
1759
1532
                    else:
1760
1533
                        fl.append(subf)
1761
 
 
 
1534
            
1762
1535
            fl.sort()
1763
1536
            for subf in fl:
1764
1537
                subp = pathjoin(path, subf)
1780
1553
        if ignoreset is not None:
1781
1554
            return ignoreset
1782
1555
 
1783
 
        ignore_globs = set()
 
1556
        ignore_globs = set(bzrlib.DEFAULT_IGNORE)
1784
1557
        ignore_globs.update(ignores.get_runtime_ignores())
1785
1558
        ignore_globs.update(ignores.get_user_ignores())
1786
1559
        if self.has_filename(bzrlib.IGNORE_FILENAME):
1801
1574
        r"""Check whether the filename matches an ignore pattern.
1802
1575
 
1803
1576
        Patterns containing '/' or '\' need to match the whole path;
1804
 
        others match against only the last component.  Patterns starting
1805
 
        with '!' are ignore exceptions.  Exceptions take precedence
1806
 
        over regular patterns and cause the filename to not be ignored.
 
1577
        others match against only the last component.
1807
1578
 
1808
1579
        If the file is ignored, returns the pattern which caused it to
1809
1580
        be ignored, otherwise None.  So this can simply be used as a
1810
1581
        boolean if desired."""
1811
1582
        if getattr(self, '_ignoreglobster', None) is None:
1812
 
            self._ignoreglobster = globbing.ExceptionGlobster(self.get_ignore_list())
 
1583
            self._ignoreglobster = globbing.Globster(self.get_ignore_list())
1813
1584
        return self._ignoreglobster.match(filename)
1814
1585
 
1815
1586
    def kind(self, file_id):
1816
1587
        return file_kind(self.id2abspath(file_id))
1817
1588
 
1818
 
    def stored_kind(self, file_id):
1819
 
        """See Tree.stored_kind"""
1820
 
        return self.inventory[file_id].kind
1821
 
 
1822
1589
    def _comparison_data(self, entry, path):
1823
1590
        abspath = self.abspath(path)
1824
1591
        try:
1855
1622
    @needs_read_lock
1856
1623
    def _last_revision(self):
1857
1624
        """helper for get_parent_ids."""
1858
 
        return _mod_revision.ensure_null(self.branch.last_revision())
 
1625
        return self.branch.last_revision()
1859
1626
 
1860
1627
    def is_locked(self):
1861
1628
        return self._control_files.is_locked()
1865
1632
            raise errors.ObjectNotLocked(self)
1866
1633
 
1867
1634
    def lock_read(self):
1868
 
        """Lock the tree for reading.
1869
 
 
1870
 
        This also locks the branch, and can be unlocked via self.unlock().
1871
 
 
1872
 
        :return: A bzrlib.lock.LogicalLockResult.
1873
 
        """
 
1635
        """See Branch.lock_read, and WorkingTree.unlock."""
1874
1636
        if not self.is_locked():
1875
1637
            self._reset_data()
1876
1638
        self.branch.lock_read()
1877
1639
        try:
1878
 
            self._control_files.lock_read()
1879
 
            return LogicalLockResult(self.unlock)
 
1640
            return self._control_files.lock_read()
1880
1641
        except:
1881
1642
            self.branch.unlock()
1882
1643
            raise
1883
1644
 
1884
1645
    def lock_tree_write(self):
1885
 
        """See MutableTree.lock_tree_write, and WorkingTree.unlock.
1886
 
 
1887
 
        :return: A bzrlib.lock.LogicalLockResult.
1888
 
        """
 
1646
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
1889
1647
        if not self.is_locked():
1890
1648
            self._reset_data()
1891
1649
        self.branch.lock_read()
1892
1650
        try:
1893
 
            self._control_files.lock_write()
1894
 
            return LogicalLockResult(self.unlock)
 
1651
            return self._control_files.lock_write()
1895
1652
        except:
1896
1653
            self.branch.unlock()
1897
1654
            raise
1898
1655
 
1899
1656
    def lock_write(self):
1900
 
        """See MutableTree.lock_write, and WorkingTree.unlock.
1901
 
 
1902
 
        :return: A bzrlib.lock.LogicalLockResult.
1903
 
        """
 
1657
        """See MutableTree.lock_write, and WorkingTree.unlock."""
1904
1658
        if not self.is_locked():
1905
1659
            self._reset_data()
1906
1660
        self.branch.lock_write()
1907
1661
        try:
1908
 
            self._control_files.lock_write()
1909
 
            return LogicalLockResult(self.unlock)
 
1662
            return self._control_files.lock_write()
1910
1663
        except:
1911
1664
            self.branch.unlock()
1912
1665
            raise
1920
1673
    def _reset_data(self):
1921
1674
        """Reset transient data that cannot be revalidated."""
1922
1675
        self._inventory_is_modified = False
1923
 
        f = self._transport.get('inventory')
1924
 
        try:
1925
 
            result = self._deserialize(f)
1926
 
        finally:
1927
 
            f.close()
 
1676
        result = self._deserialize(self._control_files.get('inventory'))
1928
1677
        self._set_inventory(result, dirty=False)
1929
1678
 
1930
1679
    @needs_tree_write_lock
1931
1680
    def set_last_revision(self, new_revision):
1932
1681
        """Change the last revision in the working tree."""
 
1682
        new_revision = osutils.safe_revision_id(new_revision)
1933
1683
        if self._change_last_revision(new_revision):
1934
1684
            self._cache_basis_inventory(new_revision)
1935
1685
 
1936
1686
    def _change_last_revision(self, new_revision):
1937
1687
        """Template method part of set_last_revision to perform the change.
1938
 
 
 
1688
        
1939
1689
        This is used to allow WorkingTree3 instances to not affect branch
1940
1690
        when their last revision is set.
1941
1691
        """
1942
 
        if _mod_revision.is_null(new_revision):
 
1692
        if new_revision is None:
1943
1693
            self.branch.set_revision_history([])
1944
1694
            return False
1945
1695
        try:
1951
1701
 
1952
1702
    def _write_basis_inventory(self, xml):
1953
1703
        """Write the basis inventory XML to the basis-inventory file"""
 
1704
        assert isinstance(xml, str), 'serialised xml must be bytestring.'
1954
1705
        path = self._basis_inventory_name()
1955
1706
        sio = StringIO(xml)
1956
 
        self._transport.put_file(path, sio,
1957
 
            mode=self.bzrdir._get_file_mode())
 
1707
        self._control_files.put(path, sio)
1958
1708
 
1959
1709
    def _create_basis_xml_from_inventory(self, revision_id, inventory):
1960
1710
        """Create the text that will be saved in basis-inventory"""
1961
 
        inventory.revision_id = revision_id
 
1711
        # TODO: jam 20070209 This should be redundant, as the revision_id
 
1712
        #       as all callers should have already converted the revision_id to
 
1713
        #       utf8
 
1714
        inventory.revision_id = osutils.safe_revision_id(revision_id)
1962
1715
        return xml7.serializer_v7.write_inventory_to_string(inventory)
1963
1716
 
1964
1717
    def _cache_basis_inventory(self, new_revision):
1967
1720
        # as commit already has that ready-to-use [while the format is the
1968
1721
        # same, that is].
1969
1722
        try:
1970
 
            # this double handles the inventory - unpack and repack -
 
1723
            # this double handles the inventory - unpack and repack - 
1971
1724
            # but is easier to understand. We can/should put a conditional
1972
1725
            # in here based on whether the inventory is in the latest format
1973
1726
            # - perhaps we should repack all inventories on a repository
1974
1727
            # upgrade ?
1975
1728
            # the fast path is to copy the raw xml from the repository. If the
1976
 
            # xml contains 'revision_id="', then we assume the right
 
1729
            # xml contains 'revision_id="', then we assume the right 
1977
1730
            # revision_id is set. We must check for this full string, because a
1978
1731
            # root node id can legitimately look like 'revision_id' but cannot
1979
1732
            # contain a '"'.
1980
 
            xml = self.branch.repository._get_inventory_xml(new_revision)
 
1733
            xml = self.branch.repository.get_inventory_xml(new_revision)
1981
1734
            firstline = xml.split('\n', 1)[0]
1982
 
            if (not 'revision_id="' in firstline or
 
1735
            if (not 'revision_id="' in firstline or 
1983
1736
                'format="7"' not in firstline):
1984
 
                inv = self.branch.repository._serializer.read_inventory_from_string(
1985
 
                    xml, new_revision)
 
1737
                inv = self.branch.repository.deserialise_inventory(
 
1738
                    new_revision, xml)
1986
1739
                xml = self._create_basis_xml_from_inventory(new_revision, inv)
1987
1740
            self._write_basis_inventory(xml)
1988
1741
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
1991
1744
    def read_basis_inventory(self):
1992
1745
        """Read the cached basis inventory."""
1993
1746
        path = self._basis_inventory_name()
1994
 
        return self._transport.get_bytes(path)
1995
 
 
 
1747
        return self._control_files.get(path).read()
 
1748
        
1996
1749
    @needs_read_lock
1997
1750
    def read_working_inventory(self):
1998
1751
        """Read the working inventory.
1999
 
 
 
1752
        
2000
1753
        :raises errors.InventoryModified: read_working_inventory will fail
2001
1754
            when the current in memory inventory has been modified.
2002
1755
        """
2003
 
        # conceptually this should be an implementation detail of the tree.
 
1756
        # conceptually this should be an implementation detail of the tree. 
2004
1757
        # XXX: Deprecate this.
2005
1758
        # ElementTree does its own conversion from UTF-8, so open in
2006
1759
        # binary.
2007
1760
        if self._inventory_is_modified:
2008
1761
            raise errors.InventoryModified(self)
2009
 
        f = self._transport.get('inventory')
2010
 
        try:
2011
 
            result = self._deserialize(f)
2012
 
        finally:
2013
 
            f.close()
 
1762
        result = self._deserialize(self._control_files.get('inventory'))
2014
1763
        self._set_inventory(result, dirty=False)
2015
1764
        return result
2016
1765
 
2017
1766
    @needs_tree_write_lock
2018
 
    def remove(self, files, verbose=False, to_file=None, keep_files=True,
2019
 
        force=False):
2020
 
        """Remove nominated files from the working inventory.
2021
 
 
2022
 
        :files: File paths relative to the basedir.
2023
 
        :keep_files: If true, the files will also be kept.
2024
 
        :force: Delete files and directories, even if they are changed and
2025
 
            even if the directories are not empty.
 
1767
    def remove(self, files, verbose=False, to_file=None):
 
1768
        """Remove nominated files from the working inventory..
 
1769
 
 
1770
        This does not remove their text.  This does not run on XXX on what? RBC
 
1771
 
 
1772
        TODO: Refuse to remove modified files unless --force is given?
 
1773
 
 
1774
        TODO: Do something useful with directories.
 
1775
 
 
1776
        TODO: Should this remove the text or not?  Tough call; not
 
1777
        removing may be useful and the user can just use use rm, and
 
1778
        is the opposite of add.  Removing it is consistent with most
 
1779
        other tools.  Maybe an option.
2026
1780
        """
 
1781
        ## TODO: Normalize names
 
1782
        ## TODO: Remove nested loops; better scalability
2027
1783
        if isinstance(files, basestring):
2028
1784
            files = [files]
2029
1785
 
2030
 
        inv_delta = []
2031
 
 
2032
 
        all_files = set() # specified and nested files 
2033
 
        unknown_nested_files=set()
2034
 
        if to_file is None:
2035
 
            to_file = sys.stdout
2036
 
 
2037
 
        files_to_backup = []
2038
 
 
2039
 
        def recurse_directory_to_add_files(directory):
2040
 
            # Recurse directory and add all files
2041
 
            # so we can check if they have changed.
2042
 
            for parent_info, file_infos in self.walkdirs(directory):
2043
 
                for relpath, basename, kind, lstat, fileid, kind in file_infos:
2044
 
                    # Is it versioned or ignored?
2045
 
                    if self.path2id(relpath):
2046
 
                        # Add nested content for deletion.
2047
 
                        all_files.add(relpath)
2048
 
                    else:
2049
 
                        # Files which are not versioned
2050
 
                        # should be treated as unknown.
2051
 
                        files_to_backup.append(relpath)
2052
 
 
2053
 
        for filename in files:
2054
 
            # Get file name into canonical form.
2055
 
            abspath = self.abspath(filename)
2056
 
            filename = self.relpath(abspath)
2057
 
            if len(filename) > 0:
2058
 
                all_files.add(filename)
2059
 
                recurse_directory_to_add_files(filename)
2060
 
 
2061
 
        files = list(all_files)
2062
 
 
2063
 
        if len(files) == 0:
2064
 
            return # nothing to do
2065
 
 
2066
 
        # Sort needed to first handle directory content before the directory
2067
 
        files.sort(reverse=True)
2068
 
 
2069
 
        # Bail out if we are going to delete files we shouldn't
2070
 
        if not keep_files and not force:
2071
 
            for (file_id, path, content_change, versioned, parent_id, name,
2072
 
                 kind, executable) in self.iter_changes(self.basis_tree(),
2073
 
                     include_unchanged=True, require_versioned=False,
2074
 
                     want_unversioned=True, specific_files=files):
2075
 
                if versioned[0] == False:
2076
 
                    # The record is unknown or newly added
2077
 
                    files_to_backup.append(path[1])
2078
 
                elif (content_change and (kind[1] is not None) and
2079
 
                        osutils.is_inside_any(files, path[1])):
2080
 
                    # Versioned and changed, but not deleted, and still
2081
 
                    # in one of the dirs to be deleted.
2082
 
                    files_to_backup.append(path[1])
2083
 
 
2084
 
        def backup(file_to_backup):
2085
 
            backup_name = self.bzrdir._available_backup_name(file_to_backup)
2086
 
            osutils.rename(abs_path, self.abspath(backup_name))
2087
 
            return "removed %s (but kept a copy: %s)" % (file_to_backup,
2088
 
                                                         backup_name)
2089
 
 
2090
 
        # Build inv_delta and delete files where applicable,
2091
 
        # do this before any modifications to inventory.
 
1786
        inv = self.inventory
 
1787
 
 
1788
        # do this before any modifications
2092
1789
        for f in files:
2093
 
            fid = self.path2id(f)
2094
 
            message = None
 
1790
            fid = inv.path2id(f)
2095
1791
            if not fid:
2096
 
                message = "%s is not versioned." % (f,)
 
1792
                note("%s is not versioned."%f)
2097
1793
            else:
2098
1794
                if verbose:
2099
 
                    # having removed it, it must be either ignored or unknown
 
1795
                    # having remove it, it must be either ignored or unknown
2100
1796
                    if self.is_ignored(f):
2101
1797
                        new_status = 'I'
2102
1798
                    else:
2103
1799
                        new_status = '?'
2104
 
                    # XXX: Really should be a more abstract reporter interface
2105
 
                    kind_ch = osutils.kind_marker(self.kind(fid))
2106
 
                    to_file.write(new_status + '       ' + f + kind_ch + '\n')
2107
 
                # Unversion file
2108
 
                inv_delta.append((f, None, fid, None))
2109
 
                message = "removed %s" % (f,)
2110
 
 
2111
 
            if not keep_files:
2112
 
                abs_path = self.abspath(f)
2113
 
                if osutils.lexists(abs_path):
2114
 
                    if (osutils.isdir(abs_path) and
2115
 
                        len(os.listdir(abs_path)) > 0):
2116
 
                        if force:
2117
 
                            osutils.rmtree(abs_path)
2118
 
                            message = "deleted %s" % (f,)
2119
 
                        else:
2120
 
                            message = backup(f)
2121
 
                    else:
2122
 
                        if f in files_to_backup:
2123
 
                            message = backup(f)
2124
 
                        else:
2125
 
                            osutils.delete_any(abs_path)
2126
 
                            message = "deleted %s" % (f,)
2127
 
                elif message is not None:
2128
 
                    # Only care if we haven't done anything yet.
2129
 
                    message = "%s does not exist." % (f,)
2130
 
 
2131
 
            # Print only one message (if any) per file.
2132
 
            if message is not None:
2133
 
                note(message)
2134
 
        self.apply_inventory_delta(inv_delta)
 
1800
                    textui.show_status(new_status, inv[fid].kind, f,
 
1801
                                       to_file=to_file)
 
1802
                del inv[fid]
 
1803
 
 
1804
        self._write_inventory(inv)
2135
1805
 
2136
1806
    @needs_tree_write_lock
2137
 
    def revert(self, filenames=None, old_tree=None, backups=True,
2138
 
               pb=None, report_changes=False):
 
1807
    def revert(self, filenames, old_tree=None, backups=True, 
 
1808
               pb=DummyProgress(), report_changes=False):
2139
1809
        from bzrlib.conflicts import resolve
2140
 
        if filenames == []:
2141
 
            filenames = None
2142
 
            symbol_versioning.warn('Using [] to revert all files is deprecated'
2143
 
                ' as of bzr 0.91.  Please use None (the default) instead.',
2144
 
                DeprecationWarning, stacklevel=2)
2145
1810
        if old_tree is None:
2146
 
            basis_tree = self.basis_tree()
2147
 
            basis_tree.lock_read()
2148
 
            old_tree = basis_tree
 
1811
            old_tree = self.basis_tree()
 
1812
        conflicts = transform.revert(self, old_tree, filenames, backups, pb,
 
1813
                                     report_changes)
 
1814
        if not len(filenames):
 
1815
            self.set_parent_ids(self.get_parent_ids()[:1])
 
1816
            resolve(self)
2149
1817
        else:
2150
 
            basis_tree = None
2151
 
        try:
2152
 
            conflicts = transform.revert(self, old_tree, filenames, backups, pb,
2153
 
                                         report_changes)
2154
 
            if filenames is None and len(self.get_parent_ids()) > 1:
2155
 
                parent_trees = []
2156
 
                last_revision = self.last_revision()
2157
 
                if last_revision != _mod_revision.NULL_REVISION:
2158
 
                    if basis_tree is None:
2159
 
                        basis_tree = self.basis_tree()
2160
 
                        basis_tree.lock_read()
2161
 
                    parent_trees.append((last_revision, basis_tree))
2162
 
                self.set_parent_trees(parent_trees)
2163
 
                resolve(self)
2164
 
            else:
2165
 
                resolve(self, filenames, ignore_misses=True, recursive=True)
2166
 
        finally:
2167
 
            if basis_tree is not None:
2168
 
                basis_tree.unlock()
 
1818
            resolve(self, filenames, ignore_misses=True)
2169
1819
        return conflicts
2170
1820
 
2171
1821
    def revision_tree(self, revision_id):
2198
1848
    def set_inventory(self, new_inventory_list):
2199
1849
        from bzrlib.inventory import (Inventory,
2200
1850
                                      InventoryDirectory,
 
1851
                                      InventoryEntry,
2201
1852
                                      InventoryFile,
2202
1853
                                      InventoryLink)
2203
1854
        inv = Inventory(self.get_root_id())
2205
1856
            name = os.path.basename(path)
2206
1857
            if name == "":
2207
1858
                continue
2208
 
            # fixme, there should be a factory function inv,add_??
 
1859
            # fixme, there should be a factory function inv,add_?? 
2209
1860
            if kind == 'directory':
2210
1861
                inv.add(InventoryDirectory(file_id, name, parent))
2211
1862
            elif kind == 'file':
2219
1870
    @needs_tree_write_lock
2220
1871
    def set_root_id(self, file_id):
2221
1872
        """Set the root id for this tree."""
2222
 
        # for compatability
 
1873
        # for compatability 
2223
1874
        if file_id is None:
2224
 
            raise ValueError(
2225
 
                'WorkingTree.set_root_id with fileid=None')
2226
 
        file_id = osutils.safe_file_id(file_id)
 
1875
            symbol_versioning.warn(symbol_versioning.zero_twelve
 
1876
                % 'WorkingTree.set_root_id with fileid=None',
 
1877
                DeprecationWarning,
 
1878
                stacklevel=3)
 
1879
            file_id = ROOT_ID
 
1880
        else:
 
1881
            file_id = osutils.safe_file_id(file_id)
2227
1882
        self._set_root_id(file_id)
2228
1883
 
2229
1884
    def _set_root_id(self, file_id):
2230
1885
        """Set the root id for this tree, in a format specific manner.
2231
1886
 
2232
 
        :param file_id: The file id to assign to the root. It must not be
 
1887
        :param file_id: The file id to assign to the root. It must not be 
2233
1888
            present in the current inventory or an error will occur. It must
2234
1889
            not be None, but rather a valid file id.
2235
1890
        """
2254
1909
 
2255
1910
    def unlock(self):
2256
1911
        """See Branch.unlock.
2257
 
 
 
1912
        
2258
1913
        WorkingTree locking just uses the Branch locking facilities.
2259
1914
        This is current because all working trees have an embedded branch
2260
1915
        within them. IF in the future, we were to make branch data shareable
2261
 
        between multiple working trees, i.e. via shared storage, then we
 
1916
        between multiple working trees, i.e. via shared storage, then we 
2262
1917
        would probably want to lock both the local tree, and the branch.
2263
1918
        """
2264
1919
        raise NotImplementedError(self.unlock)
2265
1920
 
2266
 
    _marker = object()
2267
 
 
2268
 
    def update(self, change_reporter=None, possible_transports=None,
2269
 
               revision=None, old_tip=_marker, show_base=False):
 
1921
    def update(self):
2270
1922
        """Update a working tree along its branch.
2271
1923
 
2272
1924
        This will update the branch if its bound too, which means we have
2290
1942
        - Merge current state -> basis tree of the master w.r.t. the old tree
2291
1943
          basis.
2292
1944
        - Do a 'normal' merge of the old branch basis if it is relevant.
2293
 
 
2294
 
        :param revision: The target revision to update to. Must be in the
2295
 
            revision history.
2296
 
        :param old_tip: If branch.update() has already been run, the value it
2297
 
            returned (old tip of the branch or None). _marker is used
2298
 
            otherwise.
2299
1945
        """
2300
 
        if self.branch.get_bound_location() is not None:
 
1946
        if self.branch.get_master_branch() is not None:
2301
1947
            self.lock_write()
2302
 
            update_branch = (old_tip is self._marker)
 
1948
            update_branch = True
2303
1949
        else:
2304
1950
            self.lock_tree_write()
2305
1951
            update_branch = False
2306
1952
        try:
2307
1953
            if update_branch:
2308
 
                old_tip = self.branch.update(possible_transports)
 
1954
                old_tip = self.branch.update()
2309
1955
            else:
2310
 
                if old_tip is self._marker:
2311
 
                    old_tip = None
2312
 
            return self._update_tree(old_tip, change_reporter, revision, show_base)
 
1956
                old_tip = None
 
1957
            return self._update_tree(old_tip)
2313
1958
        finally:
2314
1959
            self.unlock()
2315
1960
 
2316
1961
    @needs_tree_write_lock
2317
 
    def _update_tree(self, old_tip=None, change_reporter=None, revision=None,
2318
 
                     show_base=False):
 
1962
    def _update_tree(self, old_tip=None):
2319
1963
        """Update a tree to the master branch.
2320
1964
 
2321
1965
        :param old_tip: if supplied, the previous tip revision the branch,
2327
1971
        # cant set that until we update the working trees last revision to be
2328
1972
        # one from the new branch, because it will just get absorbed by the
2329
1973
        # parent de-duplication logic.
2330
 
        #
 
1974
        # 
2331
1975
        # We MUST save it even if an error occurs, because otherwise the users
2332
1976
        # local work is unreferenced and will appear to have been lost.
2333
 
        #
2334
 
        nb_conflicts = 0
 
1977
        # 
 
1978
        result = 0
2335
1979
        try:
2336
1980
            last_rev = self.get_parent_ids()[0]
2337
1981
        except IndexError:
2338
 
            last_rev = _mod_revision.NULL_REVISION
2339
 
        if revision is None:
2340
 
            revision = self.branch.last_revision()
2341
 
 
2342
 
        old_tip = old_tip or _mod_revision.NULL_REVISION
2343
 
 
2344
 
        if not _mod_revision.is_null(old_tip) and old_tip != last_rev:
2345
 
            # the branch we are bound to was updated
2346
 
            # merge those changes in first
2347
 
            base_tree  = self.basis_tree()
2348
 
            other_tree = self.branch.repository.revision_tree(old_tip)
2349
 
            nb_conflicts = merge.merge_inner(self.branch, other_tree,
2350
 
                                             base_tree, this_tree=self,
2351
 
                                             change_reporter=change_reporter,
2352
 
                                             show_base=show_base)
2353
 
            if nb_conflicts:
2354
 
                self.add_parent_tree((old_tip, other_tree))
2355
 
                trace.note('Rerun update after fixing the conflicts.')
2356
 
                return nb_conflicts
2357
 
 
2358
 
        if last_rev != _mod_revision.ensure_null(revision):
2359
 
            # the working tree is up to date with the branch
2360
 
            # we can merge the specified revision from master
2361
 
            to_tree = self.branch.repository.revision_tree(revision)
2362
 
            to_root_id = to_tree.get_root_id()
2363
 
 
 
1982
            last_rev = None
 
1983
        if last_rev != self.branch.last_revision():
 
1984
            # merge tree state up to new branch tip.
2364
1985
            basis = self.basis_tree()
2365
1986
            basis.lock_read()
2366
1987
            try:
2367
 
                if (basis.inventory.root is None
2368
 
                    or basis.inventory.root.file_id != to_root_id):
2369
 
                    self.set_root_id(to_root_id)
 
1988
                to_tree = self.branch.basis_tree()
 
1989
                if basis.inventory.root is None:
 
1990
                    self.set_root_id(to_tree.inventory.root.file_id)
2370
1991
                    self.flush()
 
1992
                result += merge.merge_inner(
 
1993
                                      self.branch,
 
1994
                                      to_tree,
 
1995
                                      basis,
 
1996
                                      this_tree=self)
2371
1997
            finally:
2372
1998
                basis.unlock()
2373
 
 
2374
 
            # determine the branch point
2375
 
            graph = self.branch.repository.get_graph()
2376
 
            base_rev_id = graph.find_unique_lca(self.branch.last_revision(),
2377
 
                                                last_rev)
2378
 
            base_tree = self.branch.repository.revision_tree(base_rev_id)
2379
 
 
2380
 
            nb_conflicts = merge.merge_inner(self.branch, to_tree, base_tree,
2381
 
                                             this_tree=self,
2382
 
                                             change_reporter=change_reporter,
2383
 
                                             show_base=show_base)
2384
 
            self.set_last_revision(revision)
2385
1999
            # TODO - dedup parents list with things merged by pull ?
2386
2000
            # reuse the tree we've updated to to set the basis:
2387
 
            parent_trees = [(revision, to_tree)]
 
2001
            parent_trees = [(self.branch.last_revision(), to_tree)]
2388
2002
            merges = self.get_parent_ids()[1:]
2389
2003
            # Ideally we ask the tree for the trees here, that way the working
2390
 
            # tree can decide whether to give us the entire tree or give us a
 
2004
            # tree can decide whether to give us teh entire tree or give us a
2391
2005
            # lazy initialised tree. dirstate for instance will have the trees
2392
2006
            # in ram already, whereas a last-revision + basis-inventory tree
2393
2007
            # will not, but also does not need them when setting parents.
2394
2008
            for parent in merges:
2395
2009
                parent_trees.append(
2396
2010
                    (parent, self.branch.repository.revision_tree(parent)))
2397
 
            if not _mod_revision.is_null(old_tip):
 
2011
            if old_tip is not None:
2398
2012
                parent_trees.append(
2399
2013
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
2400
2014
            self.set_parent_trees(parent_trees)
2401
2015
            last_rev = parent_trees[0][0]
2402
 
        return nb_conflicts
 
2016
        else:
 
2017
            # the working tree had the same last-revision as the master
 
2018
            # branch did. We may still have pivot local work from the local
 
2019
            # branch into old_tip:
 
2020
            if old_tip is not None:
 
2021
                self.add_parent_tree_id(old_tip)
 
2022
        if old_tip and old_tip != last_rev:
 
2023
            # our last revision was not the prior branch last revision
 
2024
            # and we have converted that last revision to a pending merge.
 
2025
            # base is somewhere between the branch tip now
 
2026
            # and the now pending merge
 
2027
 
 
2028
            # Since we just modified the working tree and inventory, flush out
 
2029
            # the current state, before we modify it again.
 
2030
            # TODO: jam 20070214 WorkingTree3 doesn't require this, dirstate
 
2031
            #       requires it only because TreeTransform directly munges the
 
2032
            #       inventory and calls tree._write_inventory(). Ultimately we
 
2033
            #       should be able to remove this extra flush.
 
2034
            self.flush()
 
2035
            from bzrlib.revision import common_ancestor
 
2036
            try:
 
2037
                base_rev_id = common_ancestor(self.branch.last_revision(),
 
2038
                                              old_tip,
 
2039
                                              self.branch.repository)
 
2040
            except errors.NoCommonAncestor:
 
2041
                base_rev_id = None
 
2042
            base_tree = self.branch.repository.revision_tree(base_rev_id)
 
2043
            other_tree = self.branch.repository.revision_tree(old_tip)
 
2044
            result += merge.merge_inner(
 
2045
                                  self.branch,
 
2046
                                  other_tree,
 
2047
                                  base_tree,
 
2048
                                  this_tree=self)
 
2049
        return result
2403
2050
 
2404
2051
    def _write_hashcache_if_dirty(self):
2405
2052
        """Write out the hashcache if it is dirty."""
2456
2103
    def walkdirs(self, prefix=""):
2457
2104
        """Walk the directories of this tree.
2458
2105
 
2459
 
        returns a generator which yields items in the form:
2460
 
                ((curren_directory_path, fileid),
2461
 
                 [(file1_path, file1_name, file1_kind, (lstat), file1_id,
2462
 
                   file1_kind), ... ])
2463
 
 
2464
2106
        This API returns a generator, which is only valid during the current
2465
2107
        tree transaction - within a single lock_read or lock_write duration.
2466
2108
 
2467
 
        If the tree is not locked, it may cause an error to be raised,
2468
 
        depending on the tree implementation.
 
2109
        If the tree is not locked, it may cause an error to be raised, depending
 
2110
        on the tree implementation.
2469
2111
        """
2470
2112
        disk_top = self.abspath(prefix)
2471
2113
        if disk_top.endswith('/'):
2477
2119
            current_disk = disk_iterator.next()
2478
2120
            disk_finished = False
2479
2121
        except OSError, e:
2480
 
            if not (e.errno == errno.ENOENT or
2481
 
                (sys.platform == 'win32' and e.errno == ERROR_PATH_NOT_FOUND)):
 
2122
            if e.errno != errno.ENOENT:
2482
2123
                raise
2483
2124
            current_disk = None
2484
2125
            disk_finished = True
2489
2130
            current_inv = None
2490
2131
            inv_finished = True
2491
2132
        while not inv_finished or not disk_finished:
2492
 
            if current_disk:
2493
 
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2494
 
                    cur_disk_dir_content) = current_disk
2495
 
            else:
2496
 
                ((cur_disk_dir_relpath, cur_disk_dir_path_from_top),
2497
 
                    cur_disk_dir_content) = ((None, None), None)
2498
2133
            if not disk_finished:
2499
2134
                # strip out .bzr dirs
2500
 
                if (cur_disk_dir_path_from_top[top_strip_len:] == '' and
2501
 
                    len(cur_disk_dir_content) > 0):
2502
 
                    # osutils.walkdirs can be made nicer -
 
2135
                if current_disk[0][1][top_strip_len:] == '':
 
2136
                    # osutils.walkdirs can be made nicer - 
2503
2137
                    # yield the path-from-prefix rather than the pathjoined
2504
2138
                    # value.
2505
 
                    bzrdir_loc = bisect_left(cur_disk_dir_content,
2506
 
                        ('.bzr', '.bzr'))
2507
 
                    if (bzrdir_loc < len(cur_disk_dir_content)
2508
 
                        and self.bzrdir.is_control_filename(
2509
 
                            cur_disk_dir_content[bzrdir_loc][0])):
 
2139
                    bzrdir_loc = bisect_left(current_disk[1], ('.bzr', '.bzr'))
 
2140
                    if current_disk[1][bzrdir_loc][0] == '.bzr':
2510
2141
                        # we dont yield the contents of, or, .bzr itself.
2511
 
                        del cur_disk_dir_content[bzrdir_loc]
 
2142
                        del current_disk[1][bzrdir_loc]
2512
2143
            if inv_finished:
2513
2144
                # everything is unknown
2514
2145
                direction = 1
2516
2147
                # everything is missing
2517
2148
                direction = -1
2518
2149
            else:
2519
 
                direction = cmp(current_inv[0][0], cur_disk_dir_relpath)
 
2150
                direction = cmp(current_inv[0][0], current_disk[0][0])
2520
2151
            if direction > 0:
2521
2152
                # disk is before inventory - unknown
2522
2153
                dirblock = [(relpath, basename, kind, stat, None, None) for
2523
 
                    relpath, basename, kind, stat, top_path in
2524
 
                    cur_disk_dir_content]
2525
 
                yield (cur_disk_dir_relpath, None), dirblock
 
2154
                    relpath, basename, kind, stat, top_path in current_disk[1]]
 
2155
                yield (current_disk[0][0], None), dirblock
2526
2156
                try:
2527
2157
                    current_disk = disk_iterator.next()
2528
2158
                except StopIteration:
2530
2160
            elif direction < 0:
2531
2161
                # inventory is before disk - missing.
2532
2162
                dirblock = [(relpath, basename, 'unknown', None, fileid, kind)
2533
 
                    for relpath, basename, dkind, stat, fileid, kind in
 
2163
                    for relpath, basename, dkind, stat, fileid, kind in 
2534
2164
                    current_inv[1]]
2535
2165
                yield (current_inv[0][0], current_inv[0][1]), dirblock
2536
2166
                try:
2542
2172
                # merge the inventory and disk data together
2543
2173
                dirblock = []
2544
2174
                for relpath, subiterator in itertools.groupby(sorted(
2545
 
                    current_inv[1] + cur_disk_dir_content,
2546
 
                    key=operator.itemgetter(0)), operator.itemgetter(1)):
 
2175
                    current_inv[1] + current_disk[1], key=operator.itemgetter(0)), operator.itemgetter(1)):
2547
2176
                    path_elements = list(subiterator)
2548
2177
                    if len(path_elements) == 2:
2549
2178
                        inv_row, disk_row = path_elements
2575
2204
                    disk_finished = True
2576
2205
 
2577
2206
    def _walkdirs(self, prefix=""):
2578
 
        """Walk the directories of this tree.
2579
 
 
2580
 
           :prefix: is used as the directrory to start with.
2581
 
           returns a generator which yields items in the form:
2582
 
                ((curren_directory_path, fileid),
2583
 
                 [(file1_path, file1_name, file1_kind, None, file1_id,
2584
 
                   file1_kind), ... ])
2585
 
        """
2586
2207
        _directory = 'directory'
2587
2208
        # get the root in the inventory
2588
2209
        inv = self.inventory
2602
2223
                relroot = ""
2603
2224
            # FIXME: stash the node in pending
2604
2225
            entry = inv[top_id]
2605
 
            if entry.kind == 'directory':
2606
 
                for name, child in entry.sorted_children():
2607
 
                    dirblock.append((relroot + name, name, child.kind, None,
2608
 
                        child.file_id, child.kind
2609
 
                        ))
 
2226
            for name, child in entry.sorted_children():
 
2227
                dirblock.append((relroot + name, name, child.kind, None,
 
2228
                    child.file_id, child.kind
 
2229
                    ))
2610
2230
            yield (currentdir[0], entry.file_id), dirblock
2611
2231
            # push the user specified dirs from dirblock
2612
2232
            for dir in reversed(dirblock):
2645
2265
        self.set_conflicts(un_resolved)
2646
2266
        return un_resolved, resolved
2647
2267
 
2648
 
    @needs_read_lock
2649
 
    def _check(self, references):
2650
 
        """Check the tree for consistency.
2651
 
 
2652
 
        :param references: A dict with keys matching the items returned by
2653
 
            self._get_check_refs(), and values from looking those keys up in
2654
 
            the repository.
2655
 
        """
2656
 
        tree_basis = self.basis_tree()
2657
 
        tree_basis.lock_read()
2658
 
        try:
2659
 
            repo_basis = references[('trees', self.last_revision())]
2660
 
            if len(list(repo_basis.iter_changes(tree_basis))) > 0:
2661
 
                raise errors.BzrCheckError(
2662
 
                    "Mismatched basis inventory content.")
2663
 
            self._validate()
2664
 
        finally:
2665
 
            tree_basis.unlock()
2666
 
 
2667
2268
    def _validate(self):
2668
2269
        """Validate internal structures.
2669
2270
 
2675
2276
        """
2676
2277
        return
2677
2278
 
2678
 
    @needs_read_lock
2679
 
    def check_state(self):
2680
 
        """Check that the working state is/isn't valid."""
2681
 
        check_refs = self._get_check_refs()
2682
 
        refs = {}
2683
 
        for ref in check_refs:
2684
 
            kind, value = ref
2685
 
            if kind == 'trees':
2686
 
                refs[ref] = self.branch.repository.revision_tree(value)
2687
 
        self._check(refs)
2688
 
 
2689
 
    @needs_tree_write_lock
2690
 
    def reset_state(self, revision_ids=None):
2691
 
        """Reset the state of the working tree.
2692
 
 
2693
 
        This does a hard-reset to a last-known-good state. This is a way to
2694
 
        fix if something got corrupted (like the .bzr/checkout/dirstate file)
2695
 
        """
2696
 
        if revision_ids is None:
2697
 
            revision_ids = self.get_parent_ids()
2698
 
        if not revision_ids:
2699
 
            rt = self.branch.repository.revision_tree(
2700
 
                _mod_revision.NULL_REVISION)
2701
 
        else:
2702
 
            rt = self.branch.repository.revision_tree(revision_ids[0])
2703
 
        self._write_inventory(rt.inventory)
2704
 
        self.set_parent_ids(revision_ids)
2705
 
 
2706
 
    def _get_rules_searcher(self, default_searcher):
2707
 
        """See Tree._get_rules_searcher."""
2708
 
        if self._rules_searcher is None:
2709
 
            self._rules_searcher = super(WorkingTree,
2710
 
                self)._get_rules_searcher(default_searcher)
2711
 
        return self._rules_searcher
2712
 
 
2713
 
    def get_shelf_manager(self):
2714
 
        """Return the ShelfManager for this WorkingTree."""
2715
 
        from bzrlib.shelf import ShelfManager
2716
 
        return ShelfManager(self, self._transport)
2717
 
 
2718
2279
 
2719
2280
class WorkingTree2(WorkingTree):
2720
2281
    """This is the Format 2 working tree.
2721
2282
 
2722
 
    This was the first weave based working tree.
 
2283
    This was the first weave based working tree. 
2723
2284
     - uses os locks for locking.
2724
2285
     - uses the branch last-revision.
2725
2286
    """
2735
2296
        if self._inventory is None:
2736
2297
            self.read_working_inventory()
2737
2298
 
2738
 
    def _get_check_refs(self):
2739
 
        """Return the references needed to perform a check of this tree."""
2740
 
        return [('trees', self.last_revision())]
2741
 
 
2742
2299
    def lock_tree_write(self):
2743
2300
        """See WorkingTree.lock_tree_write().
2744
2301
 
2745
2302
        In Format2 WorkingTrees we have a single lock for the branch and tree
2746
2303
        so lock_tree_write() degrades to lock_write().
2747
 
 
2748
 
        :return: An object with an unlock method which will release the lock
2749
 
            obtained.
2750
2304
        """
2751
2305
        self.branch.lock_write()
2752
2306
        try:
2753
 
            self._control_files.lock_write()
2754
 
            return self
 
2307
            return self._control_files.lock_write()
2755
2308
        except:
2756
2309
            self.branch.unlock()
2757
2310
            raise
2758
2311
 
2759
2312
    def unlock(self):
2760
 
        # do non-implementation specific cleanup
2761
 
        self._cleanup()
2762
 
 
2763
2313
        # we share control files:
2764
2314
        if self._control_files._lock_count == 3:
2765
2315
            # _inventory_is_modified is always False during a read lock.
2766
2316
            if self._inventory_is_modified:
2767
2317
                self.flush()
2768
2318
            self._write_hashcache_if_dirty()
2769
 
 
 
2319
                    
2770
2320
        # reverse order of locking.
2771
2321
        try:
2772
2322
            return self._control_files.unlock()
2788
2338
    def _last_revision(self):
2789
2339
        """See Mutable.last_revision."""
2790
2340
        try:
2791
 
            return self._transport.get_bytes('last-revision')
 
2341
            return osutils.safe_revision_id(
 
2342
                        self._control_files.get('last-revision').read())
2792
2343
        except errors.NoSuchFile:
2793
 
            return _mod_revision.NULL_REVISION
 
2344
            return None
2794
2345
 
2795
2346
    def _change_last_revision(self, revision_id):
2796
2347
        """See WorkingTree._change_last_revision."""
2797
 
        if revision_id is None or revision_id == _mod_revision.NULL_REVISION:
 
2348
        if revision_id is None or revision_id == NULL_REVISION:
2798
2349
            try:
2799
 
                self._transport.delete('last-revision')
 
2350
                self._control_files._transport.delete('last-revision')
2800
2351
            except errors.NoSuchFile:
2801
2352
                pass
2802
2353
            return False
2803
2354
        else:
2804
 
            self._transport.put_bytes('last-revision', revision_id,
2805
 
                mode=self.bzrdir._get_file_mode())
 
2355
            self._control_files.put_bytes('last-revision', revision_id)
2806
2356
            return True
2807
2357
 
2808
 
    def _get_check_refs(self):
2809
 
        """Return the references needed to perform a check of this tree."""
2810
 
        return [('trees', self.last_revision())]
2811
 
 
2812
2358
    @needs_tree_write_lock
2813
2359
    def set_conflicts(self, conflicts):
2814
 
        self._put_rio('conflicts', conflicts.to_stanzas(),
 
2360
        self._put_rio('conflicts', conflicts.to_stanzas(), 
2815
2361
                      CONFLICT_HEADER_1)
2816
2362
 
2817
2363
    @needs_tree_write_lock
2824
2370
    @needs_read_lock
2825
2371
    def conflicts(self):
2826
2372
        try:
2827
 
            confile = self._transport.get('conflicts')
 
2373
            confile = self._control_files.get('conflicts')
2828
2374
        except errors.NoSuchFile:
2829
2375
            return _mod_conflicts.ConflictList()
2830
2376
        try:
2831
 
            try:
2832
 
                if confile.next() != CONFLICT_HEADER_1 + '\n':
2833
 
                    raise errors.ConflictFormatError()
2834
 
            except StopIteration:
 
2377
            if confile.next() != CONFLICT_HEADER_1 + '\n':
2835
2378
                raise errors.ConflictFormatError()
2836
 
            return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2837
 
        finally:
2838
 
            confile.close()
 
2379
        except StopIteration:
 
2380
            raise errors.ConflictFormatError()
 
2381
        return _mod_conflicts.ConflictList.from_stanzas(RioReader(confile))
2839
2382
 
2840
2383
    def unlock(self):
2841
 
        # do non-implementation specific cleanup
2842
 
        self._cleanup()
2843
2384
        if self._control_files._lock_count == 1:
2844
2385
            # _inventory_is_modified is always False during a read lock.
2845
2386
            if self._inventory_is_modified:
2858
2399
            return path[:-len(suffix)]
2859
2400
 
2860
2401
 
 
2402
@deprecated_function(zero_eight)
 
2403
def is_control_file(filename):
 
2404
    """See WorkingTree.is_control_filename(filename)."""
 
2405
    ## FIXME: better check
 
2406
    filename = normpath(filename)
 
2407
    while filename != '':
 
2408
        head, tail = os.path.split(filename)
 
2409
        ## mutter('check %r for control file' % ((head, tail),))
 
2410
        if tail == '.bzr':
 
2411
            return True
 
2412
        if filename == head:
 
2413
            break
 
2414
        filename = head
 
2415
    return False
 
2416
 
 
2417
 
2861
2418
class WorkingTreeFormat(object):
2862
2419
    """An encapsulation of the initialization and open routines for a format.
2863
2420
 
2866
2423
     * a format string,
2867
2424
     * an open routine.
2868
2425
 
2869
 
    Formats are placed in an dict by their format string for reference
 
2426
    Formats are placed in an dict by their format string for reference 
2870
2427
    during workingtree opening. Its not required that these be instances, they
2871
 
    can be classes themselves with class methods - it simply depends on
 
2428
    can be classes themselves with class methods - it simply depends on 
2872
2429
    whether state is needed for a given format or not.
2873
2430
 
2874
2431
    Once a format is deprecated, just deprecate the initialize and open
2875
 
    methods on the format class. Do not deprecate the object, as the
 
2432
    methods on the format class. Do not deprecate the object, as the 
2876
2433
    object will be created every time regardless.
2877
2434
    """
2878
2435
 
2882
2439
    _formats = {}
2883
2440
    """The known formats."""
2884
2441
 
2885
 
    _extra_formats = []
2886
 
    """Extra formats that can not be used in a metadir."""
2887
 
 
2888
2442
    requires_rich_root = False
2889
2443
 
2890
2444
    upgrade_recommended = False
2891
2445
 
2892
 
    requires_normalized_unicode_filenames = False
2893
 
 
2894
 
    case_sensitive_filename = "FoRMaT"
2895
 
 
2896
 
    missing_parent_conflicts = False
2897
 
    """If this format supports missing parent conflicts."""
2898
 
 
2899
2446
    @classmethod
2900
2447
    def find_format(klass, a_bzrdir):
2901
2448
        """Return the format for the working tree object in a_bzrdir."""
2902
2449
        try:
2903
2450
            transport = a_bzrdir.get_workingtree_transport(None)
2904
 
            format_string = transport.get_bytes("format")
 
2451
            format_string = transport.get("format").read()
2905
2452
            return klass._formats[format_string]
2906
2453
        except errors.NoSuchFile:
2907
2454
            raise errors.NoWorkingTree(base=transport.base)
2908
2455
        except KeyError:
2909
 
            raise errors.UnknownFormatError(format=format_string,
2910
 
                                            kind="working tree")
 
2456
            raise errors.UnknownFormatError(format=format_string)
2911
2457
 
2912
2458
    def __eq__(self, other):
2913
2459
        return self.__class__ is other.__class__
2932
2478
        """Is this format supported?
2933
2479
 
2934
2480
        Supported formats can be initialized and opened.
2935
 
        Unsupported formats may not support initialization or committing or
 
2481
        Unsupported formats may not support initialization or committing or 
2936
2482
        some other features depending on the reason for not being supported.
2937
2483
        """
2938
2484
        return True
2939
2485
 
2940
 
    def supports_content_filtering(self):
2941
 
        """True if this format supports content filtering."""
2942
 
        return False
2943
 
 
2944
 
    def supports_views(self):
2945
 
        """True if this format supports stored views."""
2946
 
        return False
2947
 
 
2948
2486
    @classmethod
2949
2487
    def register_format(klass, format):
2950
2488
        klass._formats[format.get_format_string()] = format
2951
2489
 
2952
2490
    @classmethod
2953
 
    def register_extra_format(klass, format):
2954
 
        klass._extra_formats.append(format)
2955
 
 
2956
 
    @classmethod
2957
 
    def unregister_extra_format(klass, format):
2958
 
        klass._extra_formats.remove(format)
2959
 
 
2960
 
    @classmethod
2961
 
    def get_formats(klass):
2962
 
        return klass._formats.values() + klass._extra_formats
2963
 
 
2964
 
    @classmethod
2965
2491
    def set_default_format(klass, format):
2966
2492
        klass._default_format = format
2967
2493
 
2968
2494
    @classmethod
2969
2495
    def unregister_format(klass, format):
 
2496
        assert klass._formats[format.get_format_string()] is format
2970
2497
        del klass._formats[format.get_format_string()]
2971
2498
 
2972
2499
 
2973
2500
class WorkingTreeFormat2(WorkingTreeFormat):
2974
 
    """The second working tree format.
 
2501
    """The second working tree format. 
2975
2502
 
2976
2503
    This format modified the hash cache from the format 1 hash cache.
2977
2504
    """
2978
2505
 
2979
2506
    upgrade_recommended = True
2980
2507
 
2981
 
    requires_normalized_unicode_filenames = True
2982
 
 
2983
 
    case_sensitive_filename = "Branch-FoRMaT"
2984
 
 
2985
 
    missing_parent_conflicts = False
2986
 
 
2987
2508
    def get_format_description(self):
2988
2509
        """See WorkingTreeFormat.get_format_description()."""
2989
2510
        return "Working tree format 2"
2990
2511
 
2991
 
    def _stub_initialize_on_transport(self, transport, file_mode):
2992
 
        """Workaround: create control files for a remote working tree.
2993
 
 
 
2512
    def stub_initialize_remote(self, control_files):
 
2513
        """As a special workaround create critical control files for a remote working tree
 
2514
        
2994
2515
        This ensures that it can later be updated and dealt with locally,
2995
 
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with
 
2516
        since BzrDirFormat6 and BzrDirFormat5 cannot represent dirs with 
2996
2517
        no working tree.  (See bug #43064).
2997
2518
        """
2998
2519
        sio = StringIO()
2999
 
        inv = inventory.Inventory()
3000
 
        xml5.serializer_v5.write_inventory(inv, sio, working=True)
 
2520
        inv = Inventory()
 
2521
        xml5.serializer_v5.write_inventory(inv, sio)
3001
2522
        sio.seek(0)
3002
 
        transport.put_file('inventory', sio, file_mode)
3003
 
        transport.put_bytes('pending-merges', '', file_mode)
3004
 
 
3005
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
3006
 
                   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):
3007
2529
        """See WorkingTreeFormat.initialize()."""
3008
2530
        if not isinstance(a_bzrdir.transport, LocalTransport):
3009
2531
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
3010
 
        if from_branch is not None:
3011
 
            branch = from_branch
3012
 
        else:
3013
 
            branch = a_bzrdir.open_branch()
3014
 
        if revision_id is None:
3015
 
            revision_id = _mod_revision.ensure_null(branch.last_revision())
3016
 
        branch.lock_write()
3017
 
        try:
3018
 
            branch.generate_revision_history(revision_id)
3019
 
        finally:
3020
 
            branch.unlock()
3021
 
        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()
3022
2547
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
3023
2548
                         branch,
3024
2549
                         inv,
3025
2550
                         _internal=True,
3026
2551
                         _format=self,
3027
 
                         _bzrdir=a_bzrdir,
3028
 
                         _control_files=branch.control_files)
3029
 
        basis_tree = branch.repository.revision_tree(revision_id)
 
2552
                         _bzrdir=a_bzrdir)
 
2553
        basis_tree = branch.repository.revision_tree(revision)
3030
2554
        if basis_tree.inventory.root is not None:
3031
 
            wt.set_root_id(basis_tree.get_root_id())
 
2555
            wt.set_root_id(basis_tree.inventory.root.file_id)
3032
2556
        # set the parent list and cache the basis tree.
3033
 
        if _mod_revision.is_null(revision_id):
3034
 
            parent_trees = []
3035
 
        else:
3036
 
            parent_trees = [(revision_id, basis_tree)]
3037
 
        wt.set_parent_trees(parent_trees)
 
2557
        wt.set_parent_trees([(revision, basis_tree)])
3038
2558
        transform.build_tree(basis_tree, wt)
3039
2559
        return wt
3040
2560
 
3056
2576
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
3057
2577
                           _internal=True,
3058
2578
                           _format=self,
3059
 
                           _bzrdir=a_bzrdir,
3060
 
                           _control_files=a_bzrdir.open_branch().control_files)
 
2579
                           _bzrdir=a_bzrdir)
3061
2580
        return wt
3062
2581
 
3063
2582
class WorkingTreeFormat3(WorkingTreeFormat):
3071
2590
        - is new in bzr 0.8
3072
2591
        - uses a LockDir to guard access for writes.
3073
2592
    """
3074
 
 
 
2593
    
3075
2594
    upgrade_recommended = True
3076
2595
 
3077
 
    missing_parent_conflicts = True
3078
 
 
3079
2596
    def get_format_string(self):
3080
2597
        """See WorkingTreeFormat.get_format_string()."""
3081
2598
        return "Bazaar-NG Working Tree format 3"
3096
2613
 
3097
2614
    def _open_control_files(self, a_bzrdir):
3098
2615
        transport = a_bzrdir.get_workingtree_transport(None)
3099
 
        return LockableFiles(transport, self._lock_file_name,
 
2616
        return LockableFiles(transport, self._lock_file_name, 
3100
2617
                             self._lock_class)
3101
2618
 
3102
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
3103
 
                   accelerator_tree=None, hardlink=False):
 
2619
    def initialize(self, a_bzrdir, revision_id=None):
3104
2620
        """See WorkingTreeFormat.initialize().
3105
 
 
3106
 
        :param revision_id: if supplied, create a working tree at a different
3107
 
            revision than the branch is at.
3108
 
        :param accelerator_tree: A tree which can be used for retrieving file
3109
 
            contents more quickly than the revision tree, i.e. a workingtree.
3110
 
            The revision tree will be used for cases where accelerator_tree's
3111
 
            content is different.
3112
 
        :param hardlink: If true, hard-link files from accelerator_tree,
3113
 
            where possible.
 
2621
        
 
2622
        revision_id allows creating a working tree at a different
 
2623
        revision than the branch is at.
3114
2624
        """
3115
2625
        if not isinstance(a_bzrdir.transport, LocalTransport):
3116
2626
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
3118
2628
        control_files = self._open_control_files(a_bzrdir)
3119
2629
        control_files.create_lock()
3120
2630
        control_files.lock_write()
3121
 
        transport.put_bytes('format', self.get_format_string(),
3122
 
            mode=a_bzrdir._get_file_mode())
3123
 
        if from_branch is not None:
3124
 
            branch = from_branch
 
2631
        control_files.put_utf8('format', self.get_format_string())
 
2632
        branch = a_bzrdir.open_branch()
 
2633
        if revision_id is None:
 
2634
            revision_id = branch.last_revision()
3125
2635
        else:
3126
 
            branch = a_bzrdir.open_branch()
3127
 
        if revision_id is None:
3128
 
            revision_id = _mod_revision.ensure_null(branch.last_revision())
 
2636
            revision_id = osutils.safe_revision_id(revision_id)
3129
2637
        # WorkingTree3 can handle an inventory which has a unique root id.
3130
2638
        # as of bzr 0.12. However, bzr 0.11 and earlier fail to handle
3131
2639
        # those trees. And because there isn't a format bump inbetween, we
3144
2652
            basis_tree = branch.repository.revision_tree(revision_id)
3145
2653
            # only set an explicit root id if there is one to set.
3146
2654
            if basis_tree.inventory.root is not None:
3147
 
                wt.set_root_id(basis_tree.get_root_id())
3148
 
            if revision_id == _mod_revision.NULL_REVISION:
 
2655
                wt.set_root_id(basis_tree.inventory.root.file_id)
 
2656
            if revision_id == NULL_REVISION:
3149
2657
                wt.set_parent_trees([])
3150
2658
            else:
3151
2659
                wt.set_parent_trees([(revision_id, basis_tree)])
3158
2666
        return wt
3159
2667
 
3160
2668
    def _initial_inventory(self):
3161
 
        return inventory.Inventory()
 
2669
        return Inventory()
3162
2670
 
3163
2671
    def __init__(self):
3164
2672
        super(WorkingTreeFormat3, self).__init__()
3179
2687
 
3180
2688
    def _open(self, a_bzrdir, control_files):
3181
2689
        """Open the tree itself.
3182
 
 
 
2690
        
3183
2691
        :param a_bzrdir: the dir for the tree.
3184
2692
        :param control_files: the control files for the tree.
3185
2693
        """
3193
2701
        return self.get_format_string()
3194
2702
 
3195
2703
 
3196
 
__default_format = WorkingTreeFormat6()
 
2704
__default_format = WorkingTreeFormat4()
3197
2705
WorkingTreeFormat.register_format(__default_format)
3198
 
WorkingTreeFormat.register_format(WorkingTreeFormat5())
3199
 
WorkingTreeFormat.register_format(WorkingTreeFormat4())
3200
2706
WorkingTreeFormat.register_format(WorkingTreeFormat3())
3201
2707
WorkingTreeFormat.set_default_format(__default_format)
3202
 
# Register extra formats which have no format string are not discoverable
3203
 
# and not independently creatable. They are implicitly created as part of
3204
 
# e.g. older Bazaar formats or foreign formats.
3205
 
WorkingTreeFormat.register_extra_format(WorkingTreeFormat2())
 
2708
# formats which have no format string are not discoverable
 
2709
# and not independently creatable, so are not registered.
 
2710
_legacy_formats = [WorkingTreeFormat2(),
 
2711
                   ]
 
2712
 
 
2713
 
 
2714
class WorkingTreeTestProviderAdapter(object):
 
2715
    """A tool to generate a suite testing multiple workingtree formats at once.
 
2716
 
 
2717
    This is done by copying the test once for each transport and injecting
 
2718
    the transport_server, transport_readonly_server, and workingtree_format
 
2719
    classes into each copy. Each copy is also given a new id() to make it
 
2720
    easy to identify.
 
2721
    """
 
2722
 
 
2723
    def __init__(self, transport_server, transport_readonly_server, formats):
 
2724
        self._transport_server = transport_server
 
2725
        self._transport_readonly_server = transport_readonly_server
 
2726
        self._formats = formats
 
2727
    
 
2728
    def _clone_test(self, test, bzrdir_format, workingtree_format, variation):
 
2729
        """Clone test for adaption."""
 
2730
        new_test = deepcopy(test)
 
2731
        new_test.transport_server = self._transport_server
 
2732
        new_test.transport_readonly_server = self._transport_readonly_server
 
2733
        new_test.bzrdir_format = bzrdir_format
 
2734
        new_test.workingtree_format = workingtree_format
 
2735
        def make_new_test_id():
 
2736
            new_id = "%s(%s)" % (test.id(), variation)
 
2737
            return lambda: new_id
 
2738
        new_test.id = make_new_test_id()
 
2739
        return new_test
 
2740
    
 
2741
    def adapt(self, test):
 
2742
        from bzrlib.tests import TestSuite
 
2743
        result = TestSuite()
 
2744
        for workingtree_format, bzrdir_format in self._formats:
 
2745
            new_test = self._clone_test(
 
2746
                test,
 
2747
                bzrdir_format,
 
2748
                workingtree_format, workingtree_format.__class__.__name__)
 
2749
            result.addTest(new_test)
 
2750
        return result