~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-04 13:42:42 UTC
  • mfrom: (4463.1.2 progress)
  • Revision ID: pqm@pqm.ubuntu.com-20090804134242-l38wkokrlhd8ci6l
(mbp) updates to progress-related docstrings and remove another
        obsolete method

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
105
106
        """Activate the branch/repository from url as a fallback repository."""
106
107
        repo = self._get_fallback_repository(url)
107
108
        if repo.has_same_location(self.repository):
108
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
109
            raise errors.UnstackableLocationError(self.base, url)
109
110
        self.repository.add_fallback_repository(repo)
110
111
 
111
112
    def break_lock(self):
148
149
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
149
150
            self._partial_revision_history_cache.pop()
150
151
 
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
152
    @staticmethod
160
153
    def open(base, _unsupported=False, possible_transports=None):
161
154
        """Open the branch rooted at base.
165
158
        """
166
159
        control = bzrdir.BzrDir.open(base, _unsupported,
167
160
                                     possible_transports=possible_transports)
168
 
        return control.open_branch(unsupported=_unsupported)
 
161
        return control.open_branch(_unsupported)
169
162
 
170
163
    @staticmethod
171
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
164
    def open_from_transport(transport, _unsupported=False):
172
165
        """Open the branch rooted at transport"""
173
166
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
174
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
167
        return control.open_branch(_unsupported)
175
168
 
176
169
    @staticmethod
177
170
    def open_containing(url, possible_transports=None):
198
191
        return self.supports_tags() and self.tags.get_tag_dict()
199
192
 
200
193
    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
194
        return BranchConfig(self)
209
195
 
210
196
    def _get_config(self):
222
208
    def _get_fallback_repository(self, url):
223
209
        """Get the repository we fallback to at url."""
224
210
        url = urlutils.join(self.base, url)
225
 
        a_branch = Branch.open(url,
 
211
        a_bzrdir = bzrdir.BzrDir.open(url,
226
212
            possible_transports=[self.bzrdir.root_transport])
227
 
        return a_branch.repository
 
213
        return a_bzrdir.open_branch().repository
228
214
 
229
215
    def _get_tags_bytes(self):
230
216
        """Get the bytes of a serialised tags dict.
246
232
        if not local and not config.has_explicit_nickname():
247
233
            try:
248
234
                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
235
                if master is not None:
252
236
                    # return the master branch value
253
237
                    return master.nick
254
 
            except errors.RecursiveBind, e:
255
 
                raise e
256
238
            except errors.BzrError, e:
257
239
                # Silently fall back to local implicit nick if the master is
258
240
                # unavailable
295
277
        new_history.reverse()
296
278
        return new_history
297
279
 
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
 
        """
 
280
    def lock_write(self):
305
281
        raise NotImplementedError(self.lock_write)
306
282
 
307
283
    def lock_read(self):
308
 
        """Lock the branch for read operations.
309
 
 
310
 
        :return: A bzrlib.lock.LogicalLockResult.
311
 
        """
312
284
        raise NotImplementedError(self.lock_read)
313
285
 
314
286
    def unlock(self):
439
411
            * 'include' - the stop revision is the last item in the result
440
412
            * 'with-merges' - include the stop revision and all of its
441
413
              merged revisions in the result
442
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
443
 
              that are in both ancestries
444
414
        :param direction: either 'reverse' or 'forward':
445
415
            * reverse means return the start_revision_id first, i.e.
446
416
              start at the most recent revision and go backwards in history
468
438
        # start_revision_id.
469
439
        if self._merge_sorted_revisions_cache is None:
470
440
            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)
 
441
            graph = self.repository.get_graph()
 
442
            parent_map = dict(((key, value) for key, value in
 
443
                     graph.iter_ancestry([last_revision]) if value is not None))
 
444
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
445
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
446
                generate_revno=True)
 
447
            # Drop the sequence # before caching
 
448
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
449
 
475
450
        filtered = self._filter_merge_sorted_revisions(
476
451
            self._merge_sorted_revisions_cache, start_revision_id,
477
452
            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
453
        if direction == 'reverse':
482
454
            return filtered
483
455
        if direction == 'forward':
490
462
        """Iterate over an inclusive range of sorted revisions."""
491
463
        rev_iter = iter(merge_sorted_revisions)
492
464
        if start_revision_id is not None:
493
 
            for node in rev_iter:
494
 
                rev_id = node.key[-1]
 
465
            for rev_id, depth, revno, end_of_merge in rev_iter:
495
466
                if rev_id != start_revision_id:
496
467
                    continue
497
468
                else:
498
469
                    # The decision to include the start or not
499
470
                    # 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)
 
471
                    rev_iter = chain(
 
472
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
473
                        rev_iter)
502
474
                    break
503
475
        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)
 
476
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
477
                yield rev_id, depth, revno, end_of_merge
509
478
        elif stop_rule == 'exclude':
510
 
            for node in rev_iter:
511
 
                rev_id = node.key[-1]
 
479
            for rev_id, depth, revno, end_of_merge in rev_iter:
512
480
                if rev_id == stop_revision_id:
513
481
                    return
514
 
                yield (rev_id, node.merge_depth, node.revno,
515
 
                       node.end_of_merge)
 
482
                yield rev_id, depth, revno, end_of_merge
516
483
        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)
 
484
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
485
                yield rev_id, depth, revno, end_of_merge
521
486
                if rev_id == stop_revision_id:
522
487
                    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
488
        elif stop_rule == 'with-merges':
536
489
            stop_rev = self.repository.get_revision(stop_revision_id)
537
490
            if stop_rev.parent_ids:
538
491
                left_parent = stop_rev.parent_ids[0]
539
492
            else:
540
493
                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]
 
494
            for rev_id, depth, revno, end_of_merge in rev_iter:
547
495
                if rev_id == left_parent:
548
 
                    # reached the left parent after the stop_revision
549
496
                    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)
 
497
                yield rev_id, depth, revno, end_of_merge
560
498
        else:
561
499
            raise ValueError('invalid stop_rule %r' % stop_rule)
562
500
 
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
501
    def leave_lock_in_place(self):
609
502
        """Tell this branch object not to release the physical lock when this
610
503
        object is unlocked.
627
520
        :param other: The branch to bind to
628
521
        :type other: Branch
629
522
        """
630
 
        raise errors.UpgradeRequired(self.user_url)
 
523
        raise errors.UpgradeRequired(self.base)
631
524
 
632
525
    def set_append_revisions_only(self, enabled):
633
526
        if not self._format.supports_set_append_revisions_only():
634
 
            raise errors.UpgradeRequired(self.user_url)
 
527
            raise errors.UpgradeRequired(self.base)
635
528
        if enabled:
636
529
            value = 'True'
637
530
        else:
685
578
    def get_old_bound_location(self):
686
579
        """Return the URL of the branch we used to be bound to
687
580
        """
