/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
1
# Copyright (C) 2005, 2006 Canonical Ltd
2
#
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
#
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
#
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
17
"""WorkingTree4 format and implementation.
18
19
WorkingTree4 provides the dirstate based working tree logic.
20
21
To get a WorkingTree, call bzrdir.open_workingtree() or
22
WorkingTree.open(dir).
23
"""
24
25
import os
26
27
from bzrlib.lazy_import import lazy_import
28
lazy_import(globals(), """
29
from bisect import bisect_left
30
import collections
31
from copy import deepcopy
32
import errno
33
import itertools
34
import operator
35
import stat
36
from time import time
37
import warnings
38
39
import bzrlib
40
from bzrlib import (
41
    bzrdir,
42
    conflicts as _mod_conflicts,
43
    dirstate,
44
    errors,
45
    generate_ids,
46
    globbing,
47
    hashcache,
48
    ignores,
49
    merge,
50
    osutils,
51
    textui,
52
    transform,
53
    urlutils,
54
    xml5,
55
    xml6,
56
    )
57
import bzrlib.branch
58
from bzrlib.transport import get_transport
59
import bzrlib.ui
60
""")
61
62
from bzrlib import symbol_versioning
63
from bzrlib.decorators import needs_read_lock, needs_write_lock
2255.2.10 by Robert Collins
Now all tests matching dirstate pass - added generation of inventories for parent trees.
64
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, make_entry
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
65
from bzrlib.lockable_files import LockableFiles, TransportLock
66
from bzrlib.lockdir import LockDir
67
import bzrlib.mutabletree
68
from bzrlib.mutabletree import needs_tree_write_lock
69
from bzrlib.osutils import (
70
    compact_date,
71
    file_kind,
72
    isdir,
73
    normpath,
74
    pathjoin,
75
    rand_chars,
76
    realpath,
77
    safe_unicode,
78
    splitpath,
79
    supports_executable,
80
    )
81
from bzrlib.trace import mutter, note
82
from bzrlib.transport.local import LocalTransport
83
from bzrlib.progress import DummyProgress, ProgressPhase
84
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
85
from bzrlib.rio import RioReader, rio_file, Stanza
86
from bzrlib.symbol_versioning import (deprecated_passed,
87
        deprecated_method,
88
        deprecated_function,
89
        DEPRECATED_PARAMETER,
90
        zero_eight,
91
        zero_eleven,
92
        zero_thirteen,
93
        )
94
from bzrlib.tree import Tree
95
from bzrlib.workingtree import WorkingTree3, WorkingTreeFormat3
96
97
98
class WorkingTree4(WorkingTree3):
99
    """This is the Format 4 working tree.
100
101
    This differs from WorkingTree3 by:
102
     - having a consolidated internal dirstate.
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
103
     - not having a regular inventory attribute.
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
104
105
    This is new in bzr TODO FIXME SETMEBEFORE MERGE.
106
    """
107
108
    def __init__(self, basedir,
109
                 branch,
110
                 _control_files=None,
111
                 _format=None,
112
                 _bzrdir=None):
113
        """Construct a WorkingTree for basedir.
114
115
        If the branch is not supplied, it is opened automatically.
116
        If the branch is supplied, it must be the branch for this basedir.
117
        (branch.base is not cross checked, because for remote branches that
118
        would be meaningless).
119
        """
120
        self._format = _format
121
        self.bzrdir = _bzrdir
122
        from bzrlib.hashcache import HashCache
123
        from bzrlib.trace import note, mutter
124
        assert isinstance(basedir, basestring), \
125
            "base directory %r is not a string" % basedir
126
        basedir = safe_unicode(basedir)
127
        mutter("opening working tree %r", basedir)
128
        self._branch = branch
129
        assert isinstance(self.branch, bzrlib.branch.Branch), \
130
            "branch %r is not a Branch" % self.branch
131
        self.basedir = realpath(basedir)
132
        # if branch is at our basedir and is a format 6 or less
133
        # assume all other formats have their own control files.
