/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

merge bzr.dev.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""WorkingTree4 format and implementation.
18
18
 
43
43
    bzrdir,
44
44
    cache_utf8,
45
45
    conflicts as _mod_conflicts,
 
46
    debug,
46
47
    delta,
47
48
    dirstate,
48
49
    errors,
49
50
    generate_ids,
50
51
    globbing,
51
 
    hashcache,
52
52
    ignores,
53
53
    merge,
54
54
    osutils,
55
55
    revision as _mod_revision,
56
56
    revisiontree,
57
57
    textui,
 
58
    trace,
58
59
    transform,
59
60
    urlutils,
 
61
    views,
60
62
    xml5,
61
63
    xml6,
62
64
    )
67
69
 
68
70
from bzrlib import symbol_versioning
69
71
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
72
from bzrlib.filters import filtered_input_file, internal_size_sha_file_byname
70
73
from bzrlib.inventory import InventoryEntry, Inventory, ROOT_ID, entry_factory
71
 
from bzrlib.lockable_files import LockableFiles, TransportLock
72
 
from bzrlib.lockdir import LockDir
73
74
import bzrlib.mutabletree
74
75
from bzrlib.mutabletree import needs_tree_write_lock
75
76
from bzrlib.osutils import (
97
98
from bzrlib.workingtree import WorkingTree, WorkingTree3, WorkingTreeFormat3
98
99
 
99
100
 
100
 
# This is the Windows equivalent of ENOTDIR
101
 
# It is defined in pywin32.winerror, but we don't want a strong dependency for
102
 
# just an error code.
103
 
ERROR_PATH_NOT_FOUND = 3
104
 
ERROR_DIRECTORY = 267
105
 
 
106
 
 
107
 
class WorkingTree4(WorkingTree3):
108
 
    """This is the Format 4 working tree.
109
 
 
110
 
    This differs from WorkingTree3 by:
111
 
     - Having a consolidated internal dirstate, stored in a
112
 
       randomly-accessible sorted file on disk.
113
 
     - Not having a regular inventory attribute.  One can be synthesized 
114
 
       on demand but this is expensive and should be avoided.
115
 
 
116
 
    This is new in bzr 0.15.
117
 
    """
118
 
 
 
101
class DirStateWorkingTree(WorkingTree3):
119
102
    def __init__(self, basedir,
120
103
                 branch,
121
104
                 _control_files=None,
130
113
        """
131
114
        self._format = _format
132
115
        self.bzrdir = _bzrdir
133
 
        from bzrlib.trace import note, mutter
134
 
        assert isinstance(basedir, basestring), \
135
 
            "base directory %r is not a string" % basedir
136
116
        basedir = safe_unicode(basedir)
137
117
        mutter("opening working tree %r", basedir)
138
118
        self._branch = branch
139
 
        assert isinstance(self.branch, bzrlib.branch.Branch), \
140
 
            "branch %r is not a Branch" % self.branch
141
119
        self.basedir = realpath(basedir)
142
120
        # if branch is at our basedir and is a format 6 or less
143
121
        # assume all other formats have their own control files.
144
 
        assert isinstance(_control_files, LockableFiles), \
145
 
            "_control_files must be a LockableFiles, not %r" % _control_files
146
122
        self._control_files = _control_files
 
123
        self._transport = self._control_files._transport
147
124
        self._dirty = None
148
125
        #-------------
149
126
        # during a read or write lock these objects are set, and are
151
128
        self._dirstate = None
152
129
        self._inventory = None
153
130
        #-------------
 
131
        self._setup_directory_is_tree_reference()
 
132
        self._detect_case_handling()
 
133
        self._rules_searcher = None
 
134
        self.views = self._make_views()
 
135
        #--- allow tests to select the dirstate iter_changes implementation
 
136
        self._iter_changes = dirstate._process_entry
154
137
 
155
138
    @needs_tree_write_lock
156
139
    def _add(self, files, ids, kinds):
158
141
        state = self.current_dirstate()
159
142
        for f, file_id, kind in zip(files, ids, kinds):
160
143
            f = f.strip('/')
161
 
            assert '//' not in f
162
 
            assert '..' not in f
163
144
            if self.path2id(f):
164
145
                # special case tree root handling.
165
146
                if f == '' and self.path2id(f) == ROOT_ID:
186
167
    @needs_tree_write_lock
187
168
    def add_reference(self, sub_tree):
188
169
        # use standard implementation, which calls back to self._add
189
 
        # 
 
170
        #
190
171
        # So we don't store the reference_revision in the working dirstate,
191
 
        # it's just recorded at the moment of commit. 
 
172
        # it's just recorded at the moment of commit.
192
173
        self._add_reference(sub_tree)
193
174
 
194
175
    def break_lock(self):
233
214
            WorkingTree3._comparison_data(self, entry, path)
234
215
        # it looks like a plain directory, but it's really a reference -- see
235
216
        # also kind()
236
 
        if (self._repo_supports_tree_reference and
237
 
            kind == 'directory' and
238
 
            self._directory_is_tree_reference(path)):
 
217
        if (self._repo_supports_tree_reference and kind == 'directory'
 
218
            and entry is not None and entry.kind == 'tree-reference'):
239
219
            kind = 'tree-reference'
240
220
        return kind, executable, stat_value
241
221
 
267
247
            return self._dirstate
268
248
        local_path = self.bzrdir.get_workingtree_transport(None
269
249
            ).local_abspath('dirstate')
270
 
        self._dirstate = dirstate.DirState.on_file(local_path)
 
250
        self._dirstate = dirstate.DirState.on_file(local_path,
 
251
            self._sha1_provider())
271
252
        return self._dirstate
272
253
 
273
 
    def _directory_is_tree_reference(self, relpath):
274
 
        # as a special case, if a directory contains control files then 
275
 
        # it's a tree reference, except that the root of the tree is not
276
 
        return relpath and osutils.isdir(self.abspath(relpath) + u"/.bzr")
277
 
        # TODO: We could ask all the control formats whether they
278
 
        # recognize this directory, but at the moment there's no cheap api
279
 
        # to do that.  Since we probably can only nest bzr checkouts and
280
 
        # they always use this name it's ok for now.  -- mbp 20060306
281
 
        #
282
 
        # FIXME: There is an unhandled case here of a subdirectory
283
 
        # containing .bzr but not a branch; that will probably blow up
284
 
        # when you try to commit it.  It might happen if there is a
285
 
        # checkout in a subdirectory.  This can be avoided by not adding
286
 
        # it.  mbp 20070306
 
254
    def _sha1_provider(self):
 
255
        """A function that returns a SHA1Provider suitable for this tree.
 
256
 
 
257
        :return: None if content filtering is not supported by this tree.
 
258
          Otherwise, a SHA1Provider is returned that sha's the canonical
 
259
          form of files, i.e. after read filters are applied.
 
260
        """
 
261
        if self.supports_content_filtering():
 
262
            return ContentFilterAwareSHA1Provider(self)
 
263
        else:
 
264
            return None
287
265
 
288
266
    def filter_unversioned_files(self, paths):
289
267
        """Filter out paths that are versioned.
322
300
 
323
301
    def _generate_inventory(self):
324
302
        """Create and set self.inventory from the dirstate object.
325
 
        
 
303
 
326
304
        This is relatively expensive: we have to walk the entire dirstate.
327
305
        Ideally we would not, and can deprecate this function.
328
306
        """
332
310
        state._read_dirblocks_if_needed()
333
311
        root_key, current_entry = self._get_entry(path='')
334
312
        current_id = root_key[2]
335
 
        assert current_entry[0][0] == 'd' # directory
 
313
        if not (current_entry[0][0] == 'd'): # directory
 
314
            raise AssertionError(current_entry)
336
315
        inv = Inventory(root_id=current_id)
337
316
        # Turn some things into local variables
338
317
        minikind_to_kind = dirstate.DirState._minikind_to_kind
371
350
                    # add this entry to the parent map.
372
351
                    parent_ies[(dirname + '/' + name).strip('/')] = inv_entry
373
352
                elif kind == 'tree-reference':
374
 
                    assert self._repo_supports_tree_reference, \
375
 
                        "repository of %r " \
376
 
                        "doesn't support tree references " \
377
 
                        "required by entry %r" \
378
 
                        % (self, name)
 
353
                    if not self._repo_supports_tree_reference:
 
354
                        raise errors.UnsupportedOperation(
 
355
                            self._generate_inventory,
 
356
                            self.branch.repository)
379
357
                    inv_entry.reference_revision = link_or_sha1 or None
380
358
                elif kind != 'symlink':
381
359
                    raise AssertionError("unknown kind %r" % kind)
382
360
                # These checks cost us around 40ms on a 55k entry tree
383
 
                assert file_id not in inv_byid, ('file_id %s already in'
384
 
                    ' inventory as %s' % (file_id, inv_byid[file_id]))
385
 
                assert name_unicode not in parent_ie.children
 
361
                if file_id in inv_byid:
 
362
                    raise AssertionError('file_id %s already in'
 
363
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
 
364
                if name_unicode in parent_ie.children:
 
365
                    raise AssertionError('name %r already in parent'
 
366
                        % (name_unicode,))
386
367
                inv_byid[file_id] = inv_entry
387
368
                parent_ie.children[name_unicode] = inv_entry
388
369
        self._inventory = inv
393
374
        If either file_id or path is supplied, it is used as the key to lookup.
394
375
        If both are supplied, the fastest lookup is used, and an error is
395
376
        raised if they do not both point at the same row.
396
 
        
 
377
 
397
378
        :param file_id: An optional unicode file_id to be looked up.
398
379
        :param path: An optional unicode path to be looked up.
399
380
        :return: The dirstate row tuple for path/file_id, or (None, None)
423
404
                    return None
424
405
                else:
425
406
                    raise
426
 
        link_or_sha1 = state.update_entry(entry, file_abspath,
427
 
                                          stat_value=stat_value)
 
407
        link_or_sha1 = dirstate.update_entry(state, entry, file_abspath,
 
408
            stat_value=stat_value)
428
409
        if entry[1][0][0] == 'f':
429
 
            return link_or_sha1
 
410
            if link_or_sha1 is None:
 
411
                file_obj, statvalue = self.get_file_with_stat(file_id, path)
 
412
                try:
 
413
                    sha1 = osutils.sha_file(file_obj)
 
414
                finally:
 
415
                    file_obj.close()
 
416
                self._observed_sha1(file_id, path, (sha1, statvalue))
 
417
                return sha1
 
418
            else:
 
419
                return link_or_sha1
430
420
        return None
431
421
 
432
422
    def _get_inventory(self):
433
423
        """Get the inventory for the tree. This is only valid within a lock."""
 
424
        if 'evil' in debug.debug_flags:
 
425
            trace.mutter_callsite(2,
 
426
                "accessing .inventory forces a size of tree translation.")
434
427
        if self._inventory is not None:
435
428
            return self._inventory
436
429
        self._must_be_locked()
443
436
    @needs_read_lock
444
437
    def get_parent_ids(self):
445
438
        """See Tree.get_parent_ids.
446
 
        
 
439
 
447
440
        This implementation requests the ids list from the dirstate file.
448
441
        """
449
442
        return self.current_dirstate().get_parent_ids()
465
458
 
466
459
    def has_id(self, file_id):
467
460
        state = self.current_dirstate()
468
 
        file_id = osutils.safe_file_id(file_id)
469
461
        row, parents = self._get_entry(file_id=file_id)
470
462
        if row is None:
471
463
            return False
475
467
    @needs_read_lock
476
468
    def id2path(self, file_id):
477
469
        "Convert a file-id to a path."
478
 
        file_id = osutils.safe_file_id(file_id)
479
470
        state = self.current_dirstate()
480
471
        entry = self._get_entry(file_id=file_id)
481
472
        if entry == (None, None):
483
474
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
484
475
        return path_utf8.decode('utf8')
485
476
 
 
477
    def _is_executable_from_path_and_stat_from_basis(self, path, stat_result):
 
478
        entry = self._get_entry(path=path)
 
479
        if entry == (None, None):
 
480
            return False # Missing entries are not executable
 
481
        return entry[1][0][3] # Executable?
 
482
 
486
483
    if not osutils.supports_executable():
487
484
        def is_executable(self, file_id, path=None):
488
485
            """Test if a file is executable or not.
489
486
 
490
487
            Note: The caller is expected to take a read-lock before calling this.
491
488
            """
492
 
            file_id = osutils.safe_file_id(file_id)
493
489
            entry = self._get_entry(file_id=file_id, path=path)
494
490
            if entry == (None, None):
495
491
                return False
496
492
            return entry[1][0][3]
 
493
 
 
494
        _is_executable_from_path_and_stat = \
 
495
            _is_executable_from_path_and_stat_from_basis
497
496
    else:
498
497
        def is_executable(self, file_id, path=None):
499
498
            """Test if a file is executable or not.
500
499
 
501
500
            Note: The caller is expected to take a read-lock before calling this.
502
501
            """
 
502
            self._must_be_locked()
503
503
            if not path:
504
 
                file_id = osutils.safe_file_id(file_id)
505
504
                path = self.id2path(file_id)
506
505
            mode = os.lstat(self.abspath(path)).st_mode
507
506
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
508
507
 
 
508
    def all_file_ids(self):
 
509
        """See Tree.iter_all_file_ids"""
 
510
        self._must_be_locked()
 
511
        result = set()
 
512
        for key, tree_details in self.current_dirstate()._iter_entries():
 
513
            if tree_details[0][0] in ('a', 'r'): # relocated
 
514
                continue
 
515
            result.add(key[2])
 
516
        return result
 
517
 
509
518
    @needs_read_lock
510
519
    def __iter__(self):
511
520
        """Iterate through file_ids for this tree.
524
533
        return iter(result)
525
534
 
526
535
    def iter_references(self):
 
536
        if not self._repo_supports_tree_reference:
 
537
            # When the repo doesn't support references, we will have nothing to
 
538
            # return
 
539
            return
527
540
        for key, tree_details in self.current_dirstate()._iter_entries():
528
541
            if tree_details[0][0] in ('a', 'r'): # absent, relocated
529
542
                # not relevant to the working tree
531
544
            if not key[1]:
532
545
                # the root is not a reference.
533
546
                continue
534
 
            path = pathjoin(self.basedir, key[0].decode('utf8'), key[1].decode('utf8'))
 
547
            relpath = pathjoin(key[0].decode('utf8'), key[1].decode('utf8'))
535
548
            try:
536
 
                if self._kind(path) == 'tree-reference':
537
 
                    yield path, key[2]
 
549
                if self._kind(relpath) == 'tree-reference':
 
550
                    yield relpath, key[2]
538
551
            except errors.NoSuchFile:
539
552
                # path is missing on disk.
540
553
                continue
541
554
 
 
555
    def _observed_sha1(self, file_id, path, (sha1, statvalue)):
 
556
        """See MutableTree._observed_sha1."""
 
557
        state = self.current_dirstate()
 
558
        entry = self._get_entry(file_id=file_id, path=path)
 
559
        state._observed_sha1(entry, sha1, statvalue)
 
560
 
542
561
    def kind(self, file_id):
543
562
        """Return the kind of a file.
544
563
 
548
567
        Note: The caller is expected to take a read-lock before calling this.
549
568
        """
550
569
        relpath = self.id2path(file_id)
551
 
        assert relpath != None, \
552
 
            "path for id {%s} is None!" % file_id
 
570
        if relpath is None:
 
571
            raise AssertionError(
 
572
                "path for id {%s} is None!" % file_id)
553
573
        return self._kind(relpath)
554
574
 
555
575
    def _kind(self, relpath):
556
576
        abspath = self.abspath(relpath)
557
577
        kind = file_kind(abspath)
558
 
        if (self._repo_supports_tree_reference and
559
 
            kind == 'directory' and
560
 
            self._directory_is_tree_reference(relpath)):
561
 
            kind = 'tree-reference'
 
578
        if (self._repo_supports_tree_reference and kind == 'directory'):
 
579
            entry = self._get_entry(path=relpath)
 
580
            if entry[1] is not None:
 
581
                if entry[1][0][0] == 't':
 
582
                    kind = 'tree-reference'
562
583
        return kind
563
584
 
564
585
    @needs_read_lock
568
589
        if parent_ids:
569
590
            return parent_ids[0]
570
591
        else:
571
 
            return None
 
592
            return _mod_revision.NULL_REVISION
572
593
 
573
594
    def lock_read(self):
574
595
        """See Branch.lock_read, and WorkingTree.unlock."""
627
648
        result = []
628
649
        if not from_paths:
629
650
            return result
630
 
 
631
651
        state = self.current_dirstate()
632
 
 
633
 
        assert not isinstance(from_paths, basestring)
 
652
        if isinstance(from_paths, basestring):
 
653
            raise ValueError()
634
654
        to_dir_utf8 = to_dir.encode('utf8')
635
655
        to_entry_dirname, to_basename = os.path.split(to_dir_utf8)
636
656
        id_index = state._get_id_index()
658
678
        if self._inventory is not None:
659
679
            update_inventory = True
660
680
            inv = self.inventory
 
681
            to_dir_id = to_entry[0][2]
661
682
            to_dir_ie = inv[to_dir_id]
662
 
            to_dir_id = to_entry[0][2]
663
683
        else:
664
684
            update_inventory = False
665
685
 
729
749
                if from_missing: # implicitly just update our path mapping
730
750
                    move_file = False
731
751
                elif not after:
732
 
                    raise errors.RenameFailedFilesExist(from_rel, to_rel,
733
 
                        extra="(Use --after to update the Bazaar id)")
 
752
                    raise errors.RenameFailedFilesExist(from_rel, to_rel)
734
753
 
735
754
            rollbacks = []
736
755
            def rollback_rename():
792
811
                if minikind == 'd':
793
812
                    def update_dirblock(from_dir, to_key, to_dir_utf8):
794
813
                        """Recursively update all entries in this dirblock."""
795
 
                        assert from_dir != '', "renaming root not supported"
 
814
                        if from_dir == '':
 
815
                            raise AssertionError("renaming root not supported")
796
816
                        from_key = (from_dir, '')
797
817
                        from_block_idx, present = \
798
818
                            state._find_block_index_from_key(from_key)
811
831
 
812
832
                        # Grab a copy since move_one may update the list.
813
833
                        for entry in from_block[1][:]:
814
 
                            assert entry[0][0] == from_dir
 
834
                            if not (entry[0][0] == from_dir):
 
835
                                raise AssertionError()
815
836
                            cur_details = entry[1][0]
816
837
                            to_key = (to_dir_utf8, entry[0][1], entry[0][2])
817
838
                            from_path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
876
897
        for tree in trees:
877
898
            if not (isinstance(tree, DirStateRevisionTree) and tree._revision_id in
878
899
                parents):
879
 
                return super(WorkingTree4, self).paths2ids(paths, trees, require_versioned)
 
900
                return super(DirStateWorkingTree, self).paths2ids(paths,
 
901
                    trees, require_versioned)
880
902
        search_indexes = [0] + [1 + parents.index(tree._revision_id) for tree in trees]
881
903
        # -- make all paths utf8 --
882
904
        paths_utf8 = set()
942
964
            if not all_versioned:
943
965
                raise errors.PathsNotVersionedError(paths)
944
966
        # -- remove redundancy in supplied paths to prevent over-scanning --
945
 
        search_paths = set()
946
 
        for path in paths:
947
 
            other_paths = paths.difference(set([path]))
948
 
            if not osutils.is_inside_any(other_paths, path):
949
 
                # this is a top level path, we must check it.
950
 
                search_paths.add(path)
951
 
        # sketch: 
 
967
        search_paths = osutils.minimum_path_selection(paths)
 
968
        # sketch:
952
969
        # for all search_indexs in each path at or under each element of
953
970
        # search_paths, if the detail is relocated: add the id, and add the
954
971
        # relocated path as one to search if its not searched already. If the
1010
1027
 
1011
1028
    def read_working_inventory(self):
1012
1029
        """Read the working inventory.
1013
 
        
 
1030
 
1014
1031
        This is a meaningless operation for dirstate, but we obey it anyhow.
1015
1032
        """
1016
1033
        return self.inventory
1021
1038
 
1022
1039
        WorkingTree4 supplies revision_trees for any basis tree.
1023
1040
        """
1024
 
        revision_id = osutils.safe_revision_id(revision_id)
1025
1041
        dirstate = self.current_dirstate()
1026
1042
        parent_ids = dirstate.get_parent_ids()
1027
1043
        if revision_id not in parent_ids:
1034
1050
    @needs_tree_write_lock
1035
1051
    def set_last_revision(self, new_revision):
1036
1052
        """Change the last revision in the working tree."""
1037
 
        new_revision = osutils.safe_revision_id(new_revision)
1038
1053
        parents = self.get_parent_ids()
1039
1054
        if new_revision in (NULL_REVISION, None):
1040
 
            assert len(parents) < 2, (
1041
 
                "setting the last parent to none with a pending merge is "
1042
 
                "unsupported.")
 
1055
            if len(parents) >= 2:
 
1056
                raise AssertionError(
 
1057
                    "setting the last parent to none with a pending merge is "
 
1058
                    "unsupported.")
1043
1059
            self.set_parent_ids([])
1044
1060
        else:
1045
1061
            self.set_parent_ids([new_revision] + parents[1:],
1048
1064
    @needs_tree_write_lock
1049
1065
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
1050
1066
        """Set the parent ids to revision_ids.
1051
 
        
 
1067
 
1052
1068
        See also set_parent_trees. This api will try to retrieve the tree data
1053
1069
        for each element of revision_ids from the trees repository. If you have
1054
1070
        tree data already available, it is more efficient to use
1058
1074
        :param revision_ids: The revision_ids to set as the parent ids of this
1059
1075
            working tree. Any of these may be ghosts.
1060
1076
        """
1061
 
        revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1062
1077
        trees = []
1063
1078
        for revision_id in revision_ids:
1064
1079
            try:
1087
1102
                raise errors.GhostRevisionUnusableHere(parents_list[0][0])
1088
1103
        real_trees = []
1089
1104
        ghosts = []
 
1105
 
 
1106
        parent_ids = [rev_id for rev_id, tree in parents_list]
 
1107
        graph = self.branch.repository.get_graph()
 
1108
        heads = graph.heads(parent_ids)
 
1109
        accepted_revisions = set()
 
1110
 
1090
1111
        # convert absent trees to the null tree, which we convert back to
1091
1112
        # missing on access.
1092
1113
        for rev_id, tree in parents_list:
1093
 
            rev_id = osutils.safe_revision_id(rev_id)
 
1114
            if len(accepted_revisions) > 0:
 
1115
                # we always accept the first tree
 
1116
                if rev_id in accepted_revisions or rev_id not in heads:
 
1117
                    # We have already included either this tree, or its
 
1118
                    # descendent, so we skip it.
 
1119
                    continue
1094
1120
            _mod_revision.check_not_reserved_id(rev_id)
1095
1121
            if tree is not None:
1096
1122
                real_trees.append((rev_id, tree))
1097
1123
            else:
1098
1124
                real_trees.append((rev_id,
1099
 
                    self.branch.repository.revision_tree(None)))
 
1125
                    self.branch.repository.revision_tree(
 
1126
                        _mod_revision.NULL_REVISION)))
1100
1127
                ghosts.append(rev_id)
 
1128
            accepted_revisions.add(rev_id)
1101
1129
        dirstate.set_parent_trees(real_trees, ghosts=ghosts)
1102
1130
        self._make_dirty(reset_inventory=False)
1103
1131
 
1108
1136
        if state._dirblock_state == dirstate.DirState.IN_MEMORY_MODIFIED:
1109
1137
            self._make_dirty(reset_inventory=True)
1110
1138
 
 
1139
    def _sha_from_stat(self, path, stat_result):
 
1140
        """Get a sha digest from the tree's stat cache.
 
1141
 
 
1142
        The default implementation assumes no stat cache is present.
 
1143
 
 
1144
        :param path: The path.
 
1145
        :param stat_result: The stat result being looked up.
 
1146
        """
 
1147
        return self.current_dirstate().sha1_from_stat(path, stat_result)
 
1148
 
1111
1149
    @needs_read_lock
1112
1150
    def supports_tree_reference(self):
1113
1151
        return self._repo_supports_tree_reference
1153
1191
            return
1154
1192
        state = self.current_dirstate()
1155
1193
        state._read_dirblocks_if_needed()
1156
 
        ids_to_unversion = set()
1157
 
        for file_id in file_ids:
1158
 
            ids_to_unversion.add(osutils.safe_file_id(file_id))
 
1194
        ids_to_unversion = set(file_ids)
1159
1195
        paths_to_unversion = set()
1160
1196
        # sketch:
1161
1197
        # check if the root is to be unversioned, if so, assert for now.
1191
1227
                    # Mark this file id as having been removed
1192
1228
                    entry = block[1][entry_index]
1193
1229
                    ids_to_unversion.discard(entry[0][2])
1194
 
                    if (entry[1][0][0] == 'a'
 
1230
                    if (entry[1][0][0] in 'ar' # don't remove absent or renamed
 
1231
                                               # entries
1195
1232
                        or not state._make_absent(entry)):
1196
1233
                        entry_index += 1
1197
1234
                # go to the next block. (At the moment we dont delete empty
1222
1259
            for file_id in file_ids:
1223
1260
                self._inventory.remove_recursive_id(file_id)
1224
1261
 
 
1262
    @needs_tree_write_lock
 
1263
    def rename_one(self, from_rel, to_rel, after=False):
 
1264
        """See WorkingTree.rename_one"""
 
1265
        self.flush()
 
1266
        WorkingTree.rename_one(self, from_rel, to_rel, after)
 
1267
 
 
1268
    @needs_tree_write_lock
 
1269
    def apply_inventory_delta(self, changes):
 
1270
        """See MutableTree.apply_inventory_delta"""
 
1271
        state = self.current_dirstate()
 
1272
        state.update_by_delta(changes)
 
1273
        self._make_dirty(reset_inventory=True)
 
1274
 
 
1275
    def update_basis_by_delta(self, new_revid, delta):
 
1276
        """See MutableTree.update_basis_by_delta."""
 
1277
        if self.last_revision() == new_revid:
 
1278
            raise AssertionError()
 
1279
        self.current_dirstate().update_basis_by_delta(delta, new_revid)
 
1280
 
1225
1281
    @needs_read_lock
1226
1282
    def _validate(self):
1227
1283
        self._dirstate._validate()
1229
1285
    @needs_tree_write_lock
1230
1286
    def _write_inventory(self, inv):
1231
1287
        """Write inventory as the current inventory."""
1232
 
        assert not self._dirty, "attempting to write an inventory when the dirstate is dirty will cause data loss"
 
1288
        if self._dirty:
 
1289
            raise AssertionError("attempting to write an inventory when the "
 
1290
                "dirstate is dirty will lose pending changes")
1233
1291
        self.current_dirstate().set_state_from_inventory(inv)
1234
1292
        self._make_dirty(reset_inventory=False)
1235
1293
        if self._inventory is not None:
1237
1295
        self.flush()
1238
1296
 
1239
1297
 
1240
 
class WorkingTreeFormat4(WorkingTreeFormat3):
1241
 
    """The first consolidated dirstate working tree format.
1242
 
 
1243
 
    This format:
1244
 
        - exists within a metadir controlling .bzr
1245
 
        - includes an explicit version marker for the workingtree control
1246
 
          files, separate from the BzrDir format
1247
 
        - modifies the hash cache format
1248
 
        - is new in bzr 0.15
1249
 
        - uses a LockDir to guard access to it.
1250
 
    """
1251
 
 
1252
 
    upgrade_recommended = False
1253
 
 
1254
 
    def get_format_string(self):
1255
 
        """See WorkingTreeFormat.get_format_string()."""
1256
 
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
1257
 
 
1258
 
    def get_format_description(self):
1259
 
        """See WorkingTreeFormat.get_format_description()."""
1260
 
        return "Working tree format 4"
1261
 
 
1262
 
    def initialize(self, a_bzrdir, revision_id=None):
 
1298
class ContentFilterAwareSHA1Provider(dirstate.SHA1Provider):
 
1299
 
 
1300
    def __init__(self, tree):
 
1301
        self.tree = tree
 
1302
 
 
1303
    def sha1(self, abspath):
 
1304
        """See dirstate.SHA1Provider.sha1()."""
 
1305
        filters = self.tree._content_filter_stack(
 
1306
            self.tree.relpath(osutils.safe_unicode(abspath)))
 
1307
        return internal_size_sha_file_byname(abspath, filters)[1]
 
1308
 
 
1309
    def stat_and_sha1(self, abspath):
 
1310
        """See dirstate.SHA1Provider.stat_and_sha1()."""
 
1311
        filters = self.tree._content_filter_stack(
 
1312
            self.tree.relpath(osutils.safe_unicode(abspath)))
 
1313
        file_obj = file(abspath, 'rb', 65000)
 
1314
        try:
 
1315
            statvalue = os.fstat(file_obj.fileno())
 
1316
            if filters:
 
1317
                file_obj = filtered_input_file(file_obj, filters)
 
1318
            sha1 = osutils.size_sha_file(file_obj)[1]
 
1319
        finally:
 
1320
            file_obj.close()
 
1321
        return statvalue, sha1
 
1322
 
 
1323
 
 
1324
class WorkingTree4(DirStateWorkingTree):
 
1325
    """This is the Format 4 working tree.
 
1326
 
 
1327
    This differs from WorkingTree3 by:
 
1328
     - Having a consolidated internal dirstate, stored in a
 
1329
       randomly-accessible sorted file on disk.
 
1330
     - Not having a regular inventory attribute.  One can be synthesized
 
1331
       on demand but this is expensive and should be avoided.
 
1332
 
 
1333
    This is new in bzr 0.15.
 
1334
    """
 
1335
 
 
1336
 
 
1337
class WorkingTree5(DirStateWorkingTree):
 
1338
    """This is the Format 5 working tree.
 
1339
 
 
1340
    This differs from WorkingTree4 by:
 
1341
     - Supporting content filtering.
 
1342
 
 
1343
    This is new in bzr 1.11.
 
1344
    """
 
1345
 
 
1346
 
 
1347
class WorkingTree6(DirStateWorkingTree):
 
1348
    """This is the Format 6 working tree.
 
1349
 
 
1350
    This differs from WorkingTree5 by:
 
1351
     - Supporting a current view that may mask the set of files in a tree
 
1352
       impacted by most user operations.
 
1353
 
 
1354
    This is new in bzr 1.14.
 
1355
    """
 
1356
 
 
1357
    def _make_views(self):
 
1358
        return views.PathBasedViews(self)
 
1359
 
 
1360
 
 
1361
class DirStateWorkingTreeFormat(WorkingTreeFormat3):
 
1362
    def initialize(self, a_bzrdir, revision_id=None, from_branch=None,
 
1363
                   accelerator_tree=None, hardlink=False):
1263
1364
        """See WorkingTreeFormat.initialize().
1264
1365
 
1265
1366
        :param revision_id: allows creating a working tree at a different
1266
1367
        revision than the branch is at.
 
1368
        :param accelerator_tree: A tree which can be used for retrieving file
 
1369
            contents more quickly than the revision tree, i.e. a workingtree.
 
1370
            The revision tree will be used for cases where accelerator_tree's
 
1371
            content is different.
 
1372
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1373
            where possible.
1267
1374
 
1268
1375
        These trees get an initial random root id, if their repository supports
1269
1376
        rich root data, TREE_ROOT otherwise.
1270
1377
        """
1271
 
        revision_id = osutils.safe_revision_id(revision_id)
1272
1378
        if not isinstance(a_bzrdir.transport, LocalTransport):
1273
1379
            raise errors.NotLocalUrl(a_bzrdir.transport.base)
1274
1380
        transport = a_bzrdir.get_workingtree_transport(self)
1275
1381
        control_files = self._open_control_files(a_bzrdir)
1276
1382
        control_files.create_lock()
1277
1383
        control_files.lock_write()
1278
 
        control_files.put_utf8('format', self.get_format_string())
1279
 
        branch = a_bzrdir.open_branch()
 
1384
        transport.put_bytes('format', self.get_format_string(),
 
1385
            mode=a_bzrdir._get_file_mode())
 
1386
        if from_branch is not None:
 
1387
            branch = from_branch
 
1388
        else:
 
1389
            branch = a_bzrdir.open_branch()
1280
1390
        if revision_id is None:
1281
1391
            revision_id = branch.last_revision()
1282
1392
        local_path = transport.local_abspath('dirstate')
1284
1394
        state = dirstate.DirState.initialize(local_path)
1285
1395
        state.unlock()
1286
1396
        del state
1287
 
        wt = WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
 
1397
        wt = self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
1288
1398
                         branch,
1289
1399
                         _format=self,
1290
1400
                         _bzrdir=a_bzrdir,
1292
1402
        wt._new_tree()
1293
1403
        wt.lock_tree_write()
1294
1404
        try:
 
1405
            self._init_custom_control_files(wt)
1295
1406
            if revision_id in (None, NULL_REVISION):
1296
1407
                if branch.repository.supports_rich_root():
1297
1408
                    wt._set_root_id(generate_ids.gen_root_id())
1298
1409
                else:
1299
1410
                    wt._set_root_id(ROOT_ID)
1300
1411
                wt.flush()
1301
 
            wt.set_last_revision(revision_id)
1302
 
            wt.flush()
1303
 
            basis = wt.basis_tree()
 
1412
            basis = None
 
1413
            # frequently, we will get here due to branching.  The accelerator
 
1414
            # tree will be the tree from the branch, so the desired basis
 
1415
            # tree will often be a parent of the accelerator tree.
 
1416
            if accelerator_tree is not None:
 
1417
                try:
 
1418
                    basis = accelerator_tree.revision_tree(revision_id)
 
1419
                except errors.NoSuchRevision:
 
1420
                    pass
 
1421
            if basis is None:
 
1422
                basis = branch.repository.revision_tree(revision_id)
 
1423
            if revision_id == NULL_REVISION:
 
1424
                parents_list = []
 
1425
            else:
 
1426
                parents_list = [(revision_id, basis)]
1304
1427
            basis.lock_read()
1305
 
            # if the basis has a root id we have to use that; otherwise we use
1306
 
            # a new random one
1307
 
            basis_root_id = basis.get_root_id()
1308
 
            if basis_root_id is not None:
1309
 
                wt._set_root_id(basis_root_id)
 
1428
            try:
 
1429
                wt.set_parent_trees(parents_list, allow_leftmost_as_ghost=True)
1310
1430
                wt.flush()
1311
 
            transform.build_tree(basis, wt)
1312
 
            basis.unlock()
 
1431
                # if the basis has a root id we have to use that; otherwise we
 
1432
                # use a new random one
 
1433
                basis_root_id = basis.get_root_id()
 
1434
                if basis_root_id is not None:
 
1435
                    wt._set_root_id(basis_root_id)
 
1436
                    wt.flush()
 
1437
                # If content filtering is supported, do not use the accelerator
 
1438
                # tree - the cost of transforming the content both ways and
 
1439
                # checking for changed content can outweight the gains it gives.
 
1440
                # Note: do NOT move this logic up higher - using the basis from
 
1441
                # the accelerator tree is still desirable because that can save
 
1442
                # a minute or more of processing on large trees!
 
1443
                if wt.supports_content_filtering():
 
1444
                    accelerator_tree = None
 
1445
                # delta_from_tree is safe even for DirStateRevisionTrees,
 
1446
                # because wt4.apply_inventory_delta does not mutate the input
 
1447
                # inventory entries.
 
1448
                transform.build_tree(basis, wt, accelerator_tree,
 
1449
                                     hardlink=hardlink, delta_from_tree=True)
 
1450
            finally:
 
1451
                basis.unlock()
1313
1452
        finally:
1314
1453
            control_files.unlock()
1315
1454
            wt.unlock()
1316
1455
        return wt
1317
1456
 
 
1457
    def _init_custom_control_files(self, wt):
 
1458
        """Subclasses with custom control files should override this method.
 
1459
 
 
1460
        The working tree and control files are locked for writing when this
 
1461
        method is called.
 
1462
 
 
1463
        :param wt: the WorkingTree object
 
1464
        """
 
1465
 
1318
1466
    def _open(self, a_bzrdir, control_files):
1319
1467
        """Open the tree itself.
1320
1468
 
1321
1469
        :param a_bzrdir: the dir for the tree.
1322
1470
        :param control_files: the control files for the tree.
1323
1471
        """
1324
 
        return WorkingTree4(a_bzrdir.root_transport.local_abspath('.'),
 
1472
        return self._tree_class(a_bzrdir.root_transport.local_abspath('.'),
1325
1473
                           branch=a_bzrdir.open_branch(),
1326
1474
                           _format=self,
1327
1475
                           _bzrdir=a_bzrdir,
1328
1476
                           _control_files=control_files)
1329
1477
 
1330
1478
    def __get_matchingbzrdir(self):
 
1479
        return self._get_matchingbzrdir()
 
1480
 
 
1481
    def _get_matchingbzrdir(self):
 
1482
        """Overrideable method to get a bzrdir for testing."""
1331
1483
        # please test against something that will let us do tree references
1332
1484
        return bzrdir.format_registry.make_bzrdir(
1333
1485
            'dirstate-with-subtree')
1335
1487
    _matchingbzrdir = property(__get_matchingbzrdir)
1336
1488
 
1337
1489
 
 
1490
class WorkingTreeFormat4(DirStateWorkingTreeFormat):
 
1491
    """The first consolidated dirstate working tree format.
 
1492
 
 
1493
    This format:
 
1494
        - exists within a metadir controlling .bzr
 
1495
        - includes an explicit version marker for the workingtree control
 
1496
          files, separate from the BzrDir format
 
1497
        - modifies the hash cache format
 
1498
        - is new in bzr 0.15
 
1499
        - uses a LockDir to guard access to it.
 
1500
    """
 
1501
 
 
1502
    upgrade_recommended = False
 
1503
 
 
1504
    _tree_class = WorkingTree4
 
1505
 
 
1506
    def get_format_string(self):
 
1507
        """See WorkingTreeFormat.get_format_string()."""
 
1508
        return "Bazaar Working Tree Format 4 (bzr 0.15)\n"
 
1509
 
 
1510
    def get_format_description(self):
 
1511
        """See WorkingTreeFormat.get_format_description()."""
 
1512
        return "Working tree format 4"
 
1513
 
 
1514
 
 
1515
class WorkingTreeFormat5(DirStateWorkingTreeFormat):
 
1516
    """WorkingTree format supporting content filtering.
 
1517
    """
 
1518
 
 
1519
    upgrade_recommended = False
 
1520
 
 
1521
    _tree_class = WorkingTree5
 
1522
 
 
1523
    def get_format_string(self):
 
1524
        """See WorkingTreeFormat.get_format_string()."""
 
1525
        return "Bazaar Working Tree Format 5 (bzr 1.11)\n"
 
1526
 
 
1527
    def get_format_description(self):
 
1528
        """See WorkingTreeFormat.get_format_description()."""
 
1529
        return "Working tree format 5"
 
1530
 
 
1531
    def supports_content_filtering(self):
 
1532
        return True
 
1533
 
 
1534
 
 
1535
class WorkingTreeFormat6(DirStateWorkingTreeFormat):
 
1536
    """WorkingTree format supporting views.
 
1537
    """
 
1538
 
 
1539
    upgrade_recommended = False
 
1540
 
 
1541
    _tree_class = WorkingTree6
 
1542
 
 
1543
    def get_format_string(self):
 
1544
        """See WorkingTreeFormat.get_format_string()."""
 
1545
        return "Bazaar Working Tree Format 6 (bzr 1.14)\n"
 
1546
 
 
1547
    def get_format_description(self):
 
1548
        """See WorkingTreeFormat.get_format_description()."""
 
1549
        return "Working tree format 6"
 
1550
 
 
1551
    def _init_custom_control_files(self, wt):
 
1552
        """Subclasses with custom control files should override this method."""
 
1553
        wt._transport.put_bytes('views', '', mode=wt.bzrdir._get_file_mode())
 
1554
 
 
1555
    def supports_content_filtering(self):
 
1556
        return True
 
1557
 
 
1558
    def supports_views(self):
 
1559
        return True
 
1560
 
 
1561
 
1338
1562
class DirStateRevisionTree(Tree):
1339
1563
    """A revision tree pulling the inventory from a dirstate."""
1340
1564
 
1341
1565
    def __init__(self, dirstate, revision_id, repository):
1342
1566
        self._dirstate = dirstate
1343
 
        self._revision_id = osutils.safe_revision_id(revision_id)
 
1567
        self._revision_id = revision_id
1344
1568
        self._repository = repository
1345
1569
        self._inventory = None
1346
1570
        self._locked = 0
1347
1571
        self._dirstate_locked = False
 
1572
        self._repo_supports_tree_reference = getattr(
 
1573
            repository._format, "supports_tree_reference",
 
1574
            False)
1348
1575
 
1349
1576
    def __repr__(self):
1350
1577
        return "<%s of %s in %s>" % \
1353
1580
    def annotate_iter(self, file_id,
1354
1581
                      default_revision=_mod_revision.CURRENT_REVISION):
1355
1582
        """See Tree.annotate_iter"""
1356
 
        w = self._get_weave(file_id)
1357
 
        return w.annotate_iter(self.inventory[file_id].revision)
 
1583
        text_key = (file_id, self.inventory[file_id].revision)
 
1584
        annotations = self._repository.texts.annotate(text_key)
 
1585
        return [(key[-1], line) for (key, line) in annotations]
1358
1586
 
1359
1587
    def _get_ancestors(self, default_revision):
1360
1588
        return set(self._repository.get_ancestry(self._revision_id,
1381
1609
    def get_root_id(self):
1382
1610
        return self.path2id('')
1383
1611
 
 
1612
    def id2path(self, file_id):
 
1613
        "Convert a file-id to a path."
 
1614
        entry = self._get_entry(file_id=file_id)
 
1615
        if entry == (None, None):
 
1616
            raise errors.NoSuchId(tree=self, file_id=file_id)
 
1617
        path_utf8 = osutils.pathjoin(entry[0][0], entry[0][1])
 
1618
        return path_utf8.decode('utf8')
 
1619
 
 
1620
    def iter_references(self):
 
1621
        if not self._repo_supports_tree_reference:
 
1622
            # When the repo doesn't support references, we will have nothing to
 
1623
            # return
 
1624
            return iter([])
 
1625
        # Otherwise, fall back to the default implementation
 
1626
        return super(DirStateRevisionTree, self).iter_references()
 
1627
 
1384
1628
    def _get_parent_index(self):
1385
1629
        """Return the index in the dirstate referenced by this tree."""
1386
1630
        return self._dirstate.get_parent_ids().index(self._revision_id) + 1
1391
1635
        If either file_id or path is supplied, it is used as the key to lookup.
1392
1636
        If both are supplied, the fastest lookup is used, and an error is
1393
1637
        raised if they do not both point at the same row.
1394
 
        
 
1638
 
1395
1639
        :param file_id: An optional unicode file_id to be looked up.
1396
1640
        :param path: An optional unicode path to be looked up.
1397
1641
        :return: The dirstate row tuple for path/file_id, or (None, None)
1398
1642
        """
1399
1643
        if file_id is None and path is None:
1400
1644
            raise errors.BzrError('must supply file_id or path')
1401
 
        file_id = osutils.safe_file_id(file_id)
1402
1645
        if path is not None:
1403
1646
            path = path.encode('utf8')
1404
1647
        parent_index = self._get_parent_index()
1412
1655
 
1413
1656
        This is relatively expensive: we have to walk the entire dirstate.
1414
1657
        """
1415
 
        assert self._locked, 'cannot generate inventory of an unlocked '\
1416
 
            'dirstate revision tree'
 
1658
        if not self._locked:
 
1659
            raise AssertionError(
 
1660
                'cannot generate inventory of an unlocked '
 
1661
                'dirstate revision tree')
1417
1662
        # separate call for profiling - makes it clear where the costs are.
1418
1663
        self._dirstate._read_dirblocks_if_needed()
1419
 
        assert self._revision_id in self._dirstate.get_parent_ids(), \
1420
 
            'parent %s has disappeared from %s' % (
1421
 
            self._revision_id, self._dirstate.get_parent_ids())
 
1664
        if self._revision_id not in self._dirstate.get_parent_ids():
 
1665
            raise AssertionError(
 
1666
                'parent %s has disappeared from %s' % (
 
1667
                self._revision_id, self._dirstate.get_parent_ids()))
1422
1668
        parent_index = self._dirstate.get_parent_ids().index(self._revision_id) + 1
1423
1669
        # This is identical now to the WorkingTree _generate_inventory except
1424
1670
        # for the tree index use.
1425
1671
        root_key, current_entry = self._dirstate._get_entry(parent_index, path_utf8='')
1426
1672
        current_id = root_key[2]
1427
 
        assert current_entry[parent_index][0] == 'd'
 
1673
        if current_entry[parent_index][0] != 'd':
 
1674
            raise AssertionError()
1428
1675
        inv = Inventory(root_id=current_id, revision_id=self._revision_id)
1429
1676
        inv.root.revision = current_entry[parent_index][4]
1430
1677
        # Turn some things into local variables
1470
1717
                    raise AssertionError("cannot convert entry %r into an InventoryEntry"
1471
1718
                            % entry)
1472
1719
                # These checks cost us around 40ms on a 55k entry tree
1473
 
                assert file_id not in inv_byid
1474
 
                assert name_unicode not in parent_ie.children
 
1720
                if file_id in inv_byid:
 
1721
                    raise AssertionError('file_id %s already in'
 
1722
                        ' inventory as %s' % (file_id, inv_byid[file_id]))
 
1723
                if name_unicode in parent_ie.children:
 
1724
                    raise AssertionError('name %r already in parent'
 
1725
                        % (name_unicode,))
1475
1726
                inv_byid[file_id] = inv_entry
1476
1727
                parent_ie.children[name_unicode] = inv_entry
1477
1728
        self._inventory = inv
1497
1748
            return parent_details[1]
1498
1749
        return None
1499
1750
 
1500
 
    @symbol_versioning.deprecated_method(symbol_versioning.zero_ninety)
1501
 
    def get_weave(self, file_id):
1502
 
        return self._get_weave(file_id)
1503
 
 
1504
 
    def _get_weave(self, file_id):
1505
 
        return self._repository.weave_store.get_weave(file_id,
1506
 
                self._repository.get_transaction())
1507
 
 
1508
 
    def get_file(self, file_id):
 
1751
    def get_file(self, file_id, path=None):
1509
1752
        return StringIO(self.get_file_text(file_id))
1510
1753
 
1511
 
    def get_file_lines(self, file_id):
1512
 
        ie = self.inventory[file_id]
1513
 
        return self._get_weave(file_id).get_lines(ie.revision)
1514
 
 
1515
1754
    def get_file_size(self, file_id):
 
1755
        """See Tree.get_file_size"""
1516
1756
        return self.inventory[file_id].text_size
1517
1757
 
1518
 
    def get_file_text(self, file_id):
1519
 
        return ''.join(self.get_file_lines(file_id))
 
1758
    def get_file_text(self, file_id, path=None):
 
1759
        _, content = list(self.iter_files_bytes([(file_id, None)]))[0]
 
1760
        return ''.join(content)
1520
1761
 
1521
1762
    def get_reference_revision(self, file_id, path=None):
1522
1763
        return self.inventory[file_id].reference_revision
1523
1764
 
 
1765
    def iter_files_bytes(self, desired_files):
 
1766
        """See Tree.iter_files_bytes.
 
1767
 
 
1768
        This version is implemented on top of Repository.iter_files_bytes"""
 
1769
        parent_index = self._get_parent_index()
 
1770
        repo_desired_files = []
 
1771
        for file_id, identifier in desired_files:
 
1772
            entry = self._get_entry(file_id)
 
1773
            if entry == (None, None):
 
1774
                raise errors.NoSuchId(self, file_id)
 
1775
            repo_desired_files.append((file_id, entry[1][parent_index][4],
 
1776
                                       identifier))
 
1777
        return self._repository.iter_files_bytes(repo_desired_files)
 
1778
 
1524
1779
    def get_symlink_target(self, file_id):
1525
1780
        entry = self._get_entry(file_id=file_id)
1526
1781
        parent_index = self._get_parent_index()
1527
1782
        if entry[1][parent_index][0] != 'l':
1528
1783
            return None
1529
1784
        else:
1530
 
            # At present, none of the tree implementations supports non-ascii
1531
 
            # symlink targets. So we will just assume that the dirstate path is
1532
 
            # correct.
1533
 
            return entry[1][parent_index][1]
 
1785
            target = entry[1][parent_index][1]
 
1786
            target = target.decode('utf8')
 
1787
            return target
1534
1788
 
1535
1789
    def get_revision_id(self):
1536
1790
        """Return the revision id for this tree."""
1554
1808
        return bool(self.path2id(filename))
1555
1809
 
1556
1810
    def kind(self, file_id):
1557
 
        return self.inventory[file_id].kind
 
1811
        entry = self._get_entry(file_id=file_id)[1]
 
1812
        if entry is None:
 
1813
            raise errors.NoSuchId(tree=self, file_id=file_id)
 
1814
        return dirstate.DirState._minikind_to_kind[entry[1][0]]
 
1815
 
 
1816
    def stored_kind(self, file_id):
 
1817
        """See Tree.stored_kind"""
 
1818
        return self.kind(file_id)
 
1819
 
 
1820
    def path_content_summary(self, path):
 
1821
        """See Tree.path_content_summary."""
 
1822
        id = self.inventory.path2id(path)
 
1823
        if id is None:
 
1824
            return ('missing', None, None, None)
 
1825
        entry = self._inventory[id]
 
1826
        kind = entry.kind
 
1827
        if kind == 'file':
 
1828
            return (kind, entry.text_size, entry.executable, entry.text_sha1)
 
1829
        elif kind == 'symlink':
 
1830
            return (kind, None, None, entry.symlink_target)
 
1831
        else:
 
1832
            return (kind, None, None, None)
1558
1833
 
1559
1834
    def is_executable(self, file_id, path=None):
1560
1835
        ie = self.inventory[file_id]
1606
1881
                self._dirstate_locked = False
1607
1882
            self._repository.unlock()
1608
1883
 
 
1884
    @needs_read_lock
 
1885
    def supports_tree_reference(self):
 
1886
        return self._repo_supports_tree_reference
 
1887
 
1609
1888
    def walkdirs(self, prefix=""):
1610
1889
        # TODO: jam 20070215 This is the lazy way by using the RevisionTree
1611
 
        # implementation based on an inventory.  
 
1890
        # implementation based on an inventory.
1612
1891
        # This should be cleaned up to use the much faster Dirstate code
1613
1892
        # So for now, we just build up the parent inventory, and extract
1614
1893
        # it the same way RevisionTree does.
1643
1922
 
1644
1923
class InterDirStateTree(InterTree):
1645
1924
    """Fast path optimiser for changes_from with dirstate trees.
1646
 
    
1647
 
    This is used only when both trees are in the dirstate working file, and 
1648
 
    the source is any parent within the dirstate, and the destination is 
 
1925
 
 
1926
    This is used only when both trees are in the dirstate working file, and
 
1927
    the source is any parent within the dirstate, and the destination is
1649
1928
    the current working tree of the same dirstate.
1650
1929
    """
1651
1930
    # this could be generalized to allow comparisons between any trees in the
1664
1943
        target.set_parent_ids([revid])
1665
1944
        return target.basis_tree(), target
1666
1945
 
 
1946
    @classmethod
 
1947
    def make_source_parent_tree_python_dirstate(klass, test_case, source, target):
 
1948
        result = klass.make_source_parent_tree(source, target)
 
1949
        result[1]._iter_changes = dirstate.ProcessEntryPython
 
1950
        return result
 
1951
 
 
1952
    @classmethod
 
1953
    def make_source_parent_tree_compiled_dirstate(klass, test_case, source, target):
 
1954
        from bzrlib.tests.test__dirstate_helpers import \
 
1955
            CompiledDirstateHelpersFeature
 
1956
        if not CompiledDirstateHelpersFeature.available():
 
1957
            from bzrlib.tests import UnavailableFeature
 
1958
            raise UnavailableFeature(CompiledDirstateHelpersFeature)
 
1959
        from bzrlib._dirstate_helpers_c import ProcessEntryC
 
1960
        result = klass.make_source_parent_tree(source, target)
 
1961
        result[1]._iter_changes = ProcessEntryC
 
1962
        return result
 
1963
 
1667
1964
    _matching_from_tree_format = WorkingTreeFormat4()
1668
1965
    _matching_to_tree_format = WorkingTreeFormat4()
1669
 
    _test_mutable_trees_to_test_trees = make_source_parent_tree
1670
 
 
1671
 
    def _iter_changes(self, include_unchanged=False,
 
1966
 
 
1967
    @classmethod
 
1968
    def _test_mutable_trees_to_test_trees(klass, test_case, source, target):
 
1969
        # This method shouldn't be called, because we have python and C
 
1970
        # specific flavours.
 
1971
        raise NotImplementedError
 
1972
 
 
1973
    def iter_changes(self, include_unchanged=False,
1672
1974
                      specific_files=None, pb=None, extra_trees=[],
1673
1975
                      require_versioned=True, want_unversioned=False):
1674
1976
        """Return the changes from source to target.
1675
1977
 
1676
 
        :return: An iterator that yields tuples. See InterTree._iter_changes
 
1978
        :return: An iterator that yields tuples. See InterTree.iter_changes
1677
1979
            for details.
1678
1980
        :param specific_files: An optional list of file paths to restrict the
1679
1981
            comparison to. When mapping filenames to ids, all matches in all
1690
1992
            output. An unversioned file is defined as one with (False, False)
1691
1993
            for the versioned pair.
1692
1994
        """
1693
 
        utf8_decode = cache_utf8._utf8_decode
1694
 
        _minikind_to_kind = dirstate.DirState._minikind_to_kind
1695
 
        cmp_by_dirs = dirstate.cmp_by_dirs
1696
1995
        # NB: show_status depends on being able to pass in non-versioned files
1697
1996
        # and report them as unknown
1698
1997
        # TODO: handle extra trees in the dirstate.
1699
 
        # TODO: handle comparisons as an empty tree as a different special
1700
 
        # case? mbp 20070226
1701
 
        if extra_trees or (self.source._revision_id == NULL_REVISION):
 
1998
        if (extra_trees or specific_files == []):
1702
1999
            # we can't fast-path these cases (yet)
1703
 
            for f in super(InterDirStateTree, self)._iter_changes(
 
2000
            return super(InterDirStateTree, self).iter_changes(
1704
2001
                include_unchanged, specific_files, pb, extra_trees,
1705
 
                require_versioned, want_unversioned=want_unversioned):
1706
 
                yield f
1707
 
            return
 
2002
                require_versioned, want_unversioned=want_unversioned)
1708
2003
        parent_ids = self.target.get_parent_ids()
1709
 
        assert (self.source._revision_id in parent_ids), \
1710
 
                "revision {%s} is not stored in {%s}, but %s " \
1711
 
                "can only be used for trees stored in the dirstate" \
1712
 
                % (self.source._revision_id, self.target, self._iter_changes)
 
2004
        if not (self.source._revision_id in parent_ids
 
2005
                or self.source._revision_id == NULL_REVISION):
 
2006
            raise AssertionError(
 
2007
                "revision {%s} is not stored in {%s}, but %s "
 
2008
                "can only be used for trees stored in the dirstate"
 
2009
                % (self.source._revision_id, self.target, self.iter_changes))
1713
2010
        target_index = 0
1714
2011
        if self.source._revision_id == NULL_REVISION:
1715
2012
            source_index = None
1716
2013
            indices = (target_index,)
1717
2014
        else:
1718
 
            assert (self.source._revision_id in parent_ids), \
1719
 
                "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
1720
 
                self.source._revision_id, parent_ids)
 
2015
            if not (self.source._revision_id in parent_ids):
 
2016
                raise AssertionError(
 
2017
                    "Failure: source._revision_id: %s not in target.parent_ids(%s)" % (
 
2018
                    self.source._revision_id, parent_ids))
1721
2019
            source_index = 1 + parent_ids.index(self.source._revision_id)
1722
 
            indices = (source_index,target_index)
 
2020
            indices = (source_index, target_index)
1723
2021
        # -- make all specific_files utf8 --
1724
2022
        if specific_files:
1725
2023
            specific_files_utf8 = set()
1726
2024
            for path in specific_files:
 
2025
                # Note, if there are many specific files, using cache_utf8
 
2026
                # would be good here.
1727
2027
                specific_files_utf8.add(path.encode('utf8'))
1728
2028
            specific_files = specific_files_utf8
1729
2029
        else:
1730
2030
            specific_files = set([''])
1731
2031
        # -- specific_files is now a utf8 path set --
 
2032
 
1732
2033
        # -- get the state object and prepare it.
1733
2034
        state = self.target.current_dirstate()
1734
2035
        state._read_dirblocks_if_needed()
1735
 
        def _entries_for_path(path):
1736
 
            """Return a list with all the entries that match path for all ids.
1737
 
            """
1738
 
            dirname, basename = os.path.split(path)
1739
 
            key = (dirname, basename, '')
1740
 
            block_index, present = state._find_block_index_from_key(key)
1741
 
            if not present:
1742
 
                # the block which should contain path is absent.
1743
 
                return []
1744
 
            result = []
1745
 
            block = state._dirblocks[block_index][1]
1746
 
            entry_index, _ = state._find_entry_index(key, block)
1747
 
            # we may need to look at multiple entries at this path: walk while the specific_files match.
1748
 
            while (entry_index < len(block) and
1749
 
                block[entry_index][0][0:2] == key[0:2]):
1750
 
                result.append(block[entry_index])
1751
 
                entry_index += 1
1752
 
            return result
1753
2036
        if require_versioned:
1754
2037
            # -- check all supplied paths are versioned in a search tree. --
1755
2038
            all_versioned = True
1756
2039
            for path in specific_files:
1757
 
                path_entries = _entries_for_path(path)
 
2040
                path_entries = state._entries_for_path(path)
1758
2041
                if not path_entries:
1759
2042
                    # this specified path is not present at all: error
1760
2043
                    all_versioned = False
1776
2059
            if not all_versioned:
1777
2060
                raise errors.PathsNotVersionedError(specific_files)
1778
2061
        # -- remove redundancy in supplied specific_files to prevent over-scanning --
1779
 
        search_specific_files = set()
1780
 
        for path in specific_files:
1781
 
            other_specific_files = specific_files.difference(set([path]))
1782
 
            if not osutils.is_inside_any(other_specific_files, path):
1783
 
                # this is a top level path, we must check it.
1784
 
                search_specific_files.add(path)
1785
 
        # sketch: 
1786
 
        # compare source_index and target_index at or under each element of search_specific_files.
1787
 
        # follow the following comparison table. Note that we only want to do diff operations when
1788
 
        # the target is fdl because thats when the walkdirs logic will have exposed the pathinfo 
1789
 
        # for the target.
1790
 
        # cases:
1791
 
        # 
1792
 
        # Source | Target | disk | action
1793
 
        #   r    | fdlt   |      | add source to search, add id path move and perform
1794
 
        #        |        |      | diff check on source-target
1795
 
        #   r    | fdlt   |  a   | dangling file that was present in the basis. 
1796
 
        #        |        |      | ???
1797
 
        #   r    |  a     |      | add source to search
1798
 
        #   r    |  a     |  a   | 
1799
 
        #   r    |  r     |      | this path is present in a non-examined tree, skip.
1800
 
        #   r    |  r     |  a   | this path is present in a non-examined tree, skip.
1801
 
        #   a    | fdlt   |      | add new id
1802
 
        #   a    | fdlt   |  a   | dangling locally added file, skip
1803
 
        #   a    |  a     |      | not present in either tree, skip
1804
 
        #   a    |  a     |  a   | not present in any tree, skip
1805
 
        #   a    |  r     |      | not present in either tree at this path, skip as it
1806
 
        #        |        |      | may not be selected by the users list of paths.
1807
 
        #   a    |  r     |  a   | not present in either tree at this path, skip as it
1808
 
        #        |        |      | may not be selected by the users list of paths.
1809
 
        #  fdlt  | fdlt   |      | content in both: diff them
1810
 
        #  fdlt  | fdlt   |  a   | deleted locally, but not unversioned - show as deleted ?
1811
 
        #  fdlt  |  a     |      | unversioned: output deleted id for now
1812
 
        #  fdlt  |  a     |  a   | unversioned and deleted: output deleted id
1813
 
        #  fdlt  |  r     |      | relocated in this tree, so add target to search.
1814
 
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1815
 
        #        |        |      | this id at the other path.
1816
 
        #  fdlt  |  r     |  a   | relocated in this tree, so add target to search.
1817
 
        #        |        |      | Dont diff, we will see an r,fd; pair when we reach
1818
 
        #        |        |      | this id at the other path.
1819
 
 
1820
 
        # for all search_indexs in each path at or under each element of
1821
 
        # search_specific_files, if the detail is relocated: add the id, and add the
1822
 
        # relocated path as one to search if its not searched already. If the
1823
 
        # detail is not relocated, add the id.
1824
 
        searched_specific_files = set()
1825
 
        NULL_PARENT_DETAILS = dirstate.DirState.NULL_PARENT_DETAILS
1826
 
        # Using a list so that we can access the values and change them in
1827
 
        # nested scope. Each one is [path, file_id, entry]
1828
 
        last_source_parent = [None, None]
1829
 
        last_target_parent = [None, None]
 
2062
        search_specific_files = osutils.minimum_path_selection(specific_files)
1830
2063
 
1831
2064
        use_filesystem_for_exec = (sys.platform != 'win32')
1832
 
 
1833
 
        # Just a sentry, so that _process_entry can say that this
1834
 
        # record is handled, but isn't interesting to process (unchanged)
1835
 
        uninteresting = object()
1836
 
 
1837
 
 
1838
 
        old_dirname_to_file_id = {}
1839
 
        new_dirname_to_file_id = {}
1840
 
        # TODO: jam 20070516 - Avoid the _get_entry lookup overhead by
1841
 
        #       keeping a cache of directories that we have seen.
1842
 
 
1843
 
        def _process_entry(entry, path_info):
1844
 
            """Compare an entry and real disk to generate delta information.
1845
 
 
1846
 
            :param path_info: top_relpath, basename, kind, lstat, abspath for
1847
 
                the path of entry. If None, then the path is considered absent.
1848
 
                (Perhaps we should pass in a concrete entry for this ?)
1849
 
                Basename is returned as a utf8 string because we expect this
1850
 
                tuple will be ignored, and don't want to take the time to
1851
 
                decode.
1852
 
            :return: None if these don't match
1853
 
                     A tuple of information about the change, or
1854
 
                     the object 'uninteresting' if these match, but are
1855
 
                     basically identical.
1856
 
            """
1857
 
            if source_index is None:
1858
 
                source_details = NULL_PARENT_DETAILS
1859
 
            else:
1860
 
                source_details = entry[1][source_index]
1861
 
            target_details = entry[1][target_index]
1862
 
            target_minikind = target_details[0]
1863
 
            if path_info is not None and target_minikind in 'fdlt':
1864
 
                assert target_index == 0
1865
 
                link_or_sha1 = state.update_entry(entry, abspath=path_info[4],
1866
 
                                                  stat_value=path_info[3])
1867
 
                # The entry may have been modified by update_entry
1868
 
                target_details = entry[1][target_index]
1869
 
                target_minikind = target_details[0]
1870
 
            else:
1871
 
                link_or_sha1 = None
1872
 
            file_id = entry[0][2]
1873
 
            source_minikind = source_details[0]
1874
 
            if source_minikind in 'fdltr' and target_minikind in 'fdlt':
1875
 
                # claimed content in both: diff
1876
 
                #   r    | fdlt   |      | add source to search, add id path move and perform
1877
 
                #        |        |      | diff check on source-target
1878
 
                #   r    | fdlt   |  a   | dangling file that was present in the basis.
1879
 
                #        |        |      | ???
1880
 
                if source_minikind in 'r':
1881
 
                    # add the source to the search path to find any children it
1882
 
                    # has.  TODO ? : only add if it is a container ?
1883
 
                    if not osutils.is_inside_any(searched_specific_files,
1884
 
                                                 source_details[1]):
1885
 
                        search_specific_files.add(source_details[1])
1886
 
                    # generate the old path; this is needed for stating later
1887
 
                    # as well.
1888
 
                    old_path = source_details[1]
1889
 
                    old_dirname, old_basename = os.path.split(old_path)
1890
 
                    path = pathjoin(entry[0][0], entry[0][1])
1891
 
                    old_entry = state._get_entry(source_index,
1892
 
                                                 path_utf8=old_path)
1893
 
                    # update the source details variable to be the real
1894
 
                    # location.
1895
 
                    source_details = old_entry[1][source_index]
1896
 
                    source_minikind = source_details[0]
1897
 
                else:
1898
 
                    old_dirname = entry[0][0]
1899
 
                    old_basename = entry[0][1]
1900
 
                    old_path = path = None
1901
 
                if path_info is None:
1902
 
                    # the file is missing on disk, show as removed.
1903
 
                    content_change = True
1904
 
                    target_kind = None
1905
 
                    target_exec = False
1906
 
                else:
1907
 
                    # source and target are both versioned and disk file is present.
1908
 
                    target_kind = path_info[2]
1909
 
                    if target_kind == 'directory':
1910
 
                        if path is None:
1911
 
                            old_path = path = pathjoin(old_dirname, old_basename)
1912
 
                        new_dirname_to_file_id[path] = file_id
1913
 
                        if source_minikind != 'd':
1914
 
                            content_change = True
1915
 
                        else:
1916
 
                            # directories have no fingerprint
1917
 
                            content_change = False
1918
 
                        target_exec = False
1919
 
                    elif target_kind == 'file':
1920
 
                        if source_minikind != 'f':
1921
 
                            content_change = True
1922
 
                        else:
1923
 
                            # We could check the size, but we already have the
1924
 
                            # sha1 hash.
1925
 
                            content_change = (link_or_sha1 != source_details[1])
1926
 
                        # Target details is updated at update_entry time
1927
 
                        if use_filesystem_for_exec:
1928
 
                            # We don't need S_ISREG here, because we are sure
1929
 
                            # we are dealing with a file.
1930
 
                            target_exec = bool(stat.S_IEXEC & path_info[3].st_mode)
1931
 
                        else:
1932
 
                            target_exec = target_details[3]
1933
 
                    elif target_kind == 'symlink':
1934
 
                        if source_minikind != 'l':
1935
 
                            content_change = True
1936
 
                        else:
1937
 
                            content_change = (link_or_sha1 != source_details[1])
1938
 
                        target_exec = False
1939
 
                    elif target_kind == 'tree-reference':
1940
 
                        if source_minikind != 't':
1941
 
                            content_change = True
1942
 
                        else:
1943
 
                            content_change = False
1944
 
                        target_exec = False
1945
 
                    else:
1946
 
                        raise Exception, "unknown kind %s" % path_info[2]
1947
 
                if source_minikind == 'd':
1948
 
                    if path is None:
1949
 
                        old_path = path = pathjoin(old_dirname, old_basename)
1950
 
                    old_dirname_to_file_id[old_path] = file_id
1951
 
                # parent id is the entry for the path in the target tree
1952
 
                if old_dirname == last_source_parent[0]:
1953
 
                    source_parent_id = last_source_parent[1]
1954
 
                else:
1955
 
                    try:
1956
 
                        source_parent_id = old_dirname_to_file_id[old_dirname]
1957
 
                    except KeyError:
1958
 
                        source_parent_entry = state._get_entry(source_index,
1959
 
                                                               path_utf8=old_dirname)
1960
 
                        source_parent_id = source_parent_entry[0][2]
1961
 
                    if source_parent_id == entry[0][2]:
1962
 
                        # This is the root, so the parent is None
1963
 
                        source_parent_id = None
1964
 
                    else:
1965
 
                        last_source_parent[0] = old_dirname
1966
 
                        last_source_parent[1] = source_parent_id
1967
 
                new_dirname = entry[0][0]
1968
 
                if new_dirname == last_target_parent[0]:
1969
 
                    target_parent_id = last_target_parent[1]
1970
 
                else:
1971
 
                    try:
1972
 
                        target_parent_id = new_dirname_to_file_id[new_dirname]
1973
 
                    except KeyError:
1974
 
                        # TODO: We don't always need to do the lookup, because the
1975
 
                        #       parent entry will be the same as the source entry.
1976
 
                        target_parent_entry = state._get_entry(target_index,
1977
 
                                                               path_utf8=new_dirname)
1978
 
                        assert target_parent_entry != (None, None), (
1979
 
                            "Could not find target parent in wt: %s\nparent of: %s"
1980
 
                            % (new_dirname, entry))
1981
 
                        target_parent_id = target_parent_entry[0][2]
1982
 
                    if target_parent_id == entry[0][2]:
1983
 
                        # This is the root, so the parent is None
1984
 
                        target_parent_id = None
1985
 
                    else:
1986
 
                        last_target_parent[0] = new_dirname
1987
 
                        last_target_parent[1] = target_parent_id
1988
 
 
1989
 
                source_exec = source_details[3]
1990
 
                if (include_unchanged
1991
 
                    or content_change
1992
 
                    or source_parent_id != target_parent_id
1993
 
                    or old_basename != entry[0][1]
1994
 
                    or source_exec != target_exec
1995
 
                    ):
1996
 
                    if old_path is None:
1997
 
                        old_path = path = pathjoin(old_dirname, old_basename)
1998
 
                        old_path_u = utf8_decode(old_path)[0]
1999
 
                        path_u = old_path_u
2000
 
                    else:
2001
 
                        old_path_u = utf8_decode(old_path)[0]
2002
 
                        if old_path == path:
2003
 
                            path_u = old_path_u
2004
 
                        else:
2005
 
                            path_u = utf8_decode(path)[0]
2006
 
                    source_kind = _minikind_to_kind[source_minikind]
2007
 
                    return (entry[0][2],
2008
 
                           (old_path_u, path_u),
2009
 
                           content_change,
2010
 
                           (True, True),
2011
 
                           (source_parent_id, target_parent_id),
2012
 
                           (utf8_decode(old_basename)[0], utf8_decode(entry[0][1])[0]),
2013
 
                           (source_kind, target_kind),
2014
 
                           (source_exec, target_exec))
2015
 
                else:
2016
 
                    return uninteresting
2017
 
            elif source_minikind in 'a' and target_minikind in 'fdlt':
2018
 
                # looks like a new file
2019
 
                if path_info is not None:
2020
 
                    path = pathjoin(entry[0][0], entry[0][1])
2021
 
                    # parent id is the entry for the path in the target tree
2022
 
                    # TODO: these are the same for an entire directory: cache em.
2023
 
                    parent_id = state._get_entry(target_index,
2024
 
                                                 path_utf8=entry[0][0])[0][2]
2025
 
                    if parent_id == entry[0][2]:
2026
 
                        parent_id = None
2027
 
                    if use_filesystem_for_exec:
2028
 
                        # We need S_ISREG here, because we aren't sure if this
2029
 
                        # is a file or not.
2030
 
                        target_exec = bool(
2031
 
                            stat.S_ISREG(path_info[3].st_mode)
2032
 
                            and stat.S_IEXEC & path_info[3].st_mode)
2033
 
                    else:
2034
 
                        target_exec = target_details[3]
2035
 
                    return (entry[0][2],
2036
 
                           (None, utf8_decode(path)[0]),
2037
 
                           True,
2038
 
                           (False, True),
2039
 
                           (None, parent_id),
2040
 
                           (None, utf8_decode(entry[0][1])[0]),
2041
 
                           (None, path_info[2]),
2042
 
                           (None, target_exec))
2043
 
                else:
2044
 
                    # but its not on disk: we deliberately treat this as just
2045
 
                    # never-present. (Why ?! - RBC 20070224)
2046
 
                    pass
2047
 
            elif source_minikind in 'fdlt' and target_minikind in 'a':
2048
 
                # unversioned, possibly, or possibly not deleted: we dont care.
2049
 
                # if its still on disk, *and* theres no other entry at this
2050
 
                # path [we dont know this in this routine at the moment -
2051
 
                # perhaps we should change this - then it would be an unknown.
2052
 
                old_path = pathjoin(entry[0][0], entry[0][1])
2053
 
                # parent id is the entry for the path in the target tree
2054
 
                parent_id = state._get_entry(source_index, path_utf8=entry[0][0])[0][2]
2055
 
                if parent_id == entry[0][2]:
2056
 
                    parent_id = None
2057
 
                return (entry[0][2],
2058
 
                       (utf8_decode(old_path)[0], None),
2059
 
                       True,
2060
 
                       (True, False),
2061
 
                       (parent_id, None),
2062
 
                       (utf8_decode(entry[0][1])[0], None),
2063
 
                       (_minikind_to_kind[source_minikind], None),
2064
 
                       (source_details[3], None))
2065
 
            elif source_minikind in 'fdlt' and target_minikind in 'r':
2066
 
                # a rename; could be a true rename, or a rename inherited from
2067
 
                # a renamed parent. TODO: handle this efficiently. Its not
2068
 
                # common case to rename dirs though, so a correct but slow
2069
 
                # implementation will do.
2070
 
                if not osutils.is_inside_any(searched_specific_files, target_details[1]):
2071
 
                    search_specific_files.add(target_details[1])
2072
 
            elif source_minikind in 'ra' and target_minikind in 'ra':
2073
 
                # neither of the selected trees contain this file,
2074
 
                # so skip over it. This is not currently directly tested, but
2075
 
                # is indirectly via test_too_much.TestCommands.test_conflicts.
2076
 
                pass
2077
 
            else:
2078
 
                raise AssertionError("don't know how to compare "
2079
 
                    "source_minikind=%r, target_minikind=%r"
2080
 
                    % (source_minikind, target_minikind))
2081
 
                ## import pdb;pdb.set_trace()
2082
 
            return None
2083
 
 
2084
 
        while search_specific_files:
2085
 
            # TODO: the pending list should be lexically sorted?  the
2086
 
            # interface doesn't require it.
2087
 
            current_root = search_specific_files.pop()
2088
 
            current_root_unicode = current_root.decode('utf8')
2089
 
            searched_specific_files.add(current_root)
2090
 
            # process the entries for this containing directory: the rest will be
2091
 
            # found by their parents recursively.
2092
 
            root_entries = _entries_for_path(current_root)
2093
 
            root_abspath = self.target.abspath(current_root_unicode)
2094
 
            try:
2095
 
                root_stat = os.lstat(root_abspath)
2096
 
            except OSError, e:
2097
 
                if e.errno == errno.ENOENT:
2098
 
                    # the path does not exist: let _process_entry know that.
2099
 
                    root_dir_info = None
2100
 
                else:
2101
 
                    # some other random error: hand it up.
2102
 
                    raise
2103
 
            else:
2104
 
                root_dir_info = ('', current_root,
2105
 
                    osutils.file_kind_from_stat_mode(root_stat.st_mode), root_stat,
2106
 
                    root_abspath)
2107
 
                if root_dir_info[2] == 'directory':
2108
 
                    if self.target._directory_is_tree_reference(
2109
 
                        current_root.decode('utf8')):
2110
 
                        root_dir_info = root_dir_info[:2] + \
2111
 
                            ('tree-reference',) + root_dir_info[3:]
2112
 
 
2113
 
            if not root_entries and not root_dir_info:
2114
 
                # this specified path is not present at all, skip it.
2115
 
                continue
2116
 
            path_handled = False
2117
 
            for entry in root_entries:
2118
 
                result = _process_entry(entry, root_dir_info)
2119
 
                if result is not None:
2120
 
                    path_handled = True
2121
 
                    if result is not uninteresting:
2122
 
                        yield result
2123
 
            if want_unversioned and not path_handled and root_dir_info:
2124
 
                new_executable = bool(
2125
 
                    stat.S_ISREG(root_dir_info[3].st_mode)
2126
 
                    and stat.S_IEXEC & root_dir_info[3].st_mode)
2127
 
                yield (None,
2128
 
                       (None, current_root_unicode),
2129
 
                       True,
2130
 
                       (False, False),
2131
 
                       (None, None),
2132
 
                       (None, splitpath(current_root_unicode)[-1]),
2133
 
                       (None, root_dir_info[2]),
2134
 
                       (None, new_executable)
2135
 
                      )
2136
 
            initial_key = (current_root, '', '')
2137
 
            block_index, _ = state._find_block_index_from_key(initial_key)
2138
 
            if block_index == 0:
2139
 
                # we have processed the total root already, but because the
2140
 
                # initial key matched it we should skip it here.
2141
 
                block_index +=1
2142
 
            if root_dir_info and root_dir_info[2] == 'tree-reference':
2143
 
                current_dir_info = None
2144
 
            else:
2145
 
                dir_iterator = osutils._walkdirs_utf8(root_abspath, prefix=current_root)
2146
 
                try:
2147
 
                    current_dir_info = dir_iterator.next()
2148
 
                except OSError, e:
2149
 
                    # on win32, python2.4 has e.errno == ERROR_DIRECTORY, but
2150
 
                    # python 2.5 has e.errno == EINVAL,
2151
 
                    #            and e.winerror == ERROR_DIRECTORY
2152
 
                    e_winerror = getattr(e, 'winerror', None)
2153
 
                    win_errors = (ERROR_DIRECTORY, ERROR_PATH_NOT_FOUND)
2154
 
                    # there may be directories in the inventory even though
2155
 
                    # this path is not a file on disk: so mark it as end of
2156
 
                    # iterator
2157
 
                    if e.errno in (errno.ENOENT, errno.ENOTDIR, errno.EINVAL):
2158
 
                        current_dir_info = None
2159
 
                    elif (sys.platform == 'win32'
2160
 
                          and (e.errno in win_errors
2161
 
                               or e_winerror in win_errors)):
2162
 
                        current_dir_info = None
2163
 
                    else:
2164
 
                        raise
2165
 
                else:
2166
 
                    if current_dir_info[0][0] == '':
2167
 
                        # remove .bzr from iteration
2168
 
                        bzr_index = bisect_left(current_dir_info[1], ('.bzr',))
2169
 
                        assert current_dir_info[1][bzr_index][0] == '.bzr'
2170
 
                        del current_dir_info[1][bzr_index]
2171
 
            # walk until both the directory listing and the versioned metadata
2172
 
            # are exhausted. 
2173
 
            if (block_index < len(state._dirblocks) and
2174
 
                osutils.is_inside(current_root, state._dirblocks[block_index][0])):
2175
 
                current_block = state._dirblocks[block_index]
2176
 
            else:
2177
 
                current_block = None
2178
 
            while (current_dir_info is not None or
2179
 
                   current_block is not None):
2180
 
                if (current_dir_info and current_block
2181
 
                    and current_dir_info[0][0] != current_block[0]):
2182
 
                    if cmp_by_dirs(current_dir_info[0][0], current_block[0]) < 0:
2183
 
                        # filesystem data refers to paths not covered by the dirblock.
2184
 
                        # this has two possibilities:
2185
 
                        # A) it is versioned but empty, so there is no block for it
2186
 
                        # B) it is not versioned.
2187
 
 
2188
 
                        # if (A) then we need to recurse into it to check for
2189
 
                        # new unknown files or directories.
2190
 
                        # if (B) then we should ignore it, because we don't
2191
 
                        # recurse into unknown directories.
2192
 
                        path_index = 0
2193
 
                        while path_index < len(current_dir_info[1]):
2194
 
                                current_path_info = current_dir_info[1][path_index]
2195
 
                                if want_unversioned:
2196
 
                                    if current_path_info[2] == 'directory':
2197
 
                                        if self.target._directory_is_tree_reference(
2198
 
                                            current_path_info[0].decode('utf8')):
2199
 
                                            current_path_info = current_path_info[:2] + \
2200
 
                                                ('tree-reference',) + current_path_info[3:]
2201
 
                                    new_executable = bool(
2202
 
                                        stat.S_ISREG(current_path_info[3].st_mode)
2203
 
                                        and stat.S_IEXEC & current_path_info[3].st_mode)
2204
 
                                    yield (None,
2205
 
                                        (None, utf8_decode(current_path_info[0])[0]),
2206
 
                                        True,
2207
 
                                        (False, False),
2208
 
                                        (None, None),
2209
 
                                        (None, utf8_decode(current_path_info[1])[0]),
2210
 
                                        (None, current_path_info[2]),
2211
 
                                        (None, new_executable))
2212
 
                                # dont descend into this unversioned path if it is
2213
 
                                # a dir
2214
 
                                if current_path_info[2] in ('directory',
2215
 
                                                            'tree-reference'):
2216
 
                                    del current_dir_info[1][path_index]
2217
 
                                    path_index -= 1
2218
 
                                path_index += 1
2219
 
 
2220
 
                        # This dir info has been handled, go to the next
2221
 
                        try:
2222
 
                            current_dir_info = dir_iterator.next()
2223
 
                        except StopIteration:
2224
 
                            current_dir_info = None
2225
 
                    else:
2226
 
                        # We have a dirblock entry for this location, but there
2227
 
                        # is no filesystem path for this. This is most likely
2228
 
                        # because a directory was removed from the disk.
2229
 
                        # We don't have to report the missing directory,
2230
 
                        # because that should have already been handled, but we
2231
 
                        # need to handle all of the files that are contained
2232
 
                        # within.
2233
 
                        for current_entry in current_block[1]:
2234
 
                            # entry referring to file not present on disk.
2235
 
                            # advance the entry only, after processing.
2236
 
                            result = _process_entry(current_entry, None)
2237
 
                            if result is not None:
2238
 
                                if result is not uninteresting:
2239
 
                                    yield result
2240
 
                        block_index +=1
2241
 
                        if (block_index < len(state._dirblocks) and
2242
 
                            osutils.is_inside(current_root,
2243
 
                                              state._dirblocks[block_index][0])):
2244
 
                            current_block = state._dirblocks[block_index]
2245
 
                        else:
2246
 
                            current_block = None
2247
 
                    continue
2248
 
                entry_index = 0
2249
 
                if current_block and entry_index < len(current_block[1]):
2250
 
                    current_entry = current_block[1][entry_index]
2251
 
                else:
2252
 
                    current_entry = None
2253
 
                advance_entry = True
2254
 
                path_index = 0
2255
 
                if current_dir_info and path_index < len(current_dir_info[1]):
2256
 
                    current_path_info = current_dir_info[1][path_index]
2257
 
                    if current_path_info[2] == 'directory':
2258
 
                        if self.target._directory_is_tree_reference(
2259
 
                            current_path_info[0].decode('utf8')):
2260
 
                            current_path_info = current_path_info[:2] + \
2261
 
                                ('tree-reference',) + current_path_info[3:]
2262
 
                else:
2263
 
                    current_path_info = None
2264
 
                advance_path = True
2265
 
                path_handled = False
2266
 
                while (current_entry is not None or
2267
 
                    current_path_info is not None):
2268
 
                    if current_entry is None:
2269
 
                        # the check for path_handled when the path is adnvaced
2270
 
                        # will yield this path if needed.
2271
 
                        pass
2272
 
                    elif current_path_info is None:
2273
 
                        # no path is fine: the per entry code will handle it.
2274
 
                        result = _process_entry(current_entry, current_path_info)
2275
 
                        if result is not None:
2276
 
                            if result is not uninteresting:
2277
 
                                yield result
2278
 
                    elif (current_entry[0][1] != current_path_info[1]
2279
 
                          or current_entry[1][target_index][0] in 'ar'):
2280
 
                        # The current path on disk doesn't match the dirblock
2281
 
                        # record. Either the dirblock is marked as absent, or
2282
 
                        # the file on disk is not present at all in the
2283
 
                        # dirblock. Either way, report about the dirblock
2284
 
                        # entry, and let other code handle the filesystem one.
2285
 
 
2286
 
                        # Compare the basename for these files to determine
2287
 
                        # which comes first
2288
 
                        if current_path_info[1] < current_entry[0][1]:
2289
 
                            # extra file on disk: pass for now, but only
2290
 
                            # increment the path, not the entry
2291
 
                            advance_entry = False
2292
 
                        else:
2293
 
                            # entry referring to file not present on disk.
2294
 
                            # advance the entry only, after processing.
2295
 
                            result = _process_entry(current_entry, None)
2296
 
                            if result is not None:
2297
 
                                if result is not uninteresting:
2298
 
                                    yield result
2299
 
                            advance_path = False
2300
 
                    else:
2301
 
                        result = _process_entry(current_entry, current_path_info)
2302
 
                        if result is not None:
2303
 
                            path_handled = True
2304
 
                            if result is not uninteresting:
2305
 
                                yield result
2306
 
                    if advance_entry and current_entry is not None:
2307
 
                        entry_index += 1
2308
 
                        if entry_index < len(current_block[1]):
2309
 
                            current_entry = current_block[1][entry_index]
2310
 
                        else:
2311
 
                            current_entry = None
2312
 
                    else:
2313
 
                        advance_entry = True # reset the advance flaga
2314
 
                    if advance_path and current_path_info is not None:
2315
 
                        if not path_handled:
2316
 
                            # unversioned in all regards
2317
 
                            if want_unversioned:
2318
 
                                new_executable = bool(
2319
 
                                    stat.S_ISREG(current_path_info[3].st_mode)
2320
 
                                    and stat.S_IEXEC & current_path_info[3].st_mode)
2321
 
                                yield (None,
2322
 
                                    (None, utf8_decode(current_path_info[0])[0]),
2323
 
                                    True,
2324
 
                                    (False, False),
2325
 
                                    (None, None),
2326
 
                                    (None, utf8_decode(current_path_info[1])[0]),
2327
 
                                    (None, current_path_info[2]),
2328
 
                                    (None, new_executable))
2329
 
                            # dont descend into this unversioned path if it is
2330
 
                            # a dir
2331
 
                            if current_path_info[2] in ('directory'):
2332
 
                                del current_dir_info[1][path_index]
2333
 
                                path_index -= 1
2334
 
                        # dont descend the disk iterator into any tree 
2335
 
                        # paths.
2336
 
                        if current_path_info[2] == 'tree-reference':
2337
 
                            del current_dir_info[1][path_index]
2338
 
                            path_index -= 1
2339
 
                        path_index += 1
2340
 
                        if path_index < len(current_dir_info[1]):
2341
 
                            current_path_info = current_dir_info[1][path_index]
2342
 
                            if current_path_info[2] == 'directory':
2343
 
                                if self.target._directory_is_tree_reference(
2344
 
                                    current_path_info[0].decode('utf8')):
2345
 
                                    current_path_info = current_path_info[:2] + \
2346
 
                                        ('tree-reference',) + current_path_info[3:]
2347
 
                        else:
2348
 
                            current_path_info = None
2349
 
                        path_handled = False
2350
 
                    else:
2351
 
                        advance_path = True # reset the advance flagg.
2352
 
                if current_block is not None:
2353
 
                    block_index += 1
2354
 
                    if (block_index < len(state._dirblocks) and
2355
 
                        osutils.is_inside(current_root, state._dirblocks[block_index][0])):
2356
 
                        current_block = state._dirblocks[block_index]
2357
 
                    else:
2358
 
                        current_block = None
2359
 
                if current_dir_info is not None:
2360
 
                    try:
2361
 
                        current_dir_info = dir_iterator.next()
2362
 
                    except StopIteration:
2363
 
                        current_dir_info = None
2364
 
 
 
2065
        iter_changes = self.target._iter_changes(include_unchanged,
 
2066
            use_filesystem_for_exec, search_specific_files, state,
 
2067
            source_index, target_index, want_unversioned, self.target)
 
2068
        return iter_changes.iter_changes()
2365
2069
 
2366
2070
    @staticmethod
2367
2071
    def is_compatible(source, target):
2368
2072
        # the target must be a dirstate working tree
2369
 
        if not isinstance(target, WorkingTree4):
 
2073
        if not isinstance(target, DirStateWorkingTree):
2370
2074
            return False
2371
 
        # the source must be a revtreee or dirstate rev tree.
 
2075
        # the source must be a revtree or dirstate rev tree.
2372
2076
        if not isinstance(source,
2373
2077
            (revisiontree.RevisionTree, DirStateRevisionTree)):
2374
2078
            return False
2375
2079
        # the source revid must be in the target dirstate
2376
2080
        if not (source._revision_id == NULL_REVISION or
2377
2081
            source._revision_id in target.get_parent_ids()):
2378
 
            # TODO: what about ghosts? it may well need to 
 
2082
            # TODO: what about ghosts? it may well need to
2379
2083
            # check for them explicitly.
2380
2084
            return False
2381
2085
        return True
2391
2095
 
2392
2096
    def convert(self, tree):
2393
2097
        # lock the control files not the tree, so that we dont get tree
2394
 
        # on-unlock behaviours, and so that noone else diddles with the 
 
2098
        # on-unlock behaviours, and so that noone else diddles with the
2395
2099
        # tree during upgrade.
2396
2100
        tree._control_files.lock_write()
2397
2101
        try:
2423
2127
 
2424
2128
    def update_format(self, tree):
2425
2129
        """Change the format marker."""
2426
 
        tree._control_files.put_utf8('format',
2427
 
            self.target_format.get_format_string())
 
2130
        tree._transport.put_bytes('format',
 
2131
            self.target_format.get_format_string(),
 
2132
            mode=tree.bzrdir._get_file_mode())
 
2133
 
 
2134
 
 
2135
class Converter4to5(object):
 
2136
    """Perform an in-place upgrade of format 4 to format 5 trees."""
 
2137
 
 
2138
    def __init__(self):
 
2139
        self.target_format = WorkingTreeFormat5()
 
2140
 
 
2141
    def convert(self, tree):
 
2142
        # lock the control files not the tree, so that we don't get tree
 
2143
        # on-unlock behaviours, and so that no-one else diddles with the
 
2144
        # tree during upgrade.
 
2145
        tree._control_files.lock_write()
 
2146
        try:
 
2147
            self.update_format(tree)
 
2148
        finally:
 
2149
            tree._control_files.unlock()
 
2150
 
 
2151
    def update_format(self, tree):
 
2152
        """Change the format marker."""
 
2153
        tree._transport.put_bytes('format',
 
2154
            self.target_format.get_format_string(),
 
2155
            mode=tree.bzrdir._get_file_mode())
 
2156
 
 
2157
 
 
2158
class Converter4or5to6(object):
 
2159
    """Perform an in-place upgrade of format 4 or 5 to format 6 trees."""
 
2160
 
 
2161
    def __init__(self):
 
2162
        self.target_format = WorkingTreeFormat6()
 
2163
 
 
2164
    def convert(self, tree):
 
2165
        # lock the control files not the tree, so that we don't get tree
 
2166
        # on-unlock behaviours, and so that no-one else diddles with the
 
2167
        # tree during upgrade.
 
2168
        tree._control_files.lock_write()
 
2169
        try:
 
2170
            self.init_custom_control_files(tree)
 
2171
            self.update_format(tree)
 
2172
        finally:
 
2173
            tree._control_files.unlock()
 
2174
 
 
2175
    def init_custom_control_files(self, tree):
 
2176
        """Initialize custom control files."""
 
2177
        tree._transport.put_bytes('views', '',
 
2178
            mode=tree.bzrdir._get_file_mode())
 
2179
 
 
2180
    def update_format(self, tree):
 
2181
        """Change the format marker."""
 
2182
        tree._transport.put_bytes('format',
 
2183
            self.target_format.get_format_string(),
 
2184
            mode=tree.bzrdir._get_file_mode())