/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
2255.7.83 by John Arbash Meinel
Update some obvious copyright headers to include 2007.
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
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.
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
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
25
from cStringIO import StringIO
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.
26
import os
2255.2.138 by John Arbash Meinel
implement several new WorkingTree.move() tests
27
import sys
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.
28
29
from bzrlib.lazy_import import lazy_import
30
lazy_import(globals(), """
31
from bisect import bisect_left
32
import collections
33
from copy import deepcopy
34
import errno
35
import itertools
36
import operator
37
import stat
38
from time import time
39
import warnings
40
41
import bzrlib
42
from bzrlib import (
43
    bzrdir,
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
44
    cache_utf8,
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.
45
    conflicts as _mod_conflicts,
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
46
    delta,
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.
47
    dirstate,
48
    errors,
49
    generate_ids,
50
    globbing,
51
    hashcache,
52
    ignores,
53
    merge,
54
    osutils,
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
55
    revisiontree,
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.
56
    textui,
57
    transform,
58
    urlutils,
59
    xml5,
60
    xml6,
61
    )
62
import bzrlib.branch
63
from bzrlib.transport import get_transport
64
import bzrlib.ui
65
""")
66
67
from bzrlib import symbol_versioning
68
from bzrlib.decorators import needs_read_lock, needs_write_lock
2255.2.74 by Robert Collins
Minor performance optimisation in _generate_inventory by avoiding normalisation checks and just using a factory to create the inventory entries.
69
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, entry_factory
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.
70
from bzrlib.lockable_files import LockableFiles, TransportLock
71
from bzrlib.lockdir import LockDir
72
import bzrlib.mutabletree
73
from bzrlib.mutabletree import needs_tree_write_lock
74
from bzrlib.osutils import (
2255.2.202 by Martin Pool
WorkingTree_4.kind should report tree-references if they're
75
    file_kind,
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.
76
    isdir,
77
    normpath,
78
    pathjoin,
79
    rand_chars,
80
    realpath,
81
    safe_unicode,
82
    splitpath,
83
    )
84
from bzrlib.trace import mutter, note
85
from bzrlib.transport.local import LocalTransport
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
86
from bzrlib.tree import InterTree
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.
87
from bzrlib.progress import DummyProgress, ProgressPhase
88
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
89
from bzrlib.rio import RioReader, rio_file, Stanza
90
from bzrlib.symbol_versioning import (deprecated_passed,
91
        deprecated_method,
92
        deprecated_function,
93
        DEPRECATED_PARAMETER,
94
        )
95
from bzrlib.tree import Tree
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
96
from bzrlib.workingtree import WorkingTree, WorkingTree3, WorkingTreeFormat3
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.
97
98
99
class WorkingTree4(WorkingTree3):
100
    """This is the Format 4 working tree.
101
102
    This differs from WorkingTree3 by:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
103
     - Having a consolidated internal dirstate, stored in a
104
       randomly-accessible sorted file on disk.
105
     - Not having a regular inventory attribute.  One can be synthesized 
106
       on demand but this is expensive and should be avoided.
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.
107
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
108
    This is new in bzr 0.15.
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.
109
    """
110
111
    def __init__(self, basedir,
112
                 branch,
113
                 _control_files=None,
114
                 _format=None,
115
                 _bzrdir=None):
116
        """Construct a WorkingTree for basedir.
117
118
        If the branch is not supplied, it is opened automatically.
119
        If the branch is supplied, it must be the branch for this basedir.
120
        (branch.base is not cross checked, because for remote branches that
121
        would be meaningless).
122
        """
123
        self._format = _format
124
        self.bzrdir = _bzrdir
125
        from bzrlib.trace import note, mutter
126
        assert isinstance(basedir, basestring), \
127
            "base directory %r is not a string" % basedir
128
        basedir = safe_unicode(basedir)
129
        mutter("opening working tree %r", basedir)
130
        self._branch = branch
131
        assert isinstance(self.branch, bzrlib.branch.Branch), \
132
            "branch %r is not a Branch" % self.branch
133
        self.basedir = realpath(basedir)
134
        # if branch is at our basedir and is a format 6 or less
135
        # assume all other formats have their own control files.
136
        assert isinstance(_control_files, LockableFiles), \
137
            "_control_files must be a LockableFiles, not %r" % _control_files
138
        self._control_files = _control_files
139
        self._dirty = None
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
140
        #-------------
141
        # during a read or write lock these objects are set, and are
142
        # 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.
143
        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.
144
        self._inventory = None
145
        #-------------
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.
146
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
147
    @needs_tree_write_lock
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
148
    def _add(self, files, ids, kinds):
149
        """See MutableTree._add."""
150
        state = self.current_dirstate()
151
        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.
152
            f = f.strip('/')
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
153
            assert '//' not in f
154
            assert '..' not in f
2255.7.74 by Robert Collins
Test adding of roots to trees, it was broken on WorkingTree4.
155
            if self.path2id(f):
156
                # special case tree root handling.
157
                if f == '' and self.path2id(f) == ROOT_ID:
158
                    state.set_path_id('', generate_ids.gen_file_id(f))
159
                continue
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
160
            if file_id is None:
2255.2.20 by Robert Collins
Bypass irrelevant basis_inventory tests for dirstate.
161
                file_id = generate_ids.gen_file_id(f)
2255.2.43 by Robert Collins
WorkingTree4.add must not require a file to exist to add it when kind etc is given.
162
            # deliberately add the file with no cached stat or sha1
163
            # - on the first access it will be gathered, and we can
164
            # always change this once tests are all passing.
165
            state.add(f, file_id, kind, None, '')
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
166
        self._make_dirty(reset_inventory=True)
167
168
    def _make_dirty(self, reset_inventory):
169
        """Make the tree state dirty.
170
171
        :param reset_inventory: True if the cached inventory should be removed
172
            (presuming there is one).
173
        """
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.
174
        self._dirty = True
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
175
        if reset_inventory and self._inventory is not None:
176
            self._inventory = None
2255.2.12 by Robert Collins
Partial implementation of WorkingTree4._add.
177
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
178
    @needs_tree_write_lock
179
    def add_reference(self, sub_tree):
180
        # use standard implementation, which calls back to self._add
181
        # 
182
        # So we don't store the reference_revision in the working dirstate,
183
        # it's just recorded at the moment of commit. 
184
        self._add_reference(sub_tree)
185
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
186
    def break_lock(self):
187
        """Break a lock if one is present from another instance.
188
189
        Uses the ui factory to ask for confirmation if the lock may be from
190
        an active process.
191
192
        This will probe the repository for its lock as well.
193
        """
194
        # if the dirstate is locked by an active process, reject the break lock
195
        # call.
196
        try:
197
            if self._dirstate is None:
198
                clear = True
199
            else:
200
                clear = False
201
            state = self._current_dirstate()
202
            if state._lock_token is not None:
203
                # we already have it locked. sheese, cant break our own lock.
204
                raise errors.LockActive(self.basedir)
205
            else:
206
                try:
207
                    # try for a write lock - need permission to get one anyhow
208
                    # to break locks.
209
                    state.lock_write()
210
                except errors.LockContention:
211
                    # oslocks fail when a process is still live: fail.
212
                    # TODO: get the locked lockdir info and give to the user to
213
                    # assist in debugging.
214
                    raise errors.LockActive(self.basedir)
215
                else:
216
                    state.unlock()
217
        finally:
218
            if clear:
219
                self._dirstate = None
220
        self._control_files.break_lock()
221
        self.branch.break_lock()
222
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
223
    def _comparison_data(self, entry, path):
224
        kind, executable, stat_value = \
225
            WorkingTree3._comparison_data(self, entry, path)
226
        # it looks like a plain directory, but it's really a reference
227
        if kind == 'directory' and entry.kind == 'tree-reference':
228
            kind = 'tree-reference'
229
        return kind, executable, stat_value
230
2255.7.74 by Robert Collins
Test adding of roots to trees, it was broken on WorkingTree4.
231
    @needs_write_lock
232
    def commit(self, message=None, revprops=None, *args, **kwargs):
233
        # mark the tree as dirty post commit - commit
234
        # can change the current versioned list by doing deletes.
235
        result = WorkingTree3.commit(self, message, revprops, *args, **kwargs)
236
        self._make_dirty(reset_inventory=True)
237
        return result
238
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.
239
    def current_dirstate(self):
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
240
        """Return the current dirstate object.
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.
241
242
        This is not part of the tree interface and only exposed for ease of
243
        testing.
244
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
245
        :raises errors.NotWriteLocked: when not in a 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.
246
        """
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
247
        self._must_be_locked()
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
248
        return self._current_dirstate()
249
250
    def _current_dirstate(self):
251
        """Internal function that does not check lock status.
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
252
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
253
        This is needed for break_lock which also needs the dirstate.
254
        """
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.
255
        if self._dirstate is not None:
256
            return self._dirstate
257
        local_path = self.bzrdir.get_workingtree_transport(None
258
            ).local_abspath('dirstate')
259
        self._dirstate = dirstate.DirState.on_file(local_path)
260
        return self._dirstate
261
2255.2.81 by Robert Collins
WorkingTree4: Implement filter_unversioned_files to use dirstate bisection.
262
    def filter_unversioned_files(self, paths):
2255.7.62 by Robert Collins
Update the Tree.filter_unversioned_files docstring to reflect what the existing implementations actually do, and change the WorkingTree4 implementation to match a newly created test for it.
263
        """Filter out paths that are versioned.
2255.2.81 by Robert Collins
WorkingTree4: Implement filter_unversioned_files to use dirstate bisection.
264
265
        :return: set of paths.
266
        """
267
        # TODO: make a generic multi-bisect routine roughly that should list
268
        # the paths, then process one half at a time recursively, and feed the
269
        # results of each bisect in further still
270
        paths = sorted(paths)
271
        result = set()
2255.2.176 by Martin Pool
Merge dirstate and some small cleanups
272
        state = self.current_dirstate()
2255.2.81 by Robert Collins
WorkingTree4: Implement filter_unversioned_files to use dirstate bisection.
273
        # TODO we want a paths_to_dirblocks helper I think
274
        for path in paths:
275
            dirname, basename = os.path.split(path.encode('utf8'))
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
276
            _, _, _, path_is_versioned = state._get_block_entry_index(
277
                dirname, basename, 0)
2255.7.62 by Robert Collins
Update the Tree.filter_unversioned_files docstring to reflect what the existing implementations actually do, and change the WorkingTree4 implementation to match a newly created test for it.
278
            if not path_is_versioned:
2255.2.81 by Robert Collins
WorkingTree4: Implement filter_unversioned_files to use dirstate bisection.
279
                result.add(path)
280
        return result
281
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
282
    def flush(self):
283
        """Write all cached data to disk."""
2255.2.39 by Robert Collins
WorkingTree4: flush can only be used during write locks.
284
        if self._control_files._lock_mode != 'w':
285
            raise errors.NotWriteLocked(self)
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
286
        self.current_dirstate().save()
287
        self._inventory = None
288
        self._dirty = False
289
2255.2.34 by Robert Collins
Fix WorkingTree4 parent_ids logic to use the dirstate to answer parent ids list queries.
290
    def _generate_inventory(self):
291
        """Create and set self.inventory from the dirstate object.
292
        
293
        This is relatively expensive: we have to walk the entire dirstate.
294
        Ideally we would not, and can deprecate this function.
295
        """
2255.2.82 by Robert Collins
various notes about find_ids_across_trees
296
        #: uncomment to trap on inventory requests.
297
        # import pdb;pdb.set_trace()
2255.2.75 by Robert Collins
Correct generation of revisiontree inventories to handle out of order parents.
298
        state = self.current_dirstate()
299
        state._read_dirblocks_if_needed()
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
300
        root_key, current_entry = self._get_entry(path='')
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
301
        current_id = root_key[2]
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
302
        assert current_entry[0][0] == 'd' # directory
2255.2.75 by Robert Collins
Correct generation of revisiontree inventories to handle out of order parents.
303
        inv = Inventory(root_id=current_id)
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
304
        # Turn some things into local variables
305
        minikind_to_kind = dirstate.DirState._minikind_to_kind
306
        factory = entry_factory
307
        utf8_decode = cache_utf8._utf8_decode
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
308
        inv_byid = inv._byid
2255.2.73 by Robert Collins
50% speedup in the dirstate->inventory conversion logic by caching the parent ids as we walk the tree. Some further work would be to maintain a stack of parents as we know we visit depth first.
309
        # we could do this straight out of the dirstate; it might be fast
310
        # and should be profiled - RBC 20070216
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
311
        parent_ies = {'' : inv.root}
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
312
        for block in state._dirblocks[1:]: # skip the root
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
313
            dirname = block[0]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
314
            try:
2255.8.4 by John Arbash Meinel
Rather than using split hunks, implement a bisect_dirblocks
315
                parent_ie = parent_ies[dirname]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
316
            except KeyError:
317
                # all the paths in this block are not versioned in this tree
318
                continue
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
319
            for key, entry in block[1]:
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
320
                minikind, link_or_sha1, size, executable, stat = entry[0]
321
                if minikind in ('a', 'r'): # absent, relocated
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
322
                    # a parent tree only entry
323
                    continue
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
324
                name = key[1]
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
325
                name_unicode = utf8_decode(name)[0]
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
326
                file_id = key[2]
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
327
                kind = minikind_to_kind[minikind]
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
328
                inv_entry = factory[kind](file_id, name_unicode,
329
                                          parent_ie.file_id)
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
330
                if kind == 'file':
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
331
                    # not strictly needed: working tree
2255.2.77 by Robert Collins
Tune working inventory generation more: walk the blocks, skipping deleted rows.
332
                    #entry.executable = executable
333
                    #entry.text_size = size
334
                    #entry.text_sha1 = sha1
335
                    pass
336
                elif kind == 'directory':
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
337
                    # add this entry to the parent map.
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
338
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
339
                elif kind == 'tree-reference':
2255.2.195 by Robert Collins
Fix set_reference_revision on dirstate format trees.
340
                    inv_entry.reference_revision = link_or_sha1
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
341
                else:
342
                    assert 'unknown kind'
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
343
                # These checks cost us around 40ms on a 55k entry tree
2255.7.15 by John Arbash Meinel
Try to create an intertree test that exposes the walkdir vs dirstate mismatch. No luck yet.
344
                assert file_id not in inv_byid, ('file_id %s already in'
345
                    ' inventory as %s' % (file_id, inv_byid[file_id]))
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
346
                assert name_unicode not in parent_ie.children
347
                inv_byid[file_id] = inv_entry
348
                parent_ie.children[name_unicode] = inv_entry
2255.2.34 by Robert Collins
Fix WorkingTree4 parent_ids logic to use the dirstate to answer parent ids list queries.
349
        self._inventory = inv
350
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
351
    def _get_entry(self, file_id=None, path=None):
352
        """Get the dirstate row for file_id or path.
353
354
        If either file_id or path is supplied, it is used as the key to lookup.
355
        If both are supplied, the fastest lookup is used, and an error is
356
        raised if they do not both point at the same row.
357
        
358
        :param file_id: An optional unicode file_id to be looked up.
359
        :param path: An optional unicode path to be looked up.
360
        :return: The dirstate row tuple for path/file_id, or (None, None)
361
        """
362
        if file_id is None and path is None:
363
            raise errors.BzrError('must supply file_id or path')
364
        state = self.current_dirstate()
365
        if path is not None:
366
            path = path.encode('utf8')
367
        return state._get_entry(0, fileid_utf8=file_id, path_utf8=path)
368
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
369
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2255.2.88 by Robert Collins
Significant steps back to operation.
370
        # check file id is valid unconditionally.
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
371
        entry = self._get_entry(file_id=file_id, path=path)
372
        assert entry[0] is not None, 'what error should this raise'
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
373
        # TODO:
374
        # if row stat is valid, use cached sha1, else, get a new sha1.
2255.2.73 by Robert Collins
50% speedup in the dirstate->inventory conversion logic by caching the parent ids as we walk the tree. Some further work would be to maintain a stack of parents as we know we visit depth first.
375
        if path is None:
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
376
            path = pathjoin(entry[0][0], entry[0][1]).decode('utf8')
377
378
        file_abspath = self.abspath(path)
379
        state = self.current_dirstate()
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
380
        link_or_sha1 = state.update_entry(entry, file_abspath,
381
                                          stat_value=stat_value)
382
        if entry[1][0][0] == 'f':
383
            return link_or_sha1
384
        return None
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
385
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
386
    def _get_inventory(self):
387
        """Get the inventory for the tree. This is only valid within a lock."""
388
        if self._inventory is not None:
389
            return self._inventory
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
390
        self._must_be_locked()
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
391
        self._generate_inventory()
392
        return self._inventory
393
394
    inventory = property(_get_inventory,
395
                         doc="Inventory of this Tree")
396
397
    @needs_read_lock
2255.2.34 by Robert Collins
Fix WorkingTree4 parent_ids logic to use the dirstate to answer parent ids list queries.
398
    def get_parent_ids(self):
399
        """See Tree.get_parent_ids.
400
        
401
        This implementation requests the ids list from the dirstate file.
402
        """
403
        return self.current_dirstate().get_parent_ids()
404
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
405
    def get_reference_revision(self, entry, path=None):
406
        # referenced tree's revision is whatever's currently there
407
        return self.get_nested_tree(entry, path).last_revision()
408
409
    def get_nested_tree(self, entry, path=None):
410
        if path is None:
411
            path = self.id2path(entry.file_id)
412
        return WorkingTree.open(self.abspath(path))
413
2255.2.34 by Robert Collins
Fix WorkingTree4 parent_ids logic to use the dirstate to answer parent ids list queries.
414
    @needs_read_lock
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
415
    def get_root_id(self):
416
        """Return the id of this trees root"""
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
417
        return self._get_entry(path='')[0][2]
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
418
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
419
    def has_id(self, file_id):
420
        state = self.current_dirstate()
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
421
        file_id = osutils.safe_file_id(file_id)
2255.2.92 by James Westby
Make the WorkingTree4 has_id use the new _get_entry rather than _get_row.
422
        row, parents = self._get_entry(file_id=file_id)
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
423
        if row is None:
424
            return False
425
        return osutils.lexists(pathjoin(
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
426
                    self.basedir, row[0].decode('utf8'), row[1].decode('utf8')))
427
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
428
    @needs_read_lock
2255.2.144 by John Arbash Meinel
Simplify update_minimal a bit more, by making id_index a
429
    def id2path(self, file_id):
430
        file_id = osutils.safe_file_id(file_id)
431
        state = self.current_dirstate()
2255.2.147 by John Arbash Meinel
Move fast id => path lookups down into DirState
432
        entry = self._get_entry(file_id=file_id)
433
        if entry == (None, None):
2255.11.5 by Martin Pool
Tree.id2path should raise NoSuchId, not return None.
434
            raise errors.NoSuchId(tree=self, file_id=file_id)
2255.2.147 by John Arbash Meinel
Move fast id => path lookups down into DirState
435
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
436
        return path_utf8.decode('utf8')
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
437
438
    @needs_read_lock
439
    def __iter__(self):
440
        """Iterate through file_ids for this tree.
441
442
        file_ids are in a WorkingTree if they are in the working inventory
443
        and the working file exists.
444
        """
445
        result = []
2255.2.88 by Robert Collins
Significant steps back to operation.
446
        for key, tree_details in self.current_dirstate()._iter_entries():
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
447
            if tree_details[0][0] in ('a', 'r'): # absent, relocated
2255.2.88 by Robert Collins
Significant steps back to operation.
448
                # not relevant to the working tree
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
449
                continue
2255.2.88 by Robert Collins
Significant steps back to operation.
450
            path = pathjoin(self.basedir, key[0].decode('utf8'), key[1].decode('utf8'))
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
451
            if osutils.lexists(path):
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
452
                result.append(key[2])
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
453
        return iter(result)
454
2255.2.159 by Martin Pool
reference-trees in dirstate pass all tests.
455
    @needs_read_lock
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
456
    def kind(self, file_id):
2255.2.202 by Martin Pool
WorkingTree_4.kind should report tree-references if they're
457
        """Return the kind of a file.
458
459
        This is always the actual kind that's on disk, regardless of what it
460
        was added as.
461
        """
462
        relpath = self.id2path(file_id)
463
        assert relpath != None, \
464
            "path for id {%s} is None!" % file_id
465
        abspath = self.abspath(relpath)
466
        kind = file_kind(abspath)
467
        if kind == 'directory' and relpath != '':
468
            # as a special case, if a directory contains control files then 
469
            # it's a tree reference, except that the root of the tree is not
470
            if osutils.isdir(abspath + "/.bzr"):
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
471
                kind = 'tree-reference'
2255.2.202 by Martin Pool
WorkingTree_4.kind should report tree-references if they're
472
            # TODO: We could ask all the control formats whether they
473
            # recognize this directory, but at the moment there's no cheap api
474
            # to do that.  Since we probably can only nest bzr checkouts and
475
            # they always use this name it's ok for now.  -- mbp 20060306
2255.2.203 by Martin Pool
doc
476
            #
477
            # FIXME: There is an unhandled case here of a subdirectory
478
            # containing .bzr but not a branch; that will probably blow up
479
            # when you try to commit it.  It might happen if there is a
480
            # checkout in a subdirectory.  This can be avoided by not adding
481
            # it.  mbp 20070306
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
482
        return kind
483
2255.2.21 by Robert Collins
Add WorkingTree4._last_revision, making workingtree_implementations.test_changes_from pass.
484
    @needs_read_lock
485
    def _last_revision(self):
486
        """See Mutable.last_revision."""
487
        parent_ids = self.current_dirstate().get_parent_ids()
488
        if parent_ids:
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
489
            return parent_ids[0]
2255.2.21 by Robert Collins
Add WorkingTree4._last_revision, making workingtree_implementations.test_changes_from pass.
490
        else:
491
            return None
492
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
493
    def lock_read(self):
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
494
        """See Branch.lock_read, and WorkingTree.unlock."""
495
        self.branch.lock_read()
496
        try:
497
            self._control_files.lock_read()
498
            try:
499
                state = self.current_dirstate()
500
                if not state._lock_token:
501
                    state.lock_read()
502
            except:
503
                self._control_files.unlock()
504
                raise
505
        except:
506
            self.branch.unlock()
507
            raise
508
509
    def _lock_self_write(self):
510
        """This should be called after the branch is locked."""
511
        try:
512
            self._control_files.lock_write()
513
            try:
514
                state = self.current_dirstate()
515
                if not state._lock_token:
516
                    state.lock_write()
517
            except:
518
                self._control_files.unlock()
519
                raise
520
        except:
521
            self.branch.unlock()
522
            raise
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
523
524
    def lock_tree_write(self):
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
525
        """See MutableTree.lock_tree_write, and WorkingTree.unlock."""
526
        self.branch.lock_read()
527
        self._lock_self_write()
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
528
529
    def lock_write(self):
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
530
        """See MutableTree.lock_write, and WorkingTree.unlock."""
531
        self.branch.lock_write()
532
        self._lock_self_write()
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
533
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
534
    @needs_tree_write_lock
2255.2.137 by John Arbash Meinel
Move the WorkingTree.move() tests into their own module
535
    def move(self, from_paths, to_dir, after=False):
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
536
        """See WorkingTree.move()."""
2255.7.46 by Robert Collins
Fix WorkingTree4.move to return the moved paths, and update the tree implementation tests for move to check them.
537
        result = []
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
538
        if not from_paths:
2255.7.46 by Robert Collins
Fix WorkingTree4.move to return the moved paths, and update the tree implementation tests for move to check them.
539
            return result
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
540
541
        state = self.current_dirstate()
542
543
        assert not isinstance(from_paths, basestring)
544
        to_dir_utf8 = to_dir.encode('utf8')
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
545
        to_entry_dirname, to_basename = os.path.split(to_dir_utf8)
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
546
        id_index = state._get_id_index()
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
547
        # check destination directory
548
        # get the details for it
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
549
        to_entry_block_index, to_entry_entry_index, dir_present, entry_present = \
550
            state._get_block_entry_index(to_entry_dirname, to_basename, 0)
551
        if not entry_present:
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
552
            raise errors.BzrMoveFailedError('', to_dir,
2255.7.71 by Robert Collins
Fix blackbox test_mv usage of inventory, and the errors raised by workingtree4.move - though that should be made into a workingtree conformance test.
553
                errors.NotVersionedError(to_dir))
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
554
        to_entry = state._dirblocks[to_entry_block_index][1][to_entry_entry_index]
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
555
        # get a handle on the block itself.
556
        to_block_index = state._ensure_block(
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
557
            to_entry_block_index, to_entry_entry_index, to_dir_utf8)
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
558
        to_block = state._dirblocks[to_block_index]
559
        to_abs = self.abspath(to_dir)
560
        if not isdir(to_abs):
561
            raise errors.BzrMoveFailedError('',to_dir,
562
                errors.NotADirectory(to_abs))
563
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
564
        if to_entry[1][0][0] != 'd':
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
565
            raise errors.BzrMoveFailedError('',to_dir,
566
                errors.NotADirectory(to_abs))
567
568
        if self._inventory is not None:
569
            update_inventory = True
570
            inv = self.inventory
571
            to_dir_ie = inv[to_dir_id]
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
572
            to_dir_id = to_entry[0][2]
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
573
        else:
574
            update_inventory = False
575
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
576
        rollbacks = []
577
        def move_one(old_entry, from_path_utf8, minikind, executable,
578
                     fingerprint, packed_stat, size,
579
                     to_block, to_key, to_path_utf8):
580
            state._make_absent(old_entry)
581
            from_key = old_entry[0]
582
            rollbacks.append(
583
                lambda:state.update_minimal(from_key,
584
                    minikind,
585
                    executable=executable,
586
                    fingerprint=fingerprint,
587
                    packed_stat=packed_stat,
588
                    size=size,
589
                    path_utf8=from_path_utf8))
590
            state.update_minimal(to_key,
591
                    minikind,
592
                    executable=executable,
593
                    fingerprint=fingerprint,
594
                    packed_stat=packed_stat,
595
                    size=size,
596
                    path_utf8=to_path_utf8)
597
            added_entry_index, _ = state._find_entry_index(to_key, to_block[1])
598
            new_entry = to_block[1][added_entry_index]
599
            rollbacks.append(lambda:state._make_absent(new_entry))
600
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
601
        # create rename entries and tuples
602
        for from_rel in from_paths:
603
            # from_rel is 'pathinroot/foo/bar'
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
604
            from_rel_utf8 = from_rel.encode('utf8')
605
            from_dirname, from_tail = osutils.split(from_rel)
606
            from_dirname, from_tail_utf8 = osutils.split(from_rel_utf8)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
607
            from_entry = self._get_entry(path=from_rel)
608
            if from_entry == (None, None):
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
609
                raise errors.BzrMoveFailedError(from_rel,to_dir,
610
                    errors.NotVersionedError(path=str(from_rel)))
611
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
612
            from_id = from_entry[0][2]
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
613
            to_rel = pathjoin(to_dir, from_tail)
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
614
            to_rel_utf8 = pathjoin(to_dir_utf8, from_tail_utf8)
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
615
            item_to_entry = self._get_entry(path=to_rel)
616
            if item_to_entry != (None, None):
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
617
                raise errors.BzrMoveFailedError(from_rel, to_rel,
618
                    "Target is already versioned.")
619
620
            if from_rel == to_rel:
621
                raise errors.BzrMoveFailedError(from_rel, to_rel,
622
                    "Source and target are identical.")
623
624
            from_missing = not self.has_filename(from_rel)
625
            to_missing = not self.has_filename(to_rel)
626
            if after:
627
                move_file = False
628
            else:
629
                move_file = True
630
            if to_missing:
631
                if not move_file:
632
                    raise errors.BzrMoveFailedError(from_rel, to_rel,
633
                        errors.NoSuchFile(path=to_rel,
634
                        extra="New file has not been created yet"))
635
                elif from_missing:
636
                    # neither path exists
