~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: Robert Collins
  • Date: 2006-08-01 04:54:43 UTC
  • mfrom: (1864.6.1 plugin-imports)
  • mto: This revision was merged to the branch mainline in revision 1901.
  • Revision ID: robertc@robertcollins.net-20060801045443-b99468f4250e01c4
Merge Johns bug 51810 fixup.

Show diffs side-by-side

added added

removed removed

Lines of Context:
96
96
        deprecated_function,
97
97
        DEPRECATED_PARAMETER,
98
98
        zero_eight,
99
 
        zero_eleven,
100
99
        )
101
100
from bzrlib.trace import mutter, note
102
101
from bzrlib.transform import build_tree
159
158
    return gen_file_id('TREE_ROOT')
160
159
 
161
160
 
162
 
def needs_tree_write_lock(unbound):
163
 
    """Decorate unbound to take out and release a tree_write lock."""
164
 
    def tree_write_locked(self, *args, **kwargs):
165
 
        self.lock_tree_write()
166
 
        try:
167
 
            return unbound(self, *args, **kwargs)
168
 
        finally:
169
 
            self.unlock()
170
 
    tree_write_locked.__doc__ = unbound.__doc__
171
 
    tree_write_locked.__name__ = unbound.__name__
172
 
    return tree_write_locked
173
 
 
174
 
 
175
161
class TreeEntry(object):
176
162
    """An entry that implements the minimum interface used by commands.
177
163
 
336
322
        self.branch.break_lock()
337
323
 
338
324
    def _set_inventory(self, inv):
339
 
        assert inv.root is not None
340
325
        self._inventory = inv
341
326
        self.path2id = self._inventory.path2id
342
327
 
408
393
        return pathjoin(self.basedir, filename)
409
394
    
410
395
    def basis_tree(self):
411
 
        """Return RevisionTree for the current last revision.
412
 
        
413
 
        If the left most parent is a ghost then the returned tree will be an
414
 
        empty tree - one obtained by calling repository.revision_tree(None).
415
 
        """
416
 
        try:
417
 
            revision_id = self.get_parent_ids()[0]
418
 
        except IndexError:
419
 
            # no parents, return an empty revision tree.
420
 
            # in the future this should return the tree for
421
 
            # 'empty:' - the implicit root empty tree.
422
 
            return self.branch.repository.revision_tree(None)
423
 
        else:
 
396
        """Return RevisionTree for the current last revision."""
 
397
        revision_id = self.last_revision()
 
398
        if revision_id is not None:
424
399
            try:
425
400
                xml = self.read_basis_inventory()
426
 
                inv = bzrlib.xml6.serializer_v6.read_inventory_from_string(xml)
427
 
                if inv is not None and inv.revision_id == revision_id:
428
 
                    return bzrlib.tree.RevisionTree(self.branch.repository, 
429
 
                                                    inv, revision_id)
430
 
            except (NoSuchFile, errors.BadInventoryFormat):
431
 
                pass
432
 
        # No cached copy available, retrieve from the repository.
433
 
        # FIXME? RBC 20060403 should we cache the inventory locally
434
 
        # at this point ?
435
 
        try:
436
 
            return self.branch.repository.revision_tree(revision_id)
437
 
        except errors.RevisionNotPresent:
438
 
            # the basis tree *may* be a ghost or a low level error may have
439
 
            # occured. If the revision is present, its a problem, if its not
440
 
            # its a ghost.
441
 
            if self.branch.repository.has_revision(revision_id):
442
 
                raise
443
 
            # the basis tree is a ghost so return an empty tree.
444
 
            return self.branch.repository.revision_tree(None)
 
401
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
 
402
            except NoSuchFile:
 
403
                inv = None
 
404
            if inv is not None and inv.revision_id == revision_id:
 
405
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
 
406
                                                revision_id)
 
407
        # FIXME? RBC 20060403 should we cache the inventory here ?
 
408
        return self.branch.repository.revision_tree(revision_id)
445
409
 
446
410
    @staticmethod
447
411
    @deprecated_method(zero_eight)
507
471
        This implementation reads the pending merges list and last_revision
508
472
        value and uses that to decide what the parents list should be.
509
473
        """
510
 
        last_rev = self._last_revision()
 
474
        last_rev = self.last_revision()
511
475
        if last_rev is None:
512
476
            parents = []
513
477
        else:
514
478
            parents = [last_rev]
515
 
        try:
516
 
            merges_file = self._control_files.get_utf8('pending-merges')
517
 
        except NoSuchFile:
518
 
            pass
519
 
        else:
520
 
            for l in merges_file.readlines():