134
        assert isinstance(_control_files, LockableFiles), \
135
            "_control_files must be a LockableFiles, not %r" % _control_files
136
        self._control_files = _control_files
137
        # update the whole cache up front and write to disk if anything changed;
138
        # in the future we might want to do this more selectively
139
        # two possible ways offer themselves : in self._unlock, write the cache
140
        # if needed, or, when the cache sees a change, append it to the hash
141
        # cache file, and have the parser take the most recent entry for a
142
        # given path only.
143
        cache_filename = self.bzrdir.get_workingtree_transport(None).local_abspath('stat-cache')
144
        hc = self._hashcache = HashCache(basedir, cache_filename, self._control_files._file_mode)
145
        hc.read()
146
        # is this scan needed ? it makes things kinda slow.
147
        #hc.scan()
148
149
        if hc.needs_write:
150
            mutter("write hc")
151
            hc.write()
152
153
        self._dirty = None
154
        self._parent_revisions = None
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
155
        #-------------
156
        # during a read or write lock these objects are set, and are
157
        # None the rest of the time.
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
158
        self._dirstate = None
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
159
        self._inventory = None
160
        #-------------
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
161
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
162
    @needs_tree_write_lock
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
163
    def _add(self, files, ids, kinds):
164
        """See MutableTree._add."""
165
        state = self.current_dirstate()
166
        for f, file_id, kind in zip(files, ids, kinds):
2255.2.14 by Robert Collins
Dirstate: fix adding of directories to setup the next directories block, and test representation of symlinks. Also fix iter_rows to not reset the dirty bit.
167
            f = f.strip('/')
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
168
            assert '//' not in f
169
            assert '..' not in f
170
            if file_id is None:
2255.2.20 by Robert Collins
Bypass irrelevant basis_inventory tests for dirstate.
171
                file_id = generate_ids.gen_file_id(f)
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
172
            stat = os.lstat(self.abspath(f))
173
            sha1 = '1' * 20 # FIXME: DIRSTATE MERGE BLOCKER
174
            state.add(f, file_id, kind, stat, sha1)
2255.2.16 by Robert Collins
Implement WorkingTreeFormat4._write_inventory for better compatability with existing code, letting more test_test_trees pass, now up to test_tree_with_subdirs_and_all_content_types.
175
        self._dirty = True
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
176
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
177
    def current_dirstate(self):
178
        """Return the current dirstate object. 
179
180
        This is not part of the tree interface and only exposed for ease of
181
        testing.
182
183
        :raises errors.NotWriteLocked: when not in a lock. 
184
            XXX: This should probably be errors.NotLocked.
185
        """
186
        if not self._control_files._lock_count:
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
187
            raise errors.ObjectNotLocked(self)
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
188
        if self._dirstate is not None:
189
            return self._dirstate
190
        local_path = self.bzrdir.get_workingtree_transport(None
191
            ).local_abspath('dirstate')
192
        self._dirstate = dirstate.DirState.on_file(local_path)
193
        return self._dirstate
194
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
195
    def flush(self):
196
        """Write all cached data to disk."""
197
        self.current_dirstate().save()
198
        self._inventory = None
199
        self._dirty = False
200
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
201
    def _generate_inventory(self):
202
        """Create and set self.inventory from the dirstate object.
203
        
204
        This is relatively expensive: we have to walk the entire dirstate.
205
        Ideally we would not, and can deprecate this function.
206
        """
207
        dirstate = self.current_dirstate()
208
        rows = self._dirstate._iter_rows()
209
        root_row = rows.next()
210
        inv = Inventory(root_id=root_row[0][3].decode('utf8'))
211
        for line in rows:
212
            dirname, name, kind, fileid_utf8, size, stat, link_or_sha1 = line[0]
213
            if dirname == '/':
214
                # not in this revision tree.
215
                continue
216
            parent_id = inv[inv.path2id(dirname.decode('utf8'))].file_id
217
            file_id = fileid_utf8.decode('utf8')