688
 
        raise errors.UpgradeRequired(self.user_url)
 
581
        raise errors.UpgradeRequired(self.base)
689
582
 
690
583
    def get_commit_builder(self, parents, config=None, timestamp=None,
691
584
                           timezone=None, committer=None, revprops=None,
769
662
            stacking.
770
663
        """
771
664
        if not self._format.supports_stacking():
772
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
665
            raise errors.UnstackableBranchFormat(self._format, self.base)
773
666
        # XXX: Changing from one fallback repository to another does not check
774
667
        # that all the data you need is present in the new fallback.
775
668
        # Possibly it should.
805
698
            if len(old_repository._fallback_repositories) != 1:
806
699
                raise AssertionError("can't cope with fallback repositories "
807
700
                    "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()
 
701
            # unlock it, including unlocking the fallback
835
702
            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):
 
703
            old_repository.lock_read()
 
704
            try:
 
705
                # Repositories don't offer an interface to remove fallback
 
706
                # repositories today; take the conceptually simpler option and just
 
707
                # reopen it.  We reopen it starting from the URL so that we
 
708
                # get a separate connection for RemoteRepositories and can
 
709
                # stream from one of them to the other.  This does mean doing
 
710
                # separate SSH connection setup, but unstacking is not a
 
711
                # common operation so it's tolerable.
 
712
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
713
                new_repository = new_bzrdir.find_repository()
 
714
                self.repository = new_repository
 
715
                if self.repository._fallback_repositories:
 
716
                    raise AssertionError("didn't expect %r to have "
 
717
                        "fallback_repositories"
 
718
                        % (self.repository,))
 
719
                # this is not paired with an unlock because it's just restoring
 
720
                # the previous state; the lock's released when set_stacked_on_url
 
721
                # returns
854
722
                self.repository.lock_write()
855
 
            # Fetch from the old repository into the new.
856
 
            old_repository.lock_read()
857
 
            try:
858
723
                # XXX: If you unstack a branch while it has a working tree
859
724
                # with a pending merge, the pending-merged revisions will no
860
725
                # longer be present.  You can (probably) revert and remerge.
954
819
 
955
820
    def unbind(self):
956
821
        """Older format branches cannot bind or unbind."""
957
 
        raise errors.UpgradeRequired(self.user_url)
 
822
        raise errors.UpgradeRequired(self.base)
958
823
 
959
824
    def last_revision(self):
960
825
        """Return last revision id, or NULL_REVISION."""
1001
866
                raise errors.NoSuchRevision(self, stop_revision)
1002
867
        return other_history[self_len:stop_revision]
1003
868
 
 
869
    @needs_write_lock
1004
870
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1005
871
                         graph=None):
1006
872
        """Pull in new perfect-fit revisions.
1055
921
            self._extend_partial_history(distance_from_last)
1056
922
        return self._partial_revision_history_cache[distance_from_last]
1057
923
 
 
924
    @needs_write_lock
1058
925
    def pull(self, source, overwrite=False, stop_revision=None,
1059
926
             possible_transports=None, *args, **kwargs):
1060
927
        """Mirror source into this branch.
1118
985
        try:
1119
986
            return urlutils.join(self.base[:-1], parent)
1120
987
        except errors.InvalidURLJoin, e:
1121
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
988
            raise errors.InaccessibleParent(parent, self.base)
1122
989
 
1123
990
    def _get_parent_location(self):
1124
991
        raise NotImplementedError(self._get_parent_location)
1209
1076
        params = ChangeBranchTipParams(
1210
1077
            self, old_revno, new_revno, old_revid, new_revid)
1211
1078
        for hook in hooks:
1212
 
            hook(params)
 
1079
            try:
 
1080
                hook(params)
 
1081
            except errors.TipChangeRejected:
 
1082
                raise
 
1083
            except Exception:
 
1084
                exc_info = sys.exc_info()
 
1085
                hook_name = Branch.hooks.get_hook_name(hook)
 
1086
                raise errors.HookFailed(
 
1087
                    'pre_change_branch_tip', hook_name, exc_info)
1213
1088
 
1214
1089
    @needs_write_lock
1215
1090
    def update(self):
1264
1139
        revision_id: if not None, the revision history in the new branch will
1265
1140
                     be truncated to end with revision_id.
1266
1141
        """
1267
 
        if (repository_policy is not None and
1268
 
            repository_policy.requires_stacking()):
1269
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1270
1142
        result = to_bzrdir.create_branch()
1271
1143
        result.lock_write()
1272
1144
        try:
1303
1175
                revno = 1
1304
1176
        destination.set_last_revision_info(revno, revision_id)
1305
1177
 
 
1178
    @needs_read_lock
1306
1179
    def copy_content_into(self, destination, revision_id=None):
1307
1180
        """Copy the content of self into destination.
1308
1181
 
1309
1182
        revision_id: if not None, the revision history in the new branch will
1310
1183
                     be truncated to end with revision_id.
1311
1184
        """
1312
 
        return InterBranch.get(self, destination).copy_content_into(
1313
 
            revision_id=revision_id)
 
1185
        self.update_references(destination)
 
1186
        self._synchronize_history(destination, revision_id)
 
1187
        try:
 
1188
            parent = self.get_parent()
 
1189
        except errors.InaccessibleParent, e:
 
1190
            mutter('parent was not accessible to copy: %s', e)
 
1191
        else:
 
1192
            if parent:
 
1193
                destination.set_parent(parent)
 
1194
        if self._push_should_merge_tags():
 
1195
            self.tags.merge_to(destination.tags)
1314
1196
 
1315
1197
    def update_references(self, target):
1316
1198
        if not getattr(self._format, 'supports_reference_locations', False):
1330
1212
        target._set_all_reference_info(target_reference_dict)
1331
1213
 
1332
1214
    @needs_read_lock
1333
 
    def check(self, refs):
 
1215
    def check(self):
1334
1216
        """Check consistency of the branch.
1335
1217
 
1336
1218
        In particular this checks that revisions given in the revision-history
1339
1221
 
1340
1222
        Callers will typically also want to check the repository.
1341
1223
 
1342
 
        :param refs: Calculated refs for this branch as specified by
1343
 
            branch._get_check_refs()
1344
1224
        :return: A BranchCheckResult.
1345
1225
        """
1346
 
        result = BranchCheckResult(self)
 
1226
        ret = BranchCheckResult(self)
 
1227
        mainline_parent_id = None
1347
1228
        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
 
1229
        real_rev_history = []
 
1230
        try:
 
1231
            for revid in self.repository.iter_reverse_revision_history(
 
1232
                last_revision_id):
 
1233
                real_rev_history.append(revid)
 
1234
        except errors.RevisionNotPresent:
 
1235
            ret.ghosts_in_mainline = True
 
1236
        else:
 
1237
            ret.ghosts_in_mainline = False
 
1238
        real_rev_history.reverse()
 
1239
        if len(real_rev_history) != last_revno:
 
1240
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
1241
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
1242
        # TODO: We should probably also check that real_rev_history actually
 
1243
        #       matches self.revision_history()
 
1244
        for revision_id in real_rev_history:
 
1245
            try:
 
1246
                revision = self.repository.get_revision(revision_id)
 
1247
            except errors.NoSuchRevision, e:
 
1248
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1249
                            % revision_id)
 
