/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/branch.py

  • Committer: Ian Clatworthy
  • Date: 2009-06-10 23:29:48 UTC
  • mfrom: (4423.2.2 eol-none-bug)
  • mto: This revision was merged to the branch mainline in revision 4428.
  • Revision ID: ian.clatworthy@canonical.com-20090610232948-srfxg31kurqa769c
(igc) fix rule handling so that eol is optional

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
29
29
        errors,
30
30
        lockdir,
31
31
        lockable_files,
32
 
        remote,
33
32
        repository,
34
33
        revision as _mod_revision,
35
34
        rio,
47
46
    )
48
47
""")
49
48
 
50
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
50
from bzrlib.hooks import HookPoint, Hooks
52
51
from bzrlib.inter import InterObject
53
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
54
52
from bzrlib import registry
55
53
from bzrlib.symbol_versioning import (
56
54
    deprecated_in,
64
62
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
65
63
 
66
64
 
67
 
class Branch(bzrdir.ControlComponent):
 
65
# TODO: Maybe include checks for common corruption of newlines, etc?
 
66
 
 
67
# TODO: Some operations like log might retrieve the same revisions
 
68
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
69
# cache in memory to make this faster.  In general anything can be
 
70
# cached in memory between lock and unlock operations. .. nb thats
 
71
# what the transaction identity map provides
 
72
 
 
73
 
 
74
######################################################################
 
75
# branch objects
 
76
 
 
77
class Branch(object):
68
78
    """Branch holding a history of revisions.
69
79
 
70
 
    :ivar base:
71
 
        Base directory/url of the branch; using control_url and
72
 
        control_transport is more standardized.
 
80
    base
 
81
        Base directory/url of the branch.
73
82
 
74
83
    hooks: An instance of BranchHooks.
75
84
    """
77
86
    # - RBC 20060112
78
87
    base = None
79
88
 
80
 
    @property
81
 
    def control_transport(self):
82
 
        return self._transport
83
 
 
84
 
    @property
85
 
    def user_transport(self):
86
 
        return self.bzrdir.user_transport
87
 
 
88
89
    def __init__(self, *ignored, **ignored_too):
89
90
        self.tags = self._format.make_tags(self)
90
91
        self._revision_history_cache = None
91
92
        self._revision_id_to_revno_cache = None
92
93
        self._partial_revision_id_to_revno_cache = {}
93
 
        self._partial_revision_history_cache = []
94
94
        self._last_revision_info_cache = None
95
95
        self._merge_sorted_revisions_cache = None
96
96
        self._open_hook()
104
104
    def _activate_fallback_location(self, url):
105
105
        """Activate the branch/repository from url as a fallback repository."""
106
106
        repo = self._get_fallback_repository(url)
107
 
        if repo.has_same_location(self.repository):
108
 
            raise errors.UnstackableLocationError(self.user_url, url)
109
107
        self.repository.add_fallback_repository(repo)
110
108
 
111
109
    def break_lock(self):
127
125
            raise errors.UnstackableRepositoryFormat(self.repository._format,
128
126
                self.repository.base)
129
127
 
130
 
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
131
 
        """Extend the partial history to include a given index
132
 
 
133
 
        If a stop_index is supplied, stop when that index has been reached.
134
 
        If a stop_revision is supplied, stop when that revision is
135
 
        encountered.  Otherwise, stop when the beginning of history is
136
 
        reached.
137
 
 
138
 
        :param stop_index: The index which should be present.  When it is
139
 
            present, history extension will stop.
140
 
        :param stop_revision: The revision id which should be present.  When
141
 
            it is encountered, history extension will stop.
142
 
        """
143
 
        if len(self._partial_revision_history_cache) == 0:
144
 
            self._partial_revision_history_cache = [self.last_revision()]
145
 
        repository._iter_for_revno(
146
 
            self.repository, self._partial_revision_history_cache,
147
 
            stop_index=stop_index, stop_revision=stop_revision)
148
 
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
149
 
            self._partial_revision_history_cache.pop()
150
 
 
151
 
    def _get_check_refs(self):
152
 
        """Get the references needed for check().
153
 
 
154
 
        See bzrlib.check.
155
 
        """
156
 
        revid = self.last_revision()
157
 
        return [('revision-existence', revid), ('lefthand-distance', revid)]
158
 
 
159
128
    @staticmethod
160
129
    def open(base, _unsupported=False, possible_transports=None):
161
130
        """Open the branch rooted at base.
165
134
        """
166
135
        control = bzrdir.BzrDir.open(base, _unsupported,
167
136
                                     possible_transports=possible_transports)
168
 
        return control.open_branch(unsupported=_unsupported)
 
137
        return control.open_branch(_unsupported)
169
138
 
170
139
    @staticmethod
171
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
140
    def open_from_transport(transport, _unsupported=False):
172
141
        """Open the branch rooted at transport"""
173
142
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
174
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
143
        return control.open_branch(_unsupported)
175
144
 
176
145
    @staticmethod
177
146
    def open_containing(url, possible_transports=None):
198
167
        return self.supports_tags() and self.tags.get_tag_dict()
199
168
 
200
169
    def get_config(self):
201
 
        """Get a bzrlib.config.BranchConfig for this Branch.
202
 
 
203
 
        This can then be used to get and set configuration options for the
204
 
        branch.
205
 
 
206
 
        :return: A bzrlib.config.BranchConfig.
207
 
        """
208
170
        return BranchConfig(self)
209
171
 
210
172
    def _get_config(self):
222
184
    def _get_fallback_repository(self, url):
223
185
        """Get the repository we fallback to at url."""
224
186
        url = urlutils.join(self.base, url)
225
 
        a_branch = Branch.open(url,
 
187
        a_bzrdir = bzrdir.BzrDir.open(url,
226
188
            possible_transports=[self.bzrdir.root_transport])
227
 
        return a_branch.repository
 
189
        return a_bzrdir.open_branch().repository
228
190
 
229
191
    def _get_tags_bytes(self):
230
192
        """Get the bytes of a serialised tags dict.
246
208
        if not local and not config.has_explicit_nickname():
247
209
            try:
248
210
                master = self.get_master_branch(possible_transports)
249
 
                if master and self.user_url == master.user_url:
250
 
                    raise errors.RecursiveBind(self.user_url)
251
211
                if master is not None:
252
212
                    # return the master branch value
253
213
                    return master.nick
254
 
            except errors.RecursiveBind, e:
255
 
                raise e
256
214
            except errors.BzrError, e:
257
215
                # Silently fall back to local implicit nick if the master is
258
216
                # unavailable
295
253
        new_history.reverse()
296
254
        return new_history
297
255
 
298
 
    def lock_write(self, token=None):
299
 
        """Lock the branch for write operations.
300
 
 
301
 
        :param token: A token to permit reacquiring a previously held and
302
 
            preserved lock.
303
 
        :return: A BranchWriteLockResult.
304
 
        """
 
256
    def lock_write(self):
305
257
        raise NotImplementedError(self.lock_write)
306
258
 
307
259
    def lock_read(self):
308
 
        """Lock the branch for read operations.
309
 
 
310
 
        :return: A bzrlib.lock.LogicalLockResult.
311
 
        """
312
260
        raise NotImplementedError(self.lock_read)
313
261
 
314
262
    def unlock(self):
439
387
            * 'include' - the stop revision is the last item in the result
440
388
            * 'with-merges' - include the stop revision and all of its
441
389
              merged revisions in the result
442
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
443
 
              that are in both ancestries
444
390
        :param direction: either 'reverse' or 'forward':
445
391
            * reverse means return the start_revision_id first, i.e.
446
392
              start at the most recent revision and go backwards in history
468
414
        # start_revision_id.
469
415
        if self._merge_sorted_revisions_cache is None:
470
416
            last_revision = self.last_revision()
471
 
            known_graph = self.repository.get_known_graph_ancestry(
472
 
                [last_revision])
473
 
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
474
 
                last_revision)
 
417
            graph = self.repository.get_graph()
 
418
            parent_map = dict(((key, value) for key, value in
 
419
                     graph.iter_ancestry([last_revision]) if value is not None))
 
420
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
421
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
422
                generate_revno=True)
 
423
            # Drop the sequence # before caching
 
424
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
425
 
475
426
        filtered = self._filter_merge_sorted_revisions(
476
427
            self._merge_sorted_revisions_cache, start_revision_id,
477
428
            stop_revision_id, stop_rule)
478
 
        # Make sure we don't return revisions that are not part of the
479
 
        # start_revision_id ancestry.
480
 
        filtered = self._filter_start_non_ancestors(filtered)
481
429
        if direction == 'reverse':
482
430
            return filtered
483
431
        if direction == 'forward':
490
438
        """Iterate over an inclusive range of sorted revisions."""
491
439
        rev_iter = iter(merge_sorted_revisions)
492
440
        if start_revision_id is not None:
493
 
            for node in rev_iter:
494
 
                rev_id = node.key[-1]
 
441
            for rev_id, depth, revno, end_of_merge in rev_iter:
495
442
                if rev_id != start_revision_id:
496
443
                    continue
497
444
                else:
498
445
                    # The decision to include the start or not
499
446
                    # depends on the stop_rule if a stop is provided
500
 
                    # so pop this node back into the iterator
501
 
                    rev_iter = chain(iter([node]), rev_iter)
 
447
                    rev_iter = chain(
 
448
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
449
                        rev_iter)
502
450
                    break
503
451
        if stop_revision_id is None:
504
 
            # Yield everything
505
 
            for node in rev_iter:
506
 
                rev_id = node.key[-1]
507
 
                yield (rev_id, node.merge_depth, node.revno,
508
 
                       node.end_of_merge)
 
452
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
453
                yield rev_id, depth, revno, end_of_merge
509
454
        elif stop_rule == 'exclude':
510
 
            for node in rev_iter:
511
 
                rev_id = node.key[-1]
 
455
            for rev_id, depth, revno, end_of_merge in rev_iter:
512
456
                if rev_id == stop_revision_id:
513
457
                    return
514
 
                yield (rev_id, node.merge_depth, node.revno,
515
 
                       node.end_of_merge)
 
458
                yield rev_id, depth, revno, end_of_merge
516
459
        elif stop_rule == 'include':
517
 
            for node in rev_iter:
518
 
                rev_id = node.key[-1]
519
 
                yield (rev_id, node.merge_depth, node.revno,
520
 
                       node.end_of_merge)
 
460
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
461
                yield rev_id, depth, revno, end_of_merge
521
462
                if rev_id == stop_revision_id:
522
463
                    return
523
 
        elif stop_rule == 'with-merges-without-common-ancestry':
524
 
            # We want to exclude all revisions that are already part of the
525
 
            # stop_revision_id ancestry.
526
 
            graph = self.repository.get_graph()
527
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
528
 
                                                    [stop_revision_id])
529
 
            for node in rev_iter:
530
 
                rev_id = node.key[-1]
531
 
                if rev_id not in ancestors:
532
 
                    continue
533
 
                yield (rev_id, node.merge_depth, node.revno,
534
 
                       node.end_of_merge)
535
464
        elif stop_rule == 'with-merges':
536
465
            stop_rev = self.repository.get_revision(stop_revision_id)
537
466
            if stop_rev.parent_ids:
538
467
                left_parent = stop_rev.parent_ids[0]
539
468
            else:
540
469
                left_parent = _mod_revision.NULL_REVISION
541
 
            # left_parent is the actual revision we want to stop logging at,
542
 
            # since we want to show the merged revisions after the stop_rev too
543
 
            reached_stop_revision_id = False
544
 
            revision_id_whitelist = []
545
 
            for node in rev_iter:
546
 
                rev_id = node.key[-1]
 
470
            for rev_id, depth, revno, end_of_merge in rev_iter:
547
471
                if rev_id == left_parent:
548
 
                    # reached the left parent after the stop_revision
549
472
                    return
550
 
                if (not reached_stop_revision_id or
551
 
                        rev_id in revision_id_whitelist):
552
 
                    yield (rev_id, node.merge_depth, node.revno,
553
 
                       node.end_of_merge)
554
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
555
 
                        # only do the merged revs of rev_id from now on
556
 
                        rev = self.repository.get_revision(rev_id)
557
 
                        if rev.parent_ids:
558
 
                            reached_stop_revision_id = True
559
 
                            revision_id_whitelist.extend(rev.parent_ids)
 
473
                yield rev_id, depth, revno, end_of_merge
560
474
        else:
561
475
            raise ValueError('invalid stop_rule %r' % stop_rule)
562
476
 
563
 
    def _filter_start_non_ancestors(self, rev_iter):
564
 
        # If we started from a dotted revno, we want to consider it as a tip
565
 
        # and don't want to yield revisions that are not part of its
566
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
567
 
        # uninteresting descendants of the first parent of our tip before the
568
 
        # tip itself.
569
 
        first = rev_iter.next()
570
 
        (rev_id, merge_depth, revno, end_of_merge) = first
571
 
        yield first
572
 
        if not merge_depth:
573
 
            # We start at a mainline revision so by definition, all others
574
 
            # revisions in rev_iter are ancestors
575
 
            for node in rev_iter:
576
 
                yield node
577
 
 
578
 
        clean = False
579
 
        whitelist = set()
580
 
        pmap = self.repository.get_parent_map([rev_id])
581
 
        parents = pmap.get(rev_id, [])
582
 
        if parents:
583
 
            whitelist.update(parents)
584
 
        else:
585
 
            # If there is no parents, there is nothing of interest left
586
 
 
587
 
            # FIXME: It's hard to test this scenario here as this code is never
588
 
            # called in that case. -- vila 20100322
589
 
            return
590
 
 
591
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
592
 
            if not clean:
593
 
                if rev_id in whitelist:
594
 
                    pmap = self.repository.get_parent_map([rev_id])
595
 
                    parents = pmap.get(rev_id, [])
596
 
                    whitelist.remove(rev_id)
597
 
                    whitelist.update(parents)
598
 
                    if merge_depth == 0:
599
 
                        # We've reached the mainline, there is nothing left to
600
 
                        # filter
601
 
                        clean = True
602
 
                else:
603
 
                    # A revision that is not part of the ancestry of our
604
 
                    # starting revision.
605
 
                    continue
606
 
            yield (rev_id, merge_depth, revno, end_of_merge)
607
 
 
608
477
    def leave_lock_in_place(self):
609
478
        """Tell this branch object not to release the physical lock when this
610
479
        object is unlocked.
627
496
        :param other: The branch to bind to
628
497
        :type other: Branch
629
498
        """
630
 
        raise errors.UpgradeRequired(self.user_url)
631
 
 
632
 
    def set_append_revisions_only(self, enabled):
633
 
        if not self._format.supports_set_append_revisions_only():
634
 
            raise errors.UpgradeRequired(self.user_url)
635
 
        if enabled:
636
 
            value = 'True'
637
 
        else:
638
 
            value = 'False'
639
 
        self.get_config().set_user_option('append_revisions_only', value,
640
 
            warn_masked=True)
 
499
        raise errors.UpgradeRequired(self.base)
641
500
 
642
501
    def set_reference_info(self, file_id, tree_path, branch_location):
643
502
        """Set the branch location to use for a tree reference."""
685
544
    def get_old_bound_location(self):
686
545
        """Return the URL of the branch we used to be bound to
687
546
        """
688
 
        raise errors.UpgradeRequired(self.user_url)
 
547
        raise errors.UpgradeRequired(self.base)
689
548
 