521
 
                parents.append(l.rstrip('\n'))
522
 
        return parents
 
479
        other_parents = self.pending_merges()
 
480
        return parents + other_parents
523
481
 
524
482
    def get_root_id(self):
525
483
        """Return the id of this trees root"""
559
517
        if revision_id is None:
560
518
            transform_tree(tree, self)
561
519
        else:
562
 
            # TODO now merge from tree.last_revision to revision (to preserve
563
 
            # user local changes)
 
520
            # TODO now merge from tree.last_revision to revision
564
521
            transform_tree(tree, self)
565
 
            tree.set_parent_ids([revision_id])
 
522
            tree.set_last_revision(revision_id)
566
523
 
567
524
    @needs_write_lock
568
525
    def commit(self, message=None, revprops=None, *args, **kwargs):
578
535
        args = (DEPRECATED_PARAMETER, message, ) + args
579
536
        committed_id = Commit().commit( working_tree=self, revprops=revprops,
580
537
            *args, **kwargs)
 
538
        self._set_inventory(self.read_working_inventory())
581
539
        return committed_id
582
540
 
583
541
    def id2abspath(self, file_id):
622
580
            mode = os.lstat(self.abspath(path)).st_mode
623
581
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
624
582
 
625
 
    @needs_tree_write_lock
 
583
    @needs_write_lock
626
584
    def add(self, files, ids=None):
627
585
        """Make files versioned.
628
586
 
683
641
 
684
642
        self._write_inventory(inv)
685
643
 
686
 
    @needs_tree_write_lock
687
 
    def add_parent_tree_id(self, revision_id, allow_leftmost_as_ghost=False):
688
 
        """Add revision_id as a parent.
689
 
 
690
 
        This is equivalent to retrieving the current list of parent ids
691
 
        and setting the list to its value plus revision_id.
692
 
 
693
 
        :param revision_id: The revision id to add to the parent list. It may
694
 
        be a ghost revision as long as its not the first parent to be added,
695
 
        or the allow_leftmost_as_ghost parameter is set True.
696
 
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
697
 
        """
698
 
        parents = self.get_parent_ids() + [revision_id]
699
 
        self.set_parent_ids(parents,
700
 
            allow_leftmost_as_ghost=len(parents) > 1 or allow_leftmost_as_ghost)
701
 
 
702
 
    @needs_tree_write_lock
703
 
    def add_parent_tree(self, parent_tuple, allow_leftmost_as_ghost=False):
704
 
        """Add revision_id, tree tuple as a parent.
705
 
 
706
 
        This is equivalent to retrieving the current list of parent trees
707
 
        and setting the list to its value plus parent_tuple. See also
708
 
        add_parent_tree_id - if you only have a parent id available it will be
709
 
        simpler to use that api. If you have the parent already available, using
710
 
        this api is preferred.
711
 
 
712
 
        :param parent_tuple: The (revision id, tree) to add to the parent list.
713
 
            If the revision_id is a ghost, pass None for the tree.
714
 
        :param allow_leftmost_as_ghost: Allow the first parent to be a ghost.
715
 
        """
716
 
        parent_ids = self.get_parent_ids() + [parent_tuple[0]]
717
 
        if len(parent_ids) > 1:
718
 
            # the leftmost may have already been a ghost, preserve that if it
719
 
            # was.
720
 
            allow_leftmost_as_ghost = True
721
 
        self.set_parent_ids(parent_ids,
722
 
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
723
 
 
724
 
    @needs_tree_write_lock
 
644
    @needs_write_lock
725
645
    def add_pending_merge(self, *revision_ids):
726
646
        # TODO: Perhaps should check at this point that the
727
647
        # history of the revision is actually present?
728
 
        parents = self.get_parent_ids()
 
648
        p = self.pending_merges()
729
649
        updated = False
730
650
        for rev_id in revision_ids:
731
 
            if rev_id in parents:
 
651
            if rev_id in p:
732
652
                continue
733
 
            parents.append(rev_id)
 
653
            p.append(rev_id)
734
654
            updated = True
735
655
        if updated:
736
 
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
 
656
            self.set_pending_merges(p)
737
657
 
738
 
    @deprecated_method(zero_eleven)
739
658
    @needs_read_lock
740
659
    def pending_merges(self):
741
660
        """Return a list of pending merges.
742
661
 
743
662
        These are revisions that have been merged into the working
744
663
        directory but not yet committed.
745
 
 
746
 
        As of 0.11 this is deprecated. Please see WorkingTree.get_parent_ids()
747
 
        instead - which is available on all tree objects.
