~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-03 07:15:11 UTC
  • mfrom: (4580.1.2 408199-check-2a)
  • Revision ID: pqm@pqm.ubuntu.com-20090803071511-dwb041qzak0vjzdk
(mbp) check blackbox tests now handle the root being included in the
        file-id count

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
25
25
        bzrdir,
26
26
        cache_utf8,
27
27
        config as _mod_config,
28
 
        controldir,
29
28
        debug,
30
29
        errors,
31
30
        lockdir,
32
31
        lockable_files,
33
 
        remote,
34
32
        repository,
35
33
        revision as _mod_revision,
36
34
        rio,
48
46
    )
49
47
""")
50
48
 
51
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
50
from bzrlib.hooks import HookPoint, Hooks
53
51
from bzrlib.inter import InterObject
54
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
55
52
from bzrlib import registry
56
53
from bzrlib.symbol_versioning import (
57
54
    deprecated_in,
65
62
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
66
63
 
67
64
 
68
 
class Branch(controldir.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):
69
78
    """Branch holding a history of revisions.
70
79
 
71
 
    :ivar base:
72
 
        Base directory/url of the branch; using control_url and
73
 
        control_transport is more standardized.
 
80
    base
 
81
        Base directory/url of the branch.
74
82
 
75
83
    hooks: An instance of BranchHooks.
76
84
    """
78
86
    # - RBC 20060112
79
87
    base = None
80
88
 
81
 
    @property
82
 
    def control_transport(self):
83
 
        return self._transport
84
 
 
85
 
    @property
86
 
    def user_transport(self):
87
 
        return self.bzrdir.user_transport
88
 
 
89
89
    def __init__(self, *ignored, **ignored_too):
90
90
        self.tags = self._format.make_tags(self)
91
91
        self._revision_history_cache = None
106
106
        """Activate the branch/repository from url as a fallback repository."""
107
107
        repo = self._get_fallback_repository(url)
108
108
        if repo.has_same_location(self.repository):
109
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
109
            raise errors.UnstackableLocationError(self.base, url)
110
110
        self.repository.add_fallback_repository(repo)
111
111
 
112
112
    def break_lock(self):
149
149
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
150
150
            self._partial_revision_history_cache.pop()
151
151
 
152
 
    def _get_check_refs(self):
153
 
        """Get the references needed for check().
154
 
 
155
 
        See bzrlib.check.
156
 
        """
157
 
        revid = self.last_revision()
158
 
        return [('revision-existence', revid), ('lefthand-distance', revid)]
159
 
 
160
152
    @staticmethod
161
153
    def open(base, _unsupported=False, possible_transports=None):
162
154
        """Open the branch rooted at base.
166
158
        """
167
159
        control = bzrdir.BzrDir.open(base, _unsupported,
168
160
                                     possible_transports=possible_transports)
169
 
        return control.open_branch(unsupported=_unsupported)
 
161
        return control.open_branch(_unsupported)
170
162
 
171
163
    @staticmethod
172
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
164
    def open_from_transport(transport, _unsupported=False):
173
165
        """Open the branch rooted at transport"""
174
166
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
175
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
167
        return control.open_branch(_unsupported)
176
168
 
177
169
    @staticmethod
178
170
    def open_containing(url, possible_transports=None):
199
191
        return self.supports_tags() and self.tags.get_tag_dict()
200
192
 
201
193
    def get_config(self):
202
 
        """Get a bzrlib.config.BranchConfig for this Branch.
203
 
 
204
 
        This can then be used to get and set configuration options for the
205
 
        branch.
206
 
 
207
 
        :return: A bzrlib.config.BranchConfig.
208
 
        """
209
194
        return BranchConfig(self)
210
195
 
211
196
    def _get_config(self):
223
208
    def _get_fallback_repository(self, url):
224
209
        """Get the repository we fallback to at url."""
225
210
        url = urlutils.join(self.base, url)
226
 
        a_branch = Branch.open(url,
 
211
        a_bzrdir = bzrdir.BzrDir.open(url,
227
212
            possible_transports=[self.bzrdir.root_transport])
228
 
        return a_branch.repository
 
213
        return a_bzrdir.open_branch().repository
229
214
 
230
215
    def _get_tags_bytes(self):
231
216
        """Get the bytes of a serialised tags dict.
247
232
        if not local and not config.has_explicit_nickname():
248
233
            try:
249
234
                master = self.get_master_branch(possible_transports)
250
 
                if master and self.user_url == master.user_url:
251
 
                    raise errors.RecursiveBind(self.user_url)
252
235
                if master is not None:
253
236
                    # return the master branch value
254
237
                    return master.nick
255
 
            except errors.RecursiveBind, e:
256
 
                raise e
257
238
            except errors.BzrError, e:
258
239
                # Silently fall back to local implicit nick if the master is
259
240
                # unavailable
296
277
        new_history.reverse()
297
278
        return new_history
298
279
 
299
 
    def lock_write(self, token=None):
300
 
        """Lock the branch for write operations.
301
 
 
302
 
        :param token: A token to permit reacquiring a previously held and
303
 
            preserved lock.
304
 
        :return: A BranchWriteLockResult.
305
 
        """
 
280
    def lock_write(self):
306
281
        raise NotImplementedError(self.lock_write)
307
282
 
308
283
    def lock_read(self):
309
 
        """Lock the branch for read operations.
310
 
 
311
 
        :return: A bzrlib.lock.LogicalLockResult.
312
 
        """
313
284
        raise NotImplementedError(self.lock_read)
314
285
 
315
286
    def unlock(self):
440
411
            * 'include' - the stop revision is the last item in the result
441
412
            * 'with-merges' - include the stop revision and all of its
442
413
              merged revisions in the result
443
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
444
 
              that are in both ancestries
445
414
        :param direction: either 'reverse' or 'forward':
446
415
            * reverse means return the start_revision_id first, i.e.
447
416
              start at the most recent revision and go backwards in history
469
438
        # start_revision_id.
470
439
        if self._merge_sorted_revisions_cache is None:
471
440
            last_revision = self.last_revision()
472
 
            known_graph = self.repository.get_known_graph_ancestry(
473
 
                [last_revision])
474
 
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
475
 
                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
 
476
450
        filtered = self._filter_merge_sorted_revisions(
477
451
            self._merge_sorted_revisions_cache, start_revision_id,
478
452
            stop_revision_id, stop_rule)
479
 
        # Make sure we don't return revisions that are not part of the
480
 
        # start_revision_id ancestry.
481
 
        filtered = self._filter_start_non_ancestors(filtered)
482
453
        if direction == 'reverse':
483
454
            return filtered
484
455
        if direction == 'forward':
491
462
        """Iterate over an inclusive range of sorted revisions."""
492
463
        rev_iter = iter(merge_sorted_revisions)
493
464
        if start_revision_id is not None:
494
 
            for node in rev_iter:
495
 
                rev_id = node.key[-1]
 
465
            for rev_id, depth, revno, end_of_merge in rev_iter:
496
466
                if rev_id != start_revision_id:
497
467
                    continue
498
468
                else:
499
469
                    # The decision to include the start or not
500
470
                    # depends on the stop_rule if a stop is provided
501
 
                    # so pop this node back into the iterator
502
 
                    rev_iter = chain(iter([node]), rev_iter)
 
471
                    rev_iter = chain(
 
472
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
473
                        rev_iter)
503
474
                    break
504
475
        if stop_revision_id is None:
505
 
            # Yield everything
506
 
            for node in rev_iter:
507
 
                rev_id = node.key[-1]