690
549
    def get_commit_builder(self, parents, config=None, timestamp=None,
691
550
                           timezone=None, committer=None, revprops=None,
769
628
            stacking.
770
629
        """
771
630
        if not self._format.supports_stacking():
772
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
773
 
        # XXX: Changing from one fallback repository to another does not check
774
 
        # that all the data you need is present in the new fallback.
775
 
        # Possibly it should.
 
631
            raise errors.UnstackableBranchFormat(self._format, self.base)
776
632
        self._check_stackable_repo()
777
633
        if not url:
778
634
            try:
780
636
            except (errors.NotStacked, errors.UnstackableBranchFormat,
781
637
                errors.UnstackableRepositoryFormat):
782
638
                return
783
 
            self._unstack()
 
639
            url = ''
 
640
            # XXX: Lock correctness - should unlock our old repo if we were
 
641
            # locked.
 
642
            # repositories don't offer an interface to remove fallback
 
643
            # repositories today; take the conceptually simpler option and just
 
644
            # reopen it.
 
645
            self.repository = self.bzrdir.find_repository()
 
646
            self.repository.lock_write()
 
647
            # for every revision reference the branch has, ensure it is pulled
 
648
            # in.
 
649
            source_repository = self._get_fallback_repository(old_url)
 
650
            for revision_id in chain([self.last_revision()],
 
651
                self.tags.get_reverse_tag_dict()):
 
652
                self.repository.fetch(source_repository, revision_id,
 
653
                    find_ghosts=True)
784
654
        else:
785
655
            self._activate_fallback_location(url)
786
656
        # write this out after the repository is stacked to avoid setting a
787
657
        # stacked config that doesn't work.
788
658
        self._set_config_location('stacked_on_location', url)
789
659
 
790
 
    def _unstack(self):
791
 
        """Change a branch to be unstacked, copying data as needed.
792
 
        
793
 
        Don't call this directly, use set_stacked_on_url(None).
794
 
        """
795
 
        pb = ui.ui_factory.nested_progress_bar()
796
 
        try:
797
 
            pb.update("Unstacking")
798
 
            # The basic approach here is to fetch the tip of the branch,
799
 
            # including all available ghosts, from the existing stacked
800
 
            # repository into a new repository object without the fallbacks. 
801
 
            #
802
 
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
803
 
            # correct for CHKMap repostiories
804
 
            old_repository = self.repository
805
 
            if len(old_repository._fallback_repositories) != 1:
806
 
                raise AssertionError("can't cope with fallback repositories "
807
 
                    "of %r" % (self.repository,))
808
 
            # Open the new repository object.
809
 
            # Repositories don't offer an interface to remove fallback
810
 
            # repositories today; take the conceptually simpler option and just
811
 
            # reopen it.  We reopen it starting from the URL so that we
812
 
            # get a separate connection for RemoteRepositories and can
813
 
            # stream from one of them to the other.  This does mean doing
814
 
            # separate SSH connection setup, but unstacking is not a
815
 
            # common operation so it's tolerable.
816
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
817
 
            new_repository = new_bzrdir.find_repository()
818
 
            if new_repository._fallback_repositories:
819
 
                raise AssertionError("didn't expect %r to have "
820
 
                    "fallback_repositories"
821
 
                    % (self.repository,))
822
 
            # Replace self.repository with the new repository.
823
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
824
 
            # lock count) of self.repository to the new repository.
825
 
            lock_token = old_repository.lock_write().repository_token
826
 
            self.repository = new_repository
827
 
            if isinstance(self, remote.RemoteBranch):
828
 
                # Remote branches can have a second reference to the old
829
 
                # repository that need to be replaced.
830
 
                if self._real_branch is not None:
831
 
                    self._real_branch.repository = new_repository
832
 
            self.repository.lock_write(token=lock_token)
833
 
            if lock_token is not None:
834
 
                old_repository.leave_lock_in_place()
835
 
            old_repository.unlock()
836
 
            if lock_token is not None:
837
 
                # XXX: self.repository.leave_lock_in_place() before this
838
 
                # function will not be preserved.  Fortunately that doesn't
839
 
                # affect the current default format (2a), and would be a
840
 
                # corner-case anyway.
841
 
                #  - Andrew Bennetts, 2010/06/30
842
 
                self.repository.dont_leave_lock_in_place()
843
 
            old_lock_count = 0
844
 
            while True:
845
 
                try:
846
 
                    old_repository.unlock()
847
 
                except errors.LockNotHeld:
848
 
                    break
849
 
                old_lock_count += 1
850
 
            if old_lock_count == 0:
851
 
                raise AssertionError(
852
 
                    'old_repository should have been locked at least once.')
853
 
            for i in range(old_lock_count-1):
854
 
                self.repository.lock_write()
855
 
            # Fetch from the old repository into the new.
856
 
            old_repository.lock_read()
857
 
            try:
858
 
                # XXX: If you unstack a branch while it has a working tree
859
 
                # with a pending merge, the pending-merged revisions will no
860
 
                # longer be present.  You can (probably) revert and remerge.
861
 
                #
862
 
                # XXX: This only fetches up to the tip of the repository; it
863
 
                # doesn't bring across any tags.  That's fairly consistent
864
 
                # with how branch works, but perhaps not ideal.
865
 
                self.repository.fetch(old_repository,
866
 
                    revision_id=self.last_revision(),
867
 
                    find_ghosts=True)
868
 
            finally:
869
 
                old_repository.unlock()
870
 
        finally:
871
 
            pb.finished()
872
660
 
873
661
    def _set_tags_bytes(self, bytes):
874
662
        """Mirror method for _get_tags_bytes.
910
698
        self._revision_id_to_revno_cache = None
911
699
        self._last_revision_info_cache = None
912
700
        self._merge_sorted_revisions_cache = None
913
 
        self._partial_revision_history_cache = []
914
 
        self._partial_revision_id_to_revno_cache = {}
915
701
 
916
702
    def _gen_revision_history(self):
917
703
        """Return sequence of revision hashes on to this branch.
954
740
 
955
741
    def unbind(self):
956
742
        """Older format branches cannot bind or unbind."""
957
 
        raise errors.UpgradeRequired(self.user_url)
 
743
        raise errors.UpgradeRequired(self.base)
 
744
 
 
745
    def set_append_revisions_only(self, enabled):
 
746
        """Older format branches are never restricted to append-only"""
 
747
        raise errors.UpgradeRequired(self.base)
958
748
 
959
749
    def last_revision(self):
960
750
        """Return last revision id, or NULL_REVISION."""
1001
791
                raise errors.NoSuchRevision(self, stop_revision)
1002
792
        return other_history[self_len:stop_revision]
1003
793
 
 
794
    @needs_write_lock
1004
795
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1005
796
                         graph=None):
1006
797
        """Pull in new perfect-fit revisions.
1040
831
        except ValueError:
1041
832
            raise errors.NoSuchRevision(self, revision_id)
1042
833
 
1043
 
    @needs_read_lock
1044
834
    def get_rev_id(self, revno, history=None):
1045
835
        """Find the revision id of the specified revno."""
1046
836
        if revno == 0:
1047
837
            return _mod_revision.NULL_REVISION
1048
 
        last_revno, last_revid = self.last_revision_info()
1049
 
        if revno == last_revno:
1050
 
            return last_revid
1051
 
        if revno <= 0 or revno > last_revno:
 
838
        if history is None:
 
839
            history = self.revision_history()
 
840
        if revno <= 0 or revno > len(history):
1052
841
            raise errors.NoSuchRevision(self, revno)
1053
 
        distance_from_last = last_revno - revno
1054
 
        if len(self._partial_revision_history_cache) <= distance_from_last:
1055
 
            self._extend_partial_history(distance_from_last)
1056
 
        return self._partial_revision_history_cache[distance_from_last]
 
842
        return history[revno - 1]
1057
843
 
 
844
    @needs_write_lock
1058
845
    def pull(self, source, overwrite=False, stop_revision=None,
1059
846
             possible_transports=None, *args, **kwargs):
1060
847
        """Mirror source into this branch.
1118
905
        try:
1119
906
            return urlutils.join(self.base[:-1], parent)
1120
907
        except errors.InvalidURLJoin, e:
1121
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
908
            raise errors.InaccessibleParent(parent, self.base)
1122
909
 
1123
910
    def _get_parent_location(self):
1124
911
        raise NotImplementedError(self._get_parent_location)
1209
996
        params = ChangeBranchTipParams(
1210
997
            self, old_revno, new_revno, old_revid, new_revid)
1211
998
        for hook in hooks:
1212
 
            hook(params)
 
999
            try:
 
1000
                hook(params)
 
1001
            except errors.TipChangeRejected:
 
1002
                raise
 
1003
            except Exception:
 
1004
                exc_info = sys.exc_info()
 
1005
                hook_name = Branch.hooks.get_hook_name(hook)
 
1006
                raise errors.HookFailed(
 
1007
                    'pre_change_branch_tip', hook_name, exc_info)
1213
1008
 
1214
1009
    @needs_write_lock
1215
1010
    def update(self):
1264
1059
        revision_id: if not None, the revision history in the new branch will
1265
1060
                     be truncated to end with revision_id.
1266
1061
        """
1267
 
        if (repository_policy is not None and
1268
 
            repository_policy.requires_stacking()):
1269
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1270
1062
        result = to_bzrdir.create_branch()
1271
1063
        result.lock_write()
1272
1064
        try:
1303
1095
                revno = 1
1304
1096
        destination.set_last_revision_info(revno, revision_id)
1305
1097
 
 
1098
    @needs_read_lock
1306
1099
    def copy_content_into(self, destination, revision_id=None):
1307
1100
        """Copy the content of self into destination.
1308
1101
 
1309
1102
        revision_id: if not None, the revision history in the new branch will
1310
1103
                     be truncated to end with revision_id.
1311
1104
        """
1312
 
        return InterBranch.get(self, destination).copy_content_into(
1313
 
            revision_id=revision_id)
 
1105
        self.update_references(destination)
 
1106
        self._synchronize_history(destination, revision_id)
 
1107
        try:
 
1108
            parent = self.get_parent()
 
1109
        except errors.InaccessibleParent, e:
 
1110
            mutter('parent was not accessible to copy: %s', e)
 
1111
        else:
 
1112
            if parent:
 
1113
                destination.set_parent(parent)
 
1114
        if self._push_should_merge_tags():
 
1115
            self.tags.merge_to(destination.tags)
1314
1116
 
1315
1117
    def update_references(self, target):
1316
1118
        if not getattr(self._format, 'supports_reference_locations', False):
1330
1132
        target._set_all_reference_info(target_reference_dict)
1331
1133
 
1332
1134
    @needs_read_lock
1333
 
    def check(self, refs):
 
1135
    def check(self):
1334
1136
        """Check consistency of the branch.
1335
1137
 
1336
1138
        In particular this checks that revisions given in the revision-history
1339
1141
 
1340
1142
        Callers will typically also want to check the repository.
1341
1143
 
1342
 
        :param refs: Calculated refs for this branch as specified by
1343
 
            branch._get_check_refs()
1344
1144
        :return: A BranchCheckResult.
1345
1145
        """
1346
 
        result = BranchCheckResult(self)
 
1146
        ret = BranchCheckResult(self)
 
1147
        mainline_parent_id = None
1347
1148
        last_revno, last_revision_id = self.last_revision_info()
1348
 
        actual_revno = refs[('lefthand-distance', last_revision_id)]
1349
 
        if actual_revno != last_revno:
1350
 
            result.errors.append(errors.BzrCheckError(
1351
 
                'revno does not match len(mainline) %s != %s' % (
1352
 
                last_revno, actual_revno)))
1353
 
        # TODO: We should probably also check that self.revision_history
1354
 
        # matches the repository for older branch formats.
1355
 
        # If looking for the code that cross-checks repository parents against
1356
 
        # the iter_reverse_revision_history output, that is now a repository
1357
 
        # specific check.
1358
 
        return result
 
1149
        real_rev_history = []
 
1150
        try:
 
1151
            for revid in self.repository.iter_reverse_revision_history(
 
1152
                last_revision_id):
 
1153
                real_rev_history.append(revid)
 
1154
        except errors.RevisionNotPresent:
 
1155
            ret.ghosts_in_mainline = True
 
1156
        else:
 
1157
            ret.ghosts_in_mainline = False
 
1158
        real_rev_history.reverse()
 
1159
        if len(real_rev_history) != last_revno:
 
1160
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
1161
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
1162
        # TODO: We should probably also check that real_rev_history actually
 
1163
        #       matches self.revision_history()
 
1164
        for revision_id in real_rev_history:
 
1165
            try:
 
1166
                revision = self.repository.get_revision(revision_id)
 
1167
            except errors.NoSuchRevision, e:
 
1168
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1169
                            % revision_id)
 
1170
            # In general the first entry on the revision history has no parents.
 
1171
            # But it's not illegal for it to have parents listed; this can happen
 
1172
            # in imports from Arch when the parents weren't reachable.
 
1173
            if mainline_parent_id is not None:
 
1174
                if mainline_parent_id not in revision.parent_ids:
 
1175
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1176
                                        "parents of {%s}"
 
1177
                                        % (mainline_parent_id, revision_id))
 
1178
            mainline_parent_id = revision_id
 
1179
        return ret
1359
1180
 
1360
1181
    def _get_checkout_format(self):
1361
1182
        """Return the most suitable metadir for a checkout of this branch.
1384
1205
        """
1385
1206
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1386
1207
        # clone call. Or something. 20090224 RBC/spiv.
1387
 
        # XXX: Should this perhaps clone colocated branches as well, 
1388
 
        # rather than just the default branch? 20100319 JRV
1389
1208
        if revision_id is None:
1390
1209
            revision_id = self.last_revision()
1391
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1392
 
            revision_id=revision_id, stacked_on=stacked_on,
1393
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1210
        try:
 