1250
            # In general the first entry on the revision history has no parents.
 
1251
            # But it's not illegal for it to have parents listed; this can happen
 
1252
            # in imports from Arch when the parents weren't reachable.
 
1253
            if mainline_parent_id is not None:
 
1254
                if mainline_parent_id not in revision.parent_ids:
 
1255
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1256
                                        "parents of {%s}"
 
1257
                                        % (mainline_parent_id, revision_id))
 
1258
            mainline_parent_id = revision_id
 
1259
        return ret
1359
1260
 
1360
1261
    def _get_checkout_format(self):
1361
1262
        """Return the most suitable metadir for a checkout of this branch.
1384
1285
        """
1385
1286
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1386
1287
        # 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
1288
        if revision_id is None:
1390
1289
            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)
 
1290
        try:
 
1291
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1292
                revision_id=revision_id, stacked_on=stacked_on,
 
1293
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1294
        except errors.FileExists:
 
1295
            if not use_existing_dir:
 
1296
                raise
 
1297
        except errors.NoSuchFile:
 
1298
            if not create_prefix:
 
1299
                raise
1394
1300
        return dir_to.open_branch()
1395
1301
 
1396
1302
    def create_checkout(self, to_location, revision_id=None,
1415
1321
        if lightweight:
1416
1322
            format = self._get_checkout_format()
1417
1323
            checkout = format.initialize_on_transport(t)
1418
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1419
 
                target_branch=self)
 
1324
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1420
1325
        else:
1421
1326
            format = self._get_checkout_format()
1422
1327
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1464
1369
    def supports_tags(self):
1465
1370
        return self._format.supports_tags()
1466
1371
 
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
1372
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1480
1373
                                         other_branch):
1481
1374
        """Ensure that revision_b is a descendant of revision_a.
1545
1438
        return not (self == other)
1546
1439
 
1547
1440
    @classmethod
1548
 
    def find_format(klass, a_bzrdir, name=None):
 
1441
    def find_format(klass, a_bzrdir):
1549
1442
        """Return the format for the branch object in a_bzrdir."""
1550
1443
        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
 
1444
            transport = a_bzrdir.get_branch_transport(None)
 
1445
            format_string = transport.get("format").read()
 
1446
            return klass._formats[format_string]
1557
1447
        except errors.NoSuchFile:
1558
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1448
            raise errors.NotBranchError(path=transport.base)
1559
1449
        except KeyError:
1560
1450
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1561
1451
 
1564
1454
        """Return the current default format."""
1565
1455
        return klass._default_format
1566
1456
 
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):
 
1457
    def get_reference(self, a_bzrdir):
1582
1458
        """Get the target reference of the branch in a_bzrdir.
1583
1459
 
1584
1460
        format probing must have been completed before calling
1586
1462
        in a_bzrdir is correct.
1587
1463
 
1588
1464
        :param a_bzrdir: The bzrdir to get the branch data from.
1589
 
        :param name: Name of the colocated branch to fetch
1590
1465
        :return: None if the branch is not a reference branch.
1591
1466
        """
1592
1467
        return None
1593
1468
 
1594
1469
    @classmethod
1595
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1470
    def set_reference(self, a_bzrdir, to_branch):
1596
1471
        """Set the target reference of the branch in a_bzrdir.
1597
1472
 
1598
1473
        format probing must have been completed before calling
1600
1475
        in a_bzrdir is correct.
1601
1476
 
1602
1477
        :param a_bzrdir: The bzrdir to set the branch reference for.
1603
 
        :param name: Name of colocated branch to set, None for default
1604
1478
        :param to_branch: branch that the checkout is to reference
1605
1479
        """
1606
1480
        raise NotImplementedError(self.set_reference)
1613
1487
        """Return the short format description for this format."""
1614
1488
        raise NotImplementedError(self.get_format_description)
1615
1489
 
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):
 
1490
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1491
                           set_format=True):
1626
1492
        """Initialize a branch in a bzrdir, with specified files
1627
1493
 
1628
1494
        :param a_bzrdir: The bzrdir to initialize the branch in
1629
1495
        :param utf8_files: The files to create as a list of
1630
1496
            (filename, content) tuples
1631
 
        :param name: Name of colocated branch to create, if any
1632
1497
        :param set_format: If True, set the format with
1633
1498
            self.get_format_string.  (BzrBranch4 has its format set
1634
1499
            elsewhere)
1635
1500
        :return: a branch in this format
1636
1501
        """
1637
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1638
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1502
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1503
        branch_transport = a_bzrdir.get_branch_transport(self)
1639
1504
        lock_map = {
1640
1505
            'metadir': ('lock', lockdir.LockDir),
1641
1506
            'branch4': ('branch-lock', lockable_files.TransportLock),
1662
1527
        finally:
1663
1528
            if lock_taken:
1664
1529
                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
 
1530
        return self.open(a_bzrdir, _found=True)
1668
1531
 
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
 
        """
 
1532
    def initialize(self, a_bzrdir):
 
1533
        """Create a branch of this format in a_bzrdir."""
1674
1534
        raise NotImplementedError(self.initialize)
1675
1535
 
1676
1536
    def is_supported(self):
1706
1566
        """
1707
1567
        raise NotImplementedError(self.network_name)
1708
1568
 
1709
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1569
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1710
1570
        """Return the branch object for a_bzrdir
1711
1571
 
1712
1572
        :param a_bzrdir: A BzrDir that contains a branch.
1713
 
        :param name: Name of colocated branch to open
1714
1573
        :param _found: a private parameter, do not use it. It is used to
1715
1574
            indicate if format probing has already be done.
1716
1575
        :param ignore_fallbacks: when set, no fallback branches will be opened
1720
1579
 
1721
1580
    @classmethod
1722
1581
    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
 
        """
 
1582
        """Register a metadir format."""
1728
1583
        klass._formats[format.get_format_string()] = format
1729
1584
        # 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__)
 
1585
        # registered as class factories.
 
1586
        network_format_registry.register(format.get_format_string(), format.__class__)
1736
1587
 
1737
1588
    @classmethod
1738
1589
    def set_default_format(klass, format):
1758
1609
        return False  # by default
1759
1610
 
1760
1611
 
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
1612
class BranchHooks(Hooks):
1790
1613
    """A dictionary mapping hook name to a list of callables for branch hooks.
