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