637
                    raise errors.BzrRenameFailedError(from_rel, to_rel,
638
                        errors.PathsDoNotExist(paths=(from_rel, to_rel)))
639
            else:
640
                if from_missing: # implicitly just update our path mapping
641
                    move_file = False
2255.2.139 by John Arbash Meinel
test cases for moving after a file has already been moved.
642
                elif not after:
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
643
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
644
                        extra="(Use --after to update the Bazaar id)")
645
646
            rollbacks = []
647
            def rollback_rename():
648
                """A single rename has failed, roll it back."""
2255.2.138 by John Arbash Meinel
implement several new WorkingTree.move() tests
649
                exc_info = None
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
650
                for rollback in reversed(rollbacks):
651
                    try:
652
                        rollback()
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
653
                    except Exception, e:
654
                        import pdb;pdb.set_trace()
2255.2.138 by John Arbash Meinel
implement several new WorkingTree.move() tests
655
                        exc_info = sys.exc_info()
656
                if exc_info:
657
                    raise exc_info[0], exc_info[1], exc_info[2]
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
658
659
            # perform the disk move first - its the most likely failure point.
2255.2.139 by John Arbash Meinel
test cases for moving after a file has already been moved.
660
            if move_file:
661
                from_rel_abs = self.abspath(from_rel)
662
                to_rel_abs = self.abspath(to_rel)
663
                try:
664
                    osutils.rename(from_rel_abs, to_rel_abs)
665
                except OSError, e:
666
                    raise errors.BzrMoveFailedError(from_rel, to_rel, e[1])
2255.2.140 by John Arbash Meinel
Update tests to ensure basis tree is not modified
667
                rollbacks.append(lambda: osutils.rename(to_rel_abs, from_rel_abs))
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
668
            try:
669
                # perform the rename in the inventory next if needed: its easy
670
                # to rollback
671
                if update_inventory:
672
                    # rename the entry
673
                    from_entry = inv[from_id]
674
                    current_parent = from_entry.parent_id
675
                    inv.rename(from_id, to_dir_id, from_tail)
676
                    rollbacks.append(
677
                        lambda: inv.rename(from_id, current_parent, from_tail))
678
                # finally do the rename in the dirstate, which is a little
679
                # tricky to rollback, but least likely to need it.
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
680
                old_block_index, old_entry_index, dir_present, file_present = \
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
681
                    state._get_block_entry_index(from_dirname, from_tail_utf8, 0)
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
682
                old_block = state._dirblocks[old_block_index][1]
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
683
                old_entry = old_block[old_entry_index]
684
                from_key, old_entry_details = old_entry
685
                cur_details = old_entry_details[0]
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
686
                # remove the old row
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
687
                to_key = ((to_block[0],) + from_key[1:3])
2255.2.146 by John Arbash Meinel
Implement move_directory by factoring out move_one
688
                minikind = cur_details[0]
689
                move_one(old_entry, from_path_utf8=from_rel_utf8,
690
                         minikind=minikind,
691
                         executable=cur_details[3],
692
                         fingerprint=cur_details[1],
693
                         packed_stat=cur_details[4],
694
                         size=cur_details[2],
695
                         to_block=to_block,
696
                         to_key=to_key,
697
                         to_path_utf8=to_rel_utf8)
698
699
                if minikind == 'd':
700
                    def update_dirblock(from_dir, to_key, to_dir_utf8):
701
                        """all entries in this block need updating.
702
703
                        TODO: This is pretty ugly, and doesn't support
704
                        reverting, but it works.
705
                        """
706
                        assert from_dir != '', "renaming root not supported"
707
                        from_key = (from_dir, '')
708
                        from_block_idx, present = \
709
                            state._find_block_index_from_key(from_key)
710
                        if not present:
711
                            # This is the old record, if it isn't present, then
712
                            # there is theoretically nothing to update.
713
                            # (Unless it isn't present because of lazy loading,
714
                            # but we don't do that yet)
715
                            return
716
                        from_block = state._dirblocks[from_block_idx]
717
                        to_block_index, to_entry_index, _, _ = \
718
                            state._get_block_entry_index(to_key[0], to_key[1], 0)
719
                        to_block_index = state._ensure_block(
720
                            to_block_index, to_entry_index, to_dir_utf8)
721
                        to_block = state._dirblocks[to_block_index]
722
                        for entry in from_block[1]:
723
                            assert entry[0][0] == from_dir
724
                            cur_details = entry[1][0]
725
                            to_key = (to_dir_utf8, entry[0][1], entry[0][2])
726
                            from_path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
727
                            to_path_utf8 = osutils.pathjoin(to_dir_utf8, entry[0][1])
728
                            minikind = cur_details[0]
729
                            move_one(entry, from_path_utf8=from_path_utf8,
730
                                     minikind=minikind,
731
                                     executable=cur_details[3],
732
                                     fingerprint=cur_details[1],
733
                                     packed_stat=cur_details[4],
734
                                     size=cur_details[2],
735
                                     to_block=to_block,
736
                                     to_key=to_key,
737
                                     to_path_utf8=to_rel_utf8)
738
                            if minikind == 'd':
739
                                # We need to move all the children of this
740
                                # entry
741
                                update_dirblock(from_path_utf8, to_key,
742
                                                to_path_utf8)
743
                    update_dirblock(from_rel_utf8, to_key, to_rel_utf8)
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
744
            except:
745
                rollback_rename()
746
                raise
2255.7.46 by Robert Collins
Fix WorkingTree4.move to return the moved paths, and update the tree implementation tests for move to check them.
747
            result.append((from_rel, to_rel))
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
748
            state._dirblock_state = dirstate.DirState.IN_MEMORY_MODIFIED
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
749
            self._make_dirty(reset_inventory=False)
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
750
2255.7.46 by Robert Collins
Fix WorkingTree4.move to return the moved paths, and update the tree implementation tests for move to check them.
751
        return result
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
752
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
753
    def _must_be_locked(self):
754
        if not self._control_files._lock_count:
755
            raise errors.ObjectNotLocked(self)
756
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.
757
    def _new_tree(self):
758
        """Initialize the state in this tree to be a new tree."""
759
        self._dirty = True
760
761
    @needs_read_lock
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
762
    def path2id(self, path):
763
        """Return the id for path in this tree."""
2255.7.56 by Robert Collins
Document behaviour of tree.path2id("path/").
764
        path = path.strip('/')
2255.2.88 by Robert Collins
Significant steps back to operation.
765
        entry = self._get_entry(path=path)
766
        if entry == (None, None):
2255.2.59 by Robert Collins
All WorkingTree4 and dirstate tests passing.
767
            return None
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
768
        return entry[0][2]
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
769
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
770
    def paths2ids(self, paths, trees=[], require_versioned=True):
771
        """See Tree.paths2ids().
2255.7.24 by John Arbash Meinel
Rework cmd_inventory so that it uses paths2ids and locks the trees for read.
772
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
773
        This specialisation fast-paths the case where all the trees are in the
774
        dirstate.
775
        """
776
        if paths is None:
777
            return None
778
        parents = self.get_parent_ids()
779
        for tree in trees:
780
            if not (isinstance(tree, DirStateRevisionTree) and tree._revision_id in
781
                parents):
782
                return super(WorkingTree4, self).paths2ids(paths, trees, require_versioned)
783
        search_indexes = [0] + [1 + parents.index(tree._revision_id) for tree in trees]
784
        # -- make all paths utf8 --
785
        paths_utf8 = set()
786
        for path in paths:
787
            paths_utf8.add(path.encode('utf8'))
788
        paths = paths_utf8
789
        # -- paths is now a utf8 path set --
790
        # -- get the state object and prepare it.
791
        state = self.current_dirstate()
2255.2.133 by John Arbash Meinel
Implement _paths2ids using bisect recursive rather than loading
792
        if False and (state._dirblock_state == dirstate.DirState.NOT_IN_MEMORY
793
            and '' not in paths):
794
            paths2ids = self._paths2ids_using_bisect
795
        else:
796
            paths2ids = self._paths2ids_in_memory
797
        return paths2ids(paths, search_indexes,
798
                         require_versioned=require_versioned)
799
800
    def _paths2ids_in_memory(self, paths, search_indexes,
801
                             require_versioned=True):
802
        state = self.current_dirstate()
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
803
        state._read_dirblocks_if_needed()
804
        def _entries_for_path(path):
805
            """Return a list with all the entries that match path for all ids.
806
            """
807
            dirname, basename = os.path.split(path)
808
            key = (dirname, basename, '')
809
            block_index, present = state._find_block_index_from_key(key)
810
            if not present:
811
                # the block which should contain path is absent.
812
                return []
813
            result = []
814
            block = state._dirblocks[block_index][1]
815
            entry_index, _ = state._find_entry_index(key, block)
816
            # we may need to look at multiple entries at this path: walk while the paths match.
817
            while (entry_index < len(block) and
818
                block[entry_index][0][0:2] == key[0:2]):
819
                result.append(block[entry_index])
820
                entry_index += 1
821
            return result
822
        if require_versioned:
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
823
            # -- check all supplied paths are versioned in a search tree. --
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
824
            all_versioned = True
825
            for path in paths:
826
                path_entries = _entries_for_path(path)
827
                if not path_entries:
828
                    # this specified path is not present at all: error
829
                    all_versioned = False
830
                    break
831
                found_versioned = False
832
                # for each id at this path
833
                for entry in path_entries:
834
                    # for each tree.
835
                    for index in search_indexes:
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
836
                        if entry[1][index][0] != 'a': # absent
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
837
                            found_versioned = True
838
                            # all good: found a versioned cell
839
                            break
840
                if not found_versioned:
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
841
                    # none of the indexes was not 'absent' at all ids for this
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
842
                    # path.
843
                    all_versioned = False
844
                    break
845
            if not all_versioned:
846
                raise errors.PathsNotVersionedError(paths)
847
        # -- remove redundancy in supplied paths to prevent over-scanning --
848
        search_paths = set()
849
        for path in paths:
850
            other_paths = paths.difference(set([path]))
851
            if not osutils.is_inside_any(other_paths, path):
852
                # this is a top level path, we must check it.
853
                search_paths.add(path)
854
        # sketch: 
855
        # for all search_indexs in each path at or under each element of
856
        # search_paths, if the detail is relocated: add the id, and add the
857
        # relocated path as one to search if its not searched already. If the
858
        # detail is not relocated, add the id.
859
        searched_paths = set()
860
        found_ids = set()
861
        def _process_entry(entry):
862
            """Look at search_indexes within entry.
863
864
            If a specific tree's details are relocated, add the relocation
865
            target to search_paths if not searched already. If it is absent, do
866
            nothing. Otherwise add the id to found_ids.
867
            """
868
            for index in search_indexes:
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
869
                if entry[1][index][0] == 'r': # relocated
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
870
                    if not osutils.is_inside_any(searched_paths, entry[1][index][1]):
871
                        search_paths.add(entry[1][index][1])
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
872
                elif entry[1][index][0] != 'a': # absent
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
873
                    found_ids.add(entry[0][2])
874
        while search_paths:
875
            current_root = search_paths.pop()
876
            searched_paths.add(current_root)
877
            # process the entries for this containing directory: the rest will be
878
            # found by their parents recursively.
879
            root_entries = _entries_for_path(current_root)
880
            if not root_entries:
881
                # this specified path is not present at all, skip it.
882
                continue
883
            for entry in root_entries:
884
                _process_entry(entry)
885
            initial_key = (current_root, '', '')
886
            block_index, _ = state._find_block_index_from_key(initial_key)
887
            while (block_index < len(state._dirblocks) and
888
                osutils.is_inside(current_root, state._dirblocks[block_index][0])):
889
                for entry in state._dirblocks[block_index][1]:
890
                    _process_entry(entry)
891
                block_index += 1
892
        return found_ids
893
2255.2.133 by John Arbash Meinel
Implement _paths2ids using bisect recursive rather than loading
894
    def _paths2ids_using_bisect(self, paths, search_indexes,
895
                                require_versioned=True):
896
        state = self.current_dirstate()
897
        found_ids = set()
898
899
        split_paths = sorted(osutils.split(p) for p in paths)
900
        found = state._bisect_recursive(split_paths)
901
902
        if require_versioned:
903
            found_dir_names = set(dir_name_id[:2] for dir_name_id in found)
904
            for dir_name in split_paths:
905
                if dir_name not in found_dir_names:
906
                    raise errors.PathsNotVersionedError(paths)
907
908
        for dir_name_id, trees_info in found.iteritems():
909
            for index in search_indexes:
910
                if trees_info[index][0] not in ('r', 'a'):
911
                    found_ids.add(dir_name_id[2])
912
        return found_ids
913
2255.2.45 by Robert Collins
Dirstate - fix revision_tree() behaviour to match the interface contract.
914
    def read_working_inventory(self):
915
        """Read the working inventory.
916
        
917
        This is a meaningless operation for dirstate, but we obey it anyhow.
918
        """
919
        return self.inventory
920
2255.2.17 by Robert Collins
tweaks - finishes off all the test_test_trees tests for dirstate.
921
    @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.
922
    def revision_tree(self, revision_id):
923
        """See Tree.revision_tree.
924
925
        WorkingTree4 supplies revision_trees for any basis tree.
926
        """
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
927
        revision_id = osutils.safe_revision_id(revision_id)
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.
928
        dirstate = self.current_dirstate()
929
        parent_ids = dirstate.get_parent_ids()
930
        if revision_id not in parent_ids:
931
            raise errors.NoSuchRevisionInTree(self, revision_id)
2255.2.45 by Robert Collins
Dirstate - fix revision_tree() behaviour to match the interface contract.
932
        if revision_id in dirstate.get_ghosts():
933
            raise errors.NoSuchRevisionInTree(self, revision_id)
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.
934
        return DirStateRevisionTree(dirstate, revision_id,
935
            self.branch.repository)
936
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
937
    @needs_tree_write_lock
2255.2.37 by Robert Collins
Get TestExecutable.test_06_pull working on DirState: fix cloning and the set_last_revision api on WorkingTree4.
938
    def set_last_revision(self, new_revision):
939
        """Change the last revision in the working tree."""
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
940
        new_revision = osutils.safe_revision_id(new_revision)