748
 
        """
749
 
        return self.get_parent_ids()[1:]
750
 
 
751
 
    @needs_tree_write_lock
752
 
    def set_parent_ids(self, revision_ids, allow_leftmost_as_ghost=False):
753
 
        """Set the parent ids to revision_ids.
754
 
        
755
 
        See also set_parent_trees. This api will try to retrieve the tree data
756
 
        for each element of revision_ids from the trees repository. If you have
757
 
        tree data already available, it is more efficient to use
758
 
        set_parent_trees rather than set_parent_ids. set_parent_ids is however
759
 
        an easier API to use.
760
 
 
761
 
        :param revision_ids: The revision_ids to set as the parent ids of this
762
 
            working tree. Any of these may be ghosts.
763
 
        """
764
 
        if len(revision_ids) > 0:
765
 
            leftmost_id = revision_ids[0]
766
 
            if (not allow_leftmost_as_ghost and not
767
 
                self.branch.repository.has_revision(leftmost_id)):
768
 
                raise errors.GhostRevisionUnusableHere(leftmost_id)
769
 
            self.set_last_revision(leftmost_id)
770
 
        else:
771
 
            self.set_last_revision(None)
772
 
        merges = revision_ids[1:]
773
 
        self._control_files.put_utf8('pending-merges', '\n'.join(merges))
774
 
 
775
 
    @needs_tree_write_lock
776
 
    def set_parent_trees(self, parents_list, allow_leftmost_as_ghost=False):
777
 
        """Set the parents of the working tree.
778
 
 
779
 
        :param parents_list: A list of (revision_id, tree) tuples. 
780
 
            If tree is None, then that element is treated as an unreachable
781
 
            parent tree - i.e. a ghost.
782
 
        """
783
 
        # parent trees are not used in current format trees, delegate to
784
 
        # set_parent_ids
785
 
        self.set_parent_ids([rev for (rev, tree) in parents_list],
786
 
            allow_leftmost_as_ghost=allow_leftmost_as_ghost)
787
 
 
788
 
    @needs_tree_write_lock
 
664
        """
 
665
        try:
 
666
            merges_file = self._control_files.get_utf8('pending-merges')
 
667
        except NoSuchFile:
 
668
            return []
 
669
        p = []
 
670
        for l in merges_file.readlines():
 
671
            p.append(l.rstrip('\n'))
 
672
        return p
 
673
 
 
674
    @needs_write_lock
789
675
    def set_pending_merges(self, rev_list):
790
 
        parents = self.get_parent_ids()
791
 
        leftmost = parents[:1]
792
 
        new_parents = leftmost + rev_list
793
 
        self.set_parent_ids(new_parents)
 
676
        self._control_files.put_utf8('pending-merges', '\n'.join(rev_list))
794
677
 
795
 
    @needs_tree_write_lock
 
678
    @needs_write_lock
796
679
    def set_merge_modified(self, modified_hashes):
797
680
        def iter_stanzas():
798
681
            for file_id, hash in modified_hashes.iteritems():
799
682
                yield Stanza(file_id=file_id, hash=hash)
800
683
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
801
684
 
802
 
    @needs_tree_write_lock
 
685
    @needs_write_lock
803
686
    def _put_rio(self, filename, stanzas, header):
804
687
        my_file = rio_file(stanzas, header)
805
688
        self._control_files.put(filename, my_file)
806
689
 
807
 
    @needs_write_lock # because merge pulls data into the branch.
808
 
    def merge_from_branch(self, branch, to_revision=None):
809
 
        """Merge from a branch into this working tree.
810
 
 
811
 
        :param branch: The branch to merge from.
812
 
        :param to_revision: If non-None, the merge will merge to to_revision, but 
813
 
            not beyond it. to_revision does not need to be in the history of
814
 
            the branch when it is supplied. If None, to_revision defaults to
815
 
            branch.last_revision().
816
 
        """
817
 
        from bzrlib.merge import Merger, Merge3Merger
818
 
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
819
 
        try:
820
 
            merger = Merger(self.branch, this_tree=self, pb=pb)
821
 
            merger.pp = ProgressPhase("Merge phase", 5, pb)
822
 
            merger.pp.next_phase()
823
 
            # check that there are no
824
 
            # local alterations
825
 
            merger.check_basis(check_clean=True, require_commits=False)
826
 
            if to_revision is None:
827
 
                to_revision = branch.last_revision()
828
 
            merger.other_rev_id = to_revision
829
 
            if merger.other_rev_id is None:
830
 
                raise error.NoCommits(branch)
