~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree_4.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-04-09 20:23:07 UTC
  • mfrom: (4265.1.4 bbc-merge)
  • Revision ID: pqm@pqm.ubuntu.com-20090409202307-n0depb16qepoe21o
(jam) Change _fetch_uses_deltas = False for CHK repos until we can
        write a better fix.

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