/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

  • Committer: John Arbash Meinel
  • Date: 2007-06-01 21:40:45 UTC
  • mfrom: (2501 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2503.
  • Revision ID: john@arbash-meinel.com-20070601214045-zalht5mx39yg11l6
[merge] bzr.dev 2501

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