1791
1614
 
1860
1683
            "multiple hooks installed for transform_fallback_location, "
1861
1684
            "all are called with the url returned from the previous hook."
1862
1685
            "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
1686
 
1881
1687
 
1882
1688
# install the default hooks into the Branch class.
1921
1727
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1922
1728
 
1923
1729
 
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
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1962
 
 
1963
 
 
1964
 
class SwitchHookParams(object):
1965
 
    """Object holding parameters passed to *_switch hooks.
1966
 
 
1967
 
    There are 4 fields that hooks may wish to access:
1968
 
 
1969
 
    :ivar control_dir: BzrDir of the checkout to change
1970
 
    :ivar to_branch: branch that the checkout is to reference
1971
 
    :ivar force: skip the check for local commits in a heavy checkout
1972
 
    :ivar revision_id: revision ID to switch to (or None)
1973
 
    """
1974
 
 
1975
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1976
 
        """Create a group of SwitchHook parameters.
1977
 
 
1978
 
        :param control_dir: BzrDir of the checkout to change
1979
 
        :param to_branch: branch that the checkout is to reference
1980
 
        :param force: skip the check for local commits in a heavy checkout
1981
 
        :param revision_id: revision ID to switch to (or None)
1982
 
        """
1983
 
        self.control_dir = control_dir
1984
 
        self.to_branch = to_branch
1985
 
        self.force = force
1986
 
        self.revision_id = revision_id
1987
 
 
1988
 
    def __eq__(self, other):
1989
 
        return self.__dict__ == other.__dict__
1990
 
 
1991
 
    def __repr__(self):
1992
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1993
 
            self.control_dir, self.to_branch,
1994
 
            self.revision_id)
1995
 
 
1996
 
 
1997
1730
class BzrBranchFormat4(BranchFormat):
1998
1731
    """Bzr branch format 4.
1999
1732
 
2006
1739
        """See BranchFormat.get_format_description()."""
2007
1740
        return "Branch format 4"
2008
1741
 
2009
 
    def initialize(self, a_bzrdir, name=None):
 
1742
    def initialize(self, a_bzrdir):
2010
1743
        """Create a branch of this format in a_bzrdir."""
2011
1744
        utf8_files = [('revision-history', ''),
2012
1745
                      ('branch-name', ''),
2013
1746
                      ]
2014
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1747
        return self._initialize_helper(a_bzrdir, utf8_files,
2015
1748
                                       lock_type='branch4', set_format=False)
2016
1749
 
2017
1750
    def __init__(self):
2022
1755
        """The network name for this format is the control dirs disk label."""
2023
1756
        return self._matchingbzrdir.get_format_string()
2024
1757
 
2025
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1758
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2026
1759
        """See BranchFormat.open()."""
2027
1760
        if not _found:
2028
1761
            # we are being called directly and must probe.
2030
1763
        return BzrBranch(_format=self,
2031
1764
                         _control_files=a_bzrdir._control_files,
2032
1765
                         a_bzrdir=a_bzrdir,
2033
 
                         name=name,
2034
1766
                         _repository=a_bzrdir.open_repository())
2035
1767
 
2036
1768
    def __str__(self):
2051
1783
        """
2052
1784
        return self.get_format_string()
2053
1785
 
2054
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1786
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2055
1787
        """See BranchFormat.open()."""
2056
1788
        if not _found:
2057
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1789
            format = BranchFormat.find_format(a_bzrdir)
2058
1790
            if format.__class__ != self.__class__:
2059
1791
                raise AssertionError("wrong format %r found for %r" %
2060
1792
                    (format, self))
2061
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2062
1793
        try:
 
1794
            transport = a_bzrdir.get_branch_transport(None)
2063
1795
            control_files = lockable_files.LockableFiles(transport, 'lock',
2064
1796
                                                         lockdir.LockDir)
2065
1797
            return self._branch_class()(_format=self,
2066
1798
                              _control_files=control_files,
2067
 
                              name=name,
2068
1799
                              a_bzrdir=a_bzrdir,
2069
1800
                              _repository=a_bzrdir.find_repository(),
2070
1801
                              ignore_fallbacks=ignore_fallbacks)
2071
1802
        except errors.NoSuchFile:
2072
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1803
            raise errors.NotBranchError(path=transport.base)
2073
1804
 
2074
1805
    def __init__(self):
2075
1806
        super(BranchFormatMetadir, self).__init__()
2104
1835
        """See BranchFormat.get_format_description()."""
2105
1836
        return "Branch format 5"
2106
1837
 
2107
 
    def initialize(self, a_bzrdir, name=None):
 
1838
    def initialize(self, a_bzrdir):
2108
1839
        """Create a branch of this format in a_bzrdir."""
2109
1840
        utf8_files = [('revision-history', ''),
2110
1841
                      ('branch-name', ''),
2111
1842
                      ]
2112
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1843
        return self._initialize_helper(a_bzrdir, utf8_files)
2113
1844
 
2114
1845
    def supports_tags(self):
2115
1846
        return False
2137
1868
        """See BranchFormat.get_format_description()."""
2138
1869
        return "Branch format 6"
2139
1870
 
2140
 
    def initialize(self, a_bzrdir, name=None):
 
1871
    def initialize(self, a_bzrdir):
2141
1872
        """Create a branch of this format in a_bzrdir."""
2142
1873
        utf8_files = [('last-revision', '0 null:\n'),
2143
1874
                      ('branch.conf', ''),
2144
1875
                      ('tags', ''),
2145
1876
                      ]
2146
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1877
        return self._initialize_helper(a_bzrdir, utf8_files)
2147
1878
 
2148
1879
    def make_tags(self, branch):
2149
1880
        """See bzrlib.branch.BranchFormat.make_tags()."""
2167
1898
        """See BranchFormat.get_format_description()."""
2168
1899
        return "Branch format 8"
2169
1900
 
2170
 
    def initialize(self, a_bzrdir, name=None):
 
1901
    def initialize(self, a_bzrdir):
2171
1902
        """Create a branch of this format in a_bzrdir."""
2172
1903
        utf8_files = [('last-revision', '0 null:\n'),
2173
1904
                      ('branch.conf', ''),
2174
1905
                      ('tags', ''),
2175
1906
                      ('references', '')
2176
1907
                      ]
2177
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1908
        return self._initialize_helper(a_bzrdir, utf8_files)
2178
1909
 
2179
1910
    def __init__(self):
2180
1911
        super(BzrBranchFormat8, self).__init__()
2203
1934
    This format was introduced in bzr 1.6.