218
            entry = make_entry(kind, name.decode('utf8'), parent_id, file_id)
219
            if kind == 'file':
220
                #entry.executable = executable
221
                #entry.text_size = size
222
                #entry.text_sha1 = sha1
223
                pass
224
            inv.add(entry)
225
        self._inventory = inv
226
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
227
    def _get_inventory(self):
228
        """Get the inventory for the tree. This is only valid within a lock."""
229
        if self._inventory is not None:
230
            return self._inventory
231
        self._generate_inventory()
232
        return self._inventory
233
234
    inventory = property(_get_inventory,
235
                         doc="Inventory of this Tree")
236
237
    @needs_read_lock
238
    def get_root_id(self):
239
        """Return the id of this trees root"""
240
        return self.current_dirstate()._iter_rows().next()[0][3].decode('utf8')
241
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
242
    def has_id(self, file_id):
243
        state = self.current_dirstate()
244
        fileid_utf8 = file_id.encode('utf8')
245
        for row, parents in state._iter_rows():
246
            if row[3] == fileid_utf8:
247
                return osutils.lexists(pathjoin(
248
                    self.basedir, row[0].decode('utf8'), row[1].decode('utf8')))
249
        return False
250
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
251
    @needs_read_lock
252
    def id2path(self, fileid):
253
        state = self.current_dirstate()
254
        fileid_utf8 = fileid.encode('utf8')
255
        for row, parents in state._iter_rows():
256
            if row[3] == fileid_utf8:
257
                return (row[0] + '/' + row[1]).decode('utf8').strip('/')
258
259
    @needs_read_lock
260
    def __iter__(self):
261
        """Iterate through file_ids for this tree.
262
263
        file_ids are in a WorkingTree if they are in the working inventory
264
        and the working file exists.
265
        """
266
        result = []
267
        for row, parents in self.current_dirstate()._iter_rows():
268
            if row[0] == '/':
269
                continue
270
            path = pathjoin(self.basedir, row[0].decode('utf8'), row[1].decode('utf8'))
271
            if osutils.lexists(path):
272
                result.append(row[3].decode('utf8'))
273
        return iter(result)
274
2255.2.21 by Robert Collins
Add WorkingTree4._last_revision, making workingtree_implementations.test_changes_from pass.
275
    @needs_read_lock
276
    def _last_revision(self):
277
        """See Mutable.last_revision."""
278
        parent_ids = self.current_dirstate().get_parent_ids()
279
        if parent_ids:
280
            return parent_ids[0].decode('utf8')
281
        else:
282
            return None
283
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
284
    def _new_tree(self):
285
        """Initialize the state in this tree to be a new tree."""
286
        self._parent_revisions = [NULL_REVISION]
287
        self._dirty = True
288
289
    @needs_read_lock
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
290
    def path2id(self, path):
291
        """Return the id for path in this tree."""
292
        state = self.current_dirstate()
293
        path_utf8 = os.path.split(path.encode('utf8'))
294
        for row, parents in state._iter_rows():
295
            if row[0:2] == path_utf8:
296
                return row[3].decode('utf8')
297
        return None
298
299
    @needs_read_lock
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
300
    def revision_tree(self, revision_id):
301
        """See Tree.revision_tree.
302
303
        WorkingTree4 supplies revision_trees for any basis tree.
304
        """
305
        dirstate = self.current_dirstate()
306
        parent_ids = dirstate.get_parent_ids()
307
        if revision_id not in parent_ids:
308
            raise errors.NoSuchRevisionInTree(self, revision_id)
309
        return DirStateRevisionTree(dirstate, revision_id,
310
            self.branch.repository)
311
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
312
    @needs_tree_write_lock
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
313
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
314
        """Set the parent ids to revision_ids.
315
        
316
        See also set_parent_trees. This api will try to retrieve the tree data
317
        for each element of revision_ids from the trees repository. If you have
318
        tree data already available, it is more efficient to use
319
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
320
        an easier API to use.
321
322
        :param revision_ids: The revision_ids to set as the parent ids of this
323
            working tree. Any of these may be ghosts.
324
        """