508
 
                yield (rev_id, node.merge_depth, node.revno,
509
 
                       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
510
478
        elif stop_rule == 'exclude':
511
 
            for node in rev_iter:
512
 
                rev_id = node.key[-1]
 
479
            for rev_id, depth, revno, end_of_merge in rev_iter:
513
480
                if rev_id == stop_revision_id:
514
481
                    return
515
 
                yield (rev_id, node.merge_depth, node.revno,
516
 
                       node.end_of_merge)
 
482
                yield rev_id, depth, revno, end_of_merge
517
483
        elif stop_rule == 'include':
518
 
            for node in rev_iter:
519
 
                rev_id = node.key[-1]
520
 
                yield (rev_id, node.merge_depth, node.revno,
521
 
                       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
522
486
                if rev_id == stop_revision_id:
523
487
                    return
524
 
        elif stop_rule == 'with-merges-without-common-ancestry':
525
 
            # We want to exclude all revisions that are already part of the
526
 
            # stop_revision_id ancestry.
527
 
            graph = self.repository.get_graph()
528
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
529
 
                                                    [stop_revision_id])
530
 
            for node in rev_iter:
531
 
                rev_id = node.key[-1]
532
 
                if rev_id not in ancestors:
533
 
                    continue
534
 
                yield (rev_id, node.merge_depth, node.revno,
535
 
                       node.end_of_merge)
536
488
        elif stop_rule == 'with-merges':
537
489
            stop_rev = self.repository.get_revision(stop_revision_id)
538
490
            if stop_rev.parent_ids:
539
491
                left_parent = stop_rev.parent_ids[0]
540
492
            else:
541
493
                left_parent = _mod_revision.NULL_REVISION
542
 
            # left_parent is the actual revision we want to stop logging at,
543
 
            # since we want to show the merged revisions after the stop_rev too
544
 
            reached_stop_revision_id = False
545
 
            revision_id_whitelist = []
546
 
            for node in rev_iter:
547
 
                rev_id = node.key[-1]
 
494
            for rev_id, depth, revno, end_of_merge in rev_iter:
548
495
                if rev_id == left_parent:
549
 
                    # reached the left parent after the stop_revision
550
496
                    return
551
 
                if (not reached_stop_revision_id or
552
 
                        rev_id in revision_id_whitelist):
553
 
                    yield (rev_id, node.merge_depth, node.revno,
554
 
                       node.end_of_merge)
555
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
556
 
                        # only do the merged revs of rev_id from now on
557
 
                        rev = self.repository.get_revision(rev_id)
558
 
                        if rev.parent_ids:
559
 
                            reached_stop_revision_id = True
560
 
                            revision_id_whitelist.extend(rev.parent_ids)
 
497
                yield rev_id, depth, revno, end_of_merge
561
498
        else:
562
499
            raise ValueError('invalid stop_rule %r' % stop_rule)
563
500
 
564
 
    def _filter_start_non_ancestors(self, rev_iter):
565
 
        # If we started from a dotted revno, we want to consider it as a tip
566
 
        # and don't want to yield revisions that are not part of its
567
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
568
 
        # uninteresting descendants of the first parent of our tip before the
569
 
        # tip itself.
570
 
        first = rev_iter.next()
571
 
        (rev_id, merge_depth, revno, end_of_merge) = first
572
 
        yield first
573
 
        if not merge_depth:
574
 
            # We start at a mainline revision so by definition, all others
575
 
            # revisions in rev_iter are ancestors
576
 
            for node in rev_iter:
577
 
                yield node
578
 
 
579
 
        clean = False
580
 
        whitelist = set()
581
 
        pmap = self.repository.get_parent_map([rev_id])
582
 
        parents = pmap.get(rev_id, [])
583
 
        if parents:
584
 
            whitelist.update(parents)
585
 
        else:
586
 
            # If there is no parents, there is nothing of interest left
587
 
 
588
 
            # FIXME: It's hard to test this scenario here as this code is never
589
 
            # called in that case. -- vila 20100322
590
 
            return
591
 
 
592
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
593
 
            if not clean:
594
 
                if rev_id in whitelist:
595
 
                    pmap = self.repository.get_parent_map([rev_id])
596
 
                    parents = pmap.get(rev_id, [])
597
 
                    whitelist.remove(rev_id)
598
 
                    whitelist.update(parents)
599
 
                    if merge_depth == 0:
600
 
                        # We've reached the mainline, there is nothing left to
601
 
                        # filter
602
 
                        clean = True
603
 
                else:
604
 
                    # A revision that is not part of the ancestry of our
605
 
                    # starting revision.
606
 
                    continue
607
 
            yield (rev_id, merge_depth, revno, end_of_merge)
608
 
 
609
501
    def leave_lock_in_place(self):
610
502
        """Tell this branch object not to release the physical lock when this
611
503
        object is unlocked.
628
520
        :param other: The branch to bind to
629
521
        :type other: Branch
630
522
        """
631
 
        raise errors.UpgradeRequired(self.user_url)
 
523
        raise errors.UpgradeRequired(self.base)
632
524
 
633
525
    def set_append_revisions_only(self, enabled):
634
526
        if not self._format.supports_set_append_revisions_only():
635
 
            raise errors.UpgradeRequired(self.user_url)
 
527
            raise errors.UpgradeRequired(self.base)
636
528
        if enabled:
637
529
            value = 'True'
638
530
        else:
686
578
    def get_old_bound_location(self):
687
579
        """Return the URL of the branch we used to be bound to
688
580
        """
689
 
        raise errors.UpgradeRequired(self.user_url)
 
581
        raise errors.UpgradeRequired(self.base)
690
582
 
691
583
    def get_commit_builder(self, parents, config=None, timestamp=None,
692
584
                           timezone=None, committer=None, revprops=None,
770
662
            stacking.
771
663
        """
772
664
        if not self._format.supports_stacking():
773
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
665
            raise errors.UnstackableBranchFormat(self._format, self.base)
774
666
        # XXX: Changing from one fallback repository to another does not check
775
667
        # that all the data you need is present in the new fallback.
776
668
        # Possibly it should.
806
698
            if len(old_repository._fallback_repositories) != 1:
807
699
                raise AssertionError("can't cope with fallback repositories "
808
700
                    "of %r" % (self.repository,))
809
 
            # Open the new repository object.
810
 
            # Repositories don't offer an interface to remove fallback
811
 
            # repositories today; take the conceptually simpler option and just
812
 
            # reopen it.  We reopen it starting from the URL so that we
813
 
            # get a separate connection for RemoteRepositories and can
814
 
            # stream from one of them to the other.  This does mean doing
815
 
            # separate SSH connection setup, but unstacking is not a
816
 
            # common operation so it's tolerable.
817
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
818
 
            new_repository = new_bzrdir.find_repository()
819
 
            if new_repository._fallback_repositories:
820
 
                raise AssertionError("didn't expect %r to have "
821
 
                    "fallback_repositories"
822
 
                    % (self.repository,))
823
 
            # Replace self.repository with the new repository.
824
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
825
 
            # lock count) of self.repository to the new repository.
826
 
            lock_token = old_repository.lock_write().repository_token
827
 
            self.repository = new_repository
828
 
            if isinstance(self, remote.RemoteBranch):
829
 
                # Remote branches can have a second reference to the old
830
 
                # repository that need to be replaced.
831
 
                if self._real_branch is not None:
832
 
                    self._real_branch.repository = new_repository
833
 
            self.repository.lock_write(token=lock_token)
834
 
            if lock_token is not None:
835
 
                old_repository.leave_lock_in_place()
 
701
            # unlock it, including unlocking the fallback
836
702
            old_repository.unlock()
837
 
            if lock_token is not None:
838
 
                # XXX: self.repository.leave_lock_in_place() before this
839
 
                # function will not be preserved.  Fortunately that doesn't
840
 
                # affect the current default format (2a), and would be a
841
 
                # corner-case anyway.
842
 
                #  - Andrew Bennetts, 2010/06/30
843
 
                self.repository.dont_leave_lock_in_place()
844
 
            old_lock_count = 0
845
 
            while True:
846
 
                try:
847
 
                    old_repository.unlock()
848
 
                except errors.LockNotHeld:
849
 
                    break
850
 
                old_lock_count += 1
851
 
            if old_lock_count == 0:
852
 
                raise AssertionError(
853
 
                    'old_repository should have been locked at least once.')
854
 
            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
855
722
                self.repository.lock_write()
856
 
            # Fetch from the old repository into the new.
857
 
            old_repository.lock_read()
858
 
            try:
859
723
                # XXX: If you unstack a branch while it has a working tree
860
724
                # with a pending merge, the pending-merged revisions will no
861
725
                # longer be present.  You can (probably) revert and remerge.
955
819
 
956
820
    def unbind(self):
957
821
        """Older format branches cannot bind or unbind."""
958
 
        raise errors.UpgradeRequired(self.user_url)
 
822
        raise errors.UpgradeRequired(self.base)
959
823
 
960
824
    def last_revision(self):
961
825
        """Return last revision id, or NULL_REVISION."""
1002
866
                raise errors.NoSuchRevision(self, stop_revision)
1003
867
        return other_history[self_len:stop_revision]
1004
868
 
 
869
    @needs_write_lock
1005
870
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1006
871
                         graph=None):
1007
872
        """Pull in new perfect-fit revisions.
1056
921
            self._extend_partial_history(distance_from_last)
1057
922
        return self._partial_revision_history_cache[distance_from_last]
1058
923
 
 
924
    @needs_write_lock
1059
925
    def pull(self, source, overwrite=False, stop_revision=None,
1060
926
             possible_transports=None, *args, **kwargs):
1061
927
        """Mirror source into this branch.
1119
985
        try:
1120
986
            return urlutils.join(self.base[:-1], parent)
1121
987
        except errors.InvalidURLJoin, e:
1122
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
988
            raise errors.InaccessibleParent(parent, self.base)
1123
989
 
1124
990
    def _get_parent_location(self):
1125
991
        raise NotImplementedError(self._get_parent_location)
1210
1076
        params = ChangeBranchTipParams(
1211
1077
            self, old_revno, new_revno, old_revid, new_revid)
1212
1078
        for hook in hooks:
1213
 
            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)
1214
1088
 
1215
1089
    @needs_write_lock
1216
1090
    def update(self):
1265
1139
        revision_id: if not None, the revision history in the new branch will
1266
1140
                     be truncated to end with revision_id.
1267
1141
        """
1268
 
        if (repository_policy is not None and
1269
 
            repository_policy.requires_stacking()):
1270
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1271
1142
        result = to_bzrdir.create_branch()
1272
1143
        result.lock_write()
1273
1144
        try:
1304
1175
                revno = 1
1305
1176
        destination.set_last_revision_info(revno, revision_id)
1306
1177
 
 
1178
    @needs_read_lock
1307
1179
    def copy_content_into(self, destination, revision_id=None):
1308
1180
        """Copy the content of self into destination.
1309
1181
 
1310
1182
        revision_id: if not None, the revision history in the new branch will
1311
1183
                     be truncated to end with revision_id.
1312
1184
        """
1313
 
        return InterBranch.get(self, destination).copy_content_into(
1314
 
            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)
1315
1196
 
1316
1197
    def update_references(self, target):
1317
1198
        if not getattr(self._format, 'supports_reference_locations', False):
1331
1212
        target._set_all_reference_info(target_reference_dict)
1332
1213
 
1333
1214
    @needs_read_lock
1334
 
    def check(self, refs):
 
1215
    def check(self):
1335
1216
        """Check consistency of the branch.
1336
1217
 
1337
1218
        In particular this checks that revisions given in the revision-history
1340
1221
 
1341
1222
        Callers will typically also want to check the repository.
1342
1223
 
1343
 
        :param refs: Calculated refs for this branch as specified by
1344
 
            branch._get_check_refs()
1345
1224
        :return: A BranchCheckResult.
1346
1225
        """
1347
 
        result = BranchCheckResult(self)
 
1226
        ret = BranchCheckResult(self)
 
1227
        mainline_parent_id = None
1348
1228
        last_revno, last_revision_id = self.last_revision_info()
1349
 
        actual_revno = refs[('lefthand-distance', last_revision_id)]
1350
 
        if actual_revno != last_revno:
1351
 
            result.errors.append(errors.BzrCheckError(
1352
 
                'revno does not match len(mainline) %s != %s' % (
1353
 
                last_revno, actual_revno)))
1354
 
        # TODO: We should probably also check that self.revision_history
1355
 
        # matches the repository for older branch formats.
1356
 
        # If looking for the code that cross-checks repository parents against
1357
 
        # the iter_reverse_revision_history output, that is now a repository
1358
 
        # specific check.
1359
 
        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
1360
1260
 
1361
1261
    def _get_checkout_format(self):
1362
1262
        """Return the most suitable metadir for a checkout of this branch.
1385
1285
        """
1386
1286
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1387
1287
        # clone call. Or something. 20090224 RBC/spiv.
1388
 
        # XXX: Should this perhaps clone colocated branches as well, 
1389
 
        # rather than just the default branch? 20100319 JRV
1390
1288
        if revision_id is None:
1391
1289
            revision_id = self.last_revision()
1392
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1393
 
            revision_id=revision_id, stacked_on=stacked_on,
1394
 
            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
1395
1300
        return dir_to.open_branch()
1396
1301
 
1397
1302
    def create_checkout(self, to_location, revision_id=None,
1416
1321
        if lightweight:
1417
1322
            format = self._get_checkout_format()
1418
1323
            checkout = format.initialize_on_transport(t)
1419
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1420
 
                target_branch=self)
 
1324
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1421
1325
        else:
1422
1326
            format = self._get_checkout_format()
1423
1327
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1465
1369
    def supports_tags(self):
1466
1370
        return self._format.supports_tags()
1467
1371
 
1468
 
    def automatic_tag_name(self, revision_id):
1469
 
        """Try to automatically find the tag name for a revision.
1470
 
 
1471
 
        :param revision_id: Revision id of the revision.
1472
 
        :return: A tag name or None if no tag name could be determined.
1473
 
        """
1474
 
        for hook in Branch.hooks['automatic_tag_name']:
1475
 
            ret = hook(self, revision_id)
1476
 
            if ret is not None:
1477
 
                return ret
1478
 
        return None
1479
 
 
1480
1372
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1481
1373
                                         other_branch):
1482
1374
        """Ensure that revision_b is a descendant of revision_a.
1546
1438
        return not (self == other)
1547
1439
 
1548
1440
    @classmethod
1549
 
    def find_format(klass, a_bzrdir, name=None):
 
1441
    def find_format(klass, a_bzrdir):
1550
1442
        """Return the format for the branch object in a_bzrdir."""
1551
1443
        try:
1552
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1553
 
            format_string = transport.get_bytes("format")
1554
 
            format = klass._formats[format_string]
1555
 
            if isinstance(format, MetaDirBranchFormatFactory):
1556
 
                return format()
1557
 
            return format
 
1444
            transport = a_bzrdir.get_branch_transport(None)
 
1445
            format_string = transport.get("format").read()
 
1446
            return klass._formats[format_string]
1558
1447
        except errors.NoSuchFile:
1559
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1448
            raise errors.NotBranchError(path=transport.base)
1560
1449
        except KeyError:
1561
1450
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1562
1451
 
1565
1454
        """Return the current default format."""
1566
1455
        return klass._default_format
1567
1456
 
1568
 
    @classmethod
1569
 
    def get_formats(klass):
1570
 
        """Get all the known formats.
1571
 
 
1572
 
        Warning: This triggers a load of all lazy registered formats: do not
1573
 
        use except when that is desireed.
1574
 
        """
1575
 
        result = []
1576
 
        for fmt in klass._formats.values():
1577
 
            if isinstance(fmt, MetaDirBranchFormatFactory):
1578
 
                fmt = fmt()
1579
 
            result.append(fmt)
1580
 
        return result
1581
 
 
1582
 
    def get_reference(self, a_bzrdir, name=None):
 
1457
    def get_reference(self, a_bzrdir):
1583
1458
        """Get the target reference of the branch in a_bzrdir.
1584
1459
 
1585
1460
        format probing must have been completed before calling
1587
1462
        in a_bzrdir is correct.
1588
1463
 
1589
1464
        :param a_bzrdir: The bzrdir to get the branch data from.
1590
 
        :param name: Name of the colocated branch to fetch
1591
1465
        :return: None if the branch is not a reference branch.
1592
1466
        """
1593
1467
        return None
1594
1468
 
1595
1469
    @classmethod
1596
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1470
    def set_reference(self, a_bzrdir, to_branch):
1597
1471
        """Set the target reference of the branch in a_bzrdir.
1598
1472
 
1599
1473
        format probing must have been completed before calling
1601
1475
        in a_bzrdir is correct.
1602
1476
 
1603
1477
        :param a_bzrdir: The bzrdir to set the branch reference for.
1604
 
        :param name: Name of colocated branch to set, None for default
1605
1478
        :param to_branch: branch that the checkout is to reference
1606
1479
        """
1607
1480
        raise NotImplementedError(self.set_reference)
1614
1487
        """Return the short format description for this format."""
1615
1488
        raise NotImplementedError(self.get_format_description)
1616
1489
 
1617
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1618
 
        hooks = Branch.hooks['post_branch_init']
1619
 
        if not hooks:
1620
 
            return
1621
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1622
 
        for hook in hooks:
1623
 
            hook(params)
1624
 
 
1625
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1626
 
                           lock_type='metadir', set_format=True):
 
1490
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1491
                           set_format=True):
1627
1492
        """Initialize a branch in a bzrdir, with specified files
1628
1493
 
1629
1494
        :param a_bzrdir: The bzrdir to initialize the branch in
1630
1495
        :param utf8_files: The files to create as a list of
1631
1496
            (filename, content) tuples
1632
 
        :param name: Name of colocated branch to create, if any
1633
1497
        :param set_format: If True, set the format with
1634
1498
            self.get_format_string.  (BzrBranch4 has its format set
1635
1499
            elsewhere)
1636
1500
        :return: a branch in this format
1637
1501
        """
1638
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1639
 
        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)
1640
1504
        lock_map = {
1641
1505
            'metadir': ('lock', lockdir.LockDir),
1642
1506
            'branch4': ('branch-lock', lockable_files.TransportLock),
1663
1527
        finally:
1664
1528
            if lock_taken:
1665
1529
                control_files.unlock()
1666
 
        branch = self.open(a_bzrdir, name, _found=True)
1667
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1668
 
        return branch
 
1530
        return self.open(a_bzrdir, _found=True)
1669
1531
 
1670
 
    def initialize(self, a_bzrdir, name=None):
1671
 
        """Create a branch of this format in a_bzrdir.
1672
 
        
1673
 
        :param name: Name of the colocated branch to create.
1674
 
        """
 
1532
    def initialize(self, a_bzrdir):
 
1533
        """Create a branch of this format in a_bzrdir."""
1675
1534
        raise NotImplementedError(self.initialize)
1676
1535
 
1677
1536
    def is_supported(self):
1707
1566
        """
1708
1567
        raise NotImplementedError(self.network_name)
1709
1568
 
1710
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1569
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1711
1570
        """Return the branch object for a_bzrdir
1712
1571
 
1713
1572
        :param a_bzrdir: A BzrDir that contains a branch.
1714
 
        :param name: Name of colocated branch to open
1715
1573
        :param _found: a private parameter, do not use it. It is used to
1716
1574
            indicate if format probing has already be done.
1717
1575
        :param ignore_fallbacks: when set, no fallback branches will be opened
1721
1579
 
1722
1580
    @classmethod
1723
1581
    def register_format(klass, format):
1724
 
        """Register a metadir format.
1725
 
        
1726
 
        See MetaDirBranchFormatFactory for the ability to register a format
1727
 
        without loading the code the format needs until it is actually used.
1728
 
        """
 
1582
        """Register a metadir format."""
1729
1583
        klass._formats[format.get_format_string()] = format
1730
1584
        # Metadir formats have a network name of their format string, and get
1731
 
        # registered as factories.
1732
 
        if isinstance(format, MetaDirBranchFormatFactory):
1733
 
            network_format_registry.register(format.get_format_string(), format)
1734
 
        else:
1735
 
            network_format_registry.register(format.get_format_string(),
1736
 
                format.__class__)
 
1585
        # registered as class factories.
 
1586
        network_format_registry.register(format.get_format_string(), format.__class__)
1737
1587
 
1738
1588
    @classmethod
1739
1589
    def set_default_format(klass, format):
1759
1609
        return False  # by default
1760
1610
 
1761
1611
 
1762
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1763
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1764
 
    
1765
 
    While none of the built in BranchFormats are lazy registered yet,
1766
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1767
 
    use it, and the bzr-loom plugin uses it as well (see
1768
 
    bzrlib.plugins.loom.formats).
1769
 
    """
1770
 
 
1771
 
    def __init__(self, format_string, module_name, member_name):
1772
 
        """Create a MetaDirBranchFormatFactory.
1773
 
 
1774
 
        :param format_string: The format string the format has.
1775
 
        :param module_name: Module to load the format class from.
1776
 
        :param member_name: Attribute name within the module for the format class.
1777
 
        """
1778
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1779
 
        self._format_string = format_string
1780
 
        
1781
 
    def get_format_string(self):
1782
 
        """See BranchFormat.get_format_string."""
1783
 
        return self._format_string
1784
 
 
1785
 
    def __call__(self):
1786
 
        """Used for network_format_registry support."""
1787
 
        return self.get_obj()()
1788
 
 
1789
 
 
1790
1612
class BranchHooks(Hooks):
1791
1613
    """A dictionary mapping hook name to a list of callables for branch hooks.
1792
1614
 
1861
1683
            "multiple hooks installed for transform_fallback_location, "
1862
1684
            "all are called with the url returned from the previous hook."
1863
1685
            "The order is however undefined.", (1, 9), None))
1864
 
        self.create_hook(HookPoint('automatic_tag_name',
1865
 
            "Called to determine an automatic tag name for a revision. "
1866
 
            "automatic_tag_name is called with (branch, revision_id) and "
1867
 
            "should return a tag name or None if no tag name could be "
1868
 
            "determined. The first non-None tag name returned will be used.",
1869
 
            (2, 2), None))
1870
 
        self.create_hook(HookPoint('post_branch_init',
1871
 
            "Called after new branch initialization completes. "
1872
 
            "post_branch_init is called with a "
1873
 
            "bzrlib.branch.BranchInitHookParams. "
1874
 
            "Note that init, branch and checkout (both heavyweight and "
1875
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1876
 
        self.create_hook(HookPoint('post_switch',
1877
 
            "Called after a checkout switches branch. "
1878
 
            "post_switch is called with a "
1879
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1880
 
 
1881
1686
 
1882
1687
 
1883
1688
# install the default hooks into the Branch class.
1922
1727
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1923
1728
 
1924
1729
 
1925
 
class BranchInitHookParams(object):
1926
 
    """Object holding parameters passed to *_branch_init hooks.
1927
 
 
1928
 
    There are 4 fields that hooks may wish to access:
1929
 
 
1930
 
    :ivar format: the branch format
1931
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1932
 
    :ivar name: name of colocated branch, if any (or None)
1933
 
    :ivar branch: the branch created
1934
 
 
1935
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1936
 
    the checkout, hence they are different from the corresponding fields in
1937
 
    branch, which refer to the original branch.
1938
 
    """
1939
 
 
1940
 
    def __init__(self, format, a_bzrdir, name, branch):
1941
 
        """Create a group of BranchInitHook parameters.
1942
 
 
1943
 
        :param format: the branch format
1944
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1945
 
            initialized
1946
 
        :param name: name of colocated branch, if any (or None)
1947
 
        :param branch: the branch created
1948
 
 
1949
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1950
 
        to the checkout, hence they are different from the corresponding fields
1951
 
        in branch, which refer to the original branch.
1952
 
        """
1953
 
        self.format = format
1954
 
        self.bzrdir = a_bzrdir
1955
 
        self.name = name
1956
 
        self.branch = branch
1957
 
 
1958
 
    def __eq__(self, other):
1959
 
        return self.__dict__ == other.__dict__
1960
 
 
1961
 
    def __repr__(self):
1962
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1963
 
 
1964
 
 
1965
 
class SwitchHookParams(object):
1966
 
    """Object holding parameters passed to *_switch hooks.
1967
 
 
1968
 
    There are 4 fields that hooks may wish to access:
1969
 
 
1970
 
    :ivar control_dir: BzrDir of the checkout to change
1971
 
    :ivar to_branch: branch that the checkout is to reference
1972
 
    :ivar force: skip the check for local commits in a heavy checkout
1973
 
    :ivar revision_id: revision ID to switch to (or None)
1974
 
    """
1975
 
 
1976
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1977
 
        """Create a group of SwitchHook parameters.
1978
 
 
1979
 
        :param control_dir: BzrDir of the checkout to change
1980
 
        :param to_branch: branch that the checkout is to reference
1981
 
        :param force: skip the check for local commits in a heavy checkout
1982
 
        :param revision_id: revision ID to switch to (or None)
1983
 
        """
1984
 
        self.control_dir = control_dir
1985
 
        self.to_branch = to_branch
1986
 
        self.force = force
1987
 
        self.revision_id = revision_id
1988
 
 
1989
 
    def __eq__(self, other):
1990
 
        return self.__dict__ == other.__dict__
1991
 
 
1992
 
    def __repr__(self):
1993
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1994
 
            self.control_dir, self.to_branch,
1995
 
            self.revision_id)
1996
 
 
1997
 
 
1998
1730
class BzrBranchFormat4(BranchFormat):
1999
1731
    """Bzr branch format 4.
2000
1732
 
2007
1739
        """See BranchFormat.get_format_description()."""
2008
1740
        return "Branch format 4"
2009
1741
 
2010
 
    def initialize(self, a_bzrdir, name=None):
 
1742
    def initialize(self, a_bzrdir):
2011
1743
        """Create a branch of this format in a_bzrdir."""
2012
1744
        utf8_files = [('revision-history', ''),
2013
1745
                      ('branch-name', ''),
2014
1746
                      ]
2015
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1747
        return self._initialize_helper(a_bzrdir, utf8_files,
2016
1748
                                       lock_type='branch4', set_format=False)
2017
1749
 
2018
1750
    def __init__(self):
2023
1755
        """The network name for this format is the control dirs disk label."""
2024
1756
        return self._matchingbzrdir.get_format_string()
2025
1757
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1758
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2027
1759
        """See BranchFormat.open()."""
2028
1760
        if not _found:
2029
1761
            # we are being called directly and must probe.
2031
1763
        return BzrBranch(_format=self,
2032
1764
                         _control_files=a_bzrdir._control_files,
2033
1765
                         a_bzrdir=a_bzrdir,
2034
 
                         name=name,
2035
1766
                         _repository=a_bzrdir.open_repository())
2036
1767
 
2037
1768
    def __str__(self):
2052
1783
        """
2053
1784
        return self.get_format_string()
2054
1785
 
2055
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1786
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2056
1787
        """See BranchFormat.open()."""
2057
1788
        if not _found:
2058
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1789
            format = BranchFormat.find_format(a_bzrdir)
2059
1790
            if format.__class__ != self.__class__:
2060
1791
                raise AssertionError("wrong format %r found for %r" %
2061
1792
                    (format, self))
2062
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2063
1793
        try:
 
1794
            transport = a_bzrdir.get_branch_transport(None)
2064
1795
            control_files = lockable_files.LockableFiles(transport, 'lock',
2065
1796
                                                         lockdir.LockDir)
2066
1797
            return self._branch_class()(_format=self,
2067
1798
                              _control_files=control_files,
2068
 
                              name=name,
2069
1799
                              a_bzrdir=a_bzrdir,
2070
1800
                              _repository=a_bzrdir.find_repository(),
2071
1801
                              ignore_fallbacks=ignore_fallbacks)
2072
1802
        except errors.NoSuchFile:
2073
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1803
            raise errors.NotBranchError(path=transport.base)
2074
1804
 
2075
1805
    def __init__(self):
2076
1806
        super(BranchFormatMetadir, self).__init__()
2105
1835
        """See BranchFormat.get_format_description()."""
2106
1836
        return "Branch format 5"
2107
1837
 
2108
 
    def initialize(self, a_bzrdir, name=None):
 
1838
    def initialize(self, a_bzrdir):
2109
1839
        """Create a branch of this format in a_bzrdir."""
2110
1840
        utf8_files = [('revision-history', ''),
2111
1841
                      ('branch-name', ''),
2112
1842
                      ]
2113
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1843
        return self._initialize_helper(a_bzrdir, utf8_files)
2114
1844
 
2115
1845
    def supports_tags(self):
2116
1846
        return False
2138
1868
        """See BranchFormat.get_format_description()."""
2139
1869
        return "Branch format 6"
2140
1870
 
2141
 
    def initialize(self, a_bzrdir, name=None):
 
1871
    def initialize(self, a_bzrdir):
2142
1872
        """Create a branch of this format in a_bzrdir."""
2143
1873
        utf8_files = [('last-revision', '0 null:\n'),
2144
1874
                      ('branch.conf', ''),
2145
1875
                      ('tags', ''),
2146
1876
                      ]
2147
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1877
        return self._initialize_helper(a_bzrdir, utf8_files)
2148
1878
 
2149
1879
    def make_tags(self, branch):
2150
1880
        """See bzrlib.branch.BranchFormat.make_tags()."""
2168
1898
        """See BranchFormat.get_format_description()."""
2169
1899
        return "Branch format 8"
2170
1900
 
2171
 
    def initialize(self, a_bzrdir, name=None):
 
1901
    def initialize(self, a_bzrdir):
2172
1902
        """Create a branch of this format in a_bzrdir."""
2173
1903
        utf8_files = [('last-revision', '0 null:\n'),
2174
1904
                      ('branch.conf', ''),
2175
1905
                      ('tags', ''),
2176
1906
                      ('references', '')
2177
1907
                      ]
2178
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1908
        return self._initialize_helper(a_bzrdir, utf8_files)
2179
1909
 
2180
1910
    def __init__(self):
2181
1911
        super(BzrBranchFormat8, self).__init__()
2204
1934
    This format was introduced in bzr 1.6.
2205
1935
    """
2206
1936
 
2207
 
    def initialize(self, a_bzrdir, name=None):
 
1937
    def initialize(self, a_bzrdir):
2208
1938
        """Create a branch of this format in a_bzrdir."""
2209
1939
        utf8_files = [('last-revision', '0 null:\n'),
2210
1940
                      ('branch.conf', ''),
2211
1941
                      ('tags', ''),
2212
1942
                      ]
2213
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1943
        return self._initialize_helper(a_bzrdir, utf8_files)
2214
1944
 
2215
1945
    def _branch_class(self):
2216
1946
        return BzrBranch7
2248
1978
        """See BranchFormat.get_format_description()."""
2249
1979
        return "Checkout reference format 1"
2250
1980
 
2251
 
    def get_reference(self, a_bzrdir, name=None):
 
1981
    def get_reference(self, a_bzrdir):
2252
1982
        """See BranchFormat.get_reference()."""
2253
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2254
 
        return transport.get_bytes('location')
 
1983
        transport = a_bzrdir.get_branch_transport(None)
 
1984
        return transport.get('location').read()
2255
1985
 
2256
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1986
    def set_reference(self, a_bzrdir, to_branch):
2257
1987
        """See BranchFormat.set_reference()."""
2258
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1988
        transport = a_bzrdir.get_branch_transport(None)
2259
1989
        location = transport.put_bytes('location', to_branch.base)
2260
1990
 
2261
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1991
    def initialize(self, a_bzrdir, target_branch=None):
2262
1992
        """Create a branch of this format in a_bzrdir."""
2263
1993
        if target_branch is None:
2264
1994
            # this format does not implement branch itself, thus the implicit
2265
1995
            # creation contract must see it as uninitializable
2266
1996
            raise errors.UninitializableFormat(self)
2267
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2268
 
        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)