2204
1935
    """
2205
1936
 
2206
 
    def initialize(self, a_bzrdir, name=None):
 
1937
    def initialize(self, a_bzrdir):
2207
1938
        """Create a branch of this format in a_bzrdir."""
2208
1939
        utf8_files = [('last-revision', '0 null:\n'),
2209
1940
                      ('branch.conf', ''),
2210
1941
                      ('tags', ''),
2211
1942
                      ]
2212
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1943
        return self._initialize_helper(a_bzrdir, utf8_files)
2213
1944
 
2214
1945
    def _branch_class(self):
2215
1946
        return BzrBranch7
2247
1978
        """See BranchFormat.get_format_description()."""
2248
1979
        return "Checkout reference format 1"
2249
1980
 
2250
 
    def get_reference(self, a_bzrdir, name=None):
 
1981
    def get_reference(self, a_bzrdir):
2251
1982
        """See BranchFormat.get_reference()."""
2252
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2253
 
        return transport.get_bytes('location')
 
1983
        transport = a_bzrdir.get_branch_transport(None)
 
1984
        return transport.get('location').read()
2254
1985
 
2255
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1986
    def set_reference(self, a_bzrdir, to_branch):
2256
1987
        """See BranchFormat.set_reference()."""
2257
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1988
        transport = a_bzrdir.get_branch_transport(None)
2258
1989
        location = transport.put_bytes('location', to_branch.base)
2259
1990
 
2260
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1991
    def initialize(self, a_bzrdir, target_branch=None):
2261
1992
        """Create a branch of this format in a_bzrdir."""
2262
1993
        if target_branch is None:
2263
1994
            # this format does not implement branch itself, thus the implicit
2264
1995
            # creation contract must see it as uninitializable
2265
1996
            raise errors.UninitializableFormat(self)
2266
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2267
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1997
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1998
        branch_transport = a_bzrdir.get_branch_transport(self)
2268
1999
        branch_transport.put_bytes('location',
2269
 
            target_branch.bzrdir.user_url)
 
2000
            target_branch.bzrdir.root_transport.base)
2270
2001
        branch_transport.put_bytes('format', self.get_format_string())
2271
 
        branch = self.open(
2272
 
            a_bzrdir, name, _found=True,
 
2002
        return self.open(
 
2003
            a_bzrdir, _found=True,
2273
2004
            possible_transports=[target_branch.bzrdir.root_transport])
2274
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2275
 
        return branch
2276
2005
 
2277
2006
    def __init__(self):
2278
2007
        super(BranchReferenceFormat, self).__init__()
2284
2013
        def clone(to_bzrdir, revision_id=None,
2285
2014
            repository_policy=None):
2286
2015
            """See Branch.clone()."""
2287
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2016
            return format.initialize(to_bzrdir, a_branch)
2288
2017
            # cannot obey revision_id limits when cloning a reference ...
2289
2018
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2290
2019
            # emit some sort of warning/error to the caller ?!
2291
2020
        return clone
2292
2021
 
2293
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2022
    def open(self, a_bzrdir, _found=False, location=None,
2294
2023
             possible_transports=None, ignore_fallbacks=False):
2295
2024
        """Return the branch that the branch reference in a_bzrdir points at.
2296
2025
 
2297
2026
        :param a_bzrdir: A BzrDir that contains a branch.
2298
 
        :param name: Name of colocated branch to open, if any
2299
2027
        :param _found: a private parameter, do not use it. It is used to
2300
2028
            indicate if format probing has already be done.
2301
2029
        :param ignore_fallbacks: when set, no fallback branches will be opened
2306
2034
        :param possible_transports: An optional reusable transports list.
2307
2035
        """
2308
2036
        if not _found:
2309
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2037
            format = BranchFormat.find_format(a_bzrdir)
2310
2038
            if format.__class__ != self.__class__:
2311
2039
                raise AssertionError("wrong format %r found for %r" %
2312
2040
                    (format, self))
2313
2041
        if location is None:
2314
 
            location = self.get_reference(a_bzrdir, name)
 
2042
            location = self.get_reference(a_bzrdir)
2315
2043
        real_bzrdir = bzrdir.BzrDir.open(
2316
2044
            location, possible_transports=possible_transports)
2317
 
        result = real_bzrdir.open_branch(name=name, 
2318
 
            ignore_fallbacks=ignore_fallbacks)
 
2045
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2319
2046
        # this changes the behaviour of result.clone to create a new reference
2320
2047
        # rather than a copy of the content of the branch.
2321
2048
        # I did not use a proxy object because that needs much more extensive
2348
2075
BranchFormat.register_format(__format6)
2349
2076
BranchFormat.register_format(__format7)
2350
2077
BranchFormat.register_format(__format8)
2351
 
BranchFormat.set_default_format(__format7)
 
2078
BranchFormat.set_default_format(__format6)
2352
2079
_legacy_formats = [BzrBranchFormat4(),
2353
2080
    ]
2354
2081
network_format_registry.register(
2355
2082
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2356
2083
 
2357
2084
 
2358
 
class BranchWriteLockResult(LogicalLockResult):
2359
 
    """The result of write locking a branch.
2360
 
 
2361
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2362
 
        None.
2363
 
    :ivar unlock: A callable which will unlock the lock.
2364
 
    """
2365
 
 
2366
 
    def __init__(self, unlock, branch_token):
2367
 
        LogicalLockResult.__init__(self, unlock)
2368
 
        self.branch_token = branch_token
2369
 
 
2370
 
    def __repr__(self):
2371
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2372
 
            self.unlock)
2373
 
 
2374
 
 
2375
 
class BzrBranch(Branch, _RelockDebugMixin):
 
2085
class BzrBranch(Branch):
2376
2086
    """A branch stored in the actual filesystem.
2377
2087
 
2378
2088
    Note that it's "local" in the context of the filesystem; it doesn't
2384
2094
    :ivar repository: Repository for this branch.
2385
2095
    :ivar base: The url of the base directory for this branch; the one
2386
2096
        containing the .bzr directory.
2387
 
    :ivar name: Optional colocated branch name as it exists in the control
2388
 
        directory.
2389
2097
    """
2390
2098
 
2391
2099
    def __init__(self, _format=None,
2392
 
                 _control_files=None, a_bzrdir=None, name=None,
2393
 
                 _repository=None, ignore_fallbacks=False):
 
2100
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2101
                 ignore_fallbacks=False):
2394
2102
        """Create new branch object at a particular location."""
2395
2103
        if a_bzrdir is None:
2396
2104
            raise ValueError('a_bzrdir must be supplied')
2397
2105
        else:
2398
2106
            self.bzrdir = a_bzrdir
2399
2107
        self._base = self.bzrdir.transport.clone('..').base
2400
 
        self.name = name
2401
2108
        # XXX: We should be able to just do
2402
2109
        #   self.base = self.bzrdir.root_transport.base
2403
2110
        # but this does not quite work yet -- mbp 20080522
2410
2117
        Branch.__init__(self)
2411
2118
 
2412
2119
    def __str__(self):
2413
 
        if self.name is None:
2414
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2415
 
        else:
2416
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2417
 
                self.name)
 
2120
        return '%s(%r)' % (self.__class__.__name__, self.base)
2418
2121
 
2419
2122
    __repr__ = __str__
2420
2123
 
2431
2134
        return self.control_files.is_locked()
2432
2135
 
2433
2136
    def lock_write(self, token=None):
2434
 
        """Lock the branch for write operations.