2255.2.37 by Robert Collins
Get TestExecutable.test_06_pull working on DirState: fix cloning and the set_last_revision api on WorkingTree4.
941
        parents = self.get_parent_ids()
942
        if new_revision in (NULL_REVISION, None):
2255.2.56 by Robert Collins
Dirstate: bring set_last_revision into line with the tested API.
943
            assert len(parents) < 2, (
2255.2.37 by Robert Collins
Get TestExecutable.test_06_pull working on DirState: fix cloning and the set_last_revision api on WorkingTree4.
944
                "setting the last parent to none with a pending merge is "
945
                "unsupported.")
946
            self.set_parent_ids([])
947
        else:
2255.2.56 by Robert Collins
Dirstate: bring set_last_revision into line with the tested API.
948
            self.set_parent_ids([new_revision] + parents[1:],
949
                allow_leftmost_as_ghost=True)
2255.2.37 by Robert Collins
Get TestExecutable.test_06_pull working on DirState: fix cloning and the set_last_revision api on WorkingTree4.
950
951
    @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.
952
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
953
        """Set the parent ids to revision_ids.
954
        
955
        See also set_parent_trees. This api will try to retrieve the tree data
956
        for each element of revision_ids from the trees repository. If you have
957
        tree data already available, it is more efficient to use
958
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
959
        an easier API to use.
960
961
        :param revision_ids: The revision_ids to set as the parent ids of this
962
            working tree. Any of these may be ghosts.
963
        """
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
964
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
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.
965
        trees = []
966
        for revision_id in revision_ids:
967
            try:
968
                revtree = self.branch.repository.revision_tree(revision_id)
2255.2.24 by John Arbash Meinel
When adding ghosts revision_tree() raises RevisionNotPresent because of Knit, not NoSuchRevision
969
                # TODO: jam 20070213 KnitVersionedFile raises
970
                #       RevisionNotPresent rather than NoSuchRevision if a
971
                #       given revision_id is not present. Should Repository be
972
                #       catching it and re-raising NoSuchRevision?
973
            except (errors.NoSuchRevision, errors.RevisionNotPresent):
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.
974
                revtree = None
975
            trees.append((revision_id, revtree))
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
976
        self.current_dirstate()._validate()
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.
977
        self.set_parent_trees(trees,
978
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
979
        self.current_dirstate()._validate()
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.
980
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
981
    @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.
982
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
983
        """Set the parents of the working tree.
984
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
985
        :param parents_list: A list of (revision_id, tree) tuples.
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.
986
            If tree is None, then that element is treated as an unreachable
987
            parent tree - i.e. a ghost.
988
        """
989
        dirstate = self.current_dirstate()
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
990
        dirstate._validate()
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.
991
        if len(parents_list) > 0:
992
            if not allow_leftmost_as_ghost and parents_list[0][1] is None:
2255.2.42 by Robert Collins
Fix WorkingTree4.set_parent_trees.
993
                raise errors.GhostRevisionUnusableHere(parents_list[0][0])
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.
994
        real_trees = []
995
        ghosts = []
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
996
        # convert absent trees to the null tree, which we convert back to
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.
997
        # missing on access.
998
        for rev_id, tree in parents_list:
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
999
            rev_id = osutils.safe_revision_id(rev_id)
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.
1000
            if tree is not None:
1001
                real_trees.append((rev_id, tree))
1002
            else:
1003
                real_trees.append((rev_id,
1004
                    self.branch.repository.revision_tree(None)))
1005
                ghosts.append(rev_id)
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
1006
        dirstate._validate()
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.
1007
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
1008
        dirstate._validate()
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
1009
        self._make_dirty(reset_inventory=False)
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
1010
        dirstate._validate()
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.
1011
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
1012
    def _set_root_id(self, file_id):
1013
        """See WorkingTree.set_root_id."""
2255.2.37 by Robert Collins
Get TestExecutable.test_06_pull working on DirState: fix cloning and the set_last_revision api on WorkingTree4.
1014
        state = self.current_dirstate()
1015
        state.set_path_id('', file_id)
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
1016
        if state._dirblock_state == dirstate.DirState.IN_MEMORY_MODIFIED:
1017
            self._make_dirty(reset_inventory=True)
2255.2.15 by Robert Collins
Dirstate - truncate state file fixing bug in saving a smaller file, get more tree_implementation tests passing.
1018
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.
1019
    def unlock(self):
1020
        """Unlock in format 4 trees needs to write the entire dirstate."""
1021
        if self._control_files._lock_count == 1:
1022
            # eventually we should do signature checking during read locks for
1023
            # dirstate updates.
1024
            if self._control_files._lock_mode == 'w':
1025
                if self._dirty:
1026
                    self.flush()
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
1027
            if self._dirstate is not None:
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
1028
                # This is a no-op if there are no modifications.
1029
                self._dirstate.save()
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
1030
                self._dirstate.unlock()
2255.10.2 by John Arbash Meinel
Update to dirstate locking.
1031
            # TODO: jam 20070301 We shouldn't have to wipe the dirstate at this
1032
            #       point. Instead, it could check if the header has been
1033
            #       modified when it is locked, and if not, it can hang on to
1034
            #       the data it has in memory.
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.
1035
            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.
1036
            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.
1037
        # reverse order of locking.
1038
        try:
1039
            return self._control_files.unlock()
1040
        finally:
1041
            self.branch.unlock()
1042
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1043
    @needs_tree_write_lock
1044
    def unversion(self, file_ids):
1045
        """Remove the file ids in file_ids from the current versioned set.
1046
1047
        When a file_id is unversioned, all of its children are automatically
1048
        unversioned.
1049
1050
        :param file_ids: The file ids to stop versioning.
1051
        :raises: NoSuchId if any fileid is not currently versioned.
1052
        """
1053
        if not file_ids:
1054
            return
1055
        state = self.current_dirstate()
1056
        state._read_dirblocks_if_needed()
1057
        ids_to_unversion = set()
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
1058
        for file_id in file_ids:
1059
            ids_to_unversion.add(osutils.safe_file_id(file_id))
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1060
        paths_to_unversion = set()
1061
        # sketch:
1062
        # check if the root is to be unversioned, if so, assert for now.
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1063
        # walk the state marking unversioned things as absent.
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1064
        # if there are any un-unversioned ids at the end, raise
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1065
        for key, details in state._dirblocks[0][1]:
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1066
            if (details[0][0] not in ('a', 'r') and # absent or relocated
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1067
                key[2] in ids_to_unversion):
1068
                # I haven't written the code to unversion / yet - it should be
1069
                # supported.
1070
                raise errors.BzrError('Unversioning the / is not currently supported')
1071
        block_index = 0
1072
        while block_index < len(state._dirblocks):
1073
            # process one directory at a time.
1074
            block = state._dirblocks[block_index]
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1075
            # first check: is the path one to remove - it or its children
1076
            delete_block = False
1077
            for path in paths_to_unversion:
1078
                if (block[0].startswith(path) and
1079
                    (len(block[0]) == len(path) or
1080
                     block[0][len(path)] == '/')):
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1081
                    # this entire block should be deleted - its the block for a
1082
                    # path to unversion; or the child of one
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1083
                    delete_block = True
1084
                    break
1085
            # TODO: trim paths_to_unversion as we pass by paths
1086
            if delete_block:
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1087
                # this block is to be deleted: process it.
1088
                # TODO: we can special case the no-parents case and
1089
                # just forget the whole block.
1090
                entry_index = 0
1091
                while entry_index < len(block[1]):
2255.7.41 by John Arbash Meinel
WorkingTree.unversion() should not raise if unversioning a child and a parent.
1092
                    # Mark this file id as having been removed
1093
                    ids_to_unversion.discard(block[1][entry_index][0][2])
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1094
                    if not state._make_absent(block[1][entry_index]):
1095
                        entry_index += 1
1096
                # go to the next block. (At the moment we dont delete empty
1097
                # dirblocks)
1098
                block_index += 1
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1099
                continue
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1100
            entry_index = 0
1101
            while entry_index < len(block[1]):
1102
                entry = block[1][entry_index]
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1103
                if (entry[1][0][0] in ('a', 'r') or # absent, relocated
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1104
                    # ^ some parent row.
1105
                    entry[0][2] not in ids_to_unversion):
1106
                    # ^ not an id to unversion
1107
                    entry_index += 1
1108
                    continue
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1109
                if entry[1][0][0] == 'd':
2255.7.41 by John Arbash Meinel
WorkingTree.unversion() should not raise if unversioning a child and a parent.
1110
                    paths_to_unversion.add(pathjoin(entry[0][0], entry[0][1]))
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1111
                if not state._make_absent(entry):
1112
                    entry_index += 1
1113
                # we have unversioned this id
1114
                ids_to_unversion.remove(entry[0][2])
1115
            block_index += 1
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1116
        if ids_to_unversion:
1117
            raise errors.NoSuchId(self, iter(ids_to_unversion).next())
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
1118
        self._make_dirty(reset_inventory=False)
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1119
        # have to change the legacy inventory too.
1120
        if self._inventory is not None:
1121
            for file_id in file_ids:
2255.2.33 by Robert Collins
Correct thunko in refactoring a few commits back.
1122
                self._inventory.remove_recursive_id(file_id)
2255.2.22 by Robert Collins
Dirstate: implement WorkingTree4.unversion, letting some test_commit tests pass.
1123
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.
1124
    @needs_tree_write_lock
1125
    def _write_inventory(self, inv):
1126
        """Write inventory as the current inventory."""
1127
        assert not self._dirty, "attempting to write an inventory when the dirstate is dirty will cause data loss"
1128
        self.current_dirstate().set_state_from_inventory(inv)
2255.7.67 by Robert Collins
Fix test_inv - make setting WorkingTree4._dirty use a helper to reduce code duplication, and reset the inventory when we dont manually update it, if it exists.
1129
        self._make_dirty(reset_inventory=False)
1130
        if self._inventory is not None:
1131
            self._inventory = inv
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.
1132
        self.flush()
1133
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.
1134
1135
class WorkingTreeFormat4(WorkingTreeFormat3):
1136
    """The first consolidated dirstate working tree format.
1137
1138
    This format:
1139
        - exists within a metadir controlling .bzr
1140
        - includes an explicit version marker for the workingtree control
1141
          files, separate from the BzrDir format
1142
        - modifies the hash cache format
1143
        - is new in bzr TODO FIXME SETBEFOREMERGE
1144
        - uses a LockDir to guard access to it.
1145
    """
1146
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1147
    supports_tree_reference = True
1148
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.
1149
    def get_format_string(self):
1150
        """See WorkingTreeFormat.get_format_string()."""
1151
        return "Bazaar Working Tree format 4\n"
1152
1153
    def get_format_description(self):
1154
        """See WorkingTreeFormat.get_format_description()."""
1155
        return "Working tree format 4"
1156
1157
    def initialize(self, a_bzrdir, revision_id=None):
1158
        """See WorkingTreeFormat.initialize().
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1159
2255.2.166 by Martin Pool
(broken) Add Tree.get_root_id() & test
1160
        :param revision_id: allows creating a working tree at a different
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.
1161
        revision than the branch is at.
2255.2.166 by Martin Pool
(broken) Add Tree.get_root_id() & test
1162
1163
        These trees get an initial random root id.
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.
1164
        """
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1165
        revision_id = osutils.safe_revision_id(revision_id)
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.
1166
        if not isinstance(a_bzrdir.transport, LocalTransport):
1167
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1168
        transport = a_bzrdir.get_workingtree_transport(self)
1169
        control_files = self._open_control_files(a_bzrdir)
1170
        control_files.create_lock()
1171
        control_files.lock_write()
1172
        control_files.put_utf8('format', self.get_format_string())
1173
        branch = a_bzrdir.open_branch()
1174
        if revision_id is None:
1175
            revision_id = branch.last_revision()
1176
        local_path = transport.local_abspath('dirstate')
2255.2.166 by Martin Pool
(broken) Add Tree.get_root_id() & test
1177
        # write out new dirstate (must exist when we create the tree)
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
1178
        state = dirstate.DirState.initialize(local_path)
1179
        state.unlock()
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.
1180
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
1181
                         branch,
1182
                         _format=self,
1183
                         _bzrdir=a_bzrdir,
1184
                         _control_files=control_files)
1185
        wt._new_tree()
2255.7.42 by Robert Collins
WorkingTree4 only needs a tree write lock during initialize, not a deep write lock.
1186
        wt.lock_tree_write()
2255.2.168 by Martin Pool
merge robert, debugging
1187
        state._validate()
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.
1188
        try:
2255.2.167 by Martin Pool
Change WorkingTree4.initialize to only get a random root id if not based on a revisiontree
1189
            if revision_id in (None, NULL_REVISION):
2255.2.166 by Martin Pool
(broken) Add Tree.get_root_id() & test
1190
                wt._set_root_id(generate_ids.gen_root_id())
1191
                wt.flush()
2255.2.168 by Martin Pool
merge robert, debugging
1192
                wt.current_dirstate()._validate()
2255.2.177 by Martin Pool
merge dirstate sorting fix, add more validation tests
1193
            wt.set_last_revision(revision_id)
1194
            wt.flush()
1195
            basis = wt.basis_tree()
1196
            basis.lock_read()
1197
            # if the basis has a root id we have to use that; otherwise we use
1198
            # a new random one
1199
            basis_root_id = basis.get_root_id()
1200
            if basis_root_id is not None:
1201
                wt._set_root_id(basis_root_id)
1202
                wt.flush()
1203
            transform.build_tree(basis, wt)
1204
            basis.unlock()
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.
1205
        finally:
1206
            control_files.unlock()
1207
            wt.unlock()
1208
        return wt
1209
1210
    def _open(self, a_bzrdir, control_files):
1211
        """Open the tree itself.
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1212
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.
1213
        :param a_bzrdir: the dir for the tree.
1214
        :param control_files: the control files for the tree.
1215
        """
1216
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
1217
                           branch=a_bzrdir.open_branch(),
1218
                           _format=self,
1219
                           _bzrdir=a_bzrdir,
1220
                           _control_files=control_files)
