/brz/remove-bazaar

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