~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2007-11-15 14:47:59 UTC
  • mfrom: (2984.1.1 update_basis_161131)
  • Revision ID: pqm@pqm.ubuntu.com-20071115144759-zx0nd44rgp38riwr
(John Arbash Meinel) Fix bug #161131: when exactly 2 items were
        deleted, it would remove all items in a directory.

Show diffs side-by-side

added added

removed removed

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