2269
1999
        branch_transport.put_bytes('location',
2270
 
            target_branch.bzrdir.user_url)
 
2000
            target_branch.bzrdir.root_transport.base)
2271
2001
        branch_transport.put_bytes('format', self.get_format_string())
2272
 
        branch = self.open(
2273
 
            a_bzrdir, name, _found=True,
 
2002
        return self.open(
 
2003
            a_bzrdir, _found=True,
2274
2004
            possible_transports=[target_branch.bzrdir.root_transport])
2275
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2276
 
        return branch
2277
2005
 
2278
2006
    def __init__(self):
2279
2007
        super(BranchReferenceFormat, self).__init__()
2285
2013
        def clone(to_bzrdir, revision_id=None,
2286
2014
            repository_policy=None):
2287
2015
            """See Branch.clone()."""
2288
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2016
            return format.initialize(to_bzrdir, a_branch)
2289
2017
            # cannot obey revision_id limits when cloning a reference ...
2290
2018
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2291
2019
            # emit some sort of warning/error to the caller ?!
2292
2020
        return clone
2293
2021
 
2294
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2022
    def open(self, a_bzrdir, _found=False, location=None,
2295
2023
             possible_transports=None, ignore_fallbacks=False):
2296
2024
        """Return the branch that the branch reference in a_bzrdir points at.
2297
2025
 
2298
2026
        :param a_bzrdir: A BzrDir that contains a branch.
2299
 
        :param name: Name of colocated branch to open, if any
2300
2027
        :param _found: a private parameter, do not use it. It is used to
2301
2028
            indicate if format probing has already be done.
2302
2029
        :param ignore_fallbacks: when set, no fallback branches will be opened
2307
2034
        :param possible_transports: An optional reusable transports list.
2308
2035
        """
2309
2036
        if not _found:
2310
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2037
            format = BranchFormat.find_format(a_bzrdir)
2311
2038
            if format.__class__ != self.__class__:
2312
2039
                raise AssertionError("wrong format %r found for %r" %
2313
2040
                    (format, self))
2314
2041
        if location is None:
2315
 
            location = self.get_reference(a_bzrdir, name)
 
2042
            location = self.get_reference(a_bzrdir)
2316
2043
        real_bzrdir = bzrdir.BzrDir.open(
2317
2044
            location, possible_transports=possible_transports)
2318
 
        result = real_bzrdir.open_branch(name=name, 
2319
 
            ignore_fallbacks=ignore_fallbacks)
 
2045
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2320
2046
        # this changes the behaviour of result.clone to create a new reference
2321
2047
        # rather than a copy of the content of the branch.
2322
2048
        # I did not use a proxy object because that needs much more extensive
2349
2075
BranchFormat.register_format(__format6)
2350
2076
BranchFormat.register_format(__format7)
2351
2077
BranchFormat.register_format(__format8)
2352
 
BranchFormat.set_default_format(__format7)
 
2078
BranchFormat.set_default_format(__format6)
2353
2079
_legacy_formats = [BzrBranchFormat4(),
2354
2080
    ]
2355
2081
network_format_registry.register(
2356
2082
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2357
2083
 
2358
2084
 
2359
 
class BranchWriteLockResult(LogicalLockResult):
2360
 
    """The result of write locking a branch.
2361
 
 
2362
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2363
 
        None.
2364
 
    :ivar unlock: A callable which will unlock the lock.
2365
 
    """
2366
 
 
2367
 
    def __init__(self, unlock, branch_token):
2368
 
        LogicalLockResult.__init__(self, unlock)
2369
 
        self.branch_token = branch_token
2370
 
 
2371
 
    def __repr__(self):
2372
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2373
 
            self.unlock)
2374
 
 
2375
 
 
2376
 
class BzrBranch(Branch, _RelockDebugMixin):
 
2085
class BzrBranch(Branch):
2377
2086
    """A branch stored in the actual filesystem.
2378
2087
 
2379
2088
    Note that it's "local" in the context of the filesystem; it doesn't
2385
2094
    :ivar repository: Repository for this branch.
2386
2095
    :ivar base: The url of the base directory for this branch; the one
2387
2096
        containing the .bzr directory.
2388
 
    :ivar name: Optional colocated branch name as it exists in the control
2389
 
        directory.
2390
2097
    """
2391
2098
 
2392
2099
    def __init__(self, _format=None,
2393
 
                 _control_files=None, a_bzrdir=None, name=None,
2394
 
                 _repository=None, ignore_fallbacks=False):
 
2100
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2101
                 ignore_fallbacks=False):