831
 
            self.branch.fetch(branch, last_revision=merger.other_rev_id)
832
 
            merger.other_basis = merger.other_rev_id
833
 
            merger.other_tree = self.branch.repository.revision_tree(
834
 
                merger.other_rev_id)
835
 
            merger.pp.next_phase()
836
 
            merger.find_base()
837
 
            if merger.base_rev_id == merger.other_rev_id:
838
 
                raise errors.PointlessMerge
839
 
            merger.backup_files = False
840
 
            merger.merge_type = Merge3Merger
841
 
            merger.set_interesting_files(None)
842
 
            merger.show_base = False
843
 
            merger.reprocess = False
844
 
            conflicts = merger.do_merge()
845
 
            merger.set_pending()
846
 
        finally:
847
 
            pb.finished()
848
 
        return conflicts
849
 
 
850
690
    @needs_read_lock
851
691
    def merge_modified(self):
852
692
        try:
988
828
                # if we finished all children, pop it off the stack
989
829
                stack.pop()
990
830
 
991
 
    @needs_tree_write_lock
 
831
 
 
832
    @needs_write_lock
992
833
    def move(self, from_paths, to_name):
993
834
        """Rename files.
994
835
 
1013
854
        if not self.has_filename(to_name):
1014
855
            raise BzrError("destination %r not in working directory" % to_abs)
1015
856
        to_dir_id = inv.path2id(to_name)
1016
 
        if to_dir_id is None and to_name != '':
 
857
        if to_dir_id == None and to_name != '':
1017
858
            raise BzrError("destination %r is not a versioned directory" % to_name)
1018
859
        to_dir_ie = inv[to_dir_id]
1019
 
        if to_dir_ie.kind != 'directory':
 
860
        if to_dir_ie.kind not in ('directory', 'root_directory'):
1020
861
            raise BzrError("destination %r is not a directory" % to_abs)
1021
862
 
1022
863
        to_idpath = inv.get_idpath(to_dir_id)
1025
866
            if not self.has_filename(f):
1026
867
                raise BzrError("%r does not exist in working tree" % f)
1027
868
            f_id = inv.path2id(f)
1028
 
            if f_id is None:
 
869
            if f_id == None:
1029
870
                raise BzrError("%r is not versioned" % f)
1030
871
            name_tail = splitpath(f)[-1]
1031
872
            dest_path = pathjoin(to_name, name_tail)
1057
898
        self._write_inventory(inv)
1058
899
        return result
1059
900
 
1060
 
    @needs_tree_write_lock
 
901
    @needs_write_lock
1061
902
    def rename_one(self, from_rel, to_rel):
1062
903
        """Rename one file.
1063
904
 
1070
911
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
1071
912
 
1072
913
        file_id = inv.path2id(from_rel)
1073
 
        if file_id is None:
 
914
        if file_id == None:
1074
915
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
1075
916
 
1076
917
        entry = inv[file_id]
1082
923
 
1083
924
        to_dir, to_tail = os.path.split(to_rel)
1084
925
        to_dir_id = inv.path2id(to_dir)
1085
 
        if to_dir_id is None and to_dir != '':
 
926
        if to_dir_id == None and to_dir != '':
1086
927
            raise BzrError("can't determine destination directory id for %r" % to_dir)
1087
928
 
1088
929
        mutter("rename_one:")
1115
956
        for subp in self.extras():
1116
957
            if not self.is_ignored(subp):
1117
958
                yield subp
1118
 
    
1119
 
    @needs_tree_write_lock
1120
 
    def unversion(self, file_ids):
1121
 
        """Remove the file ids in file_ids from the current versioned set.
1122
 
 
1123
 
        When a file_id is unversioned, all of its children are automatically
1124
 
        unversioned.
1125
 
 
1126
 
        :param file_ids: The file ids to stop versioning.
1127
 
        :raises: NoSuchId if any fileid is not currently versioned.
1128
 
        """
1129
 
        for file_id in file_ids:
1130
 
            if self._inventory.has_id(file_id):
1131
 
                self._inventory.remove_recursive_id(file_id)
1132
 
            else:
1133
 
                raise errors.NoSuchId(self, file_id)
1134
 
        if len(file_ids):
1135
 
            # in the future this should just set a dirty bit to wait for the 
1136
 
            # final unlock. However, until all methods of workingtree start
1137
 
            # with the current in -memory inventory rather than triggering 
1138
 
            # a read, it is more complex - we need to teach read_inventory
1139
 
            # to know when to read, and when to not read first... and possibly
1140
 
            # to save first when the in memory one may be corrupted.