1221
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1222
    def __get_matchingbzrdir(self):
1223
        # please test against something that will let us do tree references
1224
        return bzrdir.format_registry.make_bzrdir(
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
1225
            'dirstate-with-subtree')
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1226
1227
    _matchingbzrdir = property(__get_matchingbzrdir)
1228
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.
1229
1230
class DirStateRevisionTree(Tree):
1231
    """A revision tree pulling the inventory from a dirstate."""
1232
1233
    def __init__(self, dirstate, revision_id, repository):
1234
        self._dirstate = dirstate
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1235
        self._revision_id = osutils.safe_revision_id(revision_id)
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.
1236
        self._repository = repository
1237
        self._inventory = None
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1238
        self._locked = 0
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
1239
        self._dirstate_locked = False
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.
1240
2255.2.184 by Martin Pool
Fixes for some comparison tests; repr of DirStateRevisionTree
1241
    def __repr__(self):
1242
        return "<%s of %s in %s>" % \
1243
            (self.__class__.__name__, self._revision_id, self._dirstate)
1244
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1245
    def annotate_iter(self, file_id):
1246
        """See Tree.annotate_iter"""
1247
        w = self._repository.weave_store.get_weave(file_id,
1248
                           self._repository.get_transaction())
1249
        return w.annotate_iter(self.inventory[file_id].revision)
1250
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.
1251
    def _comparison_data(self, entry, path):
2255.2.182 by Martin Pool
merge dirstate and trunk
1252
        """See Tree._comparison_data."""
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.
1253
        if entry is None:
1254
            return None, False, None
1255
        # trust the entry as RevisionTree does, but this may not be
1256
        # sensible: the entry might not have come from us?
1257
        return entry.kind, entry.executable, None
1258
2255.2.10 by Robert Collins
Now all tests matching dirstate pass - added generation of inventories for parent trees.
1259
    def _file_size(self, entry, stat_value):
1260
        return entry.text_size
1261
2255.2.78 by Robert Collins
Really finish the prior commit.
1262
    def filter_unversioned_files(self, paths):
1263
        """Filter out paths that are not versioned.
1264
1265
        :return: set of paths.
1266
        """
1267
        pred = self.has_filename
1268
        return set((p for p in paths if not pred(p)))
1269
2255.2.166 by Martin Pool
(broken) Add Tree.get_root_id() & test
1270
    def get_root_id(self):
1271
        return self.path2id('')
1272
2255.2.134 by John Arbash Meinel
Add a tree-test for get_symlink_target
1273
    def _get_parent_index(self):
1274
        """Return the index in the dirstate referenced by this tree."""
1275
        return self._dirstate.get_parent_ids().index(self._revision_id) + 1
1276
2255.2.98 by Robert Collins
Perform path2id lookups in dirstate revision trees from the dirstate index without requiring an inventory.
1277
    def _get_entry(self, file_id=None, path=None):
1278
        """Get the dirstate row for file_id or path.
1279
1280
        If either file_id or path is supplied, it is used as the key to lookup.
1281
        If both are supplied, the fastest lookup is used, and an error is
1282
        raised if they do not both point at the same row.
1283
        
1284
        :param file_id: An optional unicode file_id to be looked up.
1285
        :param path: An optional unicode path to be looked up.
1286
        :return: The dirstate row tuple for path/file_id, or (None, None)
1287
        """
1288
        if file_id is None and path is None:
1289
            raise errors.BzrError('must supply file_id or path')
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
1290
        file_id = osutils.safe_file_id(file_id)
2255.2.98 by Robert Collins
Perform path2id lookups in dirstate revision trees from the dirstate index without requiring an inventory.
1291
        if path is not None:
1292
            path = path.encode('utf8')
2255.2.134 by John Arbash Meinel
Add a tree-test for get_symlink_target
1293
        parent_index = self._get_parent_index()
2255.2.98 by Robert Collins
Perform path2id lookups in dirstate revision trees from the dirstate index without requiring an inventory.
1294
        return self._dirstate._get_entry(parent_index, fileid_utf8=file_id, path_utf8=path)
1295
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.
1296
    def _generate_inventory(self):
1297
        """Create and set self.inventory from the dirstate object.
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1298
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1299
        (So this is only called the first time the inventory is requested for
2255.2.182 by Martin Pool
merge dirstate and trunk
1300
        this tree; it then remains in memory until it's out of date.)
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1301
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.
1302
        This is relatively expensive: we have to walk the entire dirstate.
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1303
        """
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.
1304
        assert self._locked, 'cannot generate inventory of an unlocked '\
1305
            'dirstate revision tree'
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1306
        # separate call for profiling - makes it clear where the costs are.
1307
        self._dirstate._read_dirblocks_if_needed()
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.
1308
        assert self._revision_id in self._dirstate.get_parent_ids(), \
1309
            'parent %s has disappeared from %s' % (
1310
            self._revision_id, self._dirstate.get_parent_ids())
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1311
        parent_index = self._dirstate.get_parent_ids().index(self._revision_id) + 1
1312
        # This is identical now to the WorkingTree _generate_inventory except
1313
        # for the tree index use.
1314
        root_key, current_entry = self._dirstate._get_entry(parent_index, path_utf8='')
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
1315
        current_id = root_key[2]
2255.2.113 by John Arbash Meinel
545ms, 600ms: Switch memory model from storing kind to using minikind
1316
        assert current_entry[parent_index][0] == 'd'
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1317
        inv = Inventory(root_id=current_id, revision_id=self._revision_id)
1318
        inv.root.revision = current_entry[parent_index][4]
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
1319
        # Turn some things into local variables
1320
        minikind_to_kind = dirstate.DirState._minikind_to_kind
1321
        factory = entry_factory
1322
        utf8_decode = cache_utf8._utf8_decode
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
1323
        inv_byid = inv._byid
2255.2.73 by Robert Collins
50% speedup in the dirstate->inventory conversion logic by caching the parent ids as we walk the tree. Some further work would be to maintain a stack of parents as we know we visit depth first.
1324
        # we could do this straight out of the dirstate; it might be fast
1325
        # and should be profiled - RBC 20070216
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
1326
        parent_ies = {'' : inv.root}
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1327
        for block in self._dirstate._dirblocks[1:]: #skip root
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1328
            dirname = block[0]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1329
            try:
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
1330
                parent_ie = parent_ies[dirname]
2255.2.96 by Robert Collins
Restore dirstate to all tests passing condition.
1331
            except KeyError:
1332
                # all the paths in this block are not versioned in this tree
1333
                continue
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1334
            for key, entry in block[1]:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1335
                minikind, fingerprint, size, executable, revid = entry[parent_index]
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
1336
                if minikind in ('a', 'r'): # absent, relocated
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1337
                    # not this tree
1338
                    continue
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
1339
                name = key[1]
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
1340
                name_unicode = utf8_decode(name)[0]
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
1341
                file_id = key[2]
2255.2.114 by John Arbash Meinel
_get_inventory: 2.09 => 1.93s by tweaking some of the inner _generate_inventory loops
1342
                kind = minikind_to_kind[minikind]
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
1343
                inv_entry = factory[kind](file_id, name_unicode,
1344
                                          parent_ie.file_id)
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1345
                inv_entry.revision = revid
1346
                if kind == 'file':
1347
                    inv_entry.executable = executable
1348
                    inv_entry.text_size = size
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1349
                    inv_entry.text_sha1 = fingerprint
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1350
                elif kind == 'directory':
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
1351
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
2255.2.93 by Robert Collins
Dirstate - update WorkingTree4.unversion to the new layout, other tests still borked.
1352
                elif kind == 'symlink':
1353
                    inv_entry.executable = False
1354
                    inv_entry.text_size = size
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1355
                    inv_entry.symlink_target = utf8_decode(fingerprint)[0]
1356
                elif kind == 'tree-reference':
1357
                    inv_entry.reference_revision = fingerprint
2255.2.87 by Robert Collins
core dirstate tests passing with new structure.
1358
                else:
2255.2.158 by Martin Pool
Most of the integration of dirstate and subtree
1359
                    raise AssertionError("cannot convert entry %r into an InventoryEntry"
1360
                            % entry)
2255.2.115 by John Arbash Meinel
_get_inventory 1.75s: Directly update the inventory state rather than using inv.add()
1361
                # These checks cost us around 40ms on a 55k entry tree
1362
                assert file_id not in inv_byid
1363
                assert name_unicode not in parent_ie.children
1364
                inv_byid[file_id] = inv_entry
1365
                parent_ie.children[name_unicode] = inv_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.
1366
        self._inventory = inv
1367
2255.7.36 by John Arbash Meinel
All trees should implement get_file_mtime()
1368
    def get_file_mtime(self, file_id, path=None):
1369
        """Return the modification time for this record.
1370
1371
        We return the timestamp of the last-changed revision.
1372
        """
1373
        # Make sure the file exists
1374
        entry = self._get_entry(file_id, path=path)
1375
        if entry == (None, None): # do we raise?
1376
            return None
1377
        parent_index = self._get_parent_index()
1378
        last_changed_revision = entry[1][parent_index][4]
1379
        return self._repository.get_revision(last_changed_revision).timestamp
1380
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
1381
    def get_file_sha1(self, file_id, path=None, stat_value=None):
2255.10.1 by John Arbash Meinel
Update WorkingTree4 so that it doesn't use a HashCache,
1382
        entry = self._get_entry(file_id=file_id, path=path)
1383
        parent_index = self._get_parent_index()
1384
        parent_details = entry[1][parent_index]
1385
        if parent_details[0] == 'f':
1386
            return parent_details[1]
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
1387
        return None
1388
1389
    def get_file(self, file_id):
1390
        return StringIO(self.get_file_text(file_id))
1391
1392
    def get_file_lines(self, file_id):
1393
        ie = self.inventory[file_id]
1394
        return self._repository.weave_store.get_weave(file_id,
1395
                self._repository.get_transaction()).get_lines(ie.revision)
1396
1397
    def get_file_size(self, file_id):
1398
        return self.inventory[file_id].text_size
1399
1400
    def get_file_text(self, file_id):
1401
        return ''.join(self.get_file_lines(file_id))
1402
2255.2.134 by John Arbash Meinel
Add a tree-test for get_symlink_target
1403
    def get_symlink_target(self, file_id):
1404
        entry = self._get_entry(file_id=file_id)
1405
        parent_index = self._get_parent_index()
1406
        if entry[1][parent_index][0] != 'l':
1407
            return None
1408
        else:
1409
            # At present, none of the tree implementations supports non-ascii
1410
            # symlink targets. So we will just assume that the dirstate path is
1411
            # correct.
1412
            return entry[1][parent_index][1]
1413
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1414
    def get_revision_id(self):
1415
        """Return the revision id for this tree."""
1416
        return self._revision_id
1417
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
1418
    def _get_inventory(self):
1419
        if self._inventory is not None:
1420
            return self._inventory
2255.2.182 by Martin Pool
merge dirstate and trunk
1421
        self._must_be_locked()
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
1422
        self._generate_inventory()
1423
        return self._inventory
1424
1425
    inventory = property(_get_inventory,
1426
                         doc="Inventory of this Tree")
1427
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.
1428
    def get_parent_ids(self):
1429
        """The parents of a tree in the dirstate are not cached."""
1430
        return self._repository.get_revision(self._revision_id).parent_ids
1431
2255.2.30 by Robert Collins
Some workingtree_implementations/test_workingtree.py test work - add DirStateRevisionTree.has_filename, locks around appropriate calls in tests.
1432
    def has_filename(self, filename):
2255.2.104 by Robert Collins
Add WorkingTree4.paths2ids which is inventory-usage free if the trees being examined are in the dirstate.
1433
        return bool(self.path2id(filename))
2255.2.30 by Robert Collins
Some workingtree_implementations/test_workingtree.py test work - add DirStateRevisionTree.has_filename, locks around appropriate calls in tests.
1434
2255.2.182 by Martin Pool
merge dirstate and trunk
1435
    def kind(self, file_id):
1436
        return self.inventory[file_id].kind
1437
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
1438
    def is_executable(self, file_id, path=None):
1439
        ie = self.inventory[file_id]
1440
        if ie.kind != "file":
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1441
            return None
2255.2.31 by Robert Collins
Work in progress to make merge_inner work with dirstate trees.
1442
        return ie.executable
1443
2255.2.71 by John Arbash Meinel
Add a test for list_files, and implement it for DirStateRevisionTree
1444
    def list_files(self, include_root=False):
1445
        # We use a standard implementation, because DirStateRevisionTree is
1446
        # dealing with one of the parents of the current state
1447
        inv = self._get_inventory()
1448
        entries = inv.iter_entries()
1449
        if self.inventory.root is not None and not include_root:
1450
            entries.next()
1451
        for path, entry in entries:
1452
            yield path, 'V', entry.kind, entry.file_id, entry
2255.2.84 by John Arbash Meinel
Remove now-unecessary encode/decode calls for revision ids.
1453
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.
1454
    def lock_read(self):
1455
        """Lock the tree for a set of operations."""
2255.2.79 by Robert Collins
Take out repository locks from Dirstate revision trees, to improve file text access performance.
1456
        if not self._locked:
1457
            self._repository.lock_read()
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
1458
            if self._dirstate._lock_token is None:
1459
                self._dirstate.lock_read()
1460
                self._dirstate_locked = True
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1461
        self._locked += 1
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.
1462
2255.2.183 by Martin Pool
add missing _must_be_locked and a better message
1463
    def _must_be_locked(self):
1464
        if not self._locked:
1465
            raise errors.ObjectNotLocked(self)
1466
2255.2.98 by Robert Collins
Perform path2id lookups in dirstate revision trees from the dirstate index without requiring an inventory.
1467
    @needs_read_lock
2255.2.65 by John Arbash Meinel
override path2id because it should be optimized anyway
1468
    def path2id(self, path):
1469
        """Return the id for path in this tree."""
2255.2.98 by Robert Collins
Perform path2id lookups in dirstate revision trees from the dirstate index without requiring an inventory.
1470
        # lookup by path: faster than splitting and walking the ivnentory.
1471
        entry = self._get_entry(path=path)
