/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/workingtree.py

  • Committer: John Arbash Meinel
  • Date: 2006-09-15 00:44:57 UTC
  • mfrom: (2009 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2050.
  • Revision ID: john@arbash-meinel.com-20060915004457-902cec0526a39337
[merge] bzr.dev 2009

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,
99
100
        )
100
101
from bzrlib.trace import mutter, note
101
102
from bzrlib.transform import build_tree
158
159
    return gen_file_id('TREE_ROOT')
159
160
 
160
161
 
 
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
 
161
175
class TreeEntry(object):
162
176
    """An entry that implements the minimum interface used by commands.
163
177
 
394
408
        return pathjoin(self.basedir, filename)
395
409
    
396
410
    def basis_tree(self):
397
 
        """Return RevisionTree for the current last revision."""
398
 
        revision_id = self.last_revision()
399
 
        if revision_id is not None:
 
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:
400
424
            try:
401
425
                xml = self.read_basis_inventory()
402
 
                inv = bzrlib.xml5.serializer_v5.read_inventory_from_string(xml)
403
 
                inv.root.revision = revision_id
404
 
            except NoSuchFile:
405
 
                inv = None
406
 
            if inv is not None and inv.revision_id == revision_id:
407
 
                return bzrlib.tree.RevisionTree(self.branch.repository, inv,
408
 
                                                revision_id)
409
 
        # FIXME? RBC 20060403 should we cache the inventory here ?
410
 
        return self.branch.repository.revision_tree(revision_id)
 
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)
411
445
 
412
446
    @staticmethod
413
447
    @deprecated_method(zero_eight)
473
507
        This implementation reads the pending merges list and last_revision
474
508
        value and uses that to decide what the parents list should be.
475
509
        """
476
 
        last_rev = self.last_revision()
 
510
        last_rev = self._last_revision()
477
511
        if last_rev is None:
478
512
            parents = []
479
513
        else:
480
514
            parents = [last_rev]
481
 
        other_parents = self.pending_merges()
482
 
        return parents + other_parents
 
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
483
523
 
484
524
    def get_root_id(self):
485
525
        """Return the id of this trees root"""
519
559
        if revision_id is None:
520
560
            transform_tree(tree, self)
521
561
        else:
522
 
            # TODO now merge from tree.last_revision to revision
 
562
            # TODO now merge from tree.last_revision to revision (to preserve
 
563
            # user local changes)
523
564
            transform_tree(tree, self)
524
 
            tree.set_last_revision(revision_id)
 
565
            tree.set_parent_ids([revision_id])
525
566
 
526
567
    @needs_write_lock
527
568
    def commit(self, message=None, revprops=None, *args, **kwargs):
537
578
        args = (DEPRECATED_PARAMETER, message, ) + args
538
579
        committed_id = Commit().commit( working_tree=self, revprops=revprops,
539
580
            *args, **kwargs)
540
 
        self._set_inventory(self.read_working_inventory())
541
581
        return committed_id
542
582
 
543
583
    def id2abspath(self, file_id):
582
622
            mode = os.lstat(self.abspath(path)).st_mode
583
623
            return bool(stat.S_ISREG(mode) and stat.S_IEXEC & mode)
584
624
 
585
 
    @needs_write_lock
 
625
    @needs_tree_write_lock
586
626
    def add(self, files, ids=None):
587
627
        """Make files versioned.
588
628
 
643
683
 
644
684
        self._write_inventory(inv)
645
685
 
646
 
    @needs_write_lock
 
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
647
725
    def add_pending_merge(self, *revision_ids):
648
726
        # TODO: Perhaps should check at this point that the
649
727
        # history of the revision is actually present?
650
 
        p = self.pending_merges()
 
728
        parents = self.get_parent_ids()
651
729
        updated = False
652
730
        for rev_id in revision_ids:
653
 
            if rev_id in p:
 
731
            if rev_id in parents:
654
732
                continue
655
 
            p.append(rev_id)
 
733
            parents.append(rev_id)
656
734
            updated = True
657
735
        if updated:
658
 
            self.set_pending_merges(p)
 
736
            self.set_parent_ids(parents, allow_leftmost_as_ghost=True)
659
737
 
 
738
    @deprecated_method(zero_eleven)
660
739
    @needs_read_lock
661
740
    def pending_merges(self):
662
741
        """Return a list of pending merges.
663
742
 
664
743
        These are revisions that have been merged into the working
665
744
        directory but not yet committed.