2435
 
 
2436
 
        :param token: A token to permit reacquiring a previously held and
2437
 
            preserved lock.
2438
 
        :return: A BranchWriteLockResult.
2439
 
        """
2440
 
        if not self.is_locked():
2441
 
            self._note_lock('w')
2442
2137
        # All-in-one needs to always unlock/lock.
2443
2138
        repo_control = getattr(self.repository, 'control_files', None)
2444
2139
        if self.control_files == repo_control or not self.is_locked():
2445
 
            self.repository._warn_if_deprecated(self)
2446
2140
            self.repository.lock_write()
2447
2141
            took_lock = True
2448
2142
        else:
2449
2143
            took_lock = False
2450
2144
        try:
2451
 
            return BranchWriteLockResult(self.unlock,
2452
 
                self.control_files.lock_write(token=token))
 
2145
            return self.control_files.lock_write(token=token)
2453
2146
        except:
2454
2147
            if took_lock:
2455
2148
                self.repository.unlock()
2456
2149
            raise
2457
2150
 
2458
2151
    def lock_read(self):
2459
 
        """Lock the branch for read operations.
2460
 
 
2461
 
        :return: A bzrlib.lock.LogicalLockResult.
2462
 
        """
2463
 
        if not self.is_locked():
2464
 
            self._note_lock('r')
2465
2152
        # All-in-one needs to always unlock/lock.
2466
2153
        repo_control = getattr(self.repository, 'control_files', None)
2467
2154
        if self.control_files == repo_control or not self.is_locked():
2468
 
            self.repository._warn_if_deprecated(self)
2469
2155
            self.repository.lock_read()
2470
2156
            took_lock = True
2471
2157
        else:
2472
2158
            took_lock = False
2473
2159
        try:
2474
2160
            self.control_files.lock_read()
2475
 
            return LogicalLockResult(self.unlock)
2476
2161
        except:
2477
2162
            if took_lock:
2478
2163
                self.repository.unlock()
2479
2164
            raise
2480
2165
 
2481
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2482
2166
    def unlock(self):
2483
2167
        try:
2484
2168
            self.control_files.unlock()
2647
2331
        return result
2648
2332
 
2649
2333
    def get_stacked_on_url(self):
2650
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2334
        raise errors.UnstackableBranchFormat(self._format, self.base)
2651
2335
 
2652
2336
    def set_push_location(self, location):
2653
2337
        """See Branch.set_push_location."""
2843
2527
        if _mod_revision.is_null(last_revision):
2844
2528
            return
2845
2529
        if last_revision not in self._lefthand_history(revision_id):
2846
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2530
            raise errors.AppendRevisionsOnlyViolation(self.base)
2847
2531
 
2848
2532
    def _gen_revision_history(self):
2849
2533
        """Generate the revision history from last revision
2949
2633
        if branch_location is None:
2950
2634
            return Branch.reference_parent(self, file_id, path,
2951
2635
                                           possible_transports)
2952
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2636
        branch_location = urlutils.join(self.base, branch_location)
2953
2637
        return Branch.open(branch_location,
2954
2638
                           possible_transports=possible_transports)
2955
2639
 
3001
2685
        return stacked_url
3002
2686
 
3003
2687
    def _get_append_revisions_only(self):
3004
 
        return self.get_config(
3005
 
            ).get_user_option_as_bool('append_revisions_only')
 
2688
        value = self.get_config().get_user_option('append_revisions_only')
 
2689
        return value == 'True'
3006
2690
 
3007
2691
    @needs_write_lock