1211
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1212
                revision_id=revision_id, stacked_on=stacked_on,
 
1213
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1214
        except errors.FileExists:
 
1215
            if not use_existing_dir:
 
1216
                raise
 
1217
        except errors.NoSuchFile:
 
1218
            if not create_prefix:
 
1219
                raise
1394
1220
        return dir_to.open_branch()
1395
1221
 
1396
1222
    def create_checkout(self, to_location, revision_id=None,
1415
1241
        if lightweight:
1416
1242
            format = self._get_checkout_format()
1417
1243
            checkout = format.initialize_on_transport(t)
1418
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1419
 
                target_branch=self)
 
1244
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1420
1245
        else:
1421
1246
            format = self._get_checkout_format()
1422
1247
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1464
1289
    def supports_tags(self):
1465
1290
        return self._format.supports_tags()
1466
1291
 
1467
 
    def automatic_tag_name(self, revision_id):
1468
 
        """Try to automatically find the tag name for a revision.
1469
 
 
1470
 
        :param revision_id: Revision id of the revision.
1471
 
        :return: A tag name or None if no tag name could be determined.
1472
 
        """
1473
 
        for hook in Branch.hooks['automatic_tag_name']:
1474
 
            ret = hook(self, revision_id)
1475
 
            if ret is not None:
1476
 
                return ret
1477
 
        return None
1478
 
 
1479
1292
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1480
1293
                                         other_branch):
1481
1294
        """Ensure that revision_b is a descendant of revision_a.
1536
1349
    _formats = {}
1537
1350
    """The known formats."""
1538
1351
 
1539
 
    can_set_append_revisions_only = True
1540
 
 
1541
1352
    def __eq__(self, other):
1542
1353
        return self.__class__ is other.__class__
1543
1354
 
1545
1356
        return not (self == other)
1546
1357
 
1547
1358
    @classmethod
1548
 
    def find_format(klass, a_bzrdir, name=None):
 
1359
    def find_format(klass, a_bzrdir):
1549
1360
        """Return the format for the branch object in a_bzrdir."""
1550
1361
        try:
1551
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1552
 
            format_string = transport.get_bytes("format")
1553
 
            format = klass._formats[format_string]
1554
 
            if isinstance(format, MetaDirBranchFormatFactory):
1555
 
                return format()
1556
 
            return format
 
1362
            transport = a_bzrdir.get_branch_transport(None)
 
1363
            format_string = transport.get("format").read()
 
1364
            return klass._formats[format_string]
1557
1365
        except errors.NoSuchFile:
1558
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1366
            raise errors.NotBranchError(path=transport.base)
1559
1367
        except KeyError:
1560
1368
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1561
1369
 
1564
1372
        """Return the current default format."""
1565
1373
        return klass._default_format
1566
1374
 
1567
 
    @classmethod
1568
 
    def get_formats(klass):
1569
 
        """Get all the known formats.
1570
 
 
1571
 
        Warning: This triggers a load of all lazy registered formats: do not
1572
 
        use except when that is desireed.
1573
 
        """
1574
 
        result = []
1575
 
        for fmt in klass._formats.values():
1576
 
            if isinstance(fmt, MetaDirBranchFormatFactory):
1577
 
                fmt = fmt()
1578
 
            result.append(fmt)
1579
 
        return result
1580
 
 
1581
 
    def get_reference(self, a_bzrdir, name=None):
 
1375
    def get_reference(self, a_bzrdir):
1582
1376
        """Get the target reference of the branch in a_bzrdir.
1583
1377
 
1584
1378
        format probing must have been completed before calling
1586
1380
        in a_bzrdir is correct.
1587
1381
 
1588
1382
        :param a_bzrdir: The bzrdir to get the branch data from.
1589
 
        :param name: Name of the colocated branch to fetch
1590
1383
        :return: None if the branch is not a reference branch.
1591
1384
        """
1592
1385
        return None
1593
1386
 
1594
1387
    @classmethod
1595
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1388
    def set_reference(self, a_bzrdir, to_branch):
1596
1389
        """Set the target reference of the branch in a_bzrdir.
1597
1390
 
1598
1391
        format probing must have been completed before calling
1600
1393
        in a_bzrdir is correct.
1601
1394
 
1602
1395
        :param a_bzrdir: The bzrdir to set the branch reference for.
1603
 
        :param name: Name of colocated branch to set, None for default
1604
1396
        :param to_branch: branch that the checkout is to reference
1605
1397
        """
1606
1398
        raise NotImplementedError(self.set_reference)
1613
1405
        """Return the short format description for this format."""
1614
1406
        raise NotImplementedError(self.get_format_description)
1615
1407
 
1616
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1617
 
        hooks = Branch.hooks['post_branch_init']
1618
 
        if not hooks:
1619
 
            return
1620
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1621
 
        for hook in hooks:
1622
 
            hook(params)
1623
 
 
1624
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1625
 
                           lock_type='metadir', set_format=True):
 
1408
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1409
                           set_format=True):
1626
1410
        """Initialize a branch in a bzrdir, with specified files
1627
1411
 
1628
1412
        :param a_bzrdir: The bzrdir to initialize the branch in
1629
1413
        :param utf8_files: The files to create as a list of
1630
1414
            (filename, content) tuples
1631
 
        :param name: Name of colocated branch to create, if any
1632
1415
        :param set_format: If True, set the format with
1633
1416
            self.get_format_string.  (BzrBranch4 has its format set
1634
1417
            elsewhere)
1635
1418
        :return: a branch in this format
1636
1419
        """
1637
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1638
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1420
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1421
        branch_transport = a_bzrdir.get_branch_transport(self)
1639
1422
        lock_map = {
1640
1423
            'metadir': ('lock', lockdir.LockDir),
1641
1424
            'branch4': ('branch-lock', lockable_files.TransportLock),
1662
1445
        finally:
1663
1446
            if lock_taken:
1664
1447
                control_files.unlock()
1665
 
        branch = self.open(a_bzrdir, name, _found=True)
1666
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1667
 
        return branch
 
1448
        return self.open(a_bzrdir, _found=True)
1668
1449
 
1669
 
    def initialize(self, a_bzrdir, name=None):
1670
 
        """Create a branch of this format in a_bzrdir.
1671
 
        
1672
 
        :param name: Name of the colocated branch to create.
1673
 
        """
 
1450
    def initialize(self, a_bzrdir):
 
1451
        """Create a branch of this format in a_bzrdir."""
1674
1452
        raise NotImplementedError(self.initialize)
1675
1453
 
1676
1454
    def is_supported(self):
1706
1484
        """
1707
1485
        raise NotImplementedError(self.network_name)
1708
1486
 
1709
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1487
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1710
1488
        """Return the branch object for a_bzrdir
1711
1489
 
1712
1490
        :param a_bzrdir: A BzrDir that contains a branch.
1713
 
        :param name: Name of colocated branch to open
1714
1491
        :param _found: a private parameter, do not use it. It is used to
1715
1492
            indicate if format probing has already be done.
1716
1493
        :param ignore_fallbacks: when set, no fallback branches will be opened
1720
1497
 
1721
1498
    @classmethod
1722
1499
    def register_format(klass, format):
1723
 
        """Register a metadir format.
1724
 
        
1725
 
        See MetaDirBranchFormatFactory for the ability to register a format
1726
 
        without loading the code the format needs until it is actually used.
1727
 
        """
 
1500
        """Register a metadir format."""
1728
1501
        klass._formats[format.get_format_string()] = format
1729
1502
        # Metadir formats have a network name of their format string, and get
1730
 
        # registered as factories.
1731
 
        if isinstance(format, MetaDirBranchFormatFactory):
1732
 
            network_format_registry.register(format.get_format_string(), format)
1733
 
        else:
1734
 
            network_format_registry.register(format.get_format_string(),
1735
 
                format.__class__)
 
1503
        # registered as class factories.
 
1504
        network_format_registry.register(format.get_format_string(), format.__class__)
1736
1505
 
1737
1506
    @classmethod
1738
1507
    def set_default_format(klass, format):
1739
1508
        klass._default_format = format
1740
1509
 
1741
 
    def supports_set_append_revisions_only(self):
1742
 
        """True if this format supports set_append_revisions_only."""
1743
 
        return False
1744
 
 
1745
1510
    def supports_stacking(self):
1746
1511
        """True if this format records a stacked-on branch."""
1747
1512
        return False
1758
1523
        return False  # by default
1759
1524
 
1760
1525
 
1761
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1762
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1763
 
    
1764
 
    While none of the built in BranchFormats are lazy registered yet,
1765
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1766
 
    use it, and the bzr-loom plugin uses it as well (see
1767
 
    bzrlib.plugins.loom.formats).
1768
 
    """
1769
 
 
1770
 
    def __init__(self, format_string, module_name, member_name):
1771
 
        """Create a MetaDirBranchFormatFactory.
1772
 
 
1773
 
        :param format_string: The format string the format has.
1774
 
        :param module_name: Module to load the format class from.
1775
 
        :param member_name: Attribute name within the module for the format class.
1776
 
        """
1777
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1778
 
        self._format_string = format_string
1779
 
        
1780
 
    def get_format_string(self):
1781
 
        """See BranchFormat.get_format_string."""
1782
 
        return self._format_string
1783
 
 
1784
 
    def __call__(self):
1785
 
        """Used for network_format_registry support."""
1786
 
        return self.get_obj()()