666
 
        """
667
 
        try:
668
 
            merges_file = self._control_files.get_utf8('pending-merges')
669
 
        except NoSuchFile:
670
 
            return []
671
 
        p = []
672
 
        for l in merges_file.readlines():
673
 
            p.append(l.rstrip('\n'))
674
 
        return p
675
 
 
676
 
    @needs_write_lock
 
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
677
789
    def set_pending_merges(self, rev_list):
678
 
        self._control_files.put_utf8('pending-merges', '\n'.join(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)
679
794
 
680
 
    @needs_write_lock
 
795
    @needs_tree_write_lock
681
796
    def set_merge_modified(self, modified_hashes):
682
797
        def iter_stanzas():
683
798
            for file_id, hash in modified_hashes.iteritems():
684
799
                yield Stanza(file_id=file_id, hash=hash)
685
800
        self._put_rio('merge-hashes', iter_stanzas(), MERGE_MODIFIED_HEADER_1)
686
801
 
687
 
    @needs_write_lock
 
802
    @needs_tree_write_lock
688
803
    def _put_rio(self, filename, stanzas, header):
689
804
        my_file = rio_file(stanzas, header)
690
805
        self._control_files.put(filename, my_file)
691
806
 
 
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
 
692
850
    @needs_read_lock
693
851
    def merge_modified(self):
694
852
        try:
830
988
                # if we finished all children, pop it off the stack
831
989
                stack.pop()
832
990
 
833
 
 
834
 
    @needs_write_lock
 
991
    @needs_tree_write_lock
835
992
    def move(self, from_paths, to_name):
836
993
        """Rename files.
837
994
 
856
1013
        if not self.has_filename(to_name):
857
1014
            raise BzrError("destination %r not in working directory" % to_abs)
858
1015
        to_dir_id = inv.path2id(to_name)
859
 
        if to_dir_id == None and to_name != '':
 
1016
        if to_dir_id is None and to_name != '':
860
1017
            raise BzrError("destination %r is not a versioned directory" % to_name)
861
1018
        to_dir_ie = inv[to_dir_id]
862
1019
        if to_dir_ie.kind != 'directory':
868
1025
            if not self.has_filename(f):
869
1026
                raise BzrError("%r does not exist in working tree" % f)
870
1027
            f_id = inv.path2id(f)
871
 
            if f_id == None:
 
1028
            if f_id is None:
872
1029
                raise BzrError("%r is not versioned" % f)
873
1030
            name_tail = splitpath(f)[-1]
874
1031
            dest_path = pathjoin(to_name, name_tail)
900
1057
        self._write_inventory(inv)
901
1058
        return result
902
1059
 
903
 
    @needs_write_lock
 
1060
    @needs_tree_write_lock
904
1061
    def rename_one(self, from_rel, to_rel):
905
1062
        """Rename one file.
906
1063
 
913
1070
            raise BzrError("can't rename: new working file %r already exists" % to_rel)
914
1071
 
915
1072
        file_id = inv.path2id(from_rel)
916
 
        if file_id == None:
 
1073
        if file_id is None:
917
1074
            raise BzrError("can't rename: old name %r is not versioned" % from_rel)
918
1075
 
919
1076
        entry = inv[file_id]
925
1082
 
926
1083
        to_dir, to_tail = os.path.split(to_rel)
927
1084
        to_dir_id = inv.path2id(to_dir)
928
 
        if to_dir_id == None and to_dir != '':
 
1085
        if to_dir_id is None and to_dir != '':
929
1086
            raise BzrError("can't determine destination directory id for %r" % to_dir)
930
1087
 
931
1088
        mutter("rename_one:")
958
1115
        for subp in self.extras():
959
1116
            if not self.is_ignored(subp):
960
1117
                yield subp
961
 
 
 
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
    
962
1145
    @deprecated_method(zero_eight)
963
1146
    def iter_conflicts(self):
964
1147
        """List all files in the tree that have text or content conflicts.
996
1179
                repository = self.branch.repository
997
1180
                pb = bzrlib.ui.ui_factory.nested_progress_bar()
998
1181
                try:
 
1182
                    new_basis_tree = self.branch.basis_tree()
999
1183
                    merge_inner(self.branch,
1000
 
                                self.branch.basis_tree(),
1001
 
                                basis_tree, 
1002
 
                                this_tree=self, 
 
1184
                                new_basis_tree,
 
1185
                                basis_tree,
 
1186
                                this_tree=self,
1003
1187
                                pb=pb)
1004
1188
                finally:
1005
1189
                    pb.finished()