3008
2692
    def generate_revision_history(self, revision_id, last_rev=None,
3070
2754
    """
3071
2755
 
3072
2756
    def get_stacked_on_url(self):
3073
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2757
        raise errors.UnstackableBranchFormat(self._format, self.base)
3074
2758
 
3075
2759
 
3076
2760
######################################################################
3155
2839
 
3156
2840
    def __init__(self, branch):
3157
2841
        self.branch = branch
3158
 
        self.errors = []
 
2842
        self.ghosts_in_mainline = False
3159
2843
 
3160
2844
    def report_results(self, verbose):
3161
2845
        """Report the check results via trace.note.
3163
2847
        :param verbose: Requests more detailed display of what was checked,
3164
2848
            if any.
3165
2849
        """
3166
 
        note('checked branch %s format %s', self.branch.user_url,
3167
 
            self.branch._format)
3168
 
        for error in self.errors:
3169
 
            note('found error:%s', error)
 
2850
        note('checked branch %s format %s',
 
2851
             self.branch.base,
 
2852
             self.branch._format)
 
2853
        if self.ghosts_in_mainline:
 
2854
            note('branch contains ghosts in mainline')
3170
2855
 
3171
2856
 
3172
2857
class Converter5to6(object):
3264
2949
    _optimisers = []
3265
2950
    """The available optimised InterBranch types."""
3266
2951
 
3267
 
    @classmethod
3268
 
    def _get_branch_formats_to_test(klass):
3269
 
        """Return an iterable of format tuples for testing.
3270
 
        
3271
 
        :return: An iterable of (from_format, to_format) to use when testing
3272
 
            this InterBranch class. Each InterBranch class should define this
3273
 
            method itself.
3274
 
        """
3275
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2952
    @staticmethod
 
2953
    def _get_branch_formats_to_test():
 
2954
        """Return a tuple with the Branch formats to use when testing."""
 
2955
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3276
2956
 
3277
 
    @needs_write_lock
3278
2957
    def pull(self, overwrite=False, stop_revision=None,
3279
2958
             possible_transports=None, local=False):
3280
2959
        """Mirror source into target branch.
3285
2964
        """
3286
2965
        raise NotImplementedError(self.pull)
3287
2966
 
3288
 
    @needs_write_lock
3289
2967
    def update_revisions(self, stop_revision=None, overwrite=False,
3290
2968
                         graph=None):
3291
2969
        """Pull in new perfect-fit revisions.
3299
2977
        """
3300
2978
        raise NotImplementedError(self.update_revisions)
3301
2979
 
3302
 
    @needs_write_lock
3303
2980
    def push(self, overwrite=False, stop_revision=None,
3304
2981
             _override_hook_source_branch=None):
3305
2982
        """Mirror the source branch into the target branch.
3308
2985
        """
3309
2986
        raise NotImplementedError(self.push)
3310
2987
 
3311
 
    @needs_write_lock
3312
 
    def copy_content_into(self, revision_id=None):
3313
 
        """Copy the content of source into target
3314
 
 
3315
 
        revision_id: if not None, the revision history in the new branch will
3316
 
                     be truncated to end with revision_id.
3317
 
        """
3318
 
        raise NotImplementedError(self.copy_content_into)
3319
 
 
3320
2988
 
3321
2989
class GenericInterBranch(InterBranch):
3322
 
    """InterBranch implementation that uses public Branch functions."""
3323
 
 
3324
 
    @classmethod
3325
 
    def is_compatible(klass, source, target):
3326
 
        # GenericBranch uses the public API, so always compatible
3327
 
        return True
3328
 
 
3329
 
    @classmethod
3330
 
    def _get_branch_formats_to_test(klass):
3331
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3332
 
 
3333
 
    @classmethod
3334
 
    def unwrap_format(klass, format):
3335
 
        if isinstance(format, remote.RemoteBranchFormat):
3336
 
            format._ensure_real()
3337
 
            return format._custom_format
3338
 
        return format                                                                                                  
3339
 
 
3340
 
    @needs_write_lock
3341
 
    def copy_content_into(self, revision_id=None):
3342
 
        """Copy the content of source into target
3343
 
 
3344
 
        revision_id: if not None, the revision history in the new branch will
3345
 
                     be truncated to end with revision_id.
3346
 
        """
3347
 
        self.source.update_references(self.target)
3348
 
        self.source._synchronize_history(self.target, revision_id)
3349
 
        try:
3350
 
            parent = self.source.get_parent()
3351
 
        except errors.InaccessibleParent, e:
3352
 
            mutter('parent was not accessible to copy: %s', e)
3353
 
        else:
3354
 
            if parent:
3355
 
                self.target.set_parent(parent)
3356
 
        if self.source._push_should_merge_tags():
3357
 
            self.source.tags.merge_to(self.target.tags)
3358
 
 
3359
 
    @needs_write_lock
 
2990
    """InterBranch implementation that uses public Branch functions.
 
2991
    """
 
2992
 
 
2993
    @staticmethod
 
2994
    def _get_branch_formats_to_test():
 
2995
        return BranchFormat._default_format, BranchFormat._default_format
 
2996
 
3360
2997
    def update_revisions(self, stop_revision=None, overwrite=False,
3361
2998
        graph=None):
3362
2999
        """See InterBranch.update_revisions()."""
3363
 
        other_revno, other_last_revision = self.source.last_revision_info()
3364
 
        stop_revno = None # unknown
3365
 
        if stop_revision is None:
3366
 
            stop_revision = other_last_revision
3367
 
            if _mod_revision.is_null(stop_revision):
3368
 
                # if there are no commits, we're done.
3369
 
                return
3370
 
            stop_revno = other_revno
3371
 
 
3372
 
        # what's the current last revision, before we fetch [and change it
3373
 
        # possibly]
3374
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3375
 
        # we fetch here so that we don't process data twice in the common
3376
 
        # case of having something to pull, and so that the check for
3377
 
        # already merged can operate on the just fetched graph, which will
3378
 
        # be cached in memory.
3379
 
        self.target.fetch(self.source, stop_revision)
3380
 
        # Check to see if one is an ancestor of the other
3381
 
        if not overwrite:
3382
 
            if graph is None:
3383
 
                graph = self.target.repository.get_graph()
3384
 
            if self.target._check_if_descendant_or_diverged(
3385
 
                    stop_revision, last_rev, graph, self.source):
3386
 
                # stop_revision is a descendant of last_rev, but we aren't
3387
 
                # overwriting, so we're done.
3388
 
                return
3389
 
        if stop_revno is None:
3390
 
            if graph is None:
3391
 
                graph = self.target.repository.get_graph()
3392
 
            this_revno, this_last_revision = \
3393
 
                    self.target.last_revision_info()
3394
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3395
 
                            [(other_last_revision, other_revno),
3396
 
                             (this_last_revision, this_revno)])
3397
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3398
 
 
3399
 
    @needs_write_lock
 
3000
        self.source.lock_read()
 
3001
        try:
 
3002
            other_revno, other_last_revision = self.source.last_revision_info()
 
3003
            stop_revno = None # unknown
 
3004
            if stop_revision is None:
 
3005
                stop_revision = other_last_revision
 
3006
                if _mod_revision.is_null(stop_revision):
 
3007
                    # if there are no commits, we're done.
 
3008
                    return
 
3009
                stop_revno = other_revno
 
3010
 
 
3011
            # what's the current last revision, before we fetch [and change it
 
3012
            # possibly]
 
3013
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3014
            # we fetch here so that we don't process data twice in the common
 
3015
            # case of having something to pull, and so that the check for
 
3016
            # already merged can operate on the just fetched graph, which will
 
3017
            # be cached in memory.
 
3018
            self.target.fetch(self.source, stop_revision)
 
3019
            # Check to see if one is an ancestor of the other
 
3020
            if not overwrite:
 
3021
                if graph is None:
 
3022
                    graph = self.target.repository.get_graph()
 
3023
                if self.target._check_if_descendant_or_diverged(
 
3024
                        stop_revision, last_rev, graph, self.source):
 
3025
                    # stop_revision is a descendant of last_rev, but we aren't
 
3026
                    # overwriting, so we're done.
 
3027
                    return
 
3028
            if stop_revno is None:
 
3029
                if graph is None:
 
3030
                    graph = self.target.repository.get_graph()
 
3031
                this_revno, this_last_revision = \
 
3032
                        self.target.last_revision_info()
 
3033
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3034
                                [(other_last_revision, other_revno),
 
3035
                                 (this_last_revision, this_revno)])
 
3036
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
3037
        finally:
 
3038
            self.source.unlock()
 
3039
 
3400
3040
    def pull(self, overwrite=False, stop_revision=None,
3401
 
             possible_transports=None, run_hooks=True,
 
3041
             possible_transports=None, _hook_master=None, run_hooks=True,
3402
3042
             _override_hook_target=None, local=False):
3403
 
        """Pull from source into self, updating my master if any.
 
3043
        """See Branch.pull.
3404
3044
 
 
3045
        :param _hook_master: Private parameter - set the branch to
 
3046
            be supplied as the master to pull hooks.
3405
3047
        :param run_hooks: Private parameter - if false, this branch
3406
3048
            is being called because it's the master of the primary branch,
3407
3049
            so it should not run its hooks.
 
3050
        :param _override_hook_target: Private parameter - set the branch to be
 
3051
            supplied as the target_branch to pull hooks.
 
3052
        :param local: Only update the local branch, and not the bound branch.
3408
3053
        """
3409
 
        bound_location = self.target.get_bound_location()
3410
 
        if local and not bound_location:
 
3054
        # This type of branch can't be bound.
 
3055
        if local:
3411
3056
            raise errors.LocalRequiresBoundBranch()
3412
 
        master_branch = None
3413
 
        if not local and bound_location and self.source.user_url != bound_location:
3414
 
            # not pulling from master, so we need to update master.
3415
 
            master_branch = self.target.get_master_branch(possible_transports)
3416
 
            master_branch.lock_write()
 
3057
        result = PullResult()
 
3058
        result.source_branch = self.source
 
3059
        if _override_hook_target is None:
 
3060
            result.target_branch = self.target
 
3061
        else:
 
3062
            result.target_branch = _override_hook_target
 
3063
        self.source.lock_read()
3417
3064
        try:
3418
 
            if master_branch:
3419
 
                # pull from source into master.
3420
 
                master_branch.pull(self.source, overwrite, stop_revision,
3421
 
                    run_hooks=False)
3422
 
            return self._pull(overwrite,
3423
 
                stop_revision, _hook_master=master_branch,
3424
 
                run_hooks=run_hooks,
3425
 
                _override_hook_target=_override_hook_target)
 
3065
            # We assume that during 'pull' the target repository is closer than
 
3066
            # the source one.
 
3067
            self.source.update_references(self.target)
 
3068
            graph = self.target.repository.get_graph(self.source.repository)
 
3069
            # TODO: Branch formats should have a flag that indicates 
 
3070
            # that revno's are expensive, and pull() should honor that flag.
 
3071
            # -- JRV20090506
 
3072
            result.old_revno, result.old_revid = \
 
3073
                self.target.last_revision_info()
 
3074
            self.target.update_revisions(self.source, stop_revision,
 
3075
                overwrite=overwrite, graph=graph)
 
3076
            # TODO: The old revid should be specified when merging tags, 
 
3077
            # so a tags implementation that versions tags can only 
 
3078
            # pull in the most recent changes. -- JRV20090506
 
3079
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3080
                overwrite)
 