1141
 
            # so for now, we just only write it if it is indeed dirty.
1142
 
            # - RBC 20060907
1143
 
            self._write_inventory(self._inventory)
1144
 
    
 
959
 
1145
960
    @deprecated_method(zero_eight)
1146
961
    def iter_conflicts(self):
1147
962
        """List all files in the tree that have text or content conflicts.
1179
994
                repository = self.branch.repository
1180
995
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
1181
996
                try:
1182
 
                    new_basis_tree = self.branch.basis_tree()
1183
997
                    merge_inner(self.branch,
1184
 
                                new_basis_tree,
1185
 
                                basis_tree,
1186
 
                                this_tree=self,
 
998
                                self.branch.basis_tree(),
 
999
                                basis_tree, 
 
1000
                                this_tree=self, 
1187
1001
                                pb=pb)
1188
1002
                finally:
1189
1003
                    pb.finished()
1190
 
                # TODO - dedup parents list with things merged by pull ?
1191
 
                # reuse the revisiontree we merged against to set the new
1192
 
                # tree data.
1193
 
                parent_trees = [(self.branch.last_revision(), new_basis_tree)]
1194
 
                # we have to pull the merge trees out again, because 
1195
 
                # merge_inner has set the ids. - this corner is not yet 
1196
 
                # layered well enough to prevent double handling.
1197
 
                merges = self.get_parent_ids()[1:]
1198
 
                parent_trees.extend([
1199
 
                    (parent, repository.revision_tree(parent)) for
1200
 
                     parent in merges])
1201
 
                self.set_parent_trees(parent_trees)
 
1004
                self.set_last_revision(self.branch.last_revision())
1202
1005
            return count
1203
1006
        finally:
1204
1007
            source.unlock()
1297
1100
        """Yield list of PATH, IGNORE_PATTERN"""
1298
1101
        for subp in self.extras():
1299
1102
            pat = self.is_ignored(subp)
1300
 
            if pat is not None:
 
1103
            if pat != None:
1301
1104
                yield subp, pat
1302
1105
 
1303
1106
    def get_ignore_list(self):
1358
1161
        for regex, mapping in rules:
1359
1162
            match = regex.match(filename)
1360
1163
            if match is not None:
1361
 
                # one or more of the groups in mapping will have a non-None
1362
 
                # group match.
 
1164
                # one or more of the groups in mapping will have a non-None group 
 
1165
                # match.
1363
1166
                groups = match.groups()
1364
1167
                rules = [mapping[group] for group in 
1365
1168
                    mapping if groups[group] is not None]
1369
1172
    def kind(self, file_id):
1370
1173
        return file_kind(self.id2abspath(file_id))
1371
1174
 
 
1175
    @needs_read_lock
1372
1176
    def last_revision(self):
1373
1177
        """Return the last revision id of this working tree.
1374
1178
 
1375
 
        In early branch formats this was the same as the branch last_revision,
 
1179
        In early branch formats this was == the branch last_revision,
1376
1180
        but that cannot be relied upon - for working tree operations,
1377
 
        always use tree.last_revision(). This returns the left most parent id,
1378
 
        or None if there are no parents.
1379
 
 
1380
 
        This was deprecated as of 0.11. Please use get_parent_ids instead.
 
1181
        always use tree.last_revision().
1381
1182
        """
1382
 
        return self._last_revision()
1383
 
 
1384
 
    @needs_read_lock
1385
 
    def _last_revision(self):
1386
 
        """helper for get_parent_ids."""
1387
1183
        return self.branch.last_revision()
1388
1184
 
1389
1185
    def is_locked(self):
1398
1194
            self.branch.unlock()
1399
1195
            raise
1400
1196
 
1401
 
    def lock_tree_write(self):
1402
 
        """Lock the working tree for write, and the branch for read.
1403
 
 
1404
 
        This is useful for operations which only need to mutate the working
1405
 
        tree. Taking out branch write locks is a relatively expensive process
1406
 
        and may fail if the branch is on read only media. So branch write locks
1407
 
        should only be taken out when we are modifying branch data - such as in
1408
 
        operations like commit, pull, uncommit and update.