1006
 
                self.set_last_revision(self.branch.last_revision())
 
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)
1007
1202
            return count
1008
1203
        finally:
1009
1204
            source.unlock()
1102
1297
        """Yield list of PATH, IGNORE_PATTERN"""
1103
1298
        for subp in self.extras():
1104
1299
            pat = self.is_ignored(subp)
1105
 
            if pat != None:
 
1300
            if pat is not None:
1106
1301
                yield subp, pat
1107
1302
 
1108
1303
    def get_ignore_list(self):
1163
1358
        for regex, mapping in rules:
1164
1359
            match = regex.match(filename)
1165
1360
            if match is not None:
1166
 
                # one or more of the groups in mapping will have a non-None group 
1167
 
                # match.
 
1361
                # one or more of the groups in mapping will have a non-None
 
1362
                # group match.
1168
1363
                groups = match.groups()
1169
1364
                rules = [mapping[group] for group in 
1170
1365
                    mapping if groups[group] is not None]
1174
1369
    def kind(self, file_id):
1175
1370
        return file_kind(self.id2abspath(file_id))
1176
1371
 
1177
 
    @needs_read_lock
1178
1372
    def last_revision(self):
1179
1373
        """Return the last revision id of this working tree.
1180
1374
 
1181
 
        In early branch formats this was == the branch last_revision,
 
1375
        In early branch formats this was the same as the branch last_revision,
1182
1376
        but that cannot be relied upon - for working tree operations,
1183
 
        always use tree.last_revision().
 
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.
1184
1381
        """
 
1382
        return self._last_revision()
 
1383
 
 
1384
    @needs_read_lock
 
1385
    def _last_revision(self):
 
1386
        """helper for get_parent_ids."""
1185
1387
        return self.branch.last_revision()
1186
1388
 
1187
1389
    def is_locked(self):
1196
1398
            self.branch.unlock()
1197
1399
            raise
1198
1400
 
 
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
 
1199
1417
    def lock_write(self):
1200
1418
        """See Branch.lock_write, and WorkingTree.unlock."""
1201
1419
        self.branch.lock_write()
1209
1427
        return self._control_files.get_physical_lock_status()
1210
1428
 
1211
1429
    def _basis_inventory_name(self):
1212
 
        return 'basis-inventory'
 
1430
        return 'basis-inventory-cache'
1213
1431
 
1214
 
    @needs_write_lock
 
1432
    @needs_tree_write_lock
1215
1433
    def set_last_revision(self, new_revision):
1216
1434
        """Change the last revision in the working tree."""
1217
1435
        if self._change_last_revision(new_revision):
1250
1468
            # root node id can legitimately look like 'revision_id' but cannot
1251
1469
            # contain a '"'.
1252
1470
            xml = self.branch.repository.get_inventory_xml(new_revision)
1253
 
            if not 'revision_id="' in xml.split('\n', 1)[0]:
 
1471
            firstline = xml.split('\n', 1)[0]
 
1472
            if (not 'revision_id="' in firstline or 
 
1473
                'format="6"' not in firstline):
1254
1474
                inv = self.branch.repository.deserialise_inventory(
1255
1475
                    new_revision, xml)
1256
1476
                inv.revision_id = new_revision
1257
 
                xml = bzrlib.xml5.serializer_v5.write_inventory_to_string(inv)
 
1477
                xml = bzrlib.xml6.serializer_v6.write_inventory_to_string(inv)
1258
1478
            assert isinstance(xml, str), 'serialised xml must be bytestring.'
1259
1479
            path = self._basis_inventory_name()
1260
1480
            sio = StringIO(xml)
1277
1497
        self._set_inventory(result)
1278
1498
        return result
1279
1499
 
1280
 
    @needs_write_lock
 
1500
    @needs_tree_write_lock
1281
1501
    def remove(self, files, verbose=False, to_file=None):