1787
 
 
1788
 
 
1789
1526
class BranchHooks(Hooks):
1790
1527
    """A dictionary mapping hook name to a list of callables for branch hooks.
1791
1528
 
1860
1597
            "multiple hooks installed for transform_fallback_location, "
1861
1598
            "all are called with the url returned from the previous hook."
1862
1599
            "The order is however undefined.", (1, 9), None))
1863
 
        self.create_hook(HookPoint('automatic_tag_name',
1864
 
            "Called to determine an automatic tag name for a revision. "
1865
 
            "automatic_tag_name is called with (branch, revision_id) and "
1866
 
            "should return a tag name or None if no tag name could be "
1867
 
            "determined. The first non-None tag name returned will be used.",
1868
 
            (2, 2), None))
1869
 
        self.create_hook(HookPoint('post_branch_init',
1870
 
            "Called after new branch initialization completes. "
1871
 
            "post_branch_init is called with a "
1872
 
            "bzrlib.branch.BranchInitHookParams. "
1873
 
            "Note that init, branch and checkout (both heavyweight and "
1874
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1875
 
        self.create_hook(HookPoint('post_switch',
1876
 
            "Called after a checkout switches branch. "
1877
 
            "post_switch is called with a "
1878
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1879
 
 
1880
1600
 
1881
1601
 
1882
1602
# install the default hooks into the Branch class.
1921
1641
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1922
1642
 
1923
1643
 
1924
 
class BranchInitHookParams(object):
1925
 
    """Object holding parameters passed to *_branch_init hooks.
1926
 
 
1927
 
    There are 4 fields that hooks may wish to access:
1928
 
 
1929
 
    :ivar format: the branch format
1930
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1931
 
    :ivar name: name of colocated branch, if any (or None)
1932
 
    :ivar branch: the branch created
1933
 
 
1934
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1935
 
    the checkout, hence they are different from the corresponding fields in
1936
 
    branch, which refer to the original branch.
1937
 
    """
1938
 
 
1939
 
    def __init__(self, format, a_bzrdir, name, branch):
1940
 
        """Create a group of BranchInitHook parameters.
1941
 
 
1942
 
        :param format: the branch format
1943
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1944
 
            initialized
1945
 
        :param name: name of colocated branch, if any (or None)
1946
 
        :param branch: the branch created
1947
 
 
1948
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1949
 
        to the checkout, hence they are different from the corresponding fields
1950
 
        in branch, which refer to the original branch.
1951
 
        """
1952
 
        self.format = format
1953
 
        self.bzrdir = a_bzrdir
1954
 
        self.name = name
1955
 
        self.branch = branch
1956
 
 
1957
 
    def __eq__(self, other):
1958
 
        return self.__dict__ == other.__dict__
1959
 
 
1960
 
    def __repr__(self):
1961
 
        if self.branch:
1962
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1963
 
        else:
1964
 
            return "<%s of format:%s bzrdir:%s>" % (
1965
 
                self.__class__.__name__, self.branch,
1966
 
                self.format, self.bzrdir)
1967
 
 
1968
 
 
1969
 
class SwitchHookParams(object):
1970
 
    """Object holding parameters passed to *_switch hooks.
1971
 
 
1972
 
    There are 4 fields that hooks may wish to access:
1973
 
 
1974
 
    :ivar control_dir: BzrDir of the checkout to change
1975
 
    :ivar to_branch: branch that the checkout is to reference
1976
 
    :ivar force: skip the check for local commits in a heavy checkout
1977
 
    :ivar revision_id: revision ID to switch to (or None)
1978
 
    """
1979
 
 
1980
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1981
 
        """Create a group of SwitchHook parameters.
1982
 
 
1983
 
        :param control_dir: BzrDir of the checkout to change
1984
 
        :param to_branch: branch that the checkout is to reference
1985
 
        :param force: skip the check for local commits in a heavy checkout
1986
 
        :param revision_id: revision ID to switch to (or None)
1987
 
        """
1988
 
        self.control_dir = control_dir
1989
 
        self.to_branch = to_branch
1990
 
        self.force = force
1991
 
        self.revision_id = revision_id
1992
 
 
1993
 
    def __eq__(self, other):
1994
 
        return self.__dict__ == other.__dict__
1995
 
 
1996
 
    def __repr__(self):
1997
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1998
 
            self.control_dir, self.to_branch,
1999
 
            self.revision_id)
2000
 
 
2001
 
 
2002
1644
class BzrBranchFormat4(BranchFormat):
2003
1645
    """Bzr branch format 4.
2004
1646
 
2011
1653
        """See BranchFormat.get_format_description()."""
2012
1654
        return "Branch format 4"
2013
1655
 
2014
 
    def initialize(self, a_bzrdir, name=None):
 
1656
    def initialize(self, a_bzrdir):
2015
1657
        """Create a branch of this format in a_bzrdir."""
2016
1658
        utf8_files = [('revision-history', ''),
2017
1659
                      ('branch-name', ''),
2018
1660
                      ]
2019
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1661
        return self._initialize_helper(a_bzrdir, utf8_files,
2020
1662
                                       lock_type='branch4', set_format=False)
2021
1663
 
2022
1664
    def __init__(self):
2027
1669
        """The network name for this format is the control dirs disk label."""
2028
1670
        return self._matchingbzrdir.get_format_string()
2029
1671
 
2030
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1672
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2031
1673
        """See BranchFormat.open()."""
2032
1674
        if not _found:
2033
1675
            # we are being called directly and must probe.
2035
1677
        return BzrBranch(_format=self,
2036
1678
                         _control_files=a_bzrdir._control_files,
2037
1679
                         a_bzrdir=a_bzrdir,
2038
 
                         name=name,
2039
1680
                         _repository=a_bzrdir.open_repository())
2040
1681
 
2041
1682
    def __str__(self):
2056
1697
        """
2057
1698
        return self.get_format_string()
2058
1699
 
2059
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1700
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2060
1701
        """See BranchFormat.open()."""
2061
1702
        if not _found:
2062
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1703
            format = BranchFormat.find_format(a_bzrdir)
2063
1704
            if format.__class__ != self.__class__:
2064
1705
                raise AssertionError("wrong format %r found for %r" %
2065
1706
                    (format, self))
2066
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2067
1707
        try:
 
1708
            transport = a_bzrdir.get_branch_transport(None)
2068
1709
            control_files = lockable_files.LockableFiles(transport, 'lock',
2069
1710
                                                         lockdir.LockDir)
2070
1711
            return self._branch_class()(_format=self,
2071
1712
                              _control_files=control_files,
2072
 
                              name=name,
2073
1713
                              a_bzrdir=a_bzrdir,
2074
1714
                              _repository=a_bzrdir.find_repository(),
2075
1715
                              ignore_fallbacks=ignore_fallbacks)
2076
1716
        except errors.NoSuchFile:
2077
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1717
            raise errors.NotBranchError(path=transport.base)
2078
1718
 
2079
1719
    def __init__(self):
2080
1720
        super(BranchFormatMetadir, self).__init__()
2109
1749
        """See BranchFormat.get_format_description()."""
2110
1750
        return "Branch format 5"
2111
1751
 
2112
 
    def initialize(self, a_bzrdir, name=None):
 
1752
    def initialize(self, a_bzrdir):
2113
1753
        """Create a branch of this format in a_bzrdir."""
2114
1754
        utf8_files = [('revision-history', ''),
2115
1755
                      ('branch-name', ''),
2116
1756
                      ]
2117
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1757
        return self._initialize_helper(a_bzrdir, utf8_files)
2118
1758
 
2119
1759
    def supports_tags(self):
2120
1760
        return False
2142
1782
        """See BranchFormat.get_format_description()."""
2143
1783
        return "Branch format 6"
2144
1784
 
2145
 
    def initialize(self, a_bzrdir, name=None):
 
1785
    def initialize(self, a_bzrdir):
2146
1786
        """Create a branch of this format in a_bzrdir."""
2147
1787
        utf8_files = [('last-revision', '0 null:\n'),
2148
1788
                      ('branch.conf', ''),
2149
1789
                      ('tags', ''),
2150
1790
                      ]
2151
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1791
        return self._initialize_helper(a_bzrdir, utf8_files)
2152
1792
 
2153
1793
    def make_tags(self, branch):
2154
1794
        """See bzrlib.branch.BranchFormat.make_tags()."""
2155
1795
        return BasicTags(branch)
2156
1796
 
2157
 
    def supports_set_append_revisions_only(self):
2158
 
        return True
2159
1797
 
2160
1798
 
2161
1799
class BzrBranchFormat8(BranchFormatMetadir):
2172
1810
        """See BranchFormat.get_format_description()."""
2173
1811
        return "Branch format 8"
2174
1812
 
2175
 
    def initialize(self, a_bzrdir, name=None):
 
1813
    def initialize(self, a_bzrdir):
2176
1814
        """Create a branch of this format in a_bzrdir."""
2177
1815
        utf8_files = [('last-revision', '0 null:\n'),
2178
1816
                      ('branch.conf', ''),
2179
1817
                      ('tags', ''),
2180
1818
                      ('references', '')
2181
1819
                      ]
2182
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1820
        return self._initialize_helper(a_bzrdir, utf8_files)
2183
1821
 
2184
1822
    def __init__(self):
2185
1823
        super(BzrBranchFormat8, self).__init__()
2190
1828
        """See bzrlib.branch.BranchFormat.make_tags()."""
2191
1829
        return BasicTags(branch)
2192
1830
 
2193
 
    def supports_set_append_revisions_only(self):
2194
 
        return True
2195
 
 
2196
1831
    def supports_stacking(self):
2197
1832
        return True
2198
1833
 
2208
1843
    This format was introduced in bzr 1.6.
2209
1844
    """
2210
1845
 
2211
 
    def initialize(self, a_bzrdir, name=None):
 
1846
    def initialize(self, a_bzrdir):
2212
1847
        """Create a branch of this format in a_bzrdir."""
2213
1848
        utf8_files = [('last-revision', '0 null:\n'),
2214
1849
                      ('branch.conf', ''),
2215
1850
                      ('tags', ''),
2216
1851
                      ]
2217
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1852
        return self._initialize_helper(a_bzrdir, utf8_files)
2218
1853
 
2219
1854
    def _branch_class(self):