2395
2102
        """Create new branch object at a particular location."""
2396
2103
        if a_bzrdir is None:
2397
2104
            raise ValueError('a_bzrdir must be supplied')
2398
2105
        else:
2399
2106
            self.bzrdir = a_bzrdir
2400
2107
        self._base = self.bzrdir.transport.clone('..').base
2401
 
        self.name = name
2402
2108
        # XXX: We should be able to just do
2403
2109
        #   self.base = self.bzrdir.root_transport.base
2404
2110
        # but this does not quite work yet -- mbp 20080522
2411
2117
        Branch.__init__(self)
2412
2118
 
2413
2119
    def __str__(self):
2414
 
        if self.name is None:
2415
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2416
 
        else:
2417
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2418
 
                self.name)
 
2120
        return '%s(%r)' % (self.__class__.__name__, self.base)
2419
2121
 
2420
2122
    __repr__ = __str__
2421
2123
 
2432
2134
        return self.control_files.is_locked()
2433
2135
 
2434
2136
    def lock_write(self, token=None):
2435
 
        """Lock the branch for write operations.
2436
 
 
2437
 
        :param token: A token to permit reacquiring a previously held and
2438
 
            preserved lock.
2439
 
        :return: A BranchWriteLockResult.
2440
 
        """
2441
 
        if not self.is_locked():