1409
 
        """
1410
 
        self.branch.lock_read()
1411
 
        try:
1412
 
            return self._control_files.lock_write()
1413
 
        except:
1414
 
            self.branch.unlock()
1415
 
            raise
1416
 
 
1417
1197
    def lock_write(self):
1418
1198
        """See Branch.lock_write, and WorkingTree.unlock."""
1419
1199
        self.branch.lock_write()
1427
1207
        return self._control_files.get_physical_lock_status()
1428
1208
 
1429
1209
    def _basis_inventory_name(self):
1430
 
        return 'basis-inventory-cache'
 
1210
        return 'basis-inventory'
1431
1211
 
1432
 
    @needs_tree_write_lock
 
1212
    @needs_write_lock
1433
1213
    def set_last_revision(self, new_revision):
1434
1214
        """Change the last revision in the working tree."""
1435
1215
        if self._change_last_revision(new_revision):
1444
1224
        if new_revision is None:
1445
1225
            self.branch.set_revision_history([])
1446
1226
            return False
 
1227
        # current format is locked in with the branch
 
1228
        revision_history = self.branch.revision_history()
1447
1229
        try:
1448
 
            self.branch.generate_revision_history(new_revision)
1449
 
        except errors.NoSuchRevision:
1450
 
            # not present in the repo - dont try to set it deeper than the tip
1451
 
            self.branch.set_revision_history([new_revision])
 
1230
            position = revision_history.index(new_revision)
 
1231
        except ValueError:
 
1232
            raise errors.NoSuchRevision(self.branch, new_revision)
 
1233
        self.branch.set_revision_history(revision_history[:position + 1])
1452
1234
        return True
1453
1235
 
1454
1236
    def _cache_basis_inventory(self, new_revision):
1468
1250
            # root node id can legitimately look like 'revision_id' but cannot
1469
1251
            # contain a '"'.
1470
1252
            xml = self.branch.repository.get_inventory_xml(new_revision)
1471
 
            firstline = xml.split('\n', 1)[0]
1472
 
            if (not 'revision_id="' in firstline or 
1473
 
                'format="6"' not in firstline):
 
1253
            if not 'revision_id="' in xml.split('\n', 1)[0]:
1474
1254
                inv = self.branch.repository.deserialise_inventory(
1475
1255
                    new_revision, xml)
1476
1256
                inv.revision_id = new_revision
1477
 
                xml = bzrlib.xml6.serializer_v6.write_inventory_to_string(inv)
 
1257
                xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
1478
1258
            assert isinstance(xml, str), 'serialised xml must be bytestring.'
1479
1259
            path = self._basis_inventory_name()
1480
1260
            sio = StringIO(xml)
1481
1261
            self._control_files.put(path, sio)
1482
 
        except (errors.NoSuchRevision, errors.RevisionNotPresent):
 
1262
        except WeaveRevisionNotPresent:
1483
1263
            pass
1484
1264
 
1485
1265
    def read_basis_inventory(self):
1497
1277
        self._set_inventory(result)
1498
1278
        return result
1499
1279
 
1500
 
    @needs_tree_write_lock
 
1280
    @needs_write_lock
1501
1281
    def remove(self, files, verbose=False, to_file=None):
1502
1282
        """Remove nominated files from the working inventory..
1503
1283
 
1537
1317
 
1538
1318
        self._write_inventory(inv)
1539
1319
 
1540
 
    @needs_tree_write_lock
 
1320
    @needs_write_lock
1541
1321
    def revert(self, filenames, old_tree=None, backups=True, 
1542
1322
               pb=DummyProgress()):
1543
1323
        from transform import revert
1546
1326
            old_tree = self.basis_tree()
1547
1327
        conflicts = revert(self, old_tree, filenames, backups, pb)
1548
1328
        if not len(filenames):
1549
 
            self.set_parent_ids(self.get_parent_ids()[:1])
 
1329
            self.set_pending_merges([])
1550
1330
            resolve(self)
1551
1331
        else:
1552
1332
            resolve(self, filenames, ignore_misses=True)
1554
1334
 
1555
1335
    # XXX: This method should be deprecated in favour of taking in a proper
1556
1336
    # new Inventory object.
1557
 
    @needs_tree_write_lock
 
1337
    @needs_write_lock
1558
1338
    def set_inventory(self, new_inventory_list):