2220
1855
        return BzrBranch7
2227
1862
        """See BranchFormat.get_format_description()."""
2228
1863
        return "Branch format 7"
2229
1864
 
2230
 
    def supports_set_append_revisions_only(self):
2231
 
        return True
2232
 
 
2233
1865
    supports_reference_locations = False
2234
1866
 
2235
1867
 
2252
1884
        """See BranchFormat.get_format_description()."""
2253
1885
        return "Checkout reference format 1"
2254
1886
 
2255
 
    def get_reference(self, a_bzrdir, name=None):
 
1887
    def get_reference(self, a_bzrdir):
2256
1888
        """See BranchFormat.get_reference()."""
2257
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2258
 
        return transport.get_bytes('location')
 
1889
        transport = a_bzrdir.get_branch_transport(None)
 
1890
        return transport.get('location').read()
2259
1891
 
2260
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1892
    def set_reference(self, a_bzrdir, to_branch):
2261
1893
        """See BranchFormat.set_reference()."""
2262
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1894
        transport = a_bzrdir.get_branch_transport(None)
2263
1895
        location = transport.put_bytes('location', to_branch.base)
2264
1896
 
2265
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1897
    def initialize(self, a_bzrdir, target_branch=None):
2266
1898
        """Create a branch of this format in a_bzrdir."""
2267
1899
        if target_branch is None:
2268
1900
            # this format does not implement branch itself, thus the implicit
2269
1901
            # creation contract must see it as uninitializable
2270
1902
            raise errors.UninitializableFormat(self)
2271
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2272
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1903
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1904
        branch_transport = a_bzrdir.get_branch_transport(self)
2273
1905
        branch_transport.put_bytes('location',
2274
 
            target_branch.bzrdir.user_url)
 
1906
            target_branch.bzrdir.root_transport.base)
2275
1907
        branch_transport.put_bytes('format', self.get_format_string())
2276
 
        branch = self.open(
2277
 
            a_bzrdir, name, _found=True,
 
1908
        return self.open(
 
1909
            a_bzrdir, _found=True,
2278
1910
            possible_transports=[target_branch.bzrdir.root_transport])
2279
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2280
 
        return branch
2281
1911
 
2282
1912
    def __init__(self):
2283
1913
        super(BranchReferenceFormat, self).__init__()
2289
1919
        def clone(to_bzrdir, revision_id=None,
2290
1920
            repository_policy=None):
2291
1921
            """See Branch.clone()."""
2292
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
1922
            return format.initialize(to_bzrdir, a_branch)
2293
1923
            # cannot obey revision_id limits when cloning a reference ...
2294
1924
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2295
1925
            # emit some sort of warning/error to the caller ?!
2296
1926
        return clone
2297
1927
 
2298
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
1928
    def open(self, a_bzrdir, _found=False, location=None,
2299
1929
             possible_transports=None, ignore_fallbacks=False):
2300
1930
        """Return the branch that the branch reference in a_bzrdir points at.
2301
1931
 
2302
1932
        :param a_bzrdir: A BzrDir that contains a branch.
2303
 
        :param name: Name of colocated branch to open, if any
2304
1933
        :param _found: a private parameter, do not use it. It is used to
2305
1934
            indicate if format probing has already be done.
2306
1935
        :param ignore_fallbacks: when set, no fallback branches will be opened
2311
1940
        :param possible_transports: An optional reusable transports list.
2312
1941
        """
2313
1942
        if not _found:
2314
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1943
            format = BranchFormat.find_format(a_bzrdir)
2315
1944
            if format.__class__ != self.__class__:
2316
1945
                raise AssertionError("wrong format %r found for %r" %
2317
1946
                    (format, self))
2318
1947
        if location is None:
2319
 
            location = self.get_reference(a_bzrdir, name)
 
1948
            location = self.get_reference(a_bzrdir)
2320
1949
        real_bzrdir = bzrdir.BzrDir.open(
2321
1950
            location, possible_transports=possible_transports)
2322
 
        result = real_bzrdir.open_branch(name=name, 
2323
 
            ignore_fallbacks=ignore_fallbacks)
 
1951
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2324
1952
        # this changes the behaviour of result.clone to create a new reference
2325
1953
        # rather than a copy of the content of the branch.
2326
1954
        # I did not use a proxy object because that needs much more extensive
2353
1981
BranchFormat.register_format(__format6)
2354
1982
BranchFormat.register_format(__format7)
2355
1983
BranchFormat.register_format(__format8)
2356
 
BranchFormat.set_default_format(__format7)
 
1984
BranchFormat.set_default_format(__format6)
2357
1985
_legacy_formats = [BzrBranchFormat4(),
2358
1986
    ]
2359
1987
network_format_registry.register(
2360
1988
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2361
1989
 
2362
1990
 
2363
 
class BranchWriteLockResult(LogicalLockResult):
2364
 
    """The result of write locking a branch.
2365
 
 
2366
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2367
 
        None.
2368
 
    :ivar unlock: A callable which will unlock the lock.
2369
 
    """
2370
 
 
2371
 
    def __init__(self, unlock, branch_token):
2372
 
        LogicalLockResult.__init__(self, unlock)
2373
 
        self.branch_token = branch_token
2374
 
 
2375
 
    def __repr__(self):
2376
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2377
 
            self.unlock)
2378
 
 
2379
 
 
2380
 
class BzrBranch(Branch, _RelockDebugMixin):
 
1991
class BzrBranch(Branch):
2381
1992
    """A branch stored in the actual filesystem.
2382
1993
 
2383
1994
    Note that it's "local" in the context of the filesystem; it doesn't
2389
2000
    :ivar repository: Repository for this branch.
2390
2001
    :ivar base: The url of the base directory for this branch; the one
2391
2002
        containing the .bzr directory.
2392
 
    :ivar name: Optional colocated branch name as it exists in the control
2393
 
        directory.
2394
2003
    """
2395
2004
 
2396
2005
    def __init__(self, _format=None,
2397
 
                 _control_files=None, a_bzrdir=None, name=None,
2398
 
                 _repository=None, ignore_fallbacks=False):
 
2006
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2007
                 ignore_fallbacks=False):
2399
2008
        """Create new branch object at a particular location."""
2400
2009
        if a_bzrdir is None:
2401
2010
            raise ValueError('a_bzrdir must be supplied')
2402
2011
        else:
2403
2012
            self.bzrdir = a_bzrdir
2404
2013
        self._base = self.bzrdir.transport.clone('..').base
2405
 
        self.name = name
2406
2014
        # XXX: We should be able to just do
2407
2015
        #   self.base = self.bzrdir.root_transport.base
2408
2016
        # but this does not quite work yet -- mbp 20080522
2415
2023
        Branch.__init__(self)
2416
2024
 
2417
2025
    def __str__(self):
2418
 
        if self.name is None:
2419
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2420
 
        else:
2421
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2422
 
                self.name)
 
2026
        return '%s(%r)' % (self.__class__.__name__, self.base)
2423
2027
 
2424
2028
    __repr__ = __str__
2425
2029
 
2436
2040
        return self.control_files.is_locked()
2437
2041
 
2438
2042
    def lock_write(self, token=None):
2439
 
        """Lock the branch for write operations.
2440
 
 
2441
 
        :param token: A token to permit reacquiring a previously held and
2442
 
            preserved lock.
2443
 
        :return: A BranchWriteLockResult.
2444
 
        """
2445
 
        if not self.is_locked():
2446
 
            self._note_lock('w')
2447
2043
        # All-in-one needs to always unlock/lock.
2448
2044
        repo_control = getattr(self.repository, 'control_files', None)
2449
2045
        if self.control_files == repo_control or not self.is_locked():
2450
 
            self.repository._warn_if_deprecated(self)
2451
2046
            self.repository.lock_write()
2452
2047
            took_lock = True
2453
2048
        else:
2454
2049
            took_lock = False
2455
2050
        try:
2456
 
            return BranchWriteLockResult(self.unlock,
2457
 
                self.control_files.lock_write(token=token))
 
2051
            return self.control_files.lock_write(token=token)
2458
2052
        except:
2459
2053
            if took_lock:
2460
2054
                self.repository.unlock()
2461
2055
            raise
2462
2056
 
2463
2057
    def lock_read(self):
2464
 
        """Lock the branch for read operations.
2465
 
 
2466
 
        :return: A bzrlib.lock.LogicalLockResult.
2467
 
        """
2468
 
        if not self.is_locked():
2469
 
            self._note_lock('r')
2470
2058
        # All-in-one needs to always unlock/lock.
2471
2059
        repo_control = getattr(self.repository, 'control_files', None)
2472
2060
        if self.control_files == repo_control or not self.is_locked():
2473
 
            self.repository._warn_if_deprecated(self)
2474
2061
            self.repository.lock_read()
2475
2062
            took_lock = True
2476
2063
        else:
2477
2064
            took_lock = False
2478
2065
        try:
2479
2066
            self.control_files.lock_read()
2480
 
            return LogicalLockResult(self.unlock)
2481
2067
        except:
2482
2068
            if took_lock:
2483
2069
                self.repository.unlock()
2484
2070
            raise
2485
2071
 
2486
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2487
2072
    def unlock(self):
2488
2073
        try:
2489
2074
            self.control_files.unlock()
2652
2237
        return result
2653
2238
 
2654
2239
    def get_stacked_on_url(self):
2655
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2240
        raise errors.UnstackableBranchFormat(self._format, self.base)
2656
2241
 
2657
2242
    def set_push_location(self, location):
2658
2243
        """See Branch.set_push_location."""
2791
2376
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2792
2377
        super(BzrBranch8, self).__init__(*args, **kwargs)
2793
2378
        self._last_revision_info_cache = None
 
2379
        self._partial_revision_history_cache = []
2794
2380
        self._reference_info = None
2795
2381
 