2442
 
            self._note_lock('w')
2443
2137
        # All-in-one needs to always unlock/lock.
2444
2138
        repo_control = getattr(self.repository, 'control_files', None)
2445
2139
        if self.control_files == repo_control or not self.is_locked():
2446
 
            self.repository._warn_if_deprecated(self)
2447
2140
            self.repository.lock_write()
2448
2141
            took_lock = True
2449
2142
        else:
2450
2143
            took_lock = False
2451
2144
        try:
2452
 
            return BranchWriteLockResult(self.unlock,
2453
 
                self.control_files.lock_write(token=token))
 
2145
            return self.control_files.lock_write(token=token)
2454
2146
        except:
2455
2147
            if took_lock:
2456
2148
                self.repository.unlock()
2457
2149
            raise
2458
2150
 
2459
2151
    def lock_read(self):
2460
 
        """Lock the branch for read operations.
2461
 
 
2462
 
        :return: A bzrlib.lock.LogicalLockResult.
2463
 
        """
2464
 
        if not self.is_locked():
2465
 
            self._note_lock('r')
2466
2152
        # All-in-one needs to always unlock/lock.
2467
2153
        repo_control = getattr(self.repository, 'control_files', None)
2468
2154
        if self.control_files == repo_control or not self.is_locked():