1559
1339
        from bzrlib.inventory import (Inventory,
1560
1340
                                      InventoryDirectory,
1577
1357
                raise BzrError("unknown kind %r" % kind)
1578
1358
        self._write_inventory(inv)
1579
1359
 
1580
 
    @needs_tree_write_lock
 
1360
    @needs_write_lock
1581
1361
    def set_root_id(self, file_id):
1582
1362
        """Set the root id for this tree."""
1583
1363
        inv = self.read_working_inventory()
1623
1403
        Do a 'normal' merge of the old branch basis if it is relevant.
1624
1404
        """
1625
1405
        old_tip = self.branch.update()
1626
 
        # here if old_tip is not None, it is the old tip of the branch before
1627
 
        # it was updated from the master branch. This should become a pending
1628
 
        # merge in the working tree to preserve the user existing work.  we
1629
 
        # cant set that until we update the working trees last revision to be
1630
 
        # one from the new branch, because it will just get absorbed by the
1631
 
        # parent de-duplication logic.
1632
 
        # 
1633
 
        # We MUST save it even if an error occurs, because otherwise the users
1634
 
        # local work is unreferenced and will appear to have been lost.
1635
 
        # 
1636
 
        result = 0
 
1406
        if old_tip is not None:
 
1407
            self.add_pending_merge(old_tip)
 
1408
        self.branch.lock_read()
1637
1409
        try:
1638
 
            last_rev = self.get_parent_ids()[0]
1639
 
        except IndexError:
1640
 
            last_rev = None
1641
 
        if last_rev != self.branch.last_revision():
1642
 
            # merge tree state up to new branch tip.
1643
 
            basis = self.basis_tree()
1644
 
            to_tree = self.branch.basis_tree()
1645
 
            result += merge_inner(self.branch,
1646
 
                                  to_tree,
1647
 
                                  basis,
1648
 
                                  this_tree=self)
1649
 
            # TODO - dedup parents list with things merged by pull ?
1650
 
            # reuse the tree we've updated to to set the basis:
1651
 
            parent_trees = [(self.branch.last_revision(), to_tree)]
1652
 
            merges = self.get_parent_ids()[1:]
1653
 
            # Ideally we ask the tree for the trees here, that way the working
1654
 
            # tree can decide whether to give us teh entire tree or give us a
1655
 
            # lazy initialised tree. dirstate for instance will have the trees
1656
 
            # in ram already, whereas a last-revision + basis-inventory tree
1657
 
            # will not, but also does not need them when setting parents.
1658
 
            for parent in merges:
1659
 
                parent_trees.append(
1660
 
                    (parent, self.branch.repository.revision_tree(parent)))
1661
 
            if old_tip is not None:
1662
 
                parent_trees.append(
1663
 
                    (old_tip, self.branch.repository.revision_tree(old_tip)))
1664
 
            self.set_parent_trees(parent_trees)
1665
 
            last_rev = parent_trees[0][0]
1666
 
        else:
1667
 
            # the working tree had the same last-revision as the master
1668
 
            # branch did. We may still have pivot local work from the local
1669
 
            # branch into old_tip:
1670
 
            if old_tip is not None:
1671
 
                self.add_parent_tree_id(old_tip)
1672
 
        if old_tip and old_tip != last_rev:
1673
 
            # our last revision was not the prior branch last revision
1674
 
            # and we have converted that last revision to a pending merge.
1675
 
            # base is somewhere between the branch tip now
1676
 
            # and the now pending merge
1677
 
            from bzrlib.revision import common_ancestor
1678
 
            try:
1679
 
                base_rev_id = common_ancestor(self.branch.last_revision(),
1680
 
                                              old_tip,
1681
 
                                              self.branch.repository)
1682
 
            except errors.NoCommonAncestor:
1683
 
                base_rev_id = None
1684
 
            base_tree = self.branch.repository.revision_tree(base_rev_id)
1685
 
            other_tree = self.branch.repository.revision_tree(old_tip)
1686
 
            result += merge_inner(self.branch,
1687
 
                                  other_tree,
1688
 
                                  base_tree,
1689
 
                                  this_tree=self)
1690
 
        return result
 
1410
            result = 0
 
1411
            if self.last_revision() != self.branch.last_revision():
 
1412
                # merge tree state up to new branch tip.
 
1413
                basis = self.basis_tree()
 
1414
                to_tree = self.branch.basis_tree()
 
1415
                result += merge_inner(self.branch,
 
1416
                                      to_tree,
 
1417
                                      basis,
 
1418
                                      this_tree=self)
 
1419
                self.set_last_revision(self.branch.last_revision())
 
1420
            if old_tip and old_tip != self.last_revision():
 
1421
                # our last revision was not the prior branch last revision
 
1422
                # and we have converted that last revision to a pending merge.
 
1423
                # base is somewhere between the branch tip now
 
1424
                # and the now pending merge
 
1425
                from bzrlib.revision import common_ancestor
 
1426
                try:
 
1427
                    base_rev_id = common_ancestor(self.branch.last_revision(),
 
1428
                                                  old_tip,
 
1429
                                                  self.branch.repository)
 
1430
                except errors.NoCommonAncestor:
 
1431
                    base_rev_id = None
 
1432
                base_tree = self.branch.repository.revision_tree(base_rev_id)
 
1433
                other_tree = self.branch.repository.revision_tree(old_tip)
 
1434
                result += merge_inner(self.branch,
 
1435
                                      other_tree,
 
1436
                                      base_tree,
 
1437
                                      this_tree=self)
 
1438
            return result
 
1439
        finally:
 
1440
            self.branch.unlock()
1691
1441
 
1692
 
    @needs_tree_write_lock
 
1442
    @needs_write_lock
1693
1443
    def _write_inventory(self, inv):
1694
1444
        """Write inventory as the current inventory."""
1695
1445
        sio = StringIO()
1739
1489
     - uses the branch last-revision.
1740
1490
    """
1741
1491
 
1742
 
    def lock_tree_write(self):
1743
 
        """See WorkingTree.lock_tree_write().
1744
 
 
1745
 
        In Format2 WorkingTrees we have a single lock for the branch and tree
1746
 
        so lock_tree_write() degrades to lock_write().
1747
 
        """
1748
 
        self.branch.lock_write()
1749
 
        try:
1750
 
            return self._control_files.lock_write()
1751
 
        except:
1752
 
            self.branch.unlock()
1753
 
            raise
1754
 
 
1755
1492
    def unlock(self):
1756
1493
        # we share control files:
1757
1494
        if self._hashcache.needs_write and self._control_files._lock_count==3:
1774
1511
    """
1775
1512
 
1776
1513
    @needs_read_lock
1777
 
    def _last_revision(self):
1778
 
        """See WorkingTree._last_revision."""
 
1514
    def last_revision(self):
 
1515
        """See WorkingTree.last_revision."""
1779
1516
        try:
1780
1517
            return self._control_files.get_utf8('last-revision').read()
1781
1518
        except NoSuchFile:
1790
1527
                pass
1791
1528
            return False
1792
1529
        else:
 
1530
            try:
 
1531
                self.branch.revision_history().index(revision_id)
 
1532
            except ValueError:
 
1533
                raise errors.NoSuchRevision(self.branch, revision_id)
1793
1534
            self._control_files.put_utf8('last-revision', revision_id)
1794
1535
            return True
1795
1536
 
1796
 
    @needs_tree_write_lock
 
1537
    @needs_write_lock
1797
1538
    def set_conflicts(self, conflicts):
1798
1539
        self._put_rio('conflicts', conflicts.to_stanzas(), 
1799
1540
                      CONFLICT_HEADER_1)
1800
1541
 
1801
 
    @needs_tree_write_lock
 
1542
    @needs_write_lock
1802
1543
    def add_conflicts(self, new_conflicts):
1803
1544
        conflict_set = set(self.conflicts())
1804
1545
        conflict_set.update(set(list(new_conflicts)))
1965
1706
            finally:
1966
1707
                branch.unlock()
1967
1708
        revision = branch.last_revision()
1968
 
        inv = Inventory()
 
1709
        inv = Inventory() 
1969
1710
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1970
1711
                         branch,
1971
1712
                         inv,
1974
1715
                         _bzrdir=a_bzrdir)
1975
1716
        wt._write_inventory(inv)
1976
1717
        wt.set_root_id(inv.root.file_id)
1977
 
        basis_tree = branch.repository.revision_tree(revision)
1978
 
        wt.set_parent_trees([(revision, basis_tree)])
1979
 
        build_tree(basis_tree, wt)
 
1718
        wt.set_last_revision(revision)
 
1719
        wt.set_pending_merges([])
 
1720
        build_tree(wt.basis_tree(), wt)
1980
1721
        return wt
1981
1722
 
1982
1723
    def __init__(self):
2052
1793
                         _format=self,
2053
1794
                         _bzrdir=a_bzrdir,
2054
1795
                         _control_files=control_files)
2055
 
        wt.lock_tree_write()
 
1796
        wt.lock_write()
2056
1797
        try:
2057
1798
            wt._write_inventory(inv)
2058
1799
            wt.set_root_id(inv.root.file_id)
2059
 
            basis_tree = branch.repository.revision_tree(revision_id)
2060
 
            if revision_id == bzrlib.revision.NULL_REVISION:
2061
 
                wt.set_parent_trees([])
2062
 
            else:
2063
 
                wt.set_parent_trees([(revision_id, basis_tree)])
2064
 
            build_tree(basis_tree, wt)
 
1800
            wt.set_last_revision(revision_id)
 
1801
            wt.set_pending_merges([])
 
1802
            build_tree(wt.basis_tree(), wt)
2065
1803
        finally:
2066
1804
            wt.unlock()
2067
1805
            control_files.unlock()