2796
2382
    def _clear_cached_state(self):
2797
2383
        super(BzrBranch8, self)._clear_cached_state()
2798
2384
        self._last_revision_info_cache = None
 
2385
        self._partial_revision_history_cache = []
2799
2386
        self._reference_info = None
2800
2387
 
2801
2388
    def _last_revision_info(self):
2848
2435
        if _mod_revision.is_null(last_revision):
2849
2436
            return
2850
2437
        if last_revision not in self._lefthand_history(revision_id):
2851
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2438
            raise errors.AppendRevisionsOnlyViolation(self.base)
2852
2439
 
2853
2440
    def _gen_revision_history(self):
2854
2441
        """Generate the revision history from last revision
2857
2444
        self._extend_partial_history(stop_index=last_revno-1)
2858
2445
        return list(reversed(self._partial_revision_history_cache))
2859
2446
 
 
2447
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2448
        """Extend the partial history to include a given index
 
2449
 
 
2450
        If a stop_index is supplied, stop when that index has been reached.
 
2451
        If a stop_revision is supplied, stop when that revision is
 
2452
        encountered.  Otherwise, stop when the beginning of history is
 
2453
        reached.
 
2454
 
 
2455
        :param stop_index: The index which should be present.  When it is
 
2456
            present, history extension will stop.
 
2457
        :param revision_id: The revision id which should be present.  When
 
2458
            it is encountered, history extension will stop.
 
2459
        """
 
2460
        repo = self.repository
 
2461
        if len(self._partial_revision_history_cache) == 0:
 
2462
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2463
        else:
 
2464
            start_revision = self._partial_revision_history_cache[-1]
 
2465
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2466
            #skip the last revision in the list
 
2467
            next_revision = iterator.next()
 
2468
        for revision_id in iterator:
 
2469
            self._partial_revision_history_cache.append(revision_id)
 
2470
            if (stop_index is not None and
 
2471
                len(self._partial_revision_history_cache) > stop_index):
 
2472
                break
 
2473
            if revision_id == stop_revision:
 
2474
                break
 
2475
 
2860
2476
    def _write_revision_history(self, history):
2861
2477
        """Factored out of set_revision_history.
2862
2478
 
2954
2570
        if branch_location is None:
2955
2571
            return Branch.reference_parent(self, file_id, path,
2956
2572
                                           possible_transports)
2957
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2573
        branch_location = urlutils.join(self.base, branch_location)
2958
2574
        return Branch.open(branch_location,
2959
2575
                           possible_transports=possible_transports)
2960
2576
 
3005
2621
            raise errors.NotStacked(self)
3006
2622
        return stacked_url
3007
2623
 
 
2624
    def set_append_revisions_only(self, enabled):
 
2625
        if enabled:
 
2626
            value = 'True'
 
2627
        else:
 
2628
            value = 'False'
 
2629
        self.get_config().set_user_option('append_revisions_only', value,
 
2630
            warn_masked=True)
 
2631
 
3008
2632
    def _get_append_revisions_only(self):
3009
 
        return self.get_config(
3010
 
            ).get_user_option_as_bool('append_revisions_only')
 
2633
        value = self.get_config().get_user_option('append_revisions_only')
 
2634
        return value == 'True'
3011
2635
 
3012
2636
    @needs_write_lock
3013
2637
    def generate_revision_history(self, revision_id, last_rev=None,
3075
2699
    """
3076
2700
 
3077
2701
    def get_stacked_on_url(self):
3078
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2702
        raise errors.UnstackableBranchFormat(self._format, self.base)
3079
2703
 
3080
2704
 
3081
2705
######################################################################
3160
2784
 
3161
2785
    def __init__(self, branch):
3162
2786
        self.branch = branch
3163
 
        self.errors = []
 
2787
        self.ghosts_in_mainline = False
3164
2788
 
3165
2789
    def report_results(self, verbose):
3166
2790
        """Report the check results via trace.note.
3168
2792
        :param verbose: Requests more detailed display of what was checked,
3169
2793
            if any.
3170
2794
        """
3171
 
        note('checked branch %s format %s', self.branch.user_url,
3172
 
            self.branch._format)
3173
 
        for error in self.errors:
3174
 
            note('found error:%s', error)
 
2795
        note('checked branch %s format %s',
 
2796
             self.branch.base,
 
2797
             self.branch._format)
 
2798
        if self.ghosts_in_mainline:
 
2799
            note('branch contains ghosts in mainline')
3175
2800
 
3176
2801
 
3177
2802
class Converter5to6(object):
3269
2894
    _optimisers = []
3270
2895
    """The available optimised InterBranch types."""
3271
2896
 
3272
 
    @classmethod
3273
 
    def _get_branch_formats_to_test(klass):
3274
 
        """Return an iterable of format tuples for testing.
3275
 
        
3276
 
        :return: An iterable of (from_format, to_format) to use when testing
3277
 
            this InterBranch class. Each InterBranch class should define this
3278
 
            method itself.
3279
 
        """
3280
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2897
    @staticmethod
 
2898
    def _get_branch_formats_to_test():
 
2899
        """Return a tuple with the Branch formats to use when testing."""
 
2900
        raise NotImplementedError(self._get_branch_formats_to_test)
3281
2901
 
3282
 
    @needs_write_lock
3283
2902
    def pull(self, overwrite=False, stop_revision=None,
3284
2903
             possible_transports=None, local=False):
3285
2904
        """Mirror source into target branch.
3290
2909
        """
3291
2910
        raise NotImplementedError(self.pull)
3292
2911
 
3293
 
    @needs_write_lock
3294
2912
    def update_revisions(self, stop_revision=None, overwrite=False,
3295
2913
                         graph=None):
3296
2914
        """Pull in new perfect-fit revisions.
3304
2922
        """
3305
2923
        raise NotImplementedError(self.update_revisions)
3306
2924
 
3307
 
    @needs_write_lock
3308
2925
    def push(self, overwrite=False, stop_revision=None,
3309
2926
             _override_hook_source_branch=None):
3310
2927
        """Mirror the source branch into the target branch.
3315
2932
 
3316
2933
 
3317
2934
class GenericInterBranch(InterBranch):
3318
 
    """InterBranch implementation that uses public Branch functions."""
3319
 
 
3320
 
    @classmethod
3321
 
    def is_compatible(klass, source, target):
3322
 
        # GenericBranch uses the public API, so always compatible
3323
 
        return True
3324
 
 
3325
 
    @classmethod
3326
 
    def _get_branch_formats_to_test(klass):
3327
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3328
 
 
3329
 
    @classmethod
3330
 
    def unwrap_format(klass, format):
3331
 
        if isinstance(format, remote.RemoteBranchFormat):
3332
 
            format._ensure_real()
3333
 
            return format._custom_format
3334
 
        return format                                                                                                  
3335
 
 
3336
 
    @needs_write_lock
3337
 
    def copy_content_into(self, revision_id=None):
3338
 
        """Copy the content of source into target
3339
 
 
3340
 
        revision_id: if not None, the revision history in the new branch will
3341
 
                     be truncated to end with revision_id.
3342
 
        """
3343
 
        self.source.update_references(self.target)
3344
 
        self.source._synchronize_history(self.target, revision_id)
3345
 
        try:
3346
 
            parent = self.source.get_parent()
3347
 
        except errors.InaccessibleParent, e:
3348
 
            mutter('parent was not accessible to copy: %s', e)
3349
 
        else:
3350
 
            if parent:
3351
 
                self.target.set_parent(parent)
3352
 
        if self.source._push_should_merge_tags():
3353
 
            self.source.tags.merge_to(self.target.tags)
3354
 
 
3355
 
    @needs_write_lock
 
2935
    """InterBranch implementation that uses public Branch functions.
 
2936
    """
 
2937
 
 
2938
    @staticmethod
 
2939
    def _get_branch_formats_to_test():
 
2940
        return BranchFormat._default_format, BranchFormat._default_format
 
2941
 
3356
2942
    def update_revisions(self, stop_revision=None, overwrite=False,
3357
2943
        graph=None):
3358
2944
        """See InterBranch.update_revisions()."""
3359
 
        other_revno, other_last_revision = self.source.last_revision_info()
3360
 
        stop_revno = None # unknown
3361
 
        if stop_revision is None:
3362
 
            stop_revision = other_last_revision
3363
 
            if _mod_revision.is_null(stop_revision):
3364
 
                # if there are no commits, we're done.
3365
 
                return
3366
 
            stop_revno = other_revno
3367
 
 
3368
 
        # what's the current last revision, before we fetch [and change it
3369
 
        # possibly]
3370
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3371
 
        # we fetch here so that we don't process data twice in the common
3372
 
        # case of having something to pull, and so that the check for
3373
 
        # already merged can operate on the just fetched graph, which will
3374
 
        # be cached in memory.
3375
 
        self.target.fetch(self.source, stop_revision)
3376
 
        # Check to see if one is an ancestor of the other
3377
 
        if not overwrite:
3378
 
            if graph is None:
3379
 
                graph = self.target.repository.get_graph()
3380
 
            if self.target._check_if_descendant_or_diverged(
3381
 
                    stop_revision, last_rev, graph, self.source):
3382
 
                # stop_revision is a descendant of last_rev, but we aren't
3383
 
                # overwriting, so we're done.
3384
 
                return
3385
 
        if stop_revno is None:
3386
 
            if graph is None:
3387
 
                graph = self.target.repository.get_graph()
3388
 
            this_revno, this_last_revision = \
3389
 
                    self.target.last_revision_info()
3390
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3391
 
                            [(other_last_revision, other_revno),
3392
 
                             (this_last_revision, this_revno)])
3393
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3394
 
 
3395
 
    @needs_write_lock
 
2945
        self.source.lock_read()
 
2946
        try:
 
2947
            other_revno, other_last_revision = self.source.last_revision_info()
 