2469
 
            self.repository._warn_if_deprecated(self)
2470
2155
            self.repository.lock_read()
2471
2156
            took_lock = True
2472
2157
        else:
2473
2158
            took_lock = False
2474
2159
        try:
2475
2160
            self.control_files.lock_read()
2476
 
            return LogicalLockResult(self.unlock)
2477
2161
        except:
2478
2162
            if took_lock:
2479
2163
                self.repository.unlock()
2480
2164
            raise
2481
2165
 
2482
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2483
2166
    def unlock(self):
2484
2167
        try:
2485
2168
            self.control_files.unlock()
2648
2331
        return result
2649
2332
 
2650
2333
    def get_stacked_on_url(self):
2651
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2334
        raise errors.UnstackableBranchFormat(self._format, self.base)
2652
2335
 
2653
2336
    def set_push_location(self, location):
2654
2337
        """See Branch.set_push_location."""
2844
2527
        if _mod_revision.is_null(last_revision):
2845
2528
            return
2846
2529
        if last_revision not in self._lefthand_history(revision_id):
2847
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2530
            raise errors.AppendRevisionsOnlyViolation(self.base)
2848
2531
 
2849
2532
    def _gen_revision_history(self):
2850
2533
        """Generate the revision history from last revision
2950
2633
        if branch_location is None:
2951
2634
            return Branch.reference_parent(self, file_id, path,
2952
2635
                                           possible_transports)
2953
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2636
        branch_location = urlutils.join(self.base, branch_location)
2954
2637
        return Branch.open(branch_location,
2955
2638
                           possible_transports=possible_transports)
2956
2639
 
3002
2685
        return stacked_url
3003
2686
 
3004
2687
    def _get_append_revisions_only(self):
3005
 
        return self.get_config(
3006
 
            ).get_user_option_as_bool('append_revisions_only')
 
2688
        value = self.get_config().get_user_option('append_revisions_only')
 
2689
        return value == 'True'
3007
2690
 
3008
2691
    @needs_write_lock
3009
2692
    def generate_revision_history(self, revision_id, last_rev=None,
3071
2754
    """
