/brz/remove-bazaar

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