~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

  • Committer: Robert Collins
  • Date: 2007-04-19 02:27:44 UTC
  • mto: This revision was merged to the branch mainline in revision 2426.
  • Revision ID: robertc@robertcollins.net-20070419022744-pfdqz42kp1wizh43
``make docs`` now creates a man page at ``man1/bzr.1`` fixing bug 107388.
(Robert Collins)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""WorkingTree4 format and implementation.
18
18
 
28
28
 
29
29
from bzrlib.lazy_import import lazy_import
30
30
lazy_import(globals(), """
 
31
from bisect import bisect_left
 
32
import collections
 
33
from copy import deepcopy
31
34
import errno
 
35
import itertools
 
36
import operator
32
37
import stat
 
38
from time import time
 
39
import warnings
33
40
 
34
41
import bzrlib
35
42
from bzrlib import (
36
43
    bzrdir,
37
44
    cache_utf8,
38
 
    debug,
 
45
    conflicts as _mod_conflicts,
 
46
    delta,
39
47
    dirstate,
40
48
    errors,
41
49
    generate_ids,
 
50
    globbing,
 
51
    hashcache,
 
52
    ignores,
 
53
    merge,
42
54
    osutils,
43
 
    revision as _mod_revision,
44
55
    revisiontree,
45
 
    trace,
 
56
    textui,
46
57
    transform,
47
 
    views,
 
58
    urlutils,
 
59
    xml5,
 
60
    xml6,
48
61
    )
49
62
import bzrlib.branch
 
63
from bzrlib.transport import get_transport
50
64
import bzrlib.ui
51
65
""")
52
66
 
 
67
from bzrlib import symbol_versioning
53
68
from bzrlib.decorators import needs_read_lock, needs_write_lock
54
 
from bzrlib.filters import filtered_input_file, internal_size_sha_file_byname
55
 
from bzrlib.inventory import Inventory, ROOT_ID, entry_factory
 
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
56
72
import bzrlib.mutabletree
57
73
from bzrlib.mutabletree import needs_tree_write_lock
58
74
from bzrlib.osutils import (
59
75
    file_kind,
60
76
    isdir,
 
77
    normpath,
61
78
    pathjoin,
 
79
    rand_chars,
62
80
    realpath,
63
81
    safe_unicode,
 
82
    splitpath,
64
83
    )
65
 
from bzrlib.trace import mutter
 
84
from bzrlib.trace import mutter, note
66
85
from bzrlib.transport.local import LocalTransport
67
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
        )
68
95
from bzrlib.tree import Tree
69
96
from bzrlib.workingtree import WorkingTree, WorkingTree3, WorkingTreeFormat3
70
97
 
71
98
 
72
 
class DirStateWorkingTree(WorkingTree3):
 
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
 
73
118
    def __init__(self, basedir,
74
119
                 branch,
75
120
                 _control_files=None,
84
129
        """
85
130
        self._format = _format
86
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
87
135
        basedir = safe_unicode(basedir)
88
136
        mutter("opening working tree %r", basedir)
89
137
        self._branch = branch
 
138
        assert isinstance(self.branch, bzrlib.branch.Branch), \
 
139
            "branch %r is not a Branch" % self.branch
90
140
        self.basedir = realpath(basedir)
91
141
        # if branch is at our basedir and is a format 6 or less
92
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
93
145
        self._control_files = _control_files
94
 
        self._transport = self._control_files._transport
95
146
        self._dirty = None
96
147
        #-------------
97
148
        # during a read or write lock these objects are set, and are
99
150
        self._dirstate = None
100
151
        self._inventory = None
101
152
        #-------------
102
 
        self._setup_directory_is_tree_reference()
103
 
        self._detect_case_handling()
104
 
        self._rules_searcher = None
105
 
        self.views = self._make_views()
106
 
        #--- allow tests to select the dirstate iter_changes implementation
107
 
        self._iter_changes = dirstate._process_entry
108
153
 
109
154
    @needs_tree_write_lock
110
155
    def _add(self, files, ids, kinds):
112
157
        state = self.current_dirstate()
113
158
        for f, file_id, kind in zip(files, ids, kinds):
114
159
            f = f.strip('/')
 
160
            assert '//' not in f
 
161
            assert '..' not in f
115
162
            if self.path2id(f):
116
163
                # special case tree root handling.
117
164
                if f == '' and self.path2id(f) == ROOT_ID:
138
185
    @needs_tree_write_lock
139
186
    def add_reference(self, sub_tree):
140
187
        # use standard implementation, which calls back to self._add
141
 
        #
 
188
        # 
142
189
        # So we don't store the reference_revision in the working dirstate,
143
 
        # it's just recorded at the moment of commit.
 
190
        # it's just recorded at the moment of commit. 
144
191
        self._add_reference(sub_tree)
145
192
 
146
193
    def break_lock(self):
185
232
            WorkingTree3._comparison_data(self, entry, path)
186
233
        # it looks like a plain directory, but it's really a reference -- see
187
234
        # also kind()
188
 
        if (self._repo_supports_tree_reference and kind == 'directory'
189
 
            and entry is not None and entry.kind == 'tree-reference'):
 
235
        if (self._repo_supports_tree_reference and
 
236
            kind == 'directory' and
 
237
            self._directory_is_tree_reference(path)):
190
238
            kind = 'tree-reference'
191
239
        return kind, executable, stat_value
192
240
 
218
266
            return self._dirstate
219
267
        local_path = self.bzrdir.get_workingtree_transport(None
220
268
            ).local_abspath('dirstate')
221
 
        self._dirstate = dirstate.DirState.on_file(local_path,
222
 
            self._sha1_provider())
 
269
        self._dirstate = dirstate.DirState.on_file(local_path)
223
270
        return self._dirstate
224
271
 
225
 
    def _sha1_provider(self):
226
 
        """A function that returns a SHA1Provider suitable for this tree.
227
 
 
228
 
        :return: None if content filtering is not supported by this tree.
229
 
          Otherwise, a SHA1Provider is returned that sha's the canonical
230
 
          form of files, i.e. after read filters are applied.
231
 
        """
232
 
        if self.supports_content_filtering():
233
 
            return ContentFilterAwareSHA1Provider(self)
234
 
        else:
235
 
            return None
 
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
236
286
 
237
287
    def filter_unversioned_files(self, paths):
238
288
        """Filter out paths that are versioned.
271
321
 
272
322
    def _generate_inventory(self):
273
323
        """Create and set self.inventory from the dirstate object.
274
 
 
 
324
        
275
325
        This is relatively expensive: we have to walk the entire dirstate.
276
326
        Ideally we would not, and can deprecate this function.
277
327
        """
281
331
        state._read_dirblocks_if_needed()
282
332
        root_key, current_entry = self._get_entry(path='')
283
333
        current_id = root_key[2]
284
 
        if not (current_entry[0][0] == 'd'): # directory
285
 
            raise AssertionError(current_entry)
 
334
        assert current_entry[0][0] == 'd' # directory
286
335
        inv = Inventory(root_id=current_id)
287
336
        # Turn some things into local variables
288
337
        minikind_to_kind = dirstate.DirState._minikind_to_kind
321
370
                    # add this entry to the parent map.
322
371
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
323
372
                elif kind == 'tree-reference':
324
 
                    if not self._repo_supports_tree_reference:
325
 
                        raise errors.UnsupportedOperation(
326
 
                            self._generate_inventory,
327
 
                            self.branch.repository)
 
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)
328
378
                    inv_entry.reference_revision = link_or_sha1 or None
329
379
                elif kind != 'symlink':
330
380
                    raise AssertionError("unknown kind %r" % kind)
331
381
                # These checks cost us around 40ms on a 55k entry tree
332
 
                if file_id in inv_byid:
333
 
                    raise AssertionError('file_id %s already in'
334
 
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
335
 
                if name_unicode in parent_ie.children:
336
 
                    raise AssertionError('name %r already in parent'
337
 
                        % (name_unicode,))
 
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
338
385
                inv_byid[file_id] = inv_entry
339
386
                parent_ie.children[name_unicode] = inv_entry
340
387
        self._inventory = inv
345
392
        If either file_id or path is supplied, it is used as the key to lookup.
346
393
        If both are supplied, the fastest lookup is used, and an error is
347
394
        raised if they do not both point at the same row.
348
 
 
 
395
        
349
396
        :param file_id: An optional unicode file_id to be looked up.
350
397
        :param path: An optional unicode path to be looked up.
351
398
        :return: The dirstate row tuple for path/file_id, or (None, None)
360
407
    def get_file_sha1(self, file_id, path=None, stat_value=None):
361
408
        # check file id is valid unconditionally.
362
409
        entry = self._get_entry(file_id=file_id, path=path)
363
 
        if entry[0] is None:
364
 
            raise errors.NoSuchId(self, file_id)
 
410
        assert entry[0] is not None, 'what error should this raise'
365
411
        if path is None:
366
412
            path = pathjoin(entry[0][0], entry[0][1]).decode('utf8')
367
413
 
368
414
        file_abspath = self.abspath(path)
369
415
        state = self.current_dirstate()
370
 
        if stat_value is None:
371
 
            try:
372
 
                stat_value = os.lstat(file_abspath)
373
 
            except OSError, e:
374
 
                if e.errno == errno.ENOENT:
375
 
                    return None
376
 
                else:
377
 
                    raise
378
 
        link_or_sha1 = dirstate.update_entry(state, entry, file_abspath,
379
 
            stat_value=stat_value)
 
416
        link_or_sha1 = state.update_entry(entry, file_abspath,
 
417
                                          stat_value=stat_value)
380
418
        if entry[1][0][0] == 'f':
381
 
            if link_or_sha1 is None:
382
 
                file_obj, statvalue = self.get_file_with_stat(file_id, path)
383
 
                try:
384
 
                    sha1 = osutils.sha_file(file_obj)
385
 
                finally:
386
 
                    file_obj.close()
387
 
                self._observed_sha1(file_id, path, (sha1, statvalue))
388
 
                return sha1
389
 
            else:
390
 
                return link_or_sha1
 
419
            return link_or_sha1
391
420
        return None
392
421
 
393
422
    def _get_inventory(self):
394
423
        """Get the inventory for the tree. This is only valid within a lock."""
395
 
        if 'evil' in debug.debug_flags:
396
 
            trace.mutter_callsite(2,
397
 
                "accessing .inventory forces a size of tree translation.")
398
424
        if self._inventory is not None:
399
425
            return self._inventory
400
426
        self._must_be_locked()
407
433
    @needs_read_lock
408
434
    def get_parent_ids(self):
409
435
        """See Tree.get_parent_ids.
410
 
 
 
436
        
411
437
        This implementation requests the ids list from the dirstate file.
412
438
        """
413
439
        return self.current_dirstate().get_parent_ids()
429
455
 
430
456
    def has_id(self, file_id):
431
457
        state = self.current_dirstate()
 
458
        file_id = osutils.safe_file_id(file_id)
432
459
        row, parents = self._get_entry(file_id=file_id)
433
460
        if row is None:
434
461
            return False
435
462
        return osutils.lexists(pathjoin(
436
463
                    self.basedir, row[0].decode('utf8'), row[1].decode('utf8')))
437
464
 
438
 
    def has_or_had_id(self, file_id):
439
 
        state = self.current_dirstate()
440
 
        row, parents = self._get_entry(file_id=file_id)
441
 
        return row is not None
442
 
 
443
465
    @needs_read_lock
444
466
    def id2path(self, file_id):
445
 
        "Convert a file-id to a path."
 
467
        file_id = osutils.safe_file_id(file_id)
446
468
        state = self.current_dirstate()
447
469
        entry = self._get_entry(file_id=file_id)
448
470
        if entry == (None, None):
450
472
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
451
473
        return path_utf8.decode('utf8')
452
474
 
453
 
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
454
 
        entry = self._get_entry(path=path)
455
 
        if entry == (None, None):
456
 
            return False # Missing entries are not executable
457
 
        return entry[1][0][3] # Executable?
458
 
 
459
475
    if not osutils.supports_executable():
 
476
        @needs_read_lock
460
477
        def is_executable(self, file_id, path=None):
461
 
            """Test if a file is executable or not.
462
 
 
463
 
            Note: The caller is expected to take a read-lock before calling this.
464
 
            """
 
478
            file_id = osutils.safe_file_id(file_id)
465
479
            entry = self._get_entry(file_id=file_id, path=path)
466
480
            if entry == (None, None):
467
481
                return False
468
482
            return entry[1][0][3]
469
 
 
470
 
        _is_executable_from_path_and_stat = \
471
 
            _is_executable_from_path_and_stat_from_basis
472
483
    else:
 
484
        @needs_read_lock
473
485
        def is_executable(self, file_id, path=None):
474
 
            """Test if a file is executable or not.
475
 
 
476
 
            Note: The caller is expected to take a read-lock before calling this.
477
 
            """
478
 
            self._must_be_locked()
479
486
            if not path:
 
487
                file_id = osutils.safe_file_id(file_id)
480
488
                path = self.id2path(file_id)
481
489
            mode = os.lstat(self.abspath(path)).st_mode
482
490
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
483
491
 
484
 
    def all_file_ids(self):
485
 
        """See Tree.iter_all_file_ids"""
486
 
        self._must_be_locked()
487
 
        result = set()
488
 
        for key, tree_details in self.current_dirstate()._iter_entries():
489
 
            if tree_details[0][0] in ('a', 'r'): # relocated
490
 
                continue
491
 
            result.add(key[2])
492
 
        return result
493
 
 
494
492
    @needs_read_lock
495
493
    def __iter__(self):
496
494
        """Iterate through file_ids for this tree.
509
507
        return iter(result)
510
508
 
511
509
    def iter_references(self):
512
 
        if not self._repo_supports_tree_reference:
513
 
            # When the repo doesn't support references, we will have nothing to
514
 
            # return
515
 
            return
516
510
        for key, tree_details in self.current_dirstate()._iter_entries():
517
511
            if tree_details[0][0] in ('a', 'r'): # absent, relocated
518
512
                # not relevant to the working tree
520
514
            if not key[1]:
521
515
                # the root is not a reference.
522
516
                continue
523
 
            relpath = pathjoin(key[0].decode('utf8'), key[1].decode('utf8'))
 
517
            path = pathjoin(self.basedir, key[0].decode('utf8'), key[1].decode('utf8'))
524
518
            try:
525
 
                if self._kind(relpath) == 'tree-reference':
526
 
                    yield relpath, key[2]
 
519
                if self._kind(path) == 'tree-reference':
 
520
                    yield path, key[2]
527
521
            except errors.NoSuchFile:
528
522
                # path is missing on disk.
529
523
                continue
530
524
 
531
 
    def _observed_sha1(self, file_id, path, (sha1, statvalue)):
532
 
        """See MutableTree._observed_sha1."""
533
 
        state = self.current_dirstate()
534
 
        entry = self._get_entry(file_id=file_id, path=path)
535
 
        state._observed_sha1(entry, sha1, statvalue)
536
 
 
 
525
    @needs_read_lock
537
526
    def kind(self, file_id):
538
527
        """Return the kind of a file.
539
528
 
540
529
        This is always the actual kind that's on disk, regardless of what it
541
530
        was added as.
542
 
 
543
 
        Note: The caller is expected to take a read-lock before calling this.
544
531
        """
545
532
        relpath = self.id2path(file_id)
546
 
        if relpath is None:
547
 
            raise AssertionError(
548
 
                "path for id {%s} is None!" % file_id)
 
533
        assert relpath != None, \
 
534
            "path for id {%s} is None!" % file_id
549
535
        return self._kind(relpath)
550
536
 
551
537
    def _kind(self, relpath):
552
538
        abspath = self.abspath(relpath)
553
539
        kind = file_kind(abspath)
554
 
        if (self._repo_supports_tree_reference and kind == 'directory'):
555
 
            entry = self._get_entry(path=relpath)
556
 
            if entry[1] is not None:
557
 
                if entry[1][0][0] == 't':
558
 
                    kind = 'tree-reference'
 
540
        if (self._repo_supports_tree_reference and
 
541
            kind == 'directory' and
 
542
            self._directory_is_tree_reference(relpath)):
 
543
            kind = 'tree-reference'
559
544
        return kind
560
545
 
561
546
    @needs_read_lock
565
550
        if parent_ids:
566
551
            return parent_ids[0]
567
552
        else:
568
 
            return _mod_revision.NULL_REVISION
 
553
            return None
569
554
 
570
555
    def lock_read(self):
571
556
        """See Branch.lock_read, and WorkingTree.unlock."""
624
609
        result = []
625
610
        if not from_paths:
626
611
            return result
 
612
 
627
613
        state = self.current_dirstate()
628
 
        if isinstance(from_paths, basestring):
629
 
            raise ValueError()
 
614
 
 
615
        assert not isinstance(from_paths, basestring)
630
616
        to_dir_utf8 = to_dir.encode('utf8')
631
617
        to_entry_dirname, to_basename = os.path.split(to_dir_utf8)
632
618
        id_index = state._get_id_index()
654
640
        if self._inventory is not None:
655
641
            update_inventory = True
656
642
            inv = self.inventory
 
643
            to_dir_ie = inv[to_dir_id]
657
644
            to_dir_id = to_entry[0][2]
658
 
            to_dir_ie = inv[to_dir_id]
659
645
        else:
660
646
            update_inventory = False
661
647
 
684
670
            new_entry = to_block[1][added_entry_index]
685
671
            rollbacks.append(lambda:state._make_absent(new_entry))
686
672
 
 
673
        # create rename entries and tuples
687
674
        for from_rel in from_paths:
688
675
            # from_rel is 'pathinroot/foo/bar'
689
676
            from_rel_utf8 = from_rel.encode('utf8')
692
679
            from_entry = self._get_entry(path=from_rel)
693
680
            if from_entry == (None, None):
694
681
                raise errors.BzrMoveFailedError(from_rel,to_dir,
695
 
                    errors.NotVersionedError(path=from_rel))
 
682
                    errors.NotVersionedError(path=str(from_rel)))
696
683
 
697
684
            from_id = from_entry[0][2]
698
685
            to_rel = pathjoin(to_dir, from_tail)
725
712
                if from_missing: # implicitly just update our path mapping
726
713
                    move_file = False
727
714
                elif not after:
728
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
 
715
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
 
716
                        extra="(Use --after to update the Bazaar id)")
729
717
 
730
718
            rollbacks = []
731
719
            def rollback_rename():
786
774
 
787
775
                if minikind == 'd':
788
776
                    def update_dirblock(from_dir, to_key, to_dir_utf8):
789
 
                        """Recursively update all entries in this dirblock."""
790
 
                        if from_dir == '':
791
 
                            raise AssertionError("renaming root not supported")
 
777
                        """all entries in this block need updating.
 
778
 
 
779
                        TODO: This is pretty ugly, and doesn't support
 
780
                        reverting, but it works.
 
781
                        """
 
782
                        assert from_dir != '', "renaming root not supported"
792
783
                        from_key = (from_dir, '')
793
784
                        from_block_idx, present = \
794
785
                            state._find_block_index_from_key(from_key)
804
795
                        to_block_index = state._ensure_block(
805
796
                            to_block_index, to_entry_index, to_dir_utf8)
806
797
                        to_block = state._dirblocks[to_block_index]
807
 
 
808
 
                        # Grab a copy since move_one may update the list.
809
 
                        for entry in from_block[1][:]:
810
 
                            if not (entry[0][0] == from_dir):
811
 
                                raise AssertionError()
 
798
                        for entry in from_block[1]:
 
799
                            assert entry[0][0] == from_dir
812
800
                            cur_details = entry[1][0]
813
801
                            to_key = (to_dir_utf8, entry[0][1], entry[0][2])
814
802
                            from_path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
815
803
                            to_path_utf8 = osutils.pathjoin(to_dir_utf8, entry[0][1])
816
804
                            minikind = cur_details[0]
817
 
                            if minikind in 'ar':
818
 
                                # Deleted children of a renamed directory
819
 
                                # Do not need to be updated.
820
 
                                # Children that have been renamed out of this
821
 
                                # directory should also not be updated
822
 
                                continue
823
805
                            move_one(entry, from_path_utf8=from_path_utf8,
824
806
                                     minikind=minikind,
825
807
                                     executable=cur_details[3],
873
855
        for tree in trees:
874
856
            if not (isinstance(tree, DirStateRevisionTree) and tree._revision_id in
875
857
                parents):
876
 
                return super(DirStateWorkingTree, self).paths2ids(paths,
877
 
                    trees, require_versioned)
 
858
                return super(WorkingTree4, self).paths2ids(paths, trees, require_versioned)
878
859
        search_indexes = [0] + [1 + parents.index(tree._revision_id) for tree in trees]
879
860
        # -- make all paths utf8 --
880
861
        paths_utf8 = set()
940
921
            if not all_versioned:
941
922
                raise errors.PathsNotVersionedError(paths)
942
923
        # -- remove redundancy in supplied paths to prevent over-scanning --
943
 
        search_paths = osutils.minimum_path_selection(paths)
944
 
        # sketch:
 
924
        search_paths = set()
 
925
        for path in paths:
 
926
            other_paths = paths.difference(set([path]))
 
927
            if not osutils.is_inside_any(other_paths, path):
 
928
                # this is a top level path, we must check it.
 
929
                search_paths.add(path)
 
930
        # sketch: 
945
931
        # for all search_indexs in each path at or under each element of
946
932
        # search_paths, if the detail is relocated: add the id, and add the
947
933
        # relocated path as one to search if its not searched already. If the
1003
989
 
1004
990
    def read_working_inventory(self):
1005
991
        """Read the working inventory.
1006
 
 
 
992
        
1007
993
        This is a meaningless operation for dirstate, but we obey it anyhow.
1008
994
        """
1009
995
        return self.inventory
1014
1000
 
1015
1001
        WorkingTree4 supplies revision_trees for any basis tree.
1016
1002
        """
 
1003
        revision_id = osutils.safe_revision_id(revision_id)
1017
1004
        dirstate = self.current_dirstate()
1018
1005
        parent_ids = dirstate.get_parent_ids()
1019
1006
        if revision_id not in parent_ids:
1026
1013
    @needs_tree_write_lock
1027
1014
    def set_last_revision(self, new_revision):
1028
1015
        """Change the last revision in the working tree."""
 
1016
        new_revision = osutils.safe_revision_id(new_revision)
1029
1017
        parents = self.get_parent_ids()
1030
 
        if new_revision in (_mod_revision.NULL_REVISION, None):
1031
 
            if len(parents) >= 2:
1032
 
                raise AssertionError(
1033
 
                    "setting the last parent to none with a pending merge is "
1034
 
                    "unsupported.")
 
1018
        if new_revision in (NULL_REVISION, None):
 
1019
            assert len(parents) < 2, (
 
1020
                "setting the last parent to none with a pending merge is "
 
1021
                "unsupported.")
1035
1022
            self.set_parent_ids([])
1036
1023
        else:
1037
1024
            self.set_parent_ids([new_revision] + parents[1:],
1040
1027
    @needs_tree_write_lock
1041
1028
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1042
1029
        """Set the parent ids to revision_ids.
1043
 
 
 
1030
        
1044
1031
        See also set_parent_trees. This api will try to retrieve the tree data
1045
1032
        for each element of revision_ids from the trees repository. If you have
1046
1033
        tree data already available, it is more efficient to use
1050
1037
        :param revision_ids: The revision_ids to set as the parent ids of this
1051
1038
            working tree. Any of these may be ghosts.
1052
1039
        """
 
1040
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1053
1041
        trees = []
1054
1042
        for revision_id in revision_ids:
1055
1043
            try:
1061
1049
            except (errors.NoSuchRevision, errors.RevisionNotPresent):
1062
1050
                revtree = None
1063
1051
            trees.append((revision_id, revtree))
 
1052
        self.current_dirstate()._validate()
1064
1053
        self.set_parent_trees(trees,
1065
1054
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
 
1055
        self.current_dirstate()._validate()
1066
1056
 
1067
1057
    @needs_tree_write_lock
1068
1058
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
1073
1063
            parent tree - i.e. a ghost.
1074
1064
        """
1075
1065
        dirstate = self.current_dirstate()
 
1066
        dirstate._validate()
1076
1067
        if len(parents_list) > 0:
1077
1068
            if not allow_leftmost_as_ghost and parents_list[0][1] is None:
1078
1069
                raise errors.GhostRevisionUnusableHere(parents_list[0][0])
1079
1070
        real_trees = []
1080
1071
        ghosts = []
1081
 
 
1082
 
        parent_ids = [rev_id for rev_id, tree in parents_list]
1083
 
        graph = self.branch.repository.get_graph()
1084
 
        heads = graph.heads(parent_ids)
1085
 
        accepted_revisions = set()
1086
 
 
1087
1072
        # convert absent trees to the null tree, which we convert back to
1088
1073
        # missing on access.
1089
1074
        for rev_id, tree in parents_list:
1090
 
            if len(accepted_revisions) > 0:
1091
 
                # we always accept the first tree
1092
 
                if rev_id in accepted_revisions or rev_id not in heads:
1093
 
                    # We have already included either this tree, or its
1094
 
                    # descendent, so we skip it.
1095
 
                    continue
1096
 
            _mod_revision.check_not_reserved_id(rev_id)
 
1075
            rev_id = osutils.safe_revision_id(rev_id)
1097
1076
            if tree is not None:
1098
1077
                real_trees.append((rev_id, tree))
1099
1078
            else:
1100
1079
                real_trees.append((rev_id,
1101
 
                    self.branch.repository.revision_tree(
1102
 
                        _mod_revision.NULL_REVISION)))
 
1080
                    self.branch.repository.revision_tree(None)))
1103
1081
                ghosts.append(rev_id)
1104
 
            accepted_revisions.add(rev_id)
 
1082
        dirstate._validate()
1105
1083
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
 
1084
        dirstate._validate()
1106
1085
        self._make_dirty(reset_inventory=False)
 
1086
        dirstate._validate()
1107
1087
 
1108
1088
    def _set_root_id(self, file_id):
1109
1089
        """See WorkingTree.set_root_id."""
1112
1092
        if state._dirblock_state == dirstate.DirState.IN_MEMORY_MODIFIED:
1113
1093
            self._make_dirty(reset_inventory=True)
1114
1094
 
1115
 
    def _sha_from_stat(self, path, stat_result):
1116
 
        """Get a sha digest from the tree's stat cache.
1117
 
 
1118
 
        The default implementation assumes no stat cache is present.
1119
 
 
1120
 
        :param path: The path.
1121
 
        :param stat_result: The stat result being looked up.
1122
 
        """
1123
 
        return self.current_dirstate().sha1_from_stat(path, stat_result)
1124
 
 
1125
1095
    @needs_read_lock
1126
1096
    def supports_tree_reference(self):
1127
1097
        return self._repo_supports_tree_reference
1128
1098
 
1129
1099
    def unlock(self):
1130
1100
        """Unlock in format 4 trees needs to write the entire dirstate."""
1131
 
        # do non-implementation specific cleanup
1132
 
        self._cleanup()
1133
 
 
1134
1101
        if self._control_files._lock_count == 1:
1135
1102
            # eventually we should do signature checking during read locks for
1136
1103
            # dirstate updates.
1167
1134
            return
1168
1135
        state = self.current_dirstate()
1169
1136
        state._read_dirblocks_if_needed()
1170
 
        ids_to_unversion = set(file_ids)
 
1137
        ids_to_unversion = set()
 
1138
        for file_id in file_ids:
 
1139
            ids_to_unversion.add(osutils.safe_file_id(file_id))
1171
1140
        paths_to_unversion = set()
1172
1141
        # sketch:
1173
1142
        # check if the root is to be unversioned, if so, assert for now.
1200
1169
                # just forget the whole block.
1201
1170
                entry_index = 0
1202
1171
                while entry_index < len(block[1]):
 
1172
                    # Mark this file id as having been removed
1203
1173
                    entry = block[1][entry_index]
1204
 
                    if entry[1][0][0] in 'ar':
1205
 
                        # don't remove absent or renamed entries
 
1174
                    ids_to_unversion.discard(entry[0][2])
 
1175
                    if (entry[1][0][0] == 'a'
 
1176
                        or not state._make_absent(entry)):
1206
1177
                        entry_index += 1
1207
 
                    else:
1208
 
                        # Mark this file id as having been removed
1209
 
                        ids_to_unversion.discard(entry[0][2])
1210
 
                        if not state._make_absent(entry):
1211
 
                            # The block has not shrunk.
1212
 
                            entry_index += 1
1213
1178
                # go to the next block. (At the moment we dont delete empty
1214
1179
                # dirblocks)
1215
1180
                block_index += 1
1238
1203
            for file_id in file_ids:
1239
1204
                self._inventory.remove_recursive_id(file_id)
1240
1205
 
1241
 
    @needs_tree_write_lock
1242
 
    def rename_one(self, from_rel, to_rel, after=False):
1243
 
        """See WorkingTree.rename_one"""
1244
 
        self.flush()
1245
 
        WorkingTree.rename_one(self, from_rel, to_rel, after)
1246
 
 
1247
 
    @needs_tree_write_lock
1248
 
    def apply_inventory_delta(self, changes):
1249
 
        """See MutableTree.apply_inventory_delta"""
1250
 
        state = self.current_dirstate()
1251
 
        state.update_by_delta(changes)
1252
 
        self._make_dirty(reset_inventory=True)
1253
 
 
1254
 
    def update_basis_by_delta(self, new_revid, delta):
1255
 
        """See MutableTree.update_basis_by_delta."""
1256
 
        if self.last_revision() == new_revid:
1257
 
            raise AssertionError()
1258
 
        self.current_dirstate().update_basis_by_delta(delta, new_revid)
1259
 
 
1260
1206
    @needs_read_lock
1261
1207
    def _validate(self):
1262
1208
        self._dirstate._validate()
1264
1210
    @needs_tree_write_lock
1265
1211
    def _write_inventory(self, inv):
1266
1212
        """Write inventory as the current inventory."""
1267
 
        if self._dirty:
1268
 
            raise AssertionError("attempting to write an inventory when the "
1269
 
                "dirstate is dirty will lose pending changes")
 
1213
        assert not self._dirty, "attempting to write an inventory when the dirstate is dirty will cause data loss"
1270
1214
        self.current_dirstate().set_state_from_inventory(inv)
1271
1215
        self._make_dirty(reset_inventory=False)
1272
1216
        if self._inventory is not None:
1274
1218
        self.flush()
1275
1219
 
1276
1220
 
1277
 
class ContentFilterAwareSHA1Provider(dirstate.SHA1Provider):
1278
 
 
1279
 
    def __init__(self, tree):
1280
 
        self.tree = tree
1281
 
 
1282
 
    def sha1(self, abspath):
1283
 
        """See dirstate.SHA1Provider.sha1()."""
1284
 
        filters = self.tree._content_filter_stack(
1285
 
            self.tree.relpath(osutils.safe_unicode(abspath)))
1286
 
        return internal_size_sha_file_byname(abspath, filters)[1]
1287
 
 
1288
 
    def stat_and_sha1(self, abspath):
1289
 
        """See dirstate.SHA1Provider.stat_and_sha1()."""
1290
 
        filters = self.tree._content_filter_stack(
1291
 
            self.tree.relpath(osutils.safe_unicode(abspath)))
1292
 
        file_obj = file(abspath, 'rb', 65000)
1293
 
        try:
1294
 
            statvalue = os.fstat(file_obj.fileno())
1295
 
            if filters:
1296
 
                file_obj = filtered_input_file(file_obj, filters)
1297
 
            sha1 = osutils.size_sha_file(file_obj)[1]
1298
 
        finally:
1299
 
            file_obj.close()
1300
 
        return statvalue, sha1
1301
 
 
1302
 
 
1303
 
class WorkingTree4(DirStateWorkingTree):
1304
 
    """This is the Format 4 working tree.
1305
 
 
1306
 
    This differs from WorkingTree3 by:
1307
 
     - Having a consolidated internal dirstate, stored in a
1308
 
       randomly-accessible sorted file on disk.
1309
 
     - Not having a regular inventory attribute.  One can be synthesized
1310
 
       on demand but this is expensive and should be avoided.
1311
 
 
1312
 
    This is new in bzr 0.15.
1313
 
    """
1314
 
 
1315
 
 
1316
 
class WorkingTree5(DirStateWorkingTree):
1317
 
    """This is the Format 5 working tree.
1318
 
 
1319
 
    This differs from WorkingTree4 by:
1320
 
     - Supporting content filtering.
1321
 
 
1322
 
    This is new in bzr 1.11.
1323
 
    """
1324
 
 
1325
 
 
1326
 
class WorkingTree6(DirStateWorkingTree):
1327
 
    """This is the Format 6 working tree.
1328
 
 
1329
 
    This differs from WorkingTree5 by:
1330
 
     - Supporting a current view that may mask the set of files in a tree
1331
 
       impacted by most user operations.
1332
 
 
1333
 
    This is new in bzr 1.14.
1334
 
    """
1335
 
 
1336
 
    def _make_views(self):
1337
 
        return views.PathBasedViews(self)
1338
 
 
1339
 
 
1340
 
class DirStateWorkingTreeFormat(WorkingTreeFormat3):
1341
 
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
1342
 
                   accelerator_tree=None, hardlink=False):
 
1221
class WorkingTreeFormat4(WorkingTreeFormat3):
 
1222
    """The first consolidated dirstate working tree format.
 
1223
 
 
1224
    This format:
 
1225
        - exists within a metadir controlling .bzr
 
1226
        - includes an explicit version marker for the workingtree control
 
1227
          files, separate from the BzrDir format
 
1228
        - modifies the hash cache format
 
1229
        - is new in bzr 0.15
 
1230
        - uses a LockDir to guard access to it.
 
1231
    """
 
1232
 
 
1233
    upgrade_recommended = False
 
1234
 
 
1235
    def get_format_string(self):
 
1236
        """See WorkingTreeFormat.get_format_string()."""
 
1237
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
 
1238
 
 
1239
    def get_format_description(self):
 
1240
        """See WorkingTreeFormat.get_format_description()."""
 
1241
        return "Working tree format 4"
 
1242
 
 
1243
    def initialize(self, a_bzrdir, revision_id=None):
1343
1244
        """See WorkingTreeFormat.initialize().
1344
1245
 
1345
1246
        :param revision_id: allows creating a working tree at a different
1346
1247
        revision than the branch is at.
1347
 
        :param accelerator_tree: A tree which can be used for retrieving file
1348
 
            contents more quickly than the revision tree, i.e. a workingtree.
1349
 
            The revision tree will be used for cases where accelerator_tree's
1350
 
            content is different.
1351
 
        :param hardlink: If true, hard-link files from accelerator_tree,
1352
 
            where possible.
1353
1248
 
1354
 
        These trees get an initial random root id, if their repository supports
1355
 
        rich root data, TREE_ROOT otherwise.
 
1249
        These trees get an initial random root id.
1356
1250
        """
 
1251
        revision_id = osutils.safe_revision_id(revision_id)
1357
1252
        if not isinstance(a_bzrdir.transport, LocalTransport):
1358
1253
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1359
1254
        transport = a_bzrdir.get_workingtree_transport(self)
1360
1255
        control_files = self._open_control_files(a_bzrdir)
1361
1256
        control_files.create_lock()
1362
1257
        control_files.lock_write()
1363
 
        transport.put_bytes('format', self.get_format_string(),
1364
 
            mode=a_bzrdir._get_file_mode())
1365
 
        if from_branch is not None:
1366
 
            branch = from_branch
1367
 
        else:
1368
 
            branch = a_bzrdir.open_branch()
 
1258
        control_files.put_utf8('format', self.get_format_string())
 
1259
        branch = a_bzrdir.open_branch()
1369
1260
        if revision_id is None:
1370
1261
            revision_id = branch.last_revision()
1371
1262
        local_path = transport.local_abspath('dirstate')
1373
1264
        state = dirstate.DirState.initialize(local_path)
1374
1265
        state.unlock()
1375
1266
        del state
1376
 
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
1267
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
1377
1268
                         branch,
1378
1269
                         _format=self,
1379
1270
                         _bzrdir=a_bzrdir,
1380
1271
                         _control_files=control_files)
1381
1272
        wt._new_tree()
1382
1273
        wt.lock_tree_write()
 
1274
        wt.current_dirstate()._validate()
1383
1275
        try:
1384
 
            self._init_custom_control_files(wt)
1385
 
            if revision_id in (None, _mod_revision.NULL_REVISION):
1386
 
                if branch.repository.supports_rich_root():
1387
 
                    wt._set_root_id(generate_ids.gen_root_id())
1388
 
                else:
1389
 
                    wt._set_root_id(ROOT_ID)
 
1276
            if revision_id in (None, NULL_REVISION):
 
1277
                wt._set_root_id(generate_ids.gen_root_id())
1390
1278
                wt.flush()
1391
 
            basis = None
1392
 
            # frequently, we will get here due to branching.  The accelerator
1393
 
            # tree will be the tree from the branch, so the desired basis
1394
 
            # tree will often be a parent of the accelerator tree.
1395
 
            if accelerator_tree is not None:
1396
 
                try:
1397
 
                    basis = accelerator_tree.revision_tree(revision_id)
1398
 
                except errors.NoSuchRevision:
1399
 
                    pass
1400
 
            if basis is None:
1401
 
                basis = branch.repository.revision_tree(revision_id)
1402
 
            if revision_id == _mod_revision.NULL_REVISION:
1403
 
                parents_list = []
1404
 
            else:
1405
 
                parents_list = [(revision_id, basis)]
 
1279
                wt.current_dirstate()._validate()
 
1280
            wt.set_last_revision(revision_id)
 
1281
            wt.flush()
 
1282
            basis = wt.basis_tree()
1406
1283
            basis.lock_read()
1407
 
            try:
1408
 
                wt.set_parent_trees(parents_list, allow_leftmost_as_ghost=True)
 
1284
            # if the basis has a root id we have to use that; otherwise we use
 
1285
            # a new random one
 
1286
            basis_root_id = basis.get_root_id()
 
1287
            if basis_root_id is not None:
 
1288
                wt._set_root_id(basis_root_id)
1409
1289
                wt.flush()
1410
 
                # if the basis has a root id we have to use that; otherwise we
1411
 
                # use a new random one
1412
 
                basis_root_id = basis.get_root_id()
1413
 
                if basis_root_id is not None:
1414
 
                    wt._set_root_id(basis_root_id)
1415
 
                    wt.flush()
1416
 
                # If content filtering is supported, do not use the accelerator
1417
 
                # tree - the cost of transforming the content both ways and
1418
 
                # checking for changed content can outweight the gains it gives.
1419
 
                # Note: do NOT move this logic up higher - using the basis from
1420
 
                # the accelerator tree is still desirable because that can save
1421
 
                # a minute or more of processing on large trees!
1422
 
                # The original tree may not have the same content filters
1423
 
                # applied so we can't safely build the inventory delta from
1424
 
                # the source tree.
1425
 
                if wt.supports_content_filtering():
1426
 
                    if hardlink:
1427
 
                        # see https://bugs.edge.launchpad.net/bzr/+bug/408193
1428
 
                        trace.warning("hardlinking working copy files is not currently "
1429
 
                            "supported in %r" % (wt,))
1430
 
                    accelerator_tree = None
1431
 
                    delta_from_tree = False
1432
 
                else:
1433
 
                    delta_from_tree = True
1434
 
                # delta_from_tree is safe even for DirStateRevisionTrees,
1435
 
                # because wt4.apply_inventory_delta does not mutate the input
1436
 
                # inventory entries.
1437
 
                transform.build_tree(basis, wt, accelerator_tree,
1438
 
                                     hardlink=hardlink,
1439
 
                                     delta_from_tree=delta_from_tree)
1440
 
            finally:
1441
 
                basis.unlock()
 
1290
            transform.build_tree(basis, wt)
 
1291
            basis.unlock()
1442
1292
        finally:
1443
1293
            control_files.unlock()
1444
1294
            wt.unlock()
1445
1295
        return wt
1446
1296
 
1447
 
    def _init_custom_control_files(self, wt):
1448
 
        """Subclasses with custom control files should override this method.
1449
 
 
1450
 
        The working tree and control files are locked for writing when this
1451
 
        method is called.
1452
 
 
1453
 
        :param wt: the WorkingTree object
1454
 
        """
1455
 
 
1456
1297
    def _open(self, a_bzrdir, control_files):
1457
1298
        """Open the tree itself.
1458
1299
 
1459
1300
        :param a_bzrdir: the dir for the tree.
1460
1301
        :param control_files: the control files for the tree.
1461
1302
        """
1462
 
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
 
1303
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
1463
1304
                           branch=a_bzrdir.open_branch(),
1464
1305
                           _format=self,
1465
1306
                           _bzrdir=a_bzrdir,
1466
1307
                           _control_files=control_files)
1467
1308
 
1468
1309
    def __get_matchingbzrdir(self):
1469
 
        return self._get_matchingbzrdir()
1470
 
 
1471
 
    def _get_matchingbzrdir(self):
1472
 
        """Overrideable method to get a bzrdir for testing."""
1473
1310
        # please test against something that will let us do tree references
1474
1311
        return bzrdir.format_registry.make_bzrdir(
1475
1312
            'dirstate-with-subtree')
1477
1314
    _matchingbzrdir = property(__get_matchingbzrdir)
1478
1315
 
1479
1316
 
1480
 
class WorkingTreeFormat4(DirStateWorkingTreeFormat):
1481
 
    """The first consolidated dirstate working tree format.
1482
 
 
1483
 
    This format:
1484
 
        - exists within a metadir controlling .bzr
1485
 
        - includes an explicit version marker for the workingtree control
1486
 
          files, separate from the BzrDir format
1487
 
        - modifies the hash cache format
1488
 
        - is new in bzr 0.15
1489
 
        - uses a LockDir to guard access to it.
1490
 
    """
1491
 
 
1492
 
    upgrade_recommended = False
1493
 
 
1494
 
    _tree_class = WorkingTree4
1495
 
 
1496
 
    def get_format_string(self):
1497
 
        """See WorkingTreeFormat.get_format_string()."""
1498
 
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
1499
 
 
1500
 
    def get_format_description(self):
1501
 
        """See WorkingTreeFormat.get_format_description()."""
1502
 
        return "Working tree format 4"
1503
 
 
1504
 
 
1505
 
class WorkingTreeFormat5(DirStateWorkingTreeFormat):
1506
 
    """WorkingTree format supporting content filtering.
1507
 
    """
1508
 
 
1509
 
    upgrade_recommended = False
1510
 
 
1511
 
    _tree_class = WorkingTree5
1512
 
 
1513
 
    def get_format_string(self):
1514
 
        """See WorkingTreeFormat.get_format_string()."""
1515
 
        return "Bazaar Working Tree Format 5 (bzr 1.11)\n"
1516
 
 
1517
 
    def get_format_description(self):
1518
 
        """See WorkingTreeFormat.get_format_description()."""
1519
 
        return "Working tree format 5"
1520
 
 
1521
 
    def supports_content_filtering(self):
1522
 
        return True
1523
 
 
1524
 
 
1525
 
class WorkingTreeFormat6(DirStateWorkingTreeFormat):
1526
 
    """WorkingTree format supporting views.
1527
 
    """
1528
 
 
1529
 
    upgrade_recommended = False
1530
 
 
1531
 
    _tree_class = WorkingTree6
1532
 
 
1533
 
    def get_format_string(self):
1534
 
        """See WorkingTreeFormat.get_format_string()."""
1535
 
        return "Bazaar Working Tree Format 6 (bzr 1.14)\n"
1536
 
 
1537
 
    def get_format_description(self):
1538
 
        """See WorkingTreeFormat.get_format_description()."""
1539
 
        return "Working tree format 6"
1540
 
 
1541
 
    def _init_custom_control_files(self, wt):
1542
 
        """Subclasses with custom control files should override this method."""
1543
 
        wt._transport.put_bytes('views', '', mode=wt.bzrdir._get_file_mode())
1544
 
 
1545
 
    def supports_content_filtering(self):
1546
 
        return True
1547
 
 
1548
 
    def supports_views(self):
1549
 
        return True
1550
 
 
1551
 
 
1552
1317
class DirStateRevisionTree(Tree):
1553
1318
    """A revision tree pulling the inventory from a dirstate."""
1554
1319
 
1555
1320
    def __init__(self, dirstate, revision_id, repository):
1556
1321
        self._dirstate = dirstate
1557
 
        self._revision_id = revision_id
 
1322
        self._revision_id = osutils.safe_revision_id(revision_id)
1558
1323
        self._repository = repository
1559
1324
        self._inventory = None
1560
1325
        self._locked = 0
1561
1326
        self._dirstate_locked = False
1562
 
        self._repo_supports_tree_reference = getattr(
1563
 
            repository._format, "supports_tree_reference",
1564
 
            False)
1565
1327
 
1566
1328
    def __repr__(self):
1567
1329
        return "<%s of %s in %s>" % \
1568
1330
            (self.__class__.__name__, self._revision_id, self._dirstate)
1569
1331
 
1570
 
    def annotate_iter(self, file_id,
1571
 
                      default_revision=_mod_revision.CURRENT_REVISION):
 
1332
    def annotate_iter(self, file_id):
1572
1333
        """See Tree.annotate_iter"""
1573
 
        text_key = (file_id, self.inventory[file_id].revision)
1574
 
        annotations = self._repository.texts.annotate(text_key)
1575
 
        return [(key[-1], line) for (key, line) in annotations]
 
1334
        w = self._repository.weave_store.get_weave(file_id,
 
1335
                           self._repository.get_transaction())
 
1336
        return w.annotate_iter(self.inventory[file_id].revision)
1576
1337
 
1577
 
    def _get_ancestors(self, default_revision):
1578
 
        return set(self._repository.get_ancestry(self._revision_id,
1579
 
                                                 topo_sorted=False))
1580
1338
    def _comparison_data(self, entry, path):
1581
1339
        """See Tree._comparison_data."""
1582
1340
        if entry is None:
1599
1357
    def get_root_id(self):
1600
1358
        return self.path2id('')
1601
1359
 
1602
 
    def id2path(self, file_id):
1603
 
        "Convert a file-id to a path."
1604
 
        entry = self._get_entry(file_id=file_id)
1605
 
        if entry == (None, None):
1606
 
            raise errors.NoSuchId(tree=self, file_id=file_id)
1607
 
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
1608
 
        return path_utf8.decode('utf8')
1609
 
 
1610
 
    def iter_references(self):
1611
 
        if not self._repo_supports_tree_reference:
1612
 
            # When the repo doesn't support references, we will have nothing to
1613
 
            # return
1614
 
            return iter([])
1615
 
        # Otherwise, fall back to the default implementation
1616
 
        return super(DirStateRevisionTree, self).iter_references()
1617
 
 
1618
1360
    def _get_parent_index(self):
1619
1361
        """Return the index in the dirstate referenced by this tree."""
1620
1362
        return self._dirstate.get_parent_ids().index(self._revision_id) + 1
1625
1367
        If either file_id or path is supplied, it is used as the key to lookup.
1626
1368
        If both are supplied, the fastest lookup is used, and an error is
1627
1369
        raised if they do not both point at the same row.
1628
 
 
 
1370
        
1629
1371
        :param file_id: An optional unicode file_id to be looked up.
1630
1372
        :param path: An optional unicode path to be looked up.
1631
1373
        :return: The dirstate row tuple for path/file_id, or (None, None)
1632
1374
        """
1633
1375
        if file_id is None and path is None:
1634
1376
            raise errors.BzrError('must supply file_id or path')
 
1377
        file_id = osutils.safe_file_id(file_id)
1635
1378
        if path is not None:
1636
1379
            path = path.encode('utf8')
1637
1380
        parent_index = self._get_parent_index()
1645
1388
 
1646
1389
        This is relatively expensive: we have to walk the entire dirstate.
1647
1390
        """
1648
 
        if not self._locked:
1649
 
            raise AssertionError(
1650
 
                'cannot generate inventory of an unlocked '
1651
 
                'dirstate revision tree')
 
1391
        assert self._locked, 'cannot generate inventory of an unlocked '\
 
1392
            'dirstate revision tree'
1652
1393
        # separate call for profiling - makes it clear where the costs are.
1653
1394
        self._dirstate._read_dirblocks_if_needed()
1654
 
        if self._revision_id not in self._dirstate.get_parent_ids():
1655
 
            raise AssertionError(
1656
 
                'parent %s has disappeared from %s' % (
1657
 
                self._revision_id, self._dirstate.get_parent_ids()))
 
1395
        assert self._revision_id in self._dirstate.get_parent_ids(), \
 
1396
            'parent %s has disappeared from %s' % (
 
1397
            self._revision_id, self._dirstate.get_parent_ids())
1658
1398
        parent_index = self._dirstate.get_parent_ids().index(self._revision_id) + 1
1659
1399
        # This is identical now to the WorkingTree _generate_inventory except
1660
1400
        # for the tree index use.
1661
1401
        root_key, current_entry = self._dirstate._get_entry(parent_index, path_utf8='')
1662
1402
        current_id = root_key[2]
1663
 
        if current_entry[parent_index][0] != 'd':
1664
 
            raise AssertionError()
 
1403
        assert current_entry[parent_index][0] == 'd'
1665
1404
        inv = Inventory(root_id=current_id, revision_id=self._revision_id)
1666
1405
        inv.root.revision = current_entry[parent_index][4]
1667
1406
        # Turn some things into local variables
1707
1446
                    raise AssertionError("cannot convert entry %r into an InventoryEntry"
1708
1447
                            % entry)
1709
1448
                # These checks cost us around 40ms on a 55k entry tree
1710
 
                if file_id in inv_byid:
1711
 
                    raise AssertionError('file_id %s already in'
1712
 
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
1713
 
                if name_unicode in parent_ie.children:
1714
 
                    raise AssertionError('name %r already in parent'
1715
 
                        % (name_unicode,))
 
1449
                assert file_id not in inv_byid
 
1450
                assert name_unicode not in parent_ie.children
1716
1451
                inv_byid[file_id] = inv_entry
1717
1452
                parent_ie.children[name_unicode] = inv_entry
1718
1453
        self._inventory = inv
1738
1473
            return parent_details[1]
1739
1474
        return None
1740
1475
 
1741
 
    def get_file(self, file_id, path=None):
 
1476
    def get_file(self, file_id):
1742
1477
        return StringIO(self.get_file_text(file_id))
1743
1478
 
 
1479
    def get_file_lines(self, file_id):
 
1480
        ie = self.inventory[file_id]
 
1481
        return self._repository.weave_store.get_weave(file_id,
 
1482
                self._repository.get_transaction()).get_lines(ie.revision)
 
1483
 
1744
1484
    def get_file_size(self, file_id):
1745
 
        """See Tree.get_file_size"""
1746
1485
        return self.inventory[file_id].text_size
1747
1486
 
1748
 
    def get_file_text(self, file_id, path=None):
1749
 
        _, content = list(self.iter_files_bytes([(file_id, None)]))[0]
1750
 
        return ''.join(content)
 
1487
    def get_file_text(self, file_id):
 
1488
        return ''.join(self.get_file_lines(file_id))
1751
1489
 
1752
1490
    def get_reference_revision(self, file_id, path=None):
1753
1491
        return self.inventory[file_id].reference_revision
1754
1492
 
1755
 
    def iter_files_bytes(self, desired_files):
1756
 
        """See Tree.iter_files_bytes.
1757
 
 
1758
 
        This version is implemented on top of Repository.iter_files_bytes"""
1759
 
        parent_index = self._get_parent_index()
1760
 
        repo_desired_files = []
1761
 
        for file_id, identifier in desired_files:
1762
 
            entry = self._get_entry(file_id)
1763
 
            if entry == (None, None):
1764
 
                raise errors.NoSuchId(self, file_id)
1765
 
            repo_desired_files.append((file_id, entry[1][parent_index][4],
1766
 
                                       identifier))
1767
 
        return self._repository.iter_files_bytes(repo_desired_files)
1768
 
 
1769
1493
    def get_symlink_target(self, file_id):
1770
1494
        entry = self._get_entry(file_id=file_id)
1771
1495
        parent_index = self._get_parent_index()
1772
1496
        if entry[1][parent_index][0] != 'l':
1773
1497
            return None
1774
1498
        else:
1775
 
            target = entry[1][parent_index][1]
1776
 
            target = target.decode('utf8')
1777
 
            return target
 
1499
            # At present, none of the tree implementations supports non-ascii
 
1500
            # symlink targets. So we will just assume that the dirstate path is
 
1501
            # correct.
 
1502
            return entry[1][parent_index][1]
1778
1503
 
1779
1504
    def get_revision_id(self):
1780
1505
        """Return the revision id for this tree."""
1798
1523
        return bool(self.path2id(filename))
1799
1524
 
1800
1525
    def kind(self, file_id):
1801
 
        entry = self._get_entry(file_id=file_id)[1]
1802
 
        if entry is None:
1803
 
            raise errors.NoSuchId(tree=self, file_id=file_id)
1804
 
        return dirstate.DirState._minikind_to_kind[entry[1][0]]
1805
 
 
1806
 
    def stored_kind(self, file_id):
1807
 
        """See Tree.stored_kind"""
1808
 
        return self.kind(file_id)
1809
 
 
1810
 
    def path_content_summary(self, path):
1811
 
        """See Tree.path_content_summary."""
1812
 
        id = self.inventory.path2id(path)
1813
 
        if id is None:
1814
 
            return ('missing', None, None, None)
1815
 
        entry = self._inventory[id]
1816
 
        kind = entry.kind
1817
 
        if kind == 'file':
1818
 
            return (kind, entry.text_size, entry.executable, entry.text_sha1)
1819
 
        elif kind == 'symlink':
1820
 
            return (kind, None, None, entry.symlink_target)
1821
 
        else:
1822
 
            return (kind, None, None, None)
 
1526
        return self.inventory[file_id].kind
1823
1527
 
1824
1528
    def is_executable(self, file_id, path=None):
1825
1529
        ie = self.inventory[file_id]
1827
1531
            return None
1828
1532
        return ie.executable
1829
1533
 
1830
 
    def list_files(self, include_root=False, from_dir=None, recursive=True):
 
1534
    def list_files(self, include_root=False):
1831
1535
        # We use a standard implementation, because DirStateRevisionTree is
1832
1536
        # dealing with one of the parents of the current state
1833
1537
        inv = self._get_inventory()
1834
 
        if from_dir is None:
1835
 
            from_dir_id = None
1836
 
        else:
1837
 
            from_dir_id = inv.path2id(from_dir)
1838
 
            if from_dir_id is None:
1839
 
                # Directory not versioned
1840
 
                return
1841
 
        entries = inv.iter_entries(from_dir=from_dir_id, recursive=recursive)
1842
 
        if inv.root is not None and not include_root and from_dir is None:
 
1538
        entries = inv.iter_entries()
 
1539
        if self.inventory.root is not None and not include_root:
1843
1540
            entries.next()
1844
1541
        for path, entry in entries:
1845
1542
            yield path, 'V', entry.kind, entry.file_id, entry
1878
1575
                self._dirstate_locked = False
1879
1576
            self._repository.unlock()
1880
1577
 
1881
 
    @needs_read_lock
1882
 
    def supports_tree_reference(self):
1883
 
        return self._repo_supports_tree_reference
1884
 
 
1885
1578
    def walkdirs(self, prefix=""):
1886
1579
        # TODO: jam 20070215 This is the lazy way by using the RevisionTree
1887
 
        # implementation based on an inventory.
 
1580
        # implementation based on an inventory.  
1888
1581
        # This should be cleaned up to use the much faster Dirstate code
1889
1582
        # So for now, we just build up the parent inventory, and extract
1890
1583
        # it the same way RevisionTree does.
1919
1612
 
1920
1613
class InterDirStateTree(InterTree):
1921
1614
    """Fast path optimiser for changes_from with dirstate trees.
1922
 
 
1923
 
    This is used only when both trees are in the dirstate working file, and
1924
 
    the source is any parent within the dirstate, and the destination is
 
1615
    
 
1616
    This is used only when both trees are in the dirstate working file, and 
 
1617
    the source is any parent within the dirstate, and the destination is 
1925
1618
    the current working tree of the same dirstate.
1926
1619
    """
1927
1620
    # this could be generalized to allow comparisons between any trees in the
1940
1633
        target.set_parent_ids([revid])
1941
1634
        return target.basis_tree(), target
1942
1635
 
1943
 
    @classmethod
1944
 
    def make_source_parent_tree_python_dirstate(klass, test_case, source, target):
1945
 
        result = klass.make_source_parent_tree(source, target)
1946
 
        result[1]._iter_changes = dirstate.ProcessEntryPython
1947
 
        return result
1948
 
 
1949
 
    @classmethod
1950
 
    def make_source_parent_tree_compiled_dirstate(klass, test_case, source, target):
1951
 
        from bzrlib.tests.test__dirstate_helpers import \
1952
 
            CompiledDirstateHelpersFeature
1953
 
        if not CompiledDirstateHelpersFeature.available():
1954
 
            from bzrlib.tests import UnavailableFeature
1955
 
            raise UnavailableFeature(CompiledDirstateHelpersFeature)
1956
 
        from bzrlib._dirstate_helpers_pyx import ProcessEntryC
1957
 
        result = klass.make_source_parent_tree(source, target)
1958
 
        result[1]._iter_changes = ProcessEntryC
1959
 
        return result
1960
 
 
1961
1636
    _matching_from_tree_format = WorkingTreeFormat4()
1962
1637
    _matching_to_tree_format = WorkingTreeFormat4()
1963
 
 
1964
 
    @classmethod
1965
 
    def _test_mutable_trees_to_test_trees(klass, test_case, source, target):
1966
 
        # This method shouldn't be called, because we have python and C
1967
 
        # specific flavours.
1968
 
        raise NotImplementedError
1969
 
 
1970
 
    def iter_changes(self, include_unchanged=False,
 
1638
    _test_mutable_trees_to_test_trees = make_source_parent_tree
 
1639
 
 
1640
    def _iter_changes(self, include_unchanged=False,
1971
1641
                      specific_files=None, pb=None, extra_trees=[],
1972
1642
                      require_versioned=True, want_unversioned=False):
1973
1643
        """Return the changes from source to target.
1974
1644
 
1975
 
        :return: An iterator that yields tuples. See InterTree.iter_changes
 
1645
        :return: An iterator that yields tuples. See InterTree._iter_changes
1976
1646
            for details.
1977
1647
        :param specific_files: An optional list of file paths to restrict the
1978
1648
            comparison to. When mapping filenames to ids, all matches in all
1989
1659
            output. An unversioned file is defined as one with (False, False)
1990
1660
            for the versioned pair.
1991
1661
        """
 
1662
        utf8_decode_or_none = cache_utf8._utf8_decode_with_None
 
1663
        _minikind_to_kind = dirstate.DirState._minikind_to_kind
1992
1664
        # NB: show_status depends on being able to pass in non-versioned files
1993
1665
        # and report them as unknown
1994
1666
        # TODO: handle extra trees in the dirstate.
1995
 
        if (extra_trees or specific_files == []):
 
1667
        # TODO: handle comparisons as an empty tree as a different special
 
1668
        # case? mbp 20070226
 
1669
        if extra_trees or (self.source._revision_id == NULL_REVISION):
1996
1670
            # we can't fast-path these cases (yet)
1997
 
            return super(InterDirStateTree, self).iter_changes(
 
1671
            for f in super(InterDirStateTree, self)._iter_changes(
1998
1672
                include_unchanged, specific_files, pb, extra_trees,
1999
 
                require_versioned, want_unversioned=want_unversioned)
 
1673
                require_versioned, want_unversioned=want_unversioned):
 
1674
                yield f
 
1675
            return
2000
1676
        parent_ids = self.target.get_parent_ids()
2001
 
        if not (self.source._revision_id in parent_ids
2002
 
                or self.source._revision_id == _mod_revision.NULL_REVISION):
2003
 
            raise AssertionError(
2004
 
                "revision {%s} is not stored in {%s}, but %s "
2005
 
                "can only be used for trees stored in the dirstate"
2006
 
                % (self.source._revision_id, self.target, self.iter_changes))
 
1677
        assert (self.source._revision_id in parent_ids), \
 
1678
                "revision {%s} is not stored in {%s}, but %s " \
 
1679
                "can only be used for trees stored in the dirstate" \
 
1680
                % (self.source._revision_id, self.target, self._iter_changes)
2007
1681
        target_index = 0
2008
 
        if self.source._revision_id == _mod_revision.NULL_REVISION:
 
1682
        if self.source._revision_id == NULL_REVISION:
2009
1683
            source_index = None
2010
1684
            indices = (target_index,)
2011
1685
        else:
2012
 
            if not (self.source._revision_id in parent_ids):
2013
 
                raise AssertionError(
2014
 
                    "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
2015
 
                    self.source._revision_id, parent_ids))
 
1686
            assert (self.source._revision_id in parent_ids), \
 
1687
                "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
 
1688
                self.source._revision_id, parent_ids)
2016
1689
            source_index = 1 + parent_ids.index(self.source._revision_id)
2017
 
            indices = (source_index, target_index)
 
1690
            indices = (source_index,target_index)
2018
1691
        # -- make all specific_files utf8 --
2019
1692
        if specific_files:
2020
1693
            specific_files_utf8 = set()
2021
1694
            for path in specific_files:
2022
 
                # Note, if there are many specific files, using cache_utf8
2023
 
                # would be good here.
2024
1695
                specific_files_utf8.add(path.encode('utf8'))
2025
1696
            specific_files = specific_files_utf8
2026
1697
        else:
2027
1698
            specific_files = set([''])
2028
1699
        # -- specific_files is now a utf8 path set --
2029
 
 
2030
1700
        # -- get the state object and prepare it.
2031
1701
        state = self.target.current_dirstate()
2032
1702
        state._read_dirblocks_if_needed()
 
1703
        def _entries_for_path(path):
 
1704
            """Return a list with all the entries that match path for all ids.
 
1705
            """
 
1706
            dirname, basename = os.path.split(path)
 
1707
            key = (dirname, basename, '')
 
1708
            block_index, present = state._find_block_index_from_key(key)
 
1709
            if not present:
 
1710
                # the block which should contain path is absent.
 
1711
                return []
 
1712
            result = []
 
1713
            block = state._dirblocks[block_index][1]
 
1714
            entry_index, _ = state._find_entry_index(key, block)
 
1715
            # we may need to look at multiple entries at this path: walk while the specific_files match.
 
1716
            while (entry_index < len(block) and
 
1717
                block[entry_index][0][0:2] == key[0:2]):
 
1718
                result.append(block[entry_index])
 
1719
                entry_index += 1
 
1720
            return result
2033
1721
        if require_versioned:
2034
1722
            # -- check all supplied paths are versioned in a search tree. --
2035
 
            not_versioned = []
 
1723
            all_versioned = True
2036
1724
            for path in specific_files:
2037
 
                path_entries = state._entries_for_path(path)
 
1725
                path_entries = _entries_for_path(path)
2038
1726
                if not path_entries:
2039
1727
                    # this specified path is not present at all: error
2040
 
                    not_versioned.append(path)
2041
 
                    continue
 
1728
                    all_versioned = False
 
1729
                    break
2042
1730
                found_versioned = False
2043
1731
                # for each id at this path
2044
1732
                for entry in path_entries:
2051
1739
                if not found_versioned:
2052
1740
                    # none of the indexes was not 'absent' at all ids for this
2053
1741
                    # path.
2054
 
                    not_versioned.append(path)
2055
 
            if len(not_versioned) > 0:
2056
 
                raise errors.PathsNotVersionedError(not_versioned)
 
1742
                    all_versioned = False
 
1743
                    break
 
1744
            if not all_versioned:
 
1745
                raise errors.PathsNotVersionedError(specific_files)
2057
1746
        # -- remove redundancy in supplied specific_files to prevent over-scanning --
2058
 
        search_specific_files = osutils.minimum_path_selection(specific_files)
 
1747
        search_specific_files = set()
 
1748
        for path in specific_files:
 
1749
            other_specific_files = specific_files.difference(set([path]))
 
1750
            if not osutils.is_inside_any(other_specific_files, path):
 
1751
                # this is a top level path, we must check it.
 
1752
                search_specific_files.add(path)
 
1753
        # sketch: 
 
1754
        # compare source_index and target_index at or under each element of search_specific_files.
 
1755
        # follow the following comparison table. Note that we only want to do diff operations when
 
1756
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
 
1757
        # for the target.
 
1758
        # cases:
 
1759
        # 
 
1760
        # Source | Target | disk | action
 
1761
        #   r    | fdlt   |      | add source to search, add id path move and perform
 
1762
        #        |        |      | diff check on source-target
 
1763
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
 
1764
        #        |        |      | ???
 
1765
        #   r    |  a     |      | add source to search
 
1766
        #   r    |  a     |  a   | 
 
1767
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
 
1768
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
 
1769
        #   a    | fdlt   |      | add new id
 
1770
        #   a    | fdlt   |  a   | dangling locally added file, skip
 
1771
        #   a    |  a     |      | not present in either tree, skip
 
1772
        #   a    |  a     |  a   | not present in any tree, skip
 
1773
        #   a    |  r     |      | not present in either tree at this path, skip as it
 
1774
        #        |        |      | may not be selected by the users list of paths.
 
1775
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
 
1776
        #        |        |      | may not be selected by the users list of paths.
 
1777
        #  fdlt  | fdlt   |      | content in both: diff them
 
1778
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
 
1779
        #  fdlt  |  a     |      | unversioned: output deleted id for now
 
1780
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
 
1781
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
 
1782
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1783
        #        |        |      | this id at the other path.
 
1784
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
 
1785
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
 
1786
        #        |        |      | this id at the other path.
 
1787
 
 
1788
        # for all search_indexs in each path at or under each element of
 
1789
        # search_specific_files, if the detail is relocated: add the id, and add the
 
1790
        # relocated path as one to search if its not searched already. If the
 
1791
        # detail is not relocated, add the id.
 
1792
        searched_specific_files = set()
 
1793
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
 
1794
        # Using a list so that we can access the values and change them in
 
1795
        # nested scope. Each one is [path, file_id, entry]
 
1796
        last_source_parent = [None, None, None]
 
1797
        last_target_parent = [None, None, None]
2059
1798
 
2060
1799
        use_filesystem_for_exec = (sys.platform != 'win32')
2061
 
        iter_changes = self.target._iter_changes(include_unchanged,
2062
 
            use_filesystem_for_exec, search_specific_files, state,
2063
 
            source_index, target_index, want_unversioned, self.target)
2064
 
        return iter_changes.iter_changes()
 
1800
 
 
1801
        def _process_entry(entry, path_info):
 
1802
            """Compare an entry and real disk to generate delta information.
 
1803
 
 
1804
            :param path_info: top_relpath, basename, kind, lstat, abspath for
 
1805
                the path of entry. If None, then the path is considered absent.
 
1806
                (Perhaps we should pass in a concrete entry for this ?)
 
1807
                Basename is returned as a utf8 string because we expect this
 
1808
                tuple will be ignored, and don't want to take the time to
 
1809
                decode.
 
1810
            """
 
1811
            if source_index is None:
 
1812
                source_details = NULL_PARENT_DETAILS
 
1813
            else:
 
1814
                source_details = entry[1][source_index]
 
1815
            target_details = entry[1][target_index]
 
1816
            target_minikind = target_details[0]
 
1817
            if path_info is not None and target_minikind in 'fdlt':
 
1818
                assert target_index == 0
 
1819
                link_or_sha1 = state.update_entry(entry, abspath=path_info[4],
 
1820
                                                  stat_value=path_info[3])
 
1821
                # The entry may have been modified by update_entry
 
1822
                target_details = entry[1][target_index]
 
1823
                target_minikind = target_details[0]
 
1824
            else:
 
1825
                link_or_sha1 = None
 
1826
            source_minikind = source_details[0]
 
1827
            if source_minikind in 'fdltr' and target_minikind in 'fdlt':
 
1828
                # claimed content in both: diff
 
1829
                #   r    | fdlt   |      | add source to search, add id path move and perform
 
1830
                #        |        |      | diff check on source-target
 
1831
                #   r    | fdlt   |  a   | dangling file that was present in the basis.
 
1832
                #        |        |      | ???
 
1833
                if source_minikind in 'r':
 
1834
                    # add the source to the search path to find any children it
 
1835
                    # has.  TODO ? : only add if it is a container ?
 
1836
                    if not osutils.is_inside_any(searched_specific_files,
 
1837
                                                 source_details[1]):
 
1838
                        search_specific_files.add(source_details[1])
 
1839
                    # generate the old path; this is needed for stating later
 
1840
                    # as well.
 
1841
                    old_path = source_details[1]
 
1842
                    old_dirname, old_basename = os.path.split(old_path)
 
1843
                    path = pathjoin(entry[0][0], entry[0][1])
 
1844
                    old_entry = state._get_entry(source_index,
 
1845
                                                 path_utf8=old_path)
 
1846
                    # update the source details variable to be the real
 
1847
                    # location.
 
1848
                    source_details = old_entry[1][source_index]
 
1849
                    source_minikind = source_details[0]
 
1850
                else:
 
1851
                    old_dirname = entry[0][0]
 
1852
                    old_basename = entry[0][1]
 
1853
                    old_path = path = pathjoin(old_dirname, old_basename)
 
1854
                if path_info is None:
 
1855
                    # the file is missing on disk, show as removed.
 
1856
                    content_change = True
 
1857
                    target_kind = None
 
1858
                    target_exec = False
 
1859
                else:
 
1860
                    # source and target are both versioned and disk file is present.
 
1861
                    target_kind = path_info[2]
 
1862
                    if target_kind == 'directory':
 
1863
                        if source_minikind != 'd':
 
1864
                            content_change = True
 
1865
                        else:
 
1866
                            # directories have no fingerprint
 
1867
                            content_change = False
 
1868
                        target_exec = False
 
1869
                    elif target_kind == 'file':
 
1870
                        if source_minikind != 'f':
 
1871
                            content_change = True
 
1872
                        else:
 
1873
                            # We could check the size, but we already have the
 
1874
                            # sha1 hash.
 
1875
                            content_change = (link_or_sha1 != source_details[1])
 
1876
                        # Target details is updated at update_entry time
 
1877
                        if use_filesystem_for_exec:
 
1878
                            # We don't need S_ISREG here, because we are sure
 
1879
                            # we are dealing with a file.
 
1880
                            target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
 
1881
                        else:
 
1882
                            target_exec = target_details[3]
 
1883
                    elif target_kind == 'symlink':
 
1884
                        if source_minikind != 'l':
 
1885
                            content_change = True
 
1886
                        else:
 
1887
                            content_change = (link_or_sha1 != source_details[1])
 
1888
                        target_exec = False
 
1889
                    elif target_kind == 'tree-reference':
 
1890
                        if source_minikind != 't':
 
1891
                            content_change = True
 
1892
                        else:
 
1893
                            content_change = False
 
1894
                        target_exec = False
 
1895
                    else:
 
1896
                        raise Exception, "unknown kind %s" % path_info[2]
 
1897
                # parent id is the entry for the path in the target tree
 
1898
                if old_dirname == last_source_parent[0]:
 
1899
                    source_parent_id = last_source_parent[1]
 
1900
                else:
 
1901
                    source_parent_entry = state._get_entry(source_index,
 
1902
                                                           path_utf8=old_dirname)
 
1903
                    source_parent_id = source_parent_entry[0][2]
 
1904
                    if source_parent_id == entry[0][2]:
 
1905
                        # This is the root, so the parent is None
 
1906
                        source_parent_id = None
 
1907
                    else:
 
1908
                        last_source_parent[0] = old_dirname
 
1909
                        last_source_parent[1] = source_parent_id
 
1910
                        last_source_parent[2] = source_parent_entry
 
1911
                new_dirname = entry[0][0]
 
1912
                if new_dirname == last_target_parent[0]:
 
1913
                    target_parent_id = last_target_parent[1]
 
1914
                else:
 
1915
                    # TODO: We don't always need to do the lookup, because the
 
1916
                    #       parent entry will be the same as the source entry.
 
1917
                    target_parent_entry = state._get_entry(target_index,
 
1918
                                                           path_utf8=new_dirname)
 
1919
                    target_parent_id = target_parent_entry[0][2]
 
1920
                    if target_parent_id == entry[0][2]:
 
1921
                        # This is the root, so the parent is None
 
1922
                        target_parent_id = None
 
1923
                    else:
 
1924
                        last_target_parent[0] = new_dirname
 
1925
                        last_target_parent[1] = target_parent_id
 
1926
                        last_target_parent[2] = target_parent_entry
 
1927
 
 
1928
                source_exec = source_details[3]
 
1929
                return ((entry[0][2], (old_path, path), content_change,
 
1930
                        (True, True),
 
1931
                        (source_parent_id, target_parent_id),
 
1932
                        (old_basename, entry[0][1]),
 
1933
                        (_minikind_to_kind[source_minikind], target_kind),
 
1934
                        (source_exec, target_exec)),)
 
1935
            elif source_minikind in 'a' and target_minikind in 'fdlt':
 
1936
                # looks like a new file
 
1937
                if path_info is not None:
 
1938
                    path = pathjoin(entry[0][0], entry[0][1])
 
1939
                    # parent id is the entry for the path in the target tree
 
1940
                    # TODO: these are the same for an entire directory: cache em.
 
1941
                    parent_id = state._get_entry(target_index,
 
1942
                                                 path_utf8=entry[0][0])[0][2]
 
1943
                    if parent_id == entry[0][2]:
 
1944
                        parent_id = None
 
1945
                    if use_filesystem_for_exec:
 
1946
                        # We need S_ISREG here, because we aren't sure if this
 
1947
                        # is a file or not.
 
1948
                        target_exec = bool(
 
1949
                            stat.S_ISREG(path_info[3].st_mode)
 
1950
                            and stat.S_IEXEC & path_info[3].st_mode)
 
1951
                    else:
 
1952
                        target_exec = target_details[3]
 
1953
                    return ((entry[0][2], (None, path), True,
 
1954
                            (False, True),
 
1955
                            (None, parent_id),
 
1956
                            (None, entry[0][1]),
 
1957
                            (None, path_info[2]),
 
1958
                            (None, target_exec)),)
 
1959
                else:
 
1960
                    # but its not on disk: we deliberately treat this as just
 
1961
                    # never-present. (Why ?! - RBC 20070224)
 
1962
                    pass
 
1963
            elif source_minikind in 'fdlt' and target_minikind in 'a':
 
1964
                # unversioned, possibly, or possibly not deleted: we dont care.
 
1965
                # if its still on disk, *and* theres no other entry at this
 
1966
                # path [we dont know this in this routine at the moment -
 
1967
                # perhaps we should change this - then it would be an unknown.
 
1968
                old_path = pathjoin(entry[0][0], entry[0][1])
 
1969
                # parent id is the entry for the path in the target tree
 
1970
                parent_id = state._get_entry(source_index, path_utf8=entry[0][0])[0][2]
 
1971
                if parent_id == entry[0][2]:
 
1972
                    parent_id = None
 
1973
                return ((entry[0][2], (old_path, None), True,
 
1974
                        (True, False),
 
1975
                        (parent_id, None),
 
1976
                        (entry[0][1], None),
 
1977
                        (_minikind_to_kind[source_minikind], None),
 
1978
                        (source_details[3], None)),)
 
1979
            elif source_minikind in 'fdlt' and target_minikind in 'r':
 
1980
                # a rename; could be a true rename, or a rename inherited from
 
1981
                # a renamed parent. TODO: handle this efficiently. Its not
 
1982
                # common case to rename dirs though, so a correct but slow
 
1983
                # implementation will do.
 
1984
                if not osutils.is_inside_any(searched_specific_files, target_details[1]):
 
1985
                    search_specific_files.add(target_details[1])
 
1986
            elif source_minikind in 'ra' and target_minikind in 'ra':
 
1987
                # neither of the selected trees contain this file,
 
1988
                # so skip over it. This is not currently directly tested, but
 
1989
                # is indirectly via test_too_much.TestCommands.test_conflicts.
 
1990
                pass
 
1991
            else:
 
1992
                raise AssertionError("don't know how to compare "
 
1993
                    "source_minikind=%r, target_minikind=%r"
 
1994
                    % (source_minikind, target_minikind))
 
1995
                ## import pdb;pdb.set_trace()
 
1996
            return ()
 
1997
 
 
1998
        while search_specific_files:
 
1999
            # TODO: the pending list should be lexically sorted?  the
 
2000
            # interface doesn't require it.
 
2001
            current_root = search_specific_files.pop()
 
2002
            current_root_unicode = current_root.decode('utf8')
 
2003
            searched_specific_files.add(current_root)
 
2004
            # process the entries for this containing directory: the rest will be
 
2005
            # found by their parents recursively.
 
2006
            root_entries = _entries_for_path(current_root)
 
2007
            root_abspath = self.target.abspath(current_root_unicode)
 
2008
            try:
 
2009
                root_stat = os.lstat(root_abspath)
 
2010
            except OSError, e:
 
2011
                if e.errno == errno.ENOENT:
 
2012
                    # the path does not exist: let _process_entry know that.
 
2013
                    root_dir_info = None
 
2014
                else:
 
2015
                    # some other random error: hand it up.
 
2016
                    raise
 
2017
            else:
 
2018
                root_dir_info = ('', current_root,
 
2019
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
 
2020
                    root_abspath)
 
2021
                if root_dir_info[2] == 'directory':
 
2022
                    if self.target._directory_is_tree_reference(
 
2023
                        current_root.decode('utf8')):
 
2024
                        root_dir_info = root_dir_info[:2] + \
 
2025
                            ('tree-reference',) + root_dir_info[3:]
 
2026
 
 
2027
            if not root_entries and not root_dir_info:
 
2028
                # this specified path is not present at all, skip it.
 
2029
                continue
 
2030
            path_handled = False
 
2031
            for entry in root_entries:
 
2032
                for result in _process_entry(entry, root_dir_info):
 
2033
                    # this check should probably be outside the loop: one
 
2034
                    # 'iterate two trees' api, and then _iter_changes filters
 
2035
                    # unchanged pairs. - RBC 20070226
 
2036
                    path_handled = True
 
2037
                    if (include_unchanged
 
2038
                        or result[2]                    # content change
 
2039
                        or result[3][0] != result[3][1] # versioned status
 
2040
                        or result[4][0] != result[4][1] # parent id
 
2041
                        or result[5][0] != result[5][1] # name
 
2042
                        or result[6][0] != result[6][1] # kind
 
2043
                        or result[7][0] != result[7][1] # executable
 
2044
                        ):
 
2045
                        yield (result[0],
 
2046
                               (utf8_decode_or_none(result[1][0]),
 
2047
                                utf8_decode_or_none(result[1][1])),
 
2048
                               result[2],
 
2049
                               result[3],
 
2050
                               result[4],
 
2051
                               (utf8_decode_or_none(result[5][0]),
 
2052
                                utf8_decode_or_none(result[5][1])),
 
2053
                               result[6],
 
2054
                               result[7],
 
2055
                              )
 
2056
            if want_unversioned and not path_handled and root_dir_info:
 
2057
                new_executable = bool(
 
2058
                    stat.S_ISREG(root_dir_info[3].st_mode)
 
2059
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
 
2060
                yield (None,
 
2061
                       (None, current_root_unicode),
 
2062
                       True,
 
2063
                       (False, False),
 
2064
                       (None, None),
 
2065
                       (None, splitpath(current_root_unicode)[-1]),
 
2066
                       (None, root_dir_info[2]),
 
2067
                       (None, new_executable)
 
2068
                      )
 
2069
            initial_key = (current_root, '', '')
 
2070
            block_index, _ = state._find_block_index_from_key(initial_key)
 
2071
            if block_index == 0:
 
2072
                # we have processed the total root already, but because the
 
2073
                # initial key matched it we should skip it here.
 
2074
                block_index +=1
 
2075
            if root_dir_info and root_dir_info[2] == 'tree-reference':
 
2076
                current_dir_info = None
 
2077
            else:
 
2078
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
 
2079
                try:
 
2080
                    current_dir_info = dir_iterator.next()
 
2081
                except OSError, e:
 
2082
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
 
2083
                    # python 2.5 has e.errno == EINVAL,
 
2084
                    #            and e.winerror == ERROR_DIRECTORY
 
2085
                    e_winerror = getattr(e, 'winerror', None)
 
2086
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
 
2087
                    # there may be directories in the inventory even though
 
2088
                    # this path is not a file on disk: so mark it as end of
 
2089
                    # iterator
 
2090
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
 
2091
                        current_dir_info = None
 
2092
                    elif (sys.platform == 'win32'
 
2093
                          and (e.errno in win_errors
 
2094
                               or e_winerror in win_errors)):
 
2095
                        current_dir_info = None
 
2096
                    else:
 
2097
                        raise
 
2098
                else:
 
2099
                    if current_dir_info[0][0] == '':
 
2100
                        # remove .bzr from iteration
 
2101
                        bzr_index = bisect_left(current_dir_info[1], ('.bzr',))
 
2102
                        assert current_dir_info[1][bzr_index][0] == '.bzr'
 
2103
                        del current_dir_info[1][bzr_index]
 
2104
            # walk until both the directory listing and the versioned metadata
 
2105
            # are exhausted. 
 
2106
            if (block_index < len(state._dirblocks) and
 
2107
                osutils.is_inside(current_root, state._dirblocks[block_index][0])):
 
2108
                current_block = state._dirblocks[block_index]
 
2109
            else:
 
2110
                current_block = None
 
2111
            while (current_dir_info is not None or
 
2112
                   current_block is not None):
 
2113
                if (current_dir_info and current_block
 
2114
                    and current_dir_info[0][0] != current_block[0]):
 
2115
                    if current_dir_info[0][0] < current_block[0] :
 
2116
                        # filesystem data refers to paths not covered by the dirblock.
 
2117
                        # this has two possibilities:
 
2118
                        # A) it is versioned but empty, so there is no block for it
 
2119
                        # B) it is not versioned.
 
2120
                        # in either case it was processed by the containing directories walk:
 
2121
                        # if it is root/foo, when we walked root we emitted it,
 
2122
                        # or if we ere given root/foo to walk specifically, we
 
2123
                        # emitted it when checking the walk-root entries
 
2124
                        # advance the iterator and loop - we dont need to emit it.
 
2125
                        try:
 
2126
                            current_dir_info = dir_iterator.next()
 
2127
                        except StopIteration:
 
2128
                            current_dir_info = None
 
2129
                    else:
 
2130
                        # We have a dirblock entry for this location, but there
 
2131
                        # is no filesystem path for this. This is most likely
 
2132
                        # because a directory was removed from the disk.
 
2133
                        # We don't have to report the missing directory,
 
2134
                        # because that should have already been handled, but we
 
2135
                        # need to handle all of the files that are contained
 
2136
                        # within.
 
2137
                        for current_entry in current_block[1]:
 
2138
                            # entry referring to file not present on disk.
 
2139
                            # advance the entry only, after processing.
 
2140
                            for result in _process_entry(current_entry, None):
 
2141
                                # this check should probably be outside the loop: one
 
2142
                                # 'iterate two trees' api, and then _iter_changes filters
 
2143
                                # unchanged pairs. - RBC 20070226
 
2144
                                if (include_unchanged
 
2145
                                    or result[2]                    # content change
 
2146
                                    or result[3][0] != result[3][1] # versioned status
 
2147
                                    or result[4][0] != result[4][1] # parent id
 
2148
                                    or result[5][0] != result[5][1] # name
 
2149
                                    or result[6][0] != result[6][1] # kind
 
2150
                                    or result[7][0] != result[7][1] # executable
 
2151
                                    ):
 
2152
                                    yield (result[0],
 
2153
                                           (utf8_decode_or_none(result[1][0]),
 
2154
                                            utf8_decode_or_none(result[1][1])),
 
2155
                                           result[2],
 
2156
                                           result[3],
 
2157
                                           result[4],
 
2158
                                           (utf8_decode_or_none(result[5][0]),
 
2159
                                            utf8_decode_or_none(result[5][1])),
 
2160
                                           result[6],
 
2161
                                           result[7],
 
2162
                                          )
 
2163
                        block_index +=1
 
2164
                        if (block_index < len(state._dirblocks) and
 
2165
                            osutils.is_inside(current_root,
 
2166
                                              state._dirblocks[block_index][0])):
 
2167
                            current_block = state._dirblocks[block_index]
 
2168
                        else:
 
2169
                            current_block = None
 
2170
                    continue
 
2171
                entry_index = 0
 
2172
                if current_block and entry_index < len(current_block[1]):
 
2173
                    current_entry = current_block[1][entry_index]
 
2174
                else:
 
2175
                    current_entry = None
 
2176
                advance_entry = True
 
2177
                path_index = 0
 
2178
                if current_dir_info and path_index < len(current_dir_info[1]):
 
2179
                    current_path_info = current_dir_info[1][path_index]
 
2180
                    if current_path_info[2] == 'directory':
 
2181
                        if self.target._directory_is_tree_reference(
 
2182
                            current_path_info[0].decode('utf8')):
 
2183
                            current_path_info = current_path_info[:2] + \
 
2184
                                ('tree-reference',) + current_path_info[3:]
 
2185
                else:
 
2186
                    current_path_info = None
 
2187
                advance_path = True
 
2188
                path_handled = False
 
2189
                while (current_entry is not None or
 
2190
                    current_path_info is not None):
 
2191
                    if current_entry is None:
 
2192
                        # the check for path_handled when the path is adnvaced
 
2193
                        # will yield this path if needed.
 
2194
                        pass
 
2195
                    elif current_path_info is None:
 
2196
                        # no path is fine: the per entry code will handle it.
 
2197
                        for result in _process_entry(current_entry, current_path_info):
 
2198
                            # this check should probably be outside the loop: one
 
2199
                            # 'iterate two trees' api, and then _iter_changes filters
 
2200
                            # unchanged pairs. - RBC 20070226
 
2201
                            if (include_unchanged
 
2202
                                or result[2]                    # content change
 
2203
                                or result[3][0] != result[3][1] # versioned status
 
2204
                                or result[4][0] != result[4][1] # parent id
 
2205
                                or result[5][0] != result[5][1] # name
 
2206
                                or result[6][0] != result[6][1] # kind
 
2207
                                or result[7][0] != result[7][1] # executable
 
2208
                                ):
 
2209
                                yield (result[0],
 
2210
                                       (utf8_decode_or_none(result[1][0]),
 
2211
                                        utf8_decode_or_none(result[1][1])),
 
2212
                                       result[2],
 
2213
                                       result[3],
 
2214
                                       result[4],
 
2215
                                       (utf8_decode_or_none(result[5][0]),
 
2216
                                        utf8_decode_or_none(result[5][1])),
 
2217
                                       result[6],
 
2218
                                       result[7],
 
2219
                                      )
 
2220
                    elif current_entry[0][1] != current_path_info[1]:
 
2221
                        if current_path_info[1] < current_entry[0][1]:
 
2222
                            # extra file on disk: pass for now, but only
 
2223
                            # increment the path, not the entry
 
2224
                            advance_entry = False
 
2225
                        else:
 
2226
                            # entry referring to file not present on disk.
 
2227
                            # advance the entry only, after processing.
 
2228
                            for result in _process_entry(current_entry, None):
 
2229
                                # this check should probably be outside the loop: one
 
2230
                                # 'iterate two trees' api, and then _iter_changes filters
 
2231
                                # unchanged pairs. - RBC 20070226
 
2232
                                path_handled = True
 
2233
                                if (include_unchanged
 
2234
                                    or result[2]                    # content change
 
2235
                                    or result[3][0] != result[3][1] # versioned status
 
2236
                                    or result[4][0] != result[4][1] # parent id
 
2237
                                    or result[5][0] != result[5][1] # name
 
2238
                                    or result[6][0] != result[6][1] # kind
 
2239
                                    or result[7][0] != result[7][1] # executable
 
2240
                                    ):
 
2241
                                    yield (result[0],
 
2242
                                           (utf8_decode_or_none(result[1][0]),
 
2243
                                            utf8_decode_or_none(result[1][1])),
 
2244
                                           result[2],
 
2245
                                           result[3],
 
2246
                                           result[4],
 
2247
                                           (utf8_decode_or_none(result[5][0]),
 
2248
                                            utf8_decode_or_none(result[5][1])),
 
2249
                                           result[6],
 
2250
                                           result[7],
 
2251
                                          )
 
2252
                            advance_path = False
 
2253
                    else:
 
2254
                        for result in _process_entry(current_entry, current_path_info):
 
2255
                            # this check should probably be outside the loop: one
 
2256
                            # 'iterate two trees' api, and then _iter_changes filters
 
2257
                            # unchanged pairs. - RBC 20070226
 
2258
                            path_handled = True
 
2259
                            if (include_unchanged
 
2260
                                or result[2]                    # content change
 
2261
                                or result[3][0] != result[3][1] # versioned status
 
2262
                                or result[4][0] != result[4][1] # parent id
 
2263
                                or result[5][0] != result[5][1] # name
 
2264
                                or result[6][0] != result[6][1] # kind
 
2265
                                or result[7][0] != result[7][1] # executable
 
2266
                                ):
 
2267
                                yield (result[0],
 
2268
                                       (utf8_decode_or_none(result[1][0]),
 
2269
                                        utf8_decode_or_none(result[1][1])),
 
2270
                                       result[2],
 
2271
                                       result[3],
 
2272
                                       result[4],
 
2273
                                       (utf8_decode_or_none(result[5][0]),
 
2274
                                        utf8_decode_or_none(result[5][1])),
 
2275
                                       result[6],
 
2276
                                       result[7],
 
2277
                                      )
 
2278
                    if advance_entry and current_entry is not None:
 
2279
                        entry_index += 1
 
2280
                        if entry_index < len(current_block[1]):
 
2281
                            current_entry = current_block[1][entry_index]
 
2282
                        else:
 
2283
                            current_entry = None
 
2284
                    else:
 
2285
                        advance_entry = True # reset the advance flaga
 
2286
                    if advance_path and current_path_info is not None:
 
2287
                        if not path_handled:
 
2288
                            # unversioned in all regards
 
2289
                            if want_unversioned:
 
2290
                                new_executable = bool(
 
2291
                                    stat.S_ISREG(current_path_info[3].st_mode)
 
2292
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
 
2293
                                if want_unversioned:
 
2294
                                    yield (None,
 
2295
                                        (None, utf8_decode_or_none(current_path_info[0])),
 
2296
                                        True,
 
2297
                                        (False, False),
 
2298
                                        (None, None),
 
2299
                                        (None, utf8_decode_or_none(current_path_info[1])),
 
2300
                                        (None, current_path_info[2]),
 
2301
                                        (None, new_executable))
 
2302
                            # dont descend into this unversioned path if it is
 
2303
                            # a dir
 
2304
                            if current_path_info[2] in ('directory'):
 
2305
                                del current_dir_info[1][path_index]
 
2306
                                path_index -= 1
 
2307
                        # dont descend the disk iterator into any tree 
 
2308
                        # paths.
 
2309
                        if current_path_info[2] == 'tree-reference':
 
2310
                            del current_dir_info[1][path_index]
 
2311
                            path_index -= 1
 
2312
                        path_index += 1
 
2313
                        if path_index < len(current_dir_info[1]):
 
2314
                            current_path_info = current_dir_info[1][path_index]
 
2315
                            if current_path_info[2] == 'directory':
 
2316
                                if self.target._directory_is_tree_reference(
 
2317
                                    current_path_info[0].decode('utf8')):
 
2318
                                    current_path_info = current_path_info[:2] + \
 
2319
                                        ('tree-reference',) + current_path_info[3:]
 
2320
                        else:
 
2321
                            current_path_info = None
 
2322
                        path_handled = False
 
2323
                    else:
 
2324
                        advance_path = True # reset the advance flagg.
 
2325
                if current_block is not None:
 
2326
                    block_index += 1
 
2327
                    if (block_index < len(state._dirblocks) and
 
2328
                        osutils.is_inside(current_root, state._dirblocks[block_index][0])):
 
2329
                        current_block = state._dirblocks[block_index]
 
2330
                    else:
 
2331
                        current_block = None
 
2332
                if current_dir_info is not None:
 
2333
                    try:
 
2334
                        current_dir_info = dir_iterator.next()
 
2335
                    except StopIteration:
 
2336
                        current_dir_info = None
 
2337
 
2065
2338
 
2066
2339
    @staticmethod
2067
2340
    def is_compatible(source, target):
2068
2341
        # the target must be a dirstate working tree
2069
 
        if not isinstance(target, DirStateWorkingTree):
 
2342
        if not isinstance(target, WorkingTree4):
2070
2343
            return False
2071
 
        # the source must be a revtree or dirstate rev tree.
 
2344
        # the source must be a revtreee or dirstate rev tree.
2072
2345
        if not isinstance(source,
2073
2346
            (revisiontree.RevisionTree, DirStateRevisionTree)):
2074
2347
            return False
2075
2348
        # the source revid must be in the target dirstate
2076
 
        if not (source._revision_id == _mod_revision.NULL_REVISION or
 
2349
        if not (source._revision_id == NULL_REVISION or
2077
2350
            source._revision_id in target.get_parent_ids()):
2078
 
            # TODO: what about ghosts? it may well need to
 
2351
            # TODO: what about ghosts? it may well need to 
2079
2352
            # check for them explicitly.
2080
2353
            return False
2081
2354
        return True
2091
2364
 
2092
2365
    def convert(self, tree):
2093
2366
        # lock the control files not the tree, so that we dont get tree
2094
 
        # on-unlock behaviours, and so that noone else diddles with the
 
2367
        # on-unlock behaviours, and so that noone else diddles with the 
2095
2368
        # tree during upgrade.
2096
2369
        tree._control_files.lock_write()
2097
2370
        try:
2123
2396
 
2124
2397
    def update_format(self, tree):
2125
2398
        """Change the format marker."""
2126
 
        tree._transport.put_bytes('format',
2127
 
            self.target_format.get_format_string(),
2128
 
            mode=tree.bzrdir._get_file_mode())
2129
 
 
2130
 
 
2131
 
class Converter4to5(object):
2132
 
    """Perform an in-place upgrade of format 4 to format 5 trees."""
2133
 
 
2134
 
    def __init__(self):
2135
 
        self.target_format = WorkingTreeFormat5()
2136
 
 
2137
 
    def convert(self, tree):
2138
 
        # lock the control files not the tree, so that we don't get tree
2139
 
        # on-unlock behaviours, and so that no-one else diddles with the
2140
 
        # tree during upgrade.
2141
 
        tree._control_files.lock_write()
2142
 
        try:
2143
 
            self.update_format(tree)
2144
 
        finally:
2145
 
            tree._control_files.unlock()
2146
 
 
2147
 
    def update_format(self, tree):
2148
 
        """Change the format marker."""
2149
 
        tree._transport.put_bytes('format',
2150
 
            self.target_format.get_format_string(),
2151
 
            mode=tree.bzrdir._get_file_mode())
2152
 
 
2153
 
 
2154
 
class Converter4or5to6(object):
2155
 
    """Perform an in-place upgrade of format 4 or 5 to format 6 trees."""
2156
 
 
2157
 
    def __init__(self):
2158
 
        self.target_format = WorkingTreeFormat6()
2159
 
 
2160
 
    def convert(self, tree):
2161
 
        # lock the control files not the tree, so that we don't get tree
2162
 
        # on-unlock behaviours, and so that no-one else diddles with the
2163
 
        # tree during upgrade.
2164
 
        tree._control_files.lock_write()
2165
 
        try:
2166
 
            self.init_custom_control_files(tree)
2167
 
            self.update_format(tree)
2168
 
        finally:
2169
 
            tree._control_files.unlock()
2170
 
 
2171
 
    def init_custom_control_files(self, tree):
2172
 
        """Initialize custom control files."""
2173
 
        tree._transport.put_bytes('views', '',
2174
 
            mode=tree.bzrdir._get_file_mode())
2175
 
 
2176
 
    def update_format(self, tree):
2177
 
        """Change the format marker."""
2178
 
        tree._transport.put_bytes('format',
2179
 
            self.target_format.get_format_string(),
2180
 
            mode=tree.bzrdir._get_file_mode())
 
2399
        tree._control_files.put_utf8('format',
 
2400
            self.target_format.get_format_string())