/brz/remove-bazaar

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