/brz/remove-bazaar

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