1472
        if entry == (None, None):
1473
            return None
2255.2.107 by John Arbash Meinel
(working), fix dirstate to use utf8 file ids.
1474
        return entry[0][2]
2255.2.65 by John Arbash Meinel
override path2id because it should be optimized anyway
1475
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.
1476
    def unlock(self):
1477
        """Unlock, freeing any cache memory used during the lock."""
1478
        # outside of a lock, the inventory is suspect: release it.
2255.2.38 by Robert Collins
Fix WorkingTree4.pull to work.
1479
        self._locked -=1
1480
        if not self._locked:
1481
            self._inventory = None
2255.5.2 by John Arbash Meinel
(broken) lock and unlock the DirState object when locking and unlocking the Tree itself
1482
            self._locked = 0
1483
            if self._dirstate_locked:
1484
                self._dirstate.unlock()
1485
                self._dirstate_locked = False
2255.2.79 by Robert Collins
Take out repository locks from Dirstate revision trees, to improve file text access performance.
1486
            self._repository.unlock()
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1487
1488
    def walkdirs(self, prefix=""):
1489
        # TODO: jam 20070215 This is the cheap way by cheating and using the
1490
        #       RevisionTree implementation.
1491
        #       This should be cleaned up to use the much faster Dirstate code
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1492
        #       This is a little tricky, though, because the dirstate is
1493
        #       indexed by current path, not by parent path.
1494
        #       So for now, we just build up the parent inventory, and extract
1495
        #       it the same way RevisionTree does.
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1496
        _directory = 'directory'
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1497
        inv = self._get_inventory()
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1498
        top_id = inv.path2id(prefix)
1499
        if top_id is None:
1500
            pending = []
1501
        else:
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1502
            pending = [(prefix, top_id)]
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1503
        while pending:
1504
            dirblock = []
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1505
            relpath, file_id = pending.pop()
1506
            # 0 - relpath, 1- file-id
1507
            if relpath:
1508
                relroot = relpath + '/'
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1509
            else:
1510
                relroot = ""
1511
            # FIXME: stash the node in pending
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1512
            entry = inv[file_id]
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1513
            for name, child in entry.sorted_children():
1514
                toppath = relroot + name
1515
                dirblock.append((toppath, name, child.kind, None,
1516
                    child.file_id, child.kind
1517
                    ))
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1518
            yield (relpath, entry.file_id), dirblock
2255.2.69 by John Arbash Meinel
Implement annotate_iter, get_revision_id, and walkdirs so that all tree_implementations now pass
1519
            # push the user specified dirs from dirblock
1520
            for dir in reversed(dirblock):
1521
                if dir[2] == _directory:
2255.2.70 by John Arbash Meinel
Minor improvements to DirStateRevisionTree.walkdirs()
1522
                    pending.append((dir[0], dir[4]))
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
1523
1524
1525
class InterDirStateTree(InterTree):
2255.13.3 by Martin Pool
Comments and better assertions in InterDirStateTree
1526
    """Fast path optimiser for changes_from with dirstate trees.
1527
    
1528
    This is used only when both trees are in the dirstate working file, and 
1529
    the source is any parent within the dirstate, and the destination is 
1530
    the current working tree of the same dirstate.
1531
    """
1532
    # this could be generalized to allow comparisons between any trees in the
1533
    # dirstate, and possibly between trees stored in different dirstates.
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
1534
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1535
    def __init__(self, source, target):
1536
        super(InterDirStateTree, self).__init__(source, target)
1537
        if not InterDirStateTree.is_compatible(source, target):
1538
            raise Exception, "invalid source %r and target %r" % (source, target)
1539
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
1540
    @staticmethod
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1541
    def make_source_parent_tree(source, target):
1542
        """Change the source tree into a parent of the target."""
1543
        revid = source.commit('record tree')
1544
        target.branch.repository.fetch(source.branch.repository, revid)
1545
        target.set_parent_ids([revid])
1546
        return target.basis_tree(), target
2255.7.25 by John Arbash Meinel
Shave off 200+ ms of 'time bzr status' in lp tree
1547
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
1548
    _matching_from_tree_format = WorkingTreeFormat4()
1549
    _matching_to_tree_format = WorkingTreeFormat4()
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1550
    _test_mutable_trees_to_test_trees = make_source_parent_tree
1551
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1552
    def _iter_changes(self, include_unchanged=False,
1553
                      specific_files=None, pb=None, extra_trees=[],
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1554
                      require_versioned=True, want_unversioned=False):
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1555
        """Return the changes from source to target.
1556
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1557
        :return: An iterator that yields tuples. See InterTree._iter_changes
1558
            for details.
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1559
        :param specific_files: An optional list of file paths to restrict the
1560
            comparison to. When mapping filenames to ids, all matches in all
1561
            trees (including optional extra_trees) are used, and all children of
1562
            matched directories are included.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1563
        :param include_unchanged: An optional boolean requesting the inclusion of
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1564
            unchanged entries in the result.
1565
        :param extra_trees: An optional list of additional trees to use when
1566
            mapping the contents of specific_files (paths) to file_ids.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1567
        :param require_versioned: If True, all files in specific_files must be
1568
            versioned in one of source, target, extra_trees or
1569
            PathsNotVersionedError is raised.
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1570
        :param want_unversioned: Should unversioned files be returned in the
1571
            output. An unversioned file is defined as one with (False, False)
1572
            for the versioned pair.
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1573
        """
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1574
        utf8_decode = cache_utf8._utf8_decode_with_None
2255.7.31 by John Arbash Meinel
Minor cleanup.
1575
        _minikind_to_kind = dirstate.DirState._minikind_to_kind
2255.2.122 by Robert Collins
Alter intertree implementation tests to let dirstate inter-trees be correctly parameterised.
1576
        # NB: show_status depends on being able to pass in non-versioned files
1577
        # and report them as unknown
2255.2.155 by Martin Pool
Better assertion message from InterDirStateTree._iter_changes
1578
        # TODO: handle extra trees in the dirstate.
1579
        # TODO: handle comparisons as an empty tree as a different special
1580
        # case? mbp 20070226
1581
        if extra_trees or (self.source._revision_id == NULL_REVISION):
1582
            # we can't fast-path these cases (yet)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1583
            for f in super(InterDirStateTree, self)._iter_changes(
1584
                include_unchanged, specific_files, pb, extra_trees,
1585
                require_versioned):
1586
                yield f
1587
            return
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1588
        parent_ids = self.target.get_parent_ids()
2255.2.160 by Martin Pool
(merge) updates from dirstate branch
1589
        assert (self.source._revision_id in parent_ids), \
2255.2.154 by Martin Pool
Better assertion message from InterDirStateTree._iter_changes
1590
                "revision {%s} is not stored in {%s}, but %s " \
1591
                "can only be used for trees stored in the dirstate" \
1592
                % (self.source._revision_id, self.target, self._iter_changes)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1593
        target_index = 0
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1594
        if self.source._revision_id == NULL_REVISION:
1595
            source_index = None
1596
            indices = (target_index,)
1597
        else:
1598
            assert (self.source._revision_id in parent_ids), \
1599
                "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
1600
                self.source._revision_id, parent_ids)
1601
            source_index = 1 + parent_ids.index(self.source._revision_id)
1602
            indices = (source_index,target_index)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1603
        # -- make all specific_files utf8 --
1604
        if specific_files:
1605
            specific_files_utf8 = set()
1606
            for path in specific_files:
1607
                specific_files_utf8.add(path.encode('utf8'))
1608
            specific_files = specific_files_utf8
1609
        else:
1610
            specific_files = set([''])
1611
        # -- specific_files is now a utf8 path set --
1612
        # -- get the state object and prepare it.
1613
        state = self.target.current_dirstate()
1614
        state._read_dirblocks_if_needed()
1615
        def _entries_for_path(path):
1616
            """Return a list with all the entries that match path for all ids.
1617
            """
1618
            dirname, basename = os.path.split(path)
1619
            key = (dirname, basename, '')
1620
            block_index, present = state._find_block_index_from_key(key)
1621
            if not present:
1622
                # the block which should contain path is absent.
1623
                return []
1624
            result = []
1625
            block = state._dirblocks[block_index][1]
1626
            entry_index, _ = state._find_entry_index(key, block)
1627
            # we may need to look at multiple entries at this path: walk while the specific_files match.
1628
            while (entry_index < len(block) and
1629
                block[entry_index][0][0:2] == key[0:2]):
1630
                result.append(block[entry_index])
1631
                entry_index += 1
1632
            return result
1633
        if require_versioned:
1634
            # -- check all supplied paths are versioned in a search tree. --
1635
            all_versioned = True
1636
            for path in specific_files:
1637
                path_entries = _entries_for_path(path)
1638
                if not path_entries:
1639
                    # this specified path is not present at all: error
1640
                    all_versioned = False
1641
                    break
1642
                found_versioned = False
1643
                # for each id at this path
1644
                for entry in path_entries:
1645
                    # for each tree.
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1646
                    for index in indices:
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1647
                        if entry[1][index][0] != 'a': # absent
1648
                            found_versioned = True
1649
                            # all good: found a versioned cell
1650
                            break
1651
                if not found_versioned:
1652
                    # none of the indexes was not 'absent' at all ids for this
1653
                    # path.
1654
                    all_versioned = False
1655
                    break
1656
            if not all_versioned:
2255.7.62 by Robert Collins
Update the Tree.filter_unversioned_files docstring to reflect what the existing implementations actually do, and change the WorkingTree4 implementation to match a newly created test for it.
1657
                raise errors.PathsNotVersionedError(specific_files)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1658
        # -- remove redundancy in supplied specific_files to prevent over-scanning --
1659
        search_specific_files = set()
1660
        for path in specific_files:
1661
            other_specific_files = specific_files.difference(set([path]))
1662
            if not osutils.is_inside_any(other_specific_files, path):
1663
                # this is a top level path, we must check it.
1664
                search_specific_files.add(path)
1665
        # sketch: 
1666
        # compare source_index and target_index at or under each element of search_specific_files.
1667
        # follow the following comparison table. Note that we only want to do diff operations when
1668
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
1669
        # for the target.
1670
        # cases:
1671
        # 
1672
        # Source | Target | disk | action
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1673
        #   r    | fdlt   |      | add source to search, add id path move and perform
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1674
        #        |        |      | diff check on source-target
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1675
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1676
        #        |        |      | ???
1677
        #   r    |  a     |      | add source to search
1678
        #   r    |  a     |  a   | 
1679
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
1680
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1681
        #   a    | fdlt   |      | add new id
1682
        #   a    | fdlt   |  a   | dangling locally added file, skip
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1683
        #   a    |  a     |      | not present in either tree, skip
1684
        #   a    |  a     |  a   | not present in any tree, skip
1685
        #   a    |  r     |      | not present in either tree at this path, skip as it
1686
        #        |        |      | may not be selected by the users list of paths.
1687
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
1688
        #        |        |      | may not be selected by the users list of paths.
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1689
        #  fdlt  | fdlt   |      | content in both: diff them
1690
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
1691
        #  fdlt  |  a     |      | unversioned: output deleted id for now
1692
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
1693
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1694
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1695
        #        |        |      | this id at the other path.
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1696
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1697
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1698
        #        |        |      | this id at the other path.
1699
1700
        # for all search_indexs in each path at or under each element of
1701
        # search_specific_files, if the detail is relocated: add the id, and add the
1702
        # relocated path as one to search if its not searched already. If the
1703
        # detail is not relocated, add the id.
1704
        searched_specific_files = set()
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1705
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
2255.7.29 by John Arbash Meinel
approx 300ms of 'time bzr status' in lp tree by caching last parent info
1706
        # Using a list so that we can access the values and change them in
1707
        # nested scope. Each one is [path, file_id, entry]
1708
        last_source_parent = [None, None, None]
1709
        last_target_parent = [None, None, None]
1710
2255.2.192 by John Arbash Meinel
Add support for executable bit under win32
1711
        use_filesystem_for_exec = (sys.platform != 'win32')
1712
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1713
        def _process_entry(entry, path_info):
1714
            """Compare an entry and real disk to generate delta information.
1715
1716
            :param path_info: top_relpath, basename, kind, lstat, abspath for
1717
                the path of entry. If None, then the path is considered absent.
1718
                (Perhaps we should pass in a concrete entry for this ?)
2255.7.80 by John Arbash Meinel
Don't decode the path entry until we've actually decided to return the tuple.
1719
                Basename is returned as a utf8 string because we expect this
1720
                tuple will be ignored, and don't want to take the time to
1721
                decode.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1722
            """
1723
            # TODO: when a parent has been renamed, dont emit path renames for children,
2255.13.3 by Martin Pool
Comments and better assertions in InterDirStateTree
1724
            ## if path_info[1] == 'sub':
1725
            ##     import pdb;pdb.set_trace()
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1726
            if source_index is None:
1727
                source_details = NULL_PARENT_DETAILS
1728
            else:
1729
                source_details = entry[1][source_index]
2255.10.4 by John Arbash Meinel
do not update_entry from disk if it is supposed to be absent or renamed
1730
            target_details = entry[1][target_index]
1731
            target_minikind = target_details[0]
2255.13.3 by Martin Pool
Comments and better assertions in InterDirStateTree
1732
            if path_info is not None and target_minikind in 'fdlt':
2255.10.4 by John Arbash Meinel
do not update_entry from disk if it is supposed to be absent or renamed
1733
                assert target_index == 0
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1734
                link_or_sha1 = state.update_entry(entry, abspath=path_info[4],
1735
                                                  stat_value=path_info[3])
2255.10.4 by John Arbash Meinel
do not update_entry from disk if it is supposed to be absent or renamed
1736
                # The entry may have been modified by update_entry
1737
                target_details = entry[1][target_index]
1738
                target_minikind = target_details[0]
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1739
            else:
1740
                link_or_sha1 = None
2255.7.31 by John Arbash Meinel
Minor cleanup.
1741
            source_minikind = source_details[0]