3072
2755
 
3073
2756
    def get_stacked_on_url(self):
3074
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2757
        raise errors.UnstackableBranchFormat(self._format, self.base)
3075
2758
 
3076
2759
 
3077
2760
######################################################################
3156
2839
 
3157
2840
    def __init__(self, branch):
3158
2841
        self.branch = branch
3159
 
        self.errors = []
 
2842
        self.ghosts_in_mainline = False
3160
2843
 
3161
2844
    def report_results(self, verbose):
3162
2845
        """Report the check results via trace.note.
3164
2847
        :param verbose: Requests more detailed display of what was checked,
3165
2848
            if any.
3166
2849
        """
3167
 
        note('checked branch %s format %s', self.branch.user_url,
3168
 
            self.branch._format)
3169
 
        for error in self.errors:
3170
 
            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')
3171
2855
 
3172
2856
 
3173
2857
class Converter5to6(object):
3265
2949
    _optimisers = []
3266
2950
    """The available optimised InterBranch types."""
3267
2951
 
3268
 
    @classmethod
3269
 
    def _get_branch_formats_to_test(klass):
3270
 
        """Return an iterable of format tuples for testing.
3271
 
        
3272
 
        :return: An iterable of (from_format, to_format) to use when testing
3273
 
            this InterBranch class. Each InterBranch class should define this
3274
 
            method itself.
3275
 
        """
3276
 
        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)
3277
2956
 
3278
 
    @needs_write_lock
3279
2957
    def pull(self, overwrite=False, stop_revision=None,
3280
2958
             possible_transports=None, local=False):
3281
2959
        """Mirror source into target branch.
3286
2964
        """
3287
2965
        raise NotImplementedError(self.pull)
3288
2966
 
3289
 
    @needs_write_lock
3290
2967
    def update_revisions(self, stop_revision=None, overwrite=False,
3291
2968
                         graph=None):
3292
2969
        """Pull in new perfect-fit revisions.
3300
2977
        """
3301
2978
        raise NotImplementedError(self.update_revisions)
3302
2979
 
3303
 
    @needs_write_lock
3304
2980
    def push(self, overwrite=False, stop_revision=None,
3305
2981
             _override_hook_source_branch=None):
3306
2982
        """Mirror the source branch into the target branch.
3309
2985
        """
3310
2986
        raise NotImplementedError(self.push)
3311
2987
 
3312
 
    @needs_write_lock
3313
 
    def copy_content_into(self, revision_id=None):
3314
 
        """Copy the content of source into target
3315
 
 
3316
 
        revision_id: if not None, the revision history in the new branch will
3317
 
                     be truncated to end with revision_id.
3318
 
        """
3319
 
        raise NotImplementedError(self.copy_content_into)
3320
 
 
3321
2988
 
3322
2989
class GenericInterBranch(InterBranch):
3323
 
    """InterBranch implementation that uses public Branch functions."""
3324
 
 
3325
 
    @classmethod
3326
 
    def is_compatible(klass, source, target):
3327
 
        # GenericBranch uses the public API, so always compatible
3328
 
        return True
3329
 
 
3330
 
    @classmethod
3331
 
    def _get_branch_formats_to_test(klass):
3332
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3333
 
 
3334
 
    @classmethod
3335
 
    def unwrap_format(klass, format):
3336
 
        if isinstance(format, remote.RemoteBranchFormat):
3337
 
            format._ensure_real()
3338
 
            return format._custom_format
3339
 
        return format                                                                                                  
3340
 
 
3341
 
    @needs_write_lock
