/brz/remove-bazaar

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