2255.2.191 by Martin Pool
additional fix for subtree comparison
1742
            if source_minikind in 'fdltr' and target_minikind in 'fdlt':
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1743
                # claimed content in both: diff
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1744
                #   r    | fdlt   |      | add source to search, add id path move and perform
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1745
                #        |        |      | diff check on source-target
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1746
                #   r    | fdlt   |  a   | dangling file that was present in the basis.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1747
                #        |        |      | ???
2255.7.31 by John Arbash Meinel
Minor cleanup.
1748
                if source_minikind in 'r':
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1749
                    # add the source to the search path to find any children it
1750
                    # has.  TODO ? : only add if it is a container ?
2255.7.31 by John Arbash Meinel
Minor cleanup.
1751
                    if not osutils.is_inside_any(searched_specific_files,
1752
                                                 source_details[1]):
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1753
                        search_specific_files.add(source_details[1])
1754
                    # generate the old path; this is needed for stating later
1755
                    # as well.
1756
                    old_path = source_details[1]
1757
                    old_dirname, old_basename = os.path.split(old_path)
2255.7.41 by John Arbash Meinel
WorkingTree.unversion() should not raise if unversioning a child and a parent.
1758
                    path = pathjoin(entry[0][0], entry[0][1])
2255.7.31 by John Arbash Meinel
Minor cleanup.
1759
                    old_entry = state._get_entry(source_index,
1760
                                                 path_utf8=old_path)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1761
                    # update the source details variable to be the real
1762
                    # location.
1763
                    source_details = old_entry[1][source_index]
2255.7.31 by John Arbash Meinel
Minor cleanup.
1764
                    source_minikind = source_details[0]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1765
                else:
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1766
                    old_dirname = entry[0][0]
1767
                    old_basename = entry[0][1]
2255.7.41 by John Arbash Meinel
WorkingTree.unversion() should not raise if unversioning a child and a parent.
1768
                    old_path = path = pathjoin(old_dirname, old_basename)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1769
                if path_info is None:
1770
                    # the file is missing on disk, show as removed.
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1771
                    content_change = True
1772
                    target_kind = None
1773
                    target_exec = False
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1774
                else:
2255.7.3 by Robert Collins
Add tests for _iter_changes with symlinks, disabled until unversioned file support is added, as that affects the test expected value.
1775
                    # source and target are both versioned and disk file is present.
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1776
                    target_kind = path_info[2]
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1777
                    if target_kind == 'directory':
2255.7.31 by John Arbash Meinel
Minor cleanup.
1778
                        if source_minikind != 'd':
2255.7.3 by Robert Collins
Add tests for _iter_changes with symlinks, disabled until unversioned file support is added, as that affects the test expected value.
1779
                            content_change = True
1780
                        else:
1781
                            # directories have no fingerprint
1782
                            content_change = False
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1783
                        target_exec = False
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1784
                    elif target_kind == 'file':
2255.7.31 by John Arbash Meinel
Minor cleanup.
1785
                        if source_minikind != 'f':
2255.7.3 by Robert Collins
Add tests for _iter_changes with symlinks, disabled until unversioned file support is added, as that affects the test expected value.
1786
                            content_change = True
1787
                        else:
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1788
                            # We could check the size, but we already have the
1789
                            # sha1 hash.
1790
                            content_change = (link_or_sha1 != source_details[1])
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1791
                        # Target details is updated at update_entry time
2255.2.192 by John Arbash Meinel
Add support for executable bit under win32
1792
                        if use_filesystem_for_exec:
1793
                            # We don't need S_ISREG here, because we are sure
1794
                            # we are dealing with a file.
1795
                            target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
1796
                        else:
1797
                            target_exec = target_details[3]
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1798
                    elif target_kind == 'symlink':
2255.7.31 by John Arbash Meinel
Minor cleanup.
1799
                        if source_minikind != 'l':
2255.7.3 by Robert Collins
Add tests for _iter_changes with symlinks, disabled until unversioned file support is added, as that affects the test expected value.
1800
                            content_change = True
1801
                        else:
2255.10.3 by John Arbash Meinel
(broken) Change get_sha1_for_entry into update_entry
1802
                            content_change = (link_or_sha1 != source_details[1])
2255.7.3 by Robert Collins
Add tests for _iter_changes with symlinks, disabled until unversioned file support is added, as that affects the test expected value.
1803
                        target_exec = False
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1804
                    elif target_kind == 'tree-reference':
1805
                        if source_minikind != 't':
1806
                            content_change = True
1807
                        else:
1808
                            content_change = False
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1809
                    else:
2255.7.3 by Robert Collins
Add tests for _iter_changes with symlinks, disabled until unversioned file support is added, as that affects the test expected value.
1810
                        raise Exception, "unknown kind %s" % path_info[2]
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1811
                # parent id is the entry for the path in the target tree
2255.7.29 by John Arbash Meinel
approx 300ms of 'time bzr status' in lp tree by caching last parent info
1812
                if old_dirname == last_source_parent[0]:
1813
                    source_parent_id = last_source_parent[1]
1814
                else:
1815
                    source_parent_entry = state._get_entry(source_index,
1816
                                                           path_utf8=old_dirname)
1817
                    source_parent_id = source_parent_entry[0][2]
1818
                    if source_parent_id == entry[0][2]:
1819
                        # This is the root, so the parent is None
1820
                        source_parent_id = None
2255.7.30 by John Arbash Meinel
Don't cache the parent entry for root, since it is different than all other entries.
1821
                    else:
1822
                        last_source_parent[0] = old_dirname
1823
                        last_source_parent[1] = source_parent_id
1824
                        last_source_parent[2] = source_parent_entry
2255.7.29 by John Arbash Meinel
approx 300ms of 'time bzr status' in lp tree by caching last parent info
1825
1826
                new_dirname = entry[0][0]
1827
                if new_dirname == last_target_parent[0]:
1828
                    target_parent_id = last_target_parent[1]
1829
                else:
1830
                    # TODO: We don't always need to do the lookup, because the
1831
                    #       parent entry will be the same as the source entry.
2255.7.25 by John Arbash Meinel
Shave off 200+ ms of 'time bzr status' in lp tree
1832
                    target_parent_entry = state._get_entry(target_index,
2255.7.29 by John Arbash Meinel
approx 300ms of 'time bzr status' in lp tree by caching last parent info
1833
                                                           path_utf8=new_dirname)
2255.7.25 by John Arbash Meinel
Shave off 200+ ms of 'time bzr status' in lp tree
1834
                    target_parent_id = target_parent_entry[0][2]
1835
                    if target_parent_id == entry[0][2]:
1836
                        # This is the root, so the parent is None
1837
                        target_parent_id = None
2255.7.30 by John Arbash Meinel
Don't cache the parent entry for root, since it is different than all other entries.
1838
                    else:
1839
                        last_target_parent[0] = new_dirname
1840
                        last_target_parent[1] = target_parent_id
1841
                        last_target_parent[2] = target_parent_entry
2255.7.29 by John Arbash Meinel
approx 300ms of 'time bzr status' in lp tree by caching last parent info
1842
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1843
                source_exec = source_details[3]
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1844
                return ((entry[0][2], (old_path, path), content_change,
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1845
                        (True, True),
1846
                        (source_parent_id, target_parent_id),
1847
                        (old_basename, entry[0][1]),
2255.7.31 by John Arbash Meinel
Minor cleanup.
1848
                        (_minikind_to_kind[source_minikind], target_kind),
2255.7.4 by Robert Collins
Test InterTree._iter_changes with missing (absent but versioned) files.
1849
                        (source_exec, target_exec)),)
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1850
            elif source_minikind in 'a' and target_minikind in 'fdlt':
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1851
                # looks like a new file
1852
                if path_info is not None:
2255.7.41 by John Arbash Meinel
WorkingTree.unversion() should not raise if unversioning a child and a parent.
1853
                    path = pathjoin(entry[0][0], entry[0][1])
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1854
                    # parent id is the entry for the path in the target tree
1855
                    # TODO: these are the same for an entire directory: cache em.
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1856
                    parent_id = state._get_entry(target_index,
1857
                                                 path_utf8=entry[0][0])[0][2]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1858
                    if parent_id == entry[0][2]:
1859
                        parent_id = None
2255.2.192 by John Arbash Meinel
Add support for executable bit under win32
1860
                    if use_filesystem_for_exec:
1861
                        # We need S_ISREG here, because we aren't sure if this
1862
                        # is a file or not.
1863
                        target_exec = bool(
1864
                            stat.S_ISREG(path_info[3].st_mode)
1865
                            and stat.S_IEXEC & path_info[3].st_mode)
1866
                    else:
1867
                        target_exec = target_details[3]
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1868
                    return ((entry[0][2], (None, path), True,
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1869
                            (False, True),
1870
                            (None, parent_id),
1871
                            (None, entry[0][1]),
1872
                            (None, path_info[2]),
2255.10.5 by John Arbash Meinel
Fix a small bug when we have a symlink that does not need to be re-read.
1873
                            (None, target_exec)),)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1874
                else:
1875
                    # but its not on disk: we deliberately treat this as just
1876
                    # never-present. (Why ?! - RBC 20070224)
1877
                    pass
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1878
            elif source_minikind in 'fdlt' and target_minikind in 'a':
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1879
                # unversioned, possibly, or possibly not deleted: we dont care.
1880
                # if its still on disk, *and* theres no other entry at this
1881
                # path [we dont know this in this routine at the moment -
1882
                # perhaps we should change this - then it would be an unknown.
2255.7.41 by John Arbash Meinel
WorkingTree.unversion() should not raise if unversioning a child and a parent.
1883
                old_path = pathjoin(entry[0][0], entry[0][1])
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1884
                # parent id is the entry for the path in the target tree
1885
                parent_id = state._get_entry(source_index, path_utf8=entry[0][0])[0][2]
1886
                if parent_id == entry[0][2]:
1887
                    parent_id = None
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1888
                return ((entry[0][2], (old_path, None), True,
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1889
                        (True, False),
1890
                        (parent_id, None),
1891
                        (entry[0][1], None),
2255.7.31 by John Arbash Meinel
Minor cleanup.
1892
                        (_minikind_to_kind[source_minikind], None),
2255.7.1 by John Arbash Meinel
_iter_changes should return Unicode paths.
1893
                        (source_details[3], None)),)
2255.2.189 by Martin Pool
Add and fix up basic comparison of subtrees.
1894
            elif source_minikind in 'fdlt' and target_minikind in 'r':
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1895
                # a rename; could be a true rename, or a rename inherited from
1896
                # a renamed parent. TODO: handle this efficiently. Its not
1897
                # common case to rename dirs though, so a correct but slow
1898
                # implementation will do.
1899
                if not osutils.is_inside_any(searched_specific_files, target_details[1]):
1900
                    search_specific_files.add(target_details[1])
2255.7.45 by Robert Collins
Handle the source and target paths both being relocated from another path in the tree - this is possible with a pending merge.
1901
            elif source_minikind in 'r' and target_minikind in 'r':
1902
                # neither of the selected trees contain this file,
1903
                # so skip over it. This is not currently directly tested, but
1904
                # is indirectly via test_too_much.TestCommands.test_conflicts.
1905
                pass
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1906
            else:
2255.13.3 by Martin Pool
Comments and better assertions in InterDirStateTree
1907
                raise AssertionError("don't know how to compare "
1908
                    "source_minikind=%r, target_minikind=%r"
1909
                    % (source_minikind, target_minikind))
1910
                ## import pdb;pdb.set_trace()
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1911
            return ()
1912
        while search_specific_files:
1913
            # TODO: the pending list should be lexically sorted?
1914
            current_root = search_specific_files.pop()
1915
            searched_specific_files.add(current_root)
1916
            # process the entries for this containing directory: the rest will be
1917
            # found by their parents recursively.
1918
            root_entries = _entries_for_path(current_root)
1919
            root_abspath = self.target.abspath(current_root)
1920
            try:
1921
                root_stat = os.lstat(root_abspath)
1922
            except OSError, e:
1923
                if e.errno == errno.ENOENT:
2255.2.151 by Robert Collins
Handle specific_files natively for WorkingTreeFormat4._iter_changes.
1924
                    # the path does not exist: let _process_entry know that.
1925
                    root_dir_info = None
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1926
                else:
1927
                    # some other random error: hand it up.
1928
                    raise
2255.2.151 by Robert Collins
Handle specific_files natively for WorkingTreeFormat4._iter_changes.
1929
            else:
1930
                root_dir_info = ('', current_root,
1931
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
1932
                    root_abspath)
1933
            if not root_entries and not root_dir_info:
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1934
                # this specified path is not present at all, skip it.
1935
                continue
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1936
            path_handled = False
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1937
            for entry in root_entries:
1938
                for result in _process_entry(entry, root_dir_info):
1939
                    # this check should probably be outside the loop: one
1940
                    # 'iterate two trees' api, and then _iter_changes filters
1941
                    # unchanged pairs. - RBC 20070226
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1942
                    path_handled = True
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1943
                    if (include_unchanged
1944
                        or result[2]                    # content change
1945
                        or result[3][0] != result[3][1] # versioned status
1946
                        or result[4][0] != result[4][1] # parent id
1947
                        or result[5][0] != result[5][1] # name
1948
                        or result[6][0] != result[6][1] # kind
1949
                        or result[7][0] != result[7][1] # executable
1950
                        ):
2255.7.80 by John Arbash Meinel
Don't decode the path entry until we've actually decided to return the tuple.
1951
                        result = (result[0],
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1952
                            ((utf8_decode(result[1][0])[0]),
1953
                             utf8_decode(result[1][1])[0]),) + result[2:]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1954
                        yield result
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1955
            if want_unversioned and not path_handled:
1956
                new_executable = bool(
1957
                    stat.S_ISREG(root_dir_info[3].st_mode)
1958
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
1959
                yield (None, (None, current_root), True, (False, False),
1960
                    (None, None),
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
1961
                    (None, splitpath(current_root)[-1]),
1962
                    (None, root_dir_info[2]), (None, new_executable))
2255.7.28 by John Arbash Meinel
shave about 10% of the time by switching to _walkdirs_utf8
1963
            dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1964
            initial_key = (current_root, '', '')
1965
            block_index, _ = state._find_block_index_from_key(initial_key)
1966
            if block_index == 0:
1967
                # we have processed the total root already, but because the
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
1968
                # initial key matched it we should skip it here.
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1969
                block_index +=1
2255.2.151 by Robert Collins
Handle specific_files natively for WorkingTreeFormat4._iter_changes.
1970
            try:
1971
                current_dir_info = dir_iterator.next()
1972
            except OSError, e:
1973
                if e.errno in (errno.ENOENT, errno.ENOTDIR):
1974
                    # there may be directories in the inventory even though
1975
                    # this path is not a file on disk: so mark it as end of
1976
                    # iterator
1977
                    current_dir_info = None
1978
                else:
1979
                    raise
1980
            else:
1981
                if current_dir_info[0][0] == '':
1982
                    # remove .bzr from iteration
1983
                    bzr_index = bisect_left(current_dir_info[1], ('.bzr',))
1984
                    assert current_dir_info[1][bzr_index][0] == '.bzr'
1985
                    del current_dir_info[1][bzr_index]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
1986
            # walk until both the directory listing and the versioned metadata
1987
            # are exhausted. TODO: reevaluate this, perhaps we should stop when
1988
            # the versioned data runs out.
1989
            if (block_index < len(state._dirblocks) and
1990
                osutils.is_inside(current_root, state._dirblocks[block_index][0])):
1991
                current_block = state._dirblocks[block_index]
1992
            else:
1993
                current_block = None
1994
            while (current_dir_info is not None or
2255.7.35 by John Arbash Meinel
Handle the case when a directory has been removed, and isn't the last entry.
1995
                   current_block is not None):
1996
                if (current_dir_info and current_block
1997
                    and current_dir_info[0][0] != current_block[0]):
1998
                    if current_dir_info[0][0] < current_block[0] :
1999
                        # import pdb; pdb.set_trace()
2000
                        # print 'unversioned dir'
2001
                        # filesystem data refers to paths not covered by the dirblock.
2255.7.6 by Robert Collins
Test for iterating changes past empty directories.
2002
                        # this has two possibilities:
2003
                        # A) it is versioned but empty, so there is no block for it
2004
                        # B) it is not versioned.
2005
                        # in either case it was processed by the containing directories walk:
2006
                        # if it is root/foo, when we walked root we emitted it,
2007
                        # or if we ere given root/foo to walk specifically, we
2255.7.35 by John Arbash Meinel
Handle the case when a directory has been removed, and isn't the last entry.
2008
                        # emitted it when checking the walk-root entries
2255.7.6 by Robert Collins
Test for iterating changes past empty directories.
2009
                        # advance the iterator and loop - we dont need to emit it.
2010
                        try:
2011
                            current_dir_info = dir_iterator.next()
2012
                        except StopIteration:
2013
                            current_dir_info = None
2255.7.35 by John Arbash Meinel
Handle the case when a directory has been removed, and isn't the last entry.
2014
                    else:
2015
                        # We have a dirblock entry for this location, but there
2016
                        # is no filesystem path for this. This is most likely
2017
                        # because a directory was removed from the disk.
2018
                        # We don't have to report the missing directory,
2019
                        # because that should have already been handled, but we
2020
                        # need to handle all of the files that are contained
2021
                        # within.
2022
                        for current_entry in current_block[1]:
2023
                            # entry referring to file not present on disk.
2024
                            # advance the entry only, after processing.
2025
                            for result in _process_entry(current_entry, None):
2026
                                # this check should probably be outside the loop: one
2027
                                # 'iterate two trees' api, and then _iter_changes filters
2028
                                # unchanged pairs. - RBC 20070226
2029
                                if (include_unchanged
2030
                                    or result[2]                    # content change
2031
                                    or result[3][0] != result[3][1] # versioned status
2032
                                    or result[4][0] != result[4][1] # parent id
2033
                                    or result[5][0] != result[5][1] # name
2034
                                    or result[6][0] != result[6][1] # kind
2035
                                    or result[7][0] != result[7][1] # executable
2036
                                    ):
2255.7.80 by John Arbash Meinel
Don't decode the path entry until we've actually decided to return the tuple.
2037
                                    result = (result[0],
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
2038
                                        ((utf8_decode(result[1][0])[0]),
2039
                                         utf8_decode(result[1][1])[0]),) + result[2:]
2255.7.35 by John Arbash Meinel
Handle the case when a directory has been removed, and isn't the last entry.
2040
                                    yield result
2041
                        block_index +=1
2042
                        if (block_index < len(state._dirblocks) and
2043
                            osutils.is_inside(current_root,
2044
                                              state._dirblocks[block_index][0])):
2045
                            current_block = state._dirblocks[block_index]
2046
                        else:
2047
                            current_block = None
2255.7.7 by Robert Collins
continue iteration at the right point for InterDirStateTree._iter_changes.
2048
                    continue
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2049
                entry_index = 0
2050
                if current_block and entry_index < len(current_block[1]):
2051
                    current_entry = current_block[1][entry_index]
2052
                else:
2053
                    current_entry = None
2054
                advance_entry = True
2055
                path_index = 0
2056
                if current_dir_info and path_index < len(current_dir_info[1]):
2057
                    current_path_info = current_dir_info[1][path_index]
2058
                else:
2059
                    current_path_info = None
2060
                advance_path = True
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
2061
                path_handled = False
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2062
                while (current_entry is not None or
2063
                    current_path_info is not None):
2064
                    if current_entry is None:
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
2065
                        # the check for path_handled when the path is adnvaced
2066
                        # will yield this path if needed.
2067
                        pass
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2068
                    elif current_path_info is None:
2069
                        # no path is fine: the per entry code will handle it.
2070
                        for result in _process_entry(current_entry, current_path_info):
2071
                            # this check should probably be outside the loop: one
2072
                            # 'iterate two trees' api, and then _iter_changes filters
2073
                            # unchanged pairs. - RBC 20070226
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
2074
                            if (include_unchanged
2075
                                or result[2]                    # content change
2076
                                or result[3][0] != result[3][1] # versioned status
2077
                                or result[4][0] != result[4][1] # parent id
2078
                                or result[5][0] != result[5][1] # name
2079
                                or result[6][0] != result[6][1] # kind
2080
                                or result[7][0] != result[7][1] # executable
2081
                                ):
2255.7.80 by John Arbash Meinel
Don't decode the path entry until we've actually decided to return the tuple.
2082
                                result = (result[0],
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
2083
                                    ((utf8_decode(result[1][0])[0]),
2084
                                     utf8_decode(result[1][1])[0]),) + result[2:]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2085
                                yield result
2086
                    elif current_entry[0][1] != current_path_info[1]:
2087
                        if current_path_info[1] < current_entry[0][1]:
2255.7.34 by John Arbash Meinel
Clean up test_bad_files, and fix a bug in _iter_changes when
2088
                            # extra file on disk: pass for now, but only
2089
                            # increment the path, not the entry
2090
                            # import pdb; pdb.set_trace()
2091
                            # print 'unversioned file'
2092
                            advance_entry = False
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2093
                        else:
2094
                            # entry referring to file not present on disk.
2095
                            # advance the entry only, after processing.
2096
                            for result in _process_entry(current_entry, None):
2097
                                # this check should probably be outside the loop: one
2098
                                # 'iterate two trees' api, and then _iter_changes filters
2099
                                # unchanged pairs. - RBC 20070226
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
2100
                                path_handled = True
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
2101
                                if (include_unchanged
2102
                                    or result[2]                    # content change
2103
                                    or result[3][0] != result[3][1] # versioned status
2104
                                    or result[4][0] != result[4][1] # parent id
2105
                                    or result[5][0] != result[5][1] # name
2106
                                    or result[6][0] != result[6][1] # kind
2107
                                    or result[7][0] != result[7][1] # executable
2108
                                    ):
2255.7.80 by John Arbash Meinel
Don't decode the path entry until we've actually decided to return the tuple.
2109
                                    result = (result[0],
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
2110
                                        ((utf8_decode(result[1][0])[0]),
2111
                                         utf8_decode(result[1][1])[0]),) + result[2:]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2112
                                    yield result
2113
                            advance_path = False
2114
                    else:
2115
                        for result in _process_entry(current_entry, current_path_info):
2116
                            # this check should probably be outside the loop: one
2117
                            # 'iterate two trees' api, and then _iter_changes filters
2118
                            # unchanged pairs. - RBC 20070226
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
2119
                            path_handled = True
2255.7.21 by John Arbash Meinel
Get iter_changes working again, by fixing set_parent_trees to
2120
                            if (include_unchanged
2121
                                or result[2]                    # content change
2122
                                or result[3][0] != result[3][1] # versioned status
2123
                                or result[4][0] != result[4][1] # parent id
2124
                                or result[5][0] != result[5][1] # name
2125
                                or result[6][0] != result[6][1] # kind
2126
                                or result[7][0] != result[7][1] # executable
2127
                                ):
2255.7.80 by John Arbash Meinel
Don't decode the path entry until we've actually decided to return the tuple.
2128
                                result = (result[0],
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
2129
                                    ((utf8_decode(result[1][0])[0]),
2130
                                     utf8_decode(result[1][1])[0]),) + result[2:]
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2131
                                yield result
2132
                    if advance_entry and current_entry is not None:
2133
                        entry_index += 1
2134
                        if entry_index < len(current_block[1]):
2135
                            current_entry = current_block[1][entry_index]
2136
                        else:
2137
                            current_entry = None
2138
                    else:
2139
                        advance_entry = True # reset the advance flaga
2140
                    if advance_path and current_path_info is not None:
2255.7.87 by Robert Collins
Dont walk unversioned directories in _iter_changes.
2141
                        if not path_handled:
2142
                            # unversioned in all regards
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
2143
                            if want_unversioned:
2255.7.87 by Robert Collins
Dont walk unversioned directories in _iter_changes.
2144
                                new_executable = bool(
2145
                                    stat.S_ISREG(current_path_info[3].st_mode)
2146
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
2147
                                if want_unversioned:
2255.7.96 by Robert Collins
Change _iter_changes interface to yield both old and new paths.
2148
                                    yield (None, (None, current_path_info[0]),
2149
                                        True,
2150
                                        (False, False),
2151
                                        (None, None),
2152
                                        (None, current_path_info[1]),
2153
                                        (None, current_path_info[2]),
2154
                                        (None, new_executable))
2255.7.87 by Robert Collins
Dont walk unversioned directories in _iter_changes.
2155
                            # dont descend into this unversioned path if it is
2156
                            # a dir
2157
                            if current_path_info[2] == 'directory':
2158
                                del current_dir_info[1][path_index]
2159
                                path_index -= 1
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2160
                        path_index += 1
2161
                        if path_index < len(current_dir_info[1]):
2162
                            current_path_info = current_dir_info[1][path_index]
2163
                        else:
2164
                            current_path_info = None
2255.7.85 by Robert Collins
Teach _iter_changes to gather unversioned path details upon request.
2165
                        path_handled = False
2255.2.149 by Robert Collins
Crufty but existing _iter_changes implementation for WorkingTreeFormat4.
2166
                    else:
2167
                        advance_path = True # reset the advance flagg.
2168
                if current_block is not None:
2169
                    block_index += 1
2170
                    if (block_index < len(state._dirblocks) and
2171
                        osutils.is_inside(current_root, state._dirblocks[block_index][0])):
2172
                        current_block = state._dirblocks[block_index]
2173
                    else:
2174
                        current_block = None
2175
                if current_dir_info is not None:
2176
                    try:
2177
                        current_dir_info = dir_iterator.next()
2178
                    except StopIteration:
2179
                        current_dir_info = None
2180
2255.2.117 by Robert Collins
Add an InterDirStateTree InterTree optimiser.
2181
2182
    @staticmethod
2183
    def is_compatible(source, target):
2184
        # the target must be a dirstate working tree
2185
        if not isinstance(target, WorkingTree4):
2186
            return False
2187
        # the source must be a revtreee or dirstate rev tree.
2188
        if not isinstance(source,
2189
            (revisiontree.RevisionTree, DirStateRevisionTree)):
2190
            return False
2191
        # the source revid must be in the target dirstate
2192
        if not (source._revision_id == NULL_REVISION or
2193
            source._revision_id in target.get_parent_ids()):
2194
            # TODO: what about ghosts? it may well need to 
2195
            # check for them explicitly.
2196
            return False
2197
        return True
2198
2199
InterTree.register_optimiser(InterDirStateTree)
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2200
2201
2202
class Converter3to4(object):
2203
    """Perform an in-place upgrade of format 3 to format 4 trees."""
2204
2205
    def __init__(self):
2206
        self.target_format = WorkingTreeFormat4()
2207
2208
    def convert(self, tree):
2209
        # lock the control files not the tree, so that we dont get tree
2210
        # on-unlock behaviours, and so that noone else diddles with the 
2211
        # tree during upgrade.
2212
        tree._control_files.lock_write()
2213
        try:
2214
            self.create_dirstate_data(tree)
2215
            self.update_format(tree)
2216
            self.remove_xml_files(tree)
2217
        finally:
2218
            tree._control_files.unlock()
2219
2220
    def create_dirstate_data(self, tree):
2221
        """Create the dirstate based data for tree."""
2222
        local_path = tree.bzrdir.get_workingtree_transport(None
2223
            ).local_abspath('dirstate')
2224
        state = dirstate.DirState.from_tree(tree, local_path)
2225
        state.save()
2226
        state.unlock()
2227
2228
    def remove_xml_files(self, tree):
2229
        """Remove the oldformat 3 data."""
2230
        transport = tree.bzrdir.get_workingtree_transport(None)
2231
        for path in ['basis-inventory-cache', 'inventory', 'last-revision',
2232
            'pending-merges', 'stat-cache']:
2255.2.194 by Robert Collins
[BROKEN] Many updates to stop using experimental formats in tests.
2233
            try:
2234
                transport.delete(path)
2235
            except errors.NoSuchFile:
2236
                # some files are optional - just deal.
2237
                pass
2255.12.1 by Robert Collins
Implement upgrade for working trees.
2238
2239
    def update_format(self, tree):
2240
        """Change the format marker."""
2241
        tree._control_files.put_utf8('format',
2242
            self.target_format.get_format_string())