3081
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3082
            if _hook_master:
 
3083
                result.master_branch = _hook_master
 
3084
                result.local_branch = result.target_branch
 
3085
            else:
 
3086
                result.master_branch = result.target_branch
 
3087
                result.local_branch = None
 
3088
            if run_hooks:
 
3089
                for hook in Branch.hooks['post_pull']:
 
3090
                    hook(result)
3426
3091
        finally:
3427
 
            if master_branch:
3428
 
                master_branch.unlock()
 
3092
            self.source.unlock()
 
3093
        return result
3429
3094
 
3430
3095
    def push(self, overwrite=False, stop_revision=None,
3431
3096
             _override_hook_source_branch=None):
3493
3158
            _run_hooks()
3494
3159
            return result
3495
3160
 
3496
 
    def _pull(self, overwrite=False, stop_revision=None,
3497
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3161
    @classmethod
 
3162
    def is_compatible(self, source, target):
 
3163
        # GenericBranch uses the public API, so always compatible
 
3164
        return True
 
3165
 
 
3166
 
 
3167
class InterToBranch5(GenericInterBranch):
 
3168
 
 
3169
    @staticmethod
 
3170
    def _get_branch_formats_to_test():
 
3171
        return BranchFormat._default_format, BzrBranchFormat5()
 
3172
 
 
3173
    def pull(self, overwrite=False, stop_revision=None,
 
3174
             possible_transports=None, run_hooks=True,
3498
3175
             _override_hook_target=None, local=False):
3499
 
        """See Branch.pull.
3500
 
 
3501
 
        This function is the core worker, used by GenericInterBranch.pull to
3502
 
        avoid duplication when pulling source->master and source->local.
3503
 
 
3504
 
        :param _hook_master: Private parameter - set the branch to
3505
 
            be supplied as the master to pull hooks.
 
3176
        """Pull from source into self, updating my master if any.
 
3177
 
3506
3178
        :param run_hooks: Private parameter - if false, this branch
3507
3179
            is being called because it's the master of the primary branch,
3508
3180
            so it should not run its hooks.
3509
 
        :param _override_hook_target: Private parameter - set the branch to be
3510
 
            supplied as the target_branch to pull hooks.
3511
 
        :param local: Only update the local branch, and not the bound branch.
3512
3181
        """
3513
 
        # This type of branch can't be bound.
3514
 
        if local:
 
3182
        bound_location = self.target.get_bound_location()
 
3183
        if local and not bound_location:
3515
3184
            raise errors.LocalRequiresBoundBranch()
3516
 
        result = PullResult()
3517
 
        result.source_branch = self.source
3518
 
        if _override_hook_target is None:
3519
 
            result.target_branch = self.target
3520
 
        else:
3521
 
            result.target_branch = _override_hook_target
3522
 
        self.source.lock_read()
 
3185
        master_branch = None
 
3186
        if not local and bound_location and self.source.base != bound_location:
 
3187
            # not pulling from master, so we need to update master.
 
3188
            master_branch = self.target.get_master_branch(possible_transports)
 
3189
            master_branch.lock_write()
3523
3190
        try:
3524
 
            # We assume that during 'pull' the target repository is closer than
3525
 
            # the source one.
3526
 
            self.source.update_references(self.target)
3527
 
            graph = self.target.repository.get_graph(self.source.repository)
3528
 
            # TODO: Branch formats should have a flag that indicates 
3529
 
            # that revno's are expensive, and pull() should honor that flag.
3530
 
            # -- JRV20090506
3531
 
            result.old_revno, result.old_revid = \
3532
 
                self.target.last_revision_info()
3533
 
            self.target.update_revisions(self.source, stop_revision,
3534
 
                overwrite=overwrite, graph=graph)
3535
 
            # TODO: The old revid should be specified when merging tags, 
3536
 
            # so a tags implementation that versions tags can only 
3537
 
            # pull in the most recent changes. -- JRV20090506
3538
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3539
 
                overwrite)
3540
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3541
 
            if _hook_master:
3542
 
                result.master_branch = _hook_master
3543
 
                result.local_branch = result.target_branch
3544
 
            else:
3545
 
                result.master_branch = result.target_branch
3546
 
                result.local_branch = None
3547
 
            if run_hooks:
3548
 
                for hook in Branch.hooks['post_pull']:
3549
 
                    hook(result)
 
3191
            if master_branch:
 
3192
                # pull from source into master.
 
3193
                master_branch.pull(self.source, overwrite, stop_revision,
 
3194
                    run_hooks=False)
 
3195
            return super(InterToBranch5, self).pull(overwrite,
 
3196
                stop_revision, _hook_master=master_branch,
 
3197
                run_hooks=run_hooks,
 
3198
                _override_hook_target=_override_hook_target)
3550
3199
        finally:
3551
 
            self.source.unlock()
3552
 
        return result
 
3200
            if master_branch:
 
3201
                master_branch.unlock()
3553
3202
 
3554
3203
 
3555
3204
InterBranch.register_optimiser(GenericInterBranch)
 
3205
InterBranch.register_optimiser(InterToBranch5)