1282
1502
        """Remove nominated files from the working inventory..
1283
1503
 
1317
1537
 
1318
1538
        self._write_inventory(inv)
1319
1539
 
1320
 
    @needs_write_lock
 
1540
    @needs_tree_write_lock
1321
1541
    def revert(self, filenames, old_tree=None, backups=True, 
1322
1542
               pb=DummyProgress()):
1323
1543
        from transform import revert
1326
1546
            old_tree = self.basis_tree()
1327
1547
        conflicts = revert(self, old_tree, filenames, backups, pb)
1328
1548
        if not len(filenames):
1329
 
            self.set_pending_merges([])
 
1549
            self.set_parent_ids(self.get_parent_ids()[:1])
1330
1550
            resolve(self)
1331
1551
        else:
1332
1552
            resolve(self, filenames, ignore_misses=True)
1334
1554
 
1335
1555
    # XXX: This method should be deprecated in favour of taking in a proper
1336
1556
    # new Inventory object.
1337
 
    @needs_write_lock
 
1557
    @needs_tree_write_lock
1338
1558
    def set_inventory(self, new_inventory_list):
1339
1559
        from bzrlib.inventory import (Inventory,
1340
1560
                                      InventoryDirectory,
1357
1577
                raise BzrError("unknown kind %r" % kind)
1358
1578
        self._write_inventory(inv)
1359
1579
 
1360
 
    @needs_write_lock
 
1580
    @needs_tree_write_lock
1361
1581
    def set_root_id(self, file_id):
1362
1582
        """Set the root id for this tree."""
1363
1583
        inv = self.read_working_inventory()
1403
1623
        Do a 'normal' merge of the old branch basis if it is relevant.
1404
1624
        """
1405
1625
        old_tip = self.branch.update()
1406
 
        if old_tip is not None:
1407
 
            self.add_pending_merge(old_tip)
1408
 
        self.branch.lock_read()
 
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
1409
1637
        try:
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()
 
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
1441
1691
 
1442
 
    @needs_write_lock
 
1692
    @needs_tree_write_lock
1443
1693
    def _write_inventory(self, inv):
1444
1694
        """Write inventory as the current inventory."""
1445
1695
        sio = StringIO()
1489
1739
     - uses the branch last-revision.
1490
1740
    """
1491
1741
 
 
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
 
1492
1755
    def unlock(self):
1493
1756
        # we share control files:
1494
1757
        if self._hashcache.needs_write and self._control_files._lock_count==3:
1511
1774
    """
1512
1775
 
1513
1776
    @needs_read_lock
1514
 
    def last_revision(self):
1515
 
        """See WorkingTree.last_revision."""
 
1777
    def _last_revision(self):
 
1778
        """See WorkingTree._last_revision."""
1516
1779
        try:
1517
1780
            return self._control_files.get_utf8('last-revision').read()
1518
1781
        except NoSuchFile:
1530
1793
            self._control_files.put_utf8('last-revision', revision_id)
1531
1794
            return True
1532
1795
 
1533
 
    @needs_write_lock
 
1796
    @needs_tree_write_lock
1534
1797
    def set_conflicts(self, conflicts):
1535
1798
        self._put_rio('conflicts', conflicts.to_stanzas(), 
1536
1799
                      CONFLICT_HEADER_1)
1537
1800
 
1538
 
    @needs_write_lock
 
1801
    @needs_tree_write_lock
1539
1802
    def add_conflicts(self, new_conflicts):
1540
1803
        conflict_set = set(self.conflicts())
1541
1804
        conflict_set.update(set(list(new_conflicts)))
1702
1965
            finally:
1703
1966
                branch.unlock()
1704
1967
        revision = branch.last_revision()
1705
 
        inv = Inventory() 
 
1968
        inv = Inventory()
1706
1969
        wt = WorkingTree2(a_bzrdir.root_transport.local_abspath('.'),
1707
1970
                         branch,
1708
1971
                         inv,
1711
1974
                         _bzrdir=a_bzrdir)
1712
1975
        wt._write_inventory(inv)
1713
1976
        wt.set_root_id(inv.root.file_id)
1714
 
        wt.set_last_revision(revision)
1715
 
        wt.set_pending_merges([])
1716
 
        build_tree(wt.basis_tree(), wt)
 
1977
        basis_tree = branch.repository.revision_tree(revision)
 
1978
        wt.set_parent_trees([(revision, basis_tree)])
 
1979
        build_tree(basis_tree, wt)
1717
1980
        return wt
1718
1981
 
1719
1982
    def __init__(self):
1789
2052
                         _format=self,
1790
2053
                         _bzrdir=a_bzrdir,
1791
2054
                         _control_files=control_files)
1792
 
        wt.lock_write()
 
2055
        wt.lock_tree_write()
1793
2056
        try:
1794
2057
            wt._write_inventory(inv)
1795
2058
            wt.set_root_id(inv.root.file_id)
1796
 
            wt.set_last_revision(revision_id)
1797
 
            wt.set_pending_merges([])
1798
 
            build_tree(wt.basis_tree(), wt)
 
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)
1799
2065
        finally:
1800
2066
            wt.unlock()
1801
2067
            control_files.unlock()