3342
 
    def copy_content_into(self, revision_id=None):
3343
 
        """Copy the content of source into target
3344
 
 
3345
 
        revision_id: if not None, the revision history in the new branch will
3346
 
                     be truncated to end with revision_id.
3347
 
        """
3348
 
        self.source.update_references(self.target)
3349
 
        self.source._synchronize_history(self.target, revision_id)
3350
 
        try:
3351
 
            parent = self.source.get_parent()
3352
 
        except errors.InaccessibleParent, e:
3353
 
            mutter('parent was not accessible to copy: %s', e)
3354
 
        else:
3355
 
            if parent:
3356
 
                self.target.set_parent(parent)
3357
 
        if self.source._push_should_merge_tags():
3358
 
            self.source.tags.merge_to(self.target.tags)
3359
 
 
3360
 
    @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
 
3361
2997
    def update_revisions(self, stop_revision=None, overwrite=False,
3362
2998
        graph=None):
3363
2999
        """See InterBranch.update_revisions()."""
3364
 
        other_revno, other_last_revision = self.source.last_revision_info()
3365
 
        stop_revno = None # unknown
3366
 
        if stop_revision is None:
3367
 
            stop_revision = other_last_revision
3368
 
            if _mod_revision.is_null(stop_revision):
3369
 
                # if there are no commits, we're done.
3370
 
                return
3371
 
            stop_revno = other_revno
3372
 
 
3373
 
        # what's the current last revision, before we fetch [and change it
3374
 
        # possibly]
3375
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3376
 
        # we fetch here so that we don't process data twice in the common
3377
 
        # case of having something to pull, and so that the check for
3378
 
        # already merged can operate on the just fetched graph, which will
3379
 
        # be cached in memory.
3380
 
        self.target.fetch(self.source, stop_revision)
3381
 
        # Check to see if one is an ancestor of the other
3382
 
        if not overwrite:
3383
 
            if graph is None:
3384
 
                graph = self.target.repository.get_graph()
3385
 
            if self.target._check_if_descendant_or_diverged(
3386
 
                    stop_revision, last_rev, graph, self.source):
3387
 
                # stop_revision is a descendant of last_rev, but we aren't
3388
 
                # overwriting, so we're done.
3389
 
                return
3390
 
        if stop_revno is None:
3391
 
            if graph is None:
3392
 
                graph = self.target.repository.get_graph()
3393
 
            this_revno, this_last_revision = \
3394
 
                    self.target.last_revision_info()
3395
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3396
 
                            [(other_last_revision, other_revno),
3397
 
                             (this_last_revision, this_revno)])
3398
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3399
 
 
3400
 
    @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
 
3401
3040
    def pull(self, overwrite=False, stop_revision=None,
3402
 
             possible_transports=None, run_hooks=True,
 
3041
             possible_transports=None, _hook_master=None, run_hooks=True,
3403
3042
             _override_hook_target=None, local=False):
3404
 
        """Pull from source into self, updating my master if any.
 
3043
        """See Branch.pull.
3405
3044
 
 
3045
        :param _hook_master: Private parameter - set the branch to
 
3046
            be supplied as the master to pull hooks.
3406
3047
        :param run_hooks: Private parameter - if false, this branch
3407
3048
            is being called because it's the master of the primary branch,
3408
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.
3409
3053
        """
3410
 
        bound_location = self.target.get_bound_location()
3411
 
        if local and not bound_location:
 
3054
        # This type of branch can't be bound.
 
3055
        if local:
3412
3056
            raise errors.LocalRequiresBoundBranch()
3413
 
        master_branch = None
3414
 
        if not local and bound_location and self.source.user_url != bound_location:
3415
 
            # not pulling from master, so we need to update master.
3416
 
            master_branch = self.target.get_master_branch(possible_transports)
3417
 
            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()
3418
3064
        try:
3419
 
            if master_branch:
3420
 
                # pull from source into master.
3421
 
                master_branch.pull(self.source, overwrite, stop_revision,
3422
 
                    run_hooks=False)
3423
 
            return self._pull(overwrite,
3424
 
                stop_revision, _hook_master=master_branch,
3425
 
                run_hooks=run_hooks,
3426
 
                _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)
3427
3091
        finally:
3428
 
            if master_branch:
3429
 
                master_branch.unlock()
 
3092
            self.source.unlock()
 
3093
        return result
3430
3094
 
3431
3095
    def push(self, overwrite=False, stop_revision=None,
3432
3096
             _override_hook_source_branch=None):
3494
3158
            _run_hooks()
3495
3159
            return result
3496
3160
 
3497
 
    def _pull(self, overwrite=False, stop_revision=None,
3498
 
             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,
3499
3175
             _override_hook_target=None, local=False):
3500
 
        """See Branch.pull.
3501
 
 
3502
 
        This function is the core worker, used by GenericInterBranch.pull to
3503
 
        avoid duplication when pulling source->master and source->local.
3504
 
 
3505
 
        :param _hook_master: Private parameter - set the branch to
3506
 
            be supplied as the master to pull hooks.
 
3176
        """Pull from source into self, updating my master if any.
 
3177
 
3507
3178
        :param run_hooks: Private parameter - if false, this branch
3508
3179
            is being called because it's the master of the primary branch,
3509
3180
            so it should not run its hooks.
3510
 
        :param _override_hook_target: Private parameter - set the branch to be
3511
 
            supplied as the target_branch to pull hooks.
3512
 
        :param local: Only update the local branch, and not the bound branch.
3513
3181
        """
3514
 
        # This type of branch can't be bound.
3515
 
        if local:
 
3182
        bound_location = self.target.get_bound_location()
 
3183
        if local and not bound_location:
3516
3184
            raise errors.LocalRequiresBoundBranch()
3517
 
        result = PullResult()
3518
 
        result.source_branch = self.source
3519
 
        if _override_hook_target is None:
3520
 
            result.target_branch = self.target
3521
 
        else:
3522
 
            result.target_branch = _override_hook_target
3523
 
        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()
3524
3190
        try:
3525
 
            # We assume that during 'pull' the target repository is closer than
3526
 
            # the source one.
3527
 
            self.source.update_references(self.target)
3528
 
            graph = self.target.repository.get_graph(self.source.repository)
3529
 
            # TODO: Branch formats should have a flag that indicates 
3530
 
            # that revno's are expensive, and pull() should honor that flag.
3531
 
            # -- JRV20090506
3532
 
            result.old_revno, result.old_revid = \
3533
 
                self.target.last_revision_info()
3534
 
            self.target.update_revisions(self.source, stop_revision,
3535
 
                overwrite=overwrite, graph=graph)
3536
 
            # TODO: The old revid should be specified when merging tags, 
3537
 
            # so a tags implementation that versions tags can only 
3538
 
            # pull in the most recent changes. -- JRV20090506
3539
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3540
 
                overwrite)
3541
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3542
 
            if _hook_master:
3543
 
                result.master_branch = _hook_master
3544
 
                result.local_branch = result.target_branch
3545
 
            else:
3546
 
                result.master_branch = result.target_branch
3547
 
                result.local_branch = None
3548
 
            if run_hooks:
3549
 
                for hook in Branch.hooks['post_pull']:
3550
 
                    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)
3551
3199
        finally:
3552
 
            self.source.unlock()
3553
 
        return result
 
3200
            if master_branch:
 
3201
                master_branch.unlock()
3554
3202
 
3555
3203
 
3556
3204
InterBranch.register_optimiser(GenericInterBranch)
 
3205
InterBranch.register_optimiser(InterToBranch5)