2948
            stop_revno = None # unknown
 
2949
            if stop_revision is None:
 
2950
                stop_revision = other_last_revision
 
2951
                if _mod_revision.is_null(stop_revision):
 
2952
                    # if there are no commits, we're done.
 
2953
                    return
 
2954
                stop_revno = other_revno
 
2955
 
 
2956
            # what's the current last revision, before we fetch [and change it
 
2957
            # possibly]
 
2958
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2959
            # we fetch here so that we don't process data twice in the common
 
2960
            # case of having something to pull, and so that the check for
 
2961
            # already merged can operate on the just fetched graph, which will
 
2962
            # be cached in memory.
 
2963
            self.target.fetch(self.source, stop_revision)
 
2964
            # Check to see if one is an ancestor of the other
 
2965
            if not overwrite:
 
2966
                if graph is None:
 
2967
                    graph = self.target.repository.get_graph()
 
2968
                if self.target._check_if_descendant_or_diverged(
 
2969
                        stop_revision, last_rev, graph, self.source):
 
2970
                    # stop_revision is a descendant of last_rev, but we aren't
 
2971
                    # overwriting, so we're done.
 
2972
                    return
 
2973
            if stop_revno is None:
 
2974
                if graph is None:
 
2975
                    graph = self.target.repository.get_graph()
 
2976
                this_revno, this_last_revision = \
 
2977
                        self.target.last_revision_info()
 
2978
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2979
                                [(other_last_revision, other_revno),
 
2980
                                 (this_last_revision, this_revno)])
 
2981
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2982
        finally:
 
2983
            self.source.unlock()
 
2984
 
3396
2985
    def pull(self, overwrite=False, stop_revision=None,
3397
 
             possible_transports=None, run_hooks=True,
 
2986
             possible_transports=None, _hook_master=None, run_hooks=True,
3398
2987
             _override_hook_target=None, local=False):
3399
 
        """Pull from source into self, updating my master if any.
 
2988
        """See Branch.pull.
3400
2989
 
 
2990
        :param _hook_master: Private parameter - set the branch to
 
2991
            be supplied as the master to pull hooks.
3401
2992
        :param run_hooks: Private parameter - if false, this branch
3402
2993
            is being called because it's the master of the primary branch,
3403
2994
            so it should not run its hooks.
 
2995
        :param _override_hook_target: Private parameter - set the branch to be
 
2996
            supplied as the target_branch to pull hooks.
 
2997
        :param local: Only update the local branch, and not the bound branch.
3404
2998
        """
3405
 
        bound_location = self.target.get_bound_location()
3406
 
        if local and not bound_location:
 
2999
        # This type of branch can't be bound.
 
3000
        if local:
3407
3001
            raise errors.LocalRequiresBoundBranch()
3408
 
        master_branch = None
3409
 
        if not local and bound_location and self.source.user_url != bound_location:
3410
 
            # not pulling from master, so we need to update master.
3411
 
            master_branch = self.target.get_master_branch(possible_transports)
3412
 
            master_branch.lock_write()
 
3002
        result = PullResult()
 
3003
        result.source_branch = self.source
 
3004
        if _override_hook_target is None:
 
3005
            result.target_branch = self.target
 
3006
        else:
 
3007
            result.target_branch = _override_hook_target
 
3008
        self.source.lock_read()
3413
3009
        try:
3414
 
            if master_branch:
3415
 
                # pull from source into master.
3416
 
                master_branch.pull(self.source, overwrite, stop_revision,
3417
 
                    run_hooks=False)
3418
 
            return self._pull(overwrite,
3419
 
                stop_revision, _hook_master=master_branch,
3420
 
                run_hooks=run_hooks,
3421
 
                _override_hook_target=_override_hook_target)
 
3010
            # We assume that during 'pull' the target repository is closer than
 
3011
            # the source one.
 
3012
            self.source.update_references(self.target)
 
3013
            graph = self.target.repository.get_graph(self.source.repository)
 
3014
            # TODO: Branch formats should have a flag that indicates 
 
3015
            # that revno's are expensive, and pull() should honor that flag.
 
3016
            # -- JRV20090506
 
3017
            result.old_revno, result.old_revid = \
 
3018
                self.target.last_revision_info()
 
3019
            self.target.update_revisions(self.source, stop_revision,
 
3020
                overwrite=overwrite, graph=graph)
 
3021
            # TODO: The old revid should be specified when merging tags, 
 
3022
            # so a tags implementation that versions tags can only 
 
3023
            # pull in the most recent changes. -- JRV20090506
 
3024
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3025
                overwrite)
 
3026
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3027
            if _hook_master:
 
3028
                result.master_branch = _hook_master
 
3029
                result.local_branch = result.target_branch
 
3030
            else:
 
3031
                result.master_branch = result.target_branch
 
3032
                result.local_branch = None
 
3033
            if run_hooks:
 
3034
                for hook in Branch.hooks['post_pull']:
 
3035
                    hook(result)
3422
3036
        finally:
3423
 
            if master_branch:
3424
 
                master_branch.unlock()
 
3037
            self.source.unlock()
 
3038
        return result
3425
3039
 
3426
3040
    def push(self, overwrite=False, stop_revision=None,
3427
3041
             _override_hook_source_branch=None):
3444
3058
                _override_hook_source_branch=_override_hook_source_branch)
3445
3059
        finally:
3446
3060
            self.source.unlock()
 
3061
        return result
3447
3062
 
3448
3063
    def _push_with_bound_branches(self, overwrite, stop_revision,
3449
3064
            _override_hook_source_branch=None):
3489
3104
            _run_hooks()
3490
3105
            return result
3491
3106
 
3492
 
    def _pull(self, overwrite=False, stop_revision=None,
3493
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3107
    @classmethod
 
3108
    def is_compatible(self, source, target):
 
3109
        # GenericBranch uses the public API, so always compatible
 
3110
        return True
 
3111
 
 
3112
 
 
3113
class InterToBranch5(GenericInterBranch):
 
3114
 
 
3115
    @staticmethod
 
3116
    def _get_branch_formats_to_test():
 
3117
        return BranchFormat._default_format, BzrBranchFormat5()
 
3118
 
 
3119
    def pull(self, overwrite=False, stop_revision=None,
 
3120
             possible_transports=None, run_hooks=True,
3494
3121
             _override_hook_target=None, local=False):
3495
 
        """See Branch.pull.
3496
 
 
3497
 
        This function is the core worker, used by GenericInterBranch.pull to
3498
 
        avoid duplication when pulling source->master and source->local.
3499
 
 
3500
 
        :param _hook_master: Private parameter - set the branch to
3501
 
            be supplied as the master to pull hooks.
 
3122
        """Pull from source into self, updating my master if any.
 
3123
 
3502
3124
        :param run_hooks: Private parameter - if false, this branch
3503
3125
            is being called because it's the master of the primary branch,
3504
3126
            so it should not run its hooks.
3505
 
        :param _override_hook_target: Private parameter - set the branch to be
3506
 
            supplied as the target_branch to pull hooks.
3507
 
        :param local: Only update the local branch, and not the bound branch.
3508
3127
        """
3509
 
        # This type of branch can't be bound.
3510
 
        if local:
 
3128
        bound_location = self.target.get_bound_location()
 
3129
        if local and not bound_location:
3511
3130
            raise errors.LocalRequiresBoundBranch()
3512
 
        result = PullResult()
3513
 
        result.source_branch = self.source
3514
 
        if _override_hook_target is None:
3515
 
            result.target_branch = self.target
3516
 
        else:
3517
 
            result.target_branch = _override_hook_target
3518
 
        self.source.lock_read()
 
3131
        master_branch = None
 
3132
        if not local and bound_location and self.source.base != bound_location:
 
3133
            # not pulling from master, so we need to update master.
 
3134
            master_branch = self.target.get_master_branch(possible_transports)
 
3135
            master_branch.lock_write()
3519
3136
        try:
3520
 
            # We assume that during 'pull' the target repository is closer than
3521
 
            # the source one.
3522
 
            self.source.update_references(self.target)
3523
 
            graph = self.target.repository.get_graph(self.source.repository)
3524
 
            # TODO: Branch formats should have a flag that indicates 
3525
 
            # that revno's are expensive, and pull() should honor that flag.
3526
 
            # -- JRV20090506
3527
 
            result.old_revno, result.old_revid = \
3528
 
                self.target.last_revision_info()
3529
 
            self.target.update_revisions(self.source, stop_revision,
3530
 
                overwrite=overwrite, graph=graph)
3531
 
            # TODO: The old revid should be specified when merging tags, 
3532
 
            # so a tags implementation that versions tags can only 
3533
 
            # pull in the most recent changes. -- JRV20090506
3534
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3535
 
                overwrite)
3536
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3537
 
            if _hook_master:
3538
 
                result.master_branch = _hook_master
3539
 
                result.local_branch = result.target_branch
3540
 
            else:
3541
 
                result.master_branch = result.target_branch
3542
 
                result.local_branch = None
3543
 
            if run_hooks:
3544
 
                for hook in Branch.hooks['post_pull']:
3545
 
                    hook(result)
 
3137
            if master_branch:
 
3138
                # pull from source into master.
 
3139
                master_branch.pull(self.source, overwrite, stop_revision,
 
3140
                    run_hooks=False)
 
3141
            return super(InterToBranch5, self).pull(overwrite,
 
3142
                stop_revision, _hook_master=master_branch,
 
3143
                run_hooks=run_hooks,
 
3144
                _override_hook_target=_override_hook_target)
3546
3145
        finally:
3547
 
            self.source.unlock()
3548
 
        return result
 
3146
            if master_branch:
 
3147
                master_branch.unlock()
3549
3148
 
3550
3149
 
3551
3150
InterBranch.register_optimiser(GenericInterBranch)
 
3151
InterBranch.register_optimiser(InterToBranch5)