325
        trees = []
326
        for revision_id in revision_ids:
327
            try:
328
                revtree = self.branch.repository.revision_tree(revision_id)
329
            except errors.NoSuchRevision:
330
                revtree = None
331
            trees.append((revision_id, revtree))
332
        self.set_parent_trees(trees,
333
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
334
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
335
    @needs_tree_write_lock
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
336
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
337
        """Set the parents of the working tree.
338
339
        :param parents_list: A list of (revision_id, tree) tuples. 
340
            If tree is None, then that element is treated as an unreachable
341
            parent tree - i.e. a ghost.
342
        """
343
        dirstate = self.current_dirstate()
344
        if len(parents_list) > 0:
345
            if not allow_leftmost_as_ghost and parents_list[0][1] is None:
346
                raise errors.GhostRevisionUnusableHere(leftmost_id)
347
        real_trees = []
348
        ghosts = []
349
        # convert absent trees to the null tree, which we convert back to 
350
        # missing on access.
351
        for rev_id, tree in parents_list:
352
            if tree is not None:
353
                real_trees.append((rev_id, tree))
354
            else:
355
                real_trees.append((rev_id,
356
                    self.branch.repository.revision_tree(None)))
357
                ghosts.append(rev_id)
358
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
359
        self._dirty = True
360
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
361
    def _set_root_id(self, file_id):
362
        """See WorkingTree.set_root_id."""
363
        self.current_dirstate().set_path_id('', file_id)
364
        self._dirty = True
365
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
366
    def unlock(self):
367
        """Unlock in format 4 trees needs to write the entire dirstate."""
368
        if self._control_files._lock_count == 1:
369
            if self._hashcache.needs_write:
370
                self._hashcache.write()
371
            # eventually we should do signature checking during read locks for
372
            # dirstate updates.
373
            if self._control_files._lock_mode == 'w':
374
                if self._dirty:
375
                    self.flush()
376
            self._dirstate = None
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
377
            self._inventory = None
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
378
        # reverse order of locking.
379
        try:
380
            return self._control_files.unlock()
381
        finally:
382
            self.branch.unlock()
383
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
384
    @needs_tree_write_lock
385
    def unversion(self, file_ids):
386
        """Remove the file ids in file_ids from the current versioned set.
387
388
        When a file_id is unversioned, all of its children are automatically
389
        unversioned.
390
391
        :param file_ids: The file ids to stop versioning.
392
        :raises: NoSuchId if any fileid is not currently versioned.
393
        """
394
        if not file_ids:
395
            return
396
        state = self.current_dirstate()
397
        state._read_dirblocks_if_needed()
398
        ids_to_unversion = set()
399
        for fileid in file_ids:
400
            ids_to_unversion.add(fileid.encode('utf8'))
401
        paths_to_unversion = set()
402
        # sketch:
403
        # check if the root is to be unversioned, if so, assert for now.
404
        # make a copy of the _dirblocks data 
405
        # during the copy,
406
        #  skip paths in paths_to_unversion
407
        #  skip ids in ids_to_unversion, and add their paths to
408
        #  paths_to_unversion if they are a directory
409
        # if there are any un-unversioned ids at the end, raise
410
        if state._root_row[0][3] in ids_to_unversion:
411
            # I haven't written the code to unversion / yet - it should be 
412
            # supported.
413
            raise errors.BzrError('Unversioning the / is not currently supported')
414
        new_blocks = []
415
        for block in state._dirblocks:
416
            # first check: is the path one to remove - it or its children
417
            delete_block = False
418
            for path in paths_to_unversion:
419
                if (block[0].startswith(path) and
420
                    (len(block[0]) == len(path) or
421
                     block[0][len(path)] == '/')):
422
                    # this path should be deleted
423
                    delete_block = True
424
                    break
425
            # TODO: trim paths_to_unversion as we pass by paths
426
            if delete_block:
427
                # this block is to be deleted. skip it.
428
                continue
429
            # copy undeleted rows from within the the block
430
            new_blocks.append((block[0], []))
431
            new_row = new_blocks[-1][1]
432
            for row, row_parents in block[1]:
433
                if row[3] not in ids_to_unversion:
434
                    new_row.append((row, row_parents))
435
                else:
436
                    # skip the row, and if its a dir mark its path to be removed
437
                    if row[2] == 'directory':
438
                        paths_to_unversion.add((row[0] + '/' + row[1]).strip('/'))
439
                    assert not row_parents, "not ready to preserve parents."
440
                    ids_to_unversion.remove(row[3])
441
        if ids_to_unversion:
442
            raise errors.NoSuchId(self, iter(ids_to_unversion).next())
443
        state._dirblocks = new_blocks
444
        state._dirblock_state = dirstate.DirState.IN_MEMORY_MODIFIED
445
        # have to change the legacy inventory too.
446
        if self._inventory is not None:
447
            for file_id in file_ids:
448
                if self._inventory.has_id(file_id):
449
                    self._inventory.remove_recursive_id(file_id)
450
2255.2.16 by Robert Collins
Implement WorkingTreeFormat4._write_inventory for better compatability with existing code, letting more test_test_trees pass, now up to test_tree_with_subdirs_and_all_content_types.
451
    @needs_tree_write_lock
452
    def _write_inventory(self, inv):
453
        """Write inventory as the current inventory."""
454
        assert not self._dirty, "attempting to write an inventory when the dirstate is dirty will cause data loss"
455
        self.current_dirstate().set_state_from_inventory(inv)
456
        self._dirty = True
457
        self.flush()
458
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
459
460
class WorkingTreeFormat4(WorkingTreeFormat3):
461
    """The first consolidated dirstate working tree format.
462
463
    This format:
464
        - exists within a metadir controlling .bzr
465
        - includes an explicit version marker for the workingtree control
466
          files, separate from the BzrDir format
467
        - modifies the hash cache format
468
        - is new in bzr TODO FIXME SETBEFOREMERGE
469
        - uses a LockDir to guard access to it.
470
    """
471
472
    def get_format_string(self):
473
        """See WorkingTreeFormat.get_format_string()."""
474
        return "Bazaar Working Tree format 4\n"
475
476
    def get_format_description(self):
477
        """See WorkingTreeFormat.get_format_description()."""
478
        return "Working tree format 4"
479
480
    def initialize(self, a_bzrdir, revision_id=None):
481
        """See WorkingTreeFormat.initialize().
482
        
483
        revision_id allows creating a working tree at a different
484
        revision than the branch is at.
485
        """
486
        if not isinstance(a_bzrdir.transport, LocalTransport):
487
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
488
        transport = a_bzrdir.get_workingtree_transport(self)
489
        control_files = self._open_control_files(a_bzrdir)
490
        control_files.create_lock()
491
        control_files.lock_write()
492
        control_files.put_utf8('format', self.get_format_string())
493
        branch = a_bzrdir.open_branch()
494
        if revision_id is None:
495
            revision_id = branch.last_revision()
496
        local_path = transport.local_abspath('dirstate')
497
        dirstate.DirState.initialize(local_path)
498
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
499
                         branch,
500
                         _format=self,
501
                         _bzrdir=a_bzrdir,
502
                         _control_files=control_files)
503
        wt._new_tree()
504
        wt.lock_write()
505
        try:
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
506
            #wt.current_dirstate().set_path_id('', NEWROOT)
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
507
            wt.set_last_revision(revision_id)
2255.2.16 by Robert Collins
Implement WorkingTreeFormat4._write_inventory for better compatability with existing code, letting more test_test_trees pass, now up to test_tree_with_subdirs_and_all_content_types.
508
            wt.flush()
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
509
            transform.build_tree(wt.basis_tree(), wt)
510
        finally:
511
            control_files.unlock()
512
            wt.unlock()
513
        return wt
514
515
516
    def _open(self, a_bzrdir, control_files):
517
        """Open the tree itself.
518
        
519
        :param a_bzrdir: the dir for the tree.
520
        :param control_files: the control files for the tree.
521
        """
522
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
523
                           branch=a_bzrdir.open_branch(),
524
                           _format=self,
525
                           _bzrdir=a_bzrdir,
526
                           _control_files=control_files)
527
528
529
class DirStateRevisionTree(Tree):
530
    """A revision tree pulling the inventory from a dirstate."""
531
532
    def __init__(self, dirstate, revision_id, repository):
533
        self._dirstate = dirstate
534
        self._revision_id = revision_id
535
        self._repository = repository
536
        self._inventory = None
537
        self._locked = False
538
539
    def _comparison_data(self, entry, path):
540
        """See Tree._comparison_data."""
541
        if entry is None:
542
            return None, False, None
543
        # trust the entry as RevisionTree does, but this may not be
544
        # sensible: the entry might not have come from us?
545
        return entry.kind, entry.executable, None
546
2255.2.10 by Robert Collins
Now all tests matching dirstate pass - added generation of inventories for parent trees.
547
    def _file_size(self, entry, stat_value):
548
        return entry.text_size
549
550
    def get_file_sha1(self, file_id, path=None, stat_value=None):
551
        # TODO: if path is present, fast-path on that, as inventory
552
        # might not be present
553
        ie = self.inventory[file_id]
554
        if ie.kind == "file":
555
            return ie.text_sha1
556
        return None
557
558
    def get_file_size(self, file_id):
559
        return self.inventory[file_id].text_size
560
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
561
    def _get_inventory(self):
562
        if self._inventory is not None:
563
            return self._inventory
564
        self._generate_inventory()
565
        return self._inventory
566
567
    inventory = property(_get_inventory,
568
                         doc="Inventory of this Tree")
569
570
    def _generate_inventory(self):
571
        """Create and set self.inventory from the dirstate object.
572
        
573
        This is relatively expensive: we have to walk the entire dirstate.
574
        Ideally we would not, and instead would """
575
        assert self._locked, 'cannot generate inventory of an unlocked '\
576
            'dirstate revision tree'
577
        assert self._revision_id in self._dirstate.get_parent_ids(), \
578
            'parent %s has disappeared from %s' % (
579
            self._revision_id, self._dirstate.get_parent_ids())
2255.2.10 by Robert Collins
Now all tests matching dirstate pass - added generation of inventories for parent trees.
580
        parent_index = self._dirstate.get_parent_ids().index(self._revision_id)
581
        rows = self._dirstate._iter_rows()
582
        root_row = rows.next()
583
        inv = Inventory(root_id=root_row[0][3].decode('utf8'),
584
            revision_id=self._revision_id)
585
        for line in rows:
586
            revid, kind, dirname, name, size, executable, sha1 = line[1][parent_index]
587
            if not revid:
588
                # not in this revision tree.
589
                continue
590
            parent_id = inv[inv.path2id(dirname.decode('utf8'))].file_id
591
            file_id = line[0][3].decode('utf8')
592
            entry = make_entry(kind, name.decode('utf8'), parent_id, file_id)
593
            entry.revision = revid.decode('utf8')
594
            if kind == 'file':
595
                entry.executable = executable
596
                entry.text_size = size
597
                entry.text_sha1 = sha1
598
            inv.add(entry)
2255.2.3 by Robert Collins
Split out working tree format 4 to its own file, create stub dirstate revision object, start working on dirstate.set_parent_trees - a key failure point.
599
        self._inventory = inv
600
601
    def get_parent_ids(self):
602
        """The parents of a tree in the dirstate are not cached."""
603
        return self._repository.get_revision(self._revision_id).parent_ids
604
605
    def lock_read(self):
606
        """Lock the tree for a set of operations."""
607
        self._locked = True
608
609
    def unlock(self):
610
        """Unlock, freeing any cache memory used during the lock."""
611
        # outside of a lock, the inventory is suspect: release it.
612
        self._inventory = None
613
        self._locked = False