~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Martin Pool
  • Date: 2010-04-01 04:41:18 UTC
  • mto: This revision was merged to the branch mainline in revision 5128.
  • Revision ID: mbp@sourcefrog.net-20100401044118-shyctqc02ob08ngz
ignore .testrepository

Show diffs side-by-side

added added

removed removed

Lines of Context:
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,
51
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
52
50
from bzrlib.hooks import HookPoint, Hooks
53
51
from bzrlib.inter import InterObject
54
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
55
53
from bzrlib import registry
56
54
from bzrlib.symbol_versioning import (
57
55
    deprecated_in,
65
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
66
64
 
67
65
 
68
 
class Branch(controldir.ControlComponent):
 
66
# TODO: Maybe include checks for common corruption of newlines, etc?
 
67
 
 
68
# TODO: Some operations like log might retrieve the same revisions
 
69
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
70
# cache in memory to make this faster.  In general anything can be
 
71
# cached in memory between lock and unlock operations. .. nb thats
 
72
# what the transaction identity map provides
 
73
 
 
74
 
 
75
######################################################################
 
76
# branch objects
 
77
 
 
78
class Branch(object):
69
79
    """Branch holding a history of revisions.
70
80
 
71
 
    :ivar base:
72
 
        Base directory/url of the branch; using control_url and
73
 
        control_transport is more standardized.
 
81
    base
 
82
        Base directory/url of the branch.
74
83
 
75
84
    hooks: An instance of BranchHooks.
76
85
    """
78
87
    # - RBC 20060112
79
88
    base = None
80
89
 
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
90
    def __init__(self, *ignored, **ignored_too):
90
91
        self.tags = self._format.make_tags(self)
91
92
        self._revision_history_cache = None
106
107
        """Activate the branch/repository from url as a fallback repository."""
107
108
        repo = self._get_fallback_repository(url)
108
109
        if repo.has_same_location(self.repository):
109
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
110
            raise errors.UnstackableLocationError(self.base, url)
110
111
        self.repository.add_fallback_repository(repo)
111
112
 
112
113
    def break_lock(self):
199
200
        return self.supports_tags() and self.tags.get_tag_dict()
200
201
 
201
202
    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
203
        return BranchConfig(self)
210
204
 
211
205
    def _get_config(self):
247
241
        if not local and not config.has_explicit_nickname():
248
242
            try:
249
243
                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
244
                if master is not None:
253
245
                    # return the master branch value
254
246
                    return master.nick
255
 
            except errors.RecursiveBind, e:
256
 
                raise e
257
247
            except errors.BzrError, e:
258
248
                # Silently fall back to local implicit nick if the master is
259
249
                # unavailable
296
286
        new_history.reverse()
297
287
        return new_history
298
288
 
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
 
        """
 
289
    def lock_write(self):
306
290
        raise NotImplementedError(self.lock_write)
307
291
 
308
292
    def lock_read(self):
309
 
        """Lock the branch for read operations.
310
 
 
311
 
        :return: A bzrlib.lock.LogicalLockResult.
312
 
        """
313
293
        raise NotImplementedError(self.lock_read)
314
294
 
315
295
    def unlock(self):
440
420
            * 'include' - the stop revision is the last item in the result
441
421
            * 'with-merges' - include the stop revision and all of its
442
422
              merged revisions in the result
443
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
444
 
              that are in both ancestries
445
423
        :param direction: either 'reverse' or 'forward':
446
424
            * reverse means return the start_revision_id first, i.e.
447
425
              start at the most recent revision and go backwards in history
469
447
        # start_revision_id.
470
448
        if self._merge_sorted_revisions_cache is None:
471
449
            last_revision = self.last_revision()
472
 
            known_graph = self.repository.get_known_graph_ancestry(
473
 
                [last_revision])
 
450
            last_key = (last_revision,)
 
451
            known_graph = self.repository.revisions.get_known_graph_ancestry(
 
452
                [last_key])
474
453
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
475
 
                last_revision)
 
454
                last_key)
476
455
        filtered = self._filter_merge_sorted_revisions(
477
456
            self._merge_sorted_revisions_cache, start_revision_id,
478
457
            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
458
        if direction == 'reverse':
483
459
            return filtered
484
460
        if direction == 'forward':
521
497
                       node.end_of_merge)
522
498
                if rev_id == stop_revision_id:
523
499
                    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
500
        elif stop_rule == 'with-merges':
537
501
            stop_rev = self.repository.get_revision(stop_revision_id)
538
502
            if stop_rev.parent_ids:
561
525
        else:
562
526
            raise ValueError('invalid stop_rule %r' % stop_rule)
563
527
 
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
528
    def leave_lock_in_place(self):
610
529
        """Tell this branch object not to release the physical lock when this
611
530
        object is unlocked.
628
547
        :param other: The branch to bind to
629
548
        :type other: Branch
630
549
        """
631
 
        raise errors.UpgradeRequired(self.user_url)
 
550
        raise errors.UpgradeRequired(self.base)
632
551
 
633
552
    def set_append_revisions_only(self, enabled):
634
553
        if not self._format.supports_set_append_revisions_only():
635
 
            raise errors.UpgradeRequired(self.user_url)
 
554
            raise errors.UpgradeRequired(self.base)
636
555
        if enabled:
637
556
            value = 'True'
638
557
        else:
686
605
    def get_old_bound_location(self):
687
606
        """Return the URL of the branch we used to be bound to
688
607
        """
689
 
        raise errors.UpgradeRequired(self.user_url)
 
608
        raise errors.UpgradeRequired(self.base)
690
609
 
691
610
    def get_commit_builder(self, parents, config=None, timestamp=None,
692
611
                           timezone=None, committer=None, revprops=None,
770
689
            stacking.
771
690
        """
772
691
        if not self._format.supports_stacking():
773
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
692
            raise errors.UnstackableBranchFormat(self._format, self.base)
774
693
        # XXX: Changing from one fallback repository to another does not check
775
694
        # that all the data you need is present in the new fallback.
776
695
        # Possibly it should.
806
725
            if len(old_repository._fallback_repositories) != 1:
807
726
                raise AssertionError("can't cope with fallback repositories "
808
727
                    "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()
 
728
            # unlock it, including unlocking the fallback
836
729
            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):
 
730
            old_repository.lock_read()
 
731
            try:
 
732
                # Repositories don't offer an interface to remove fallback
 
733
                # repositories today; take the conceptually simpler option and just
 
734
                # reopen it.  We reopen it starting from the URL so that we
 
735
                # get a separate connection for RemoteRepositories and can
 
736
                # stream from one of them to the other.  This does mean doing
 
737
                # separate SSH connection setup, but unstacking is not a
 
738
                # common operation so it's tolerable.
 
739
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
740
                new_repository = new_bzrdir.find_repository()
 
741
                self.repository = new_repository
 
742
                if self.repository._fallback_repositories:
 
743
                    raise AssertionError("didn't expect %r to have "
 
744
                        "fallback_repositories"
 
745
                        % (self.repository,))
 
746
                # this is not paired with an unlock because it's just restoring
 
747
                # the previous state; the lock's released when set_stacked_on_url
 
748
                # returns
855
749
                self.repository.lock_write()
856
 
            # Fetch from the old repository into the new.
857
 
            old_repository.lock_read()
858
 
            try:
859
750
                # XXX: If you unstack a branch while it has a working tree
860
751
                # with a pending merge, the pending-merged revisions will no
861
752
                # longer be present.  You can (probably) revert and remerge.
955
846
 
956
847
    def unbind(self):
957
848
        """Older format branches cannot bind or unbind."""
958
 
        raise errors.UpgradeRequired(self.user_url)
 
849
        raise errors.UpgradeRequired(self.base)
959
850
 
960
851
    def last_revision(self):
961
852
        """Return last revision id, or NULL_REVISION."""
1002
893
                raise errors.NoSuchRevision(self, stop_revision)
1003
894
        return other_history[self_len:stop_revision]
1004
895
 
 
896
    @needs_write_lock
1005
897
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1006
898
                         graph=None):
1007
899
        """Pull in new perfect-fit revisions.
1056
948
            self._extend_partial_history(distance_from_last)
1057
949
        return self._partial_revision_history_cache[distance_from_last]
1058
950
 
 
951
    @needs_write_lock
1059
952
    def pull(self, source, overwrite=False, stop_revision=None,
1060
953
             possible_transports=None, *args, **kwargs):
1061
954
        """Mirror source into this branch.
1119
1012
        try:
1120
1013
            return urlutils.join(self.base[:-1], parent)
1121
1014
        except errors.InvalidURLJoin, e:
1122
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
1015
            raise errors.InaccessibleParent(parent, self.base)
1123
1016
 
1124
1017
    def _get_parent_location(self):
1125
1018
        raise NotImplementedError(self._get_parent_location)
1304
1197
                revno = 1
1305
1198
        destination.set_last_revision_info(revno, revision_id)
1306
1199
 
 
1200
    @needs_read_lock
1307
1201
    def copy_content_into(self, destination, revision_id=None):
1308
1202
        """Copy the content of self into destination.
1309
1203
 
1310
1204
        revision_id: if not None, the revision history in the new branch will
1311
1205
                     be truncated to end with revision_id.
1312
1206
        """
1313
 
        return InterBranch.get(self, destination).copy_content_into(
1314
 
            revision_id=revision_id)
 
1207
        self.update_references(destination)
 
1208
        self._synchronize_history(destination, revision_id)
 
1209
        try:
 
1210
            parent = self.get_parent()
 
1211
        except errors.InaccessibleParent, e:
 
1212
            mutter('parent was not accessible to copy: %s', e)
 
1213
        else:
 
1214
            if parent:
 
1215
                destination.set_parent(parent)
 
1216
        if self._push_should_merge_tags():
 
1217
            self.tags.merge_to(destination.tags)
1315
1218
 
1316
1219
    def update_references(self, target):
1317
1220
        if not getattr(self._format, 'supports_reference_locations', False):
1385
1288
        """
1386
1289
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1387
1290
        # 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
1291
        if revision_id is None:
1391
1292
            revision_id = self.last_revision()
1392
1293
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1551
1452
        try:
1552
1453
            transport = a_bzrdir.get_branch_transport(None, name=name)
1553
1454
            format_string = transport.get_bytes("format")
1554
 
            format = klass._formats[format_string]
1555
 
            if isinstance(format, MetaDirBranchFormatFactory):
1556
 
                return format()
1557
 
            return format
 
1455
            return klass._formats[format_string]
1558
1456
        except errors.NoSuchFile:
1559
1457
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1560
1458
        except KeyError:
1565
1463
        """Return the current default format."""
1566
1464
        return klass._default_format
1567
1465
 
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):
 
1466
    def get_reference(self, a_bzrdir):
1583
1467
        """Get the target reference of the branch in a_bzrdir.
1584
1468
 
1585
1469
        format probing must have been completed before calling
1587
1471
        in a_bzrdir is correct.
1588
1472
 
1589
1473
        :param a_bzrdir: The bzrdir to get the branch data from.
1590
 
        :param name: Name of the colocated branch to fetch
1591
1474
        :return: None if the branch is not a reference branch.
1592
1475
        """
1593
1476
        return None
1594
1477
 
1595
1478
    @classmethod
1596
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1479
    def set_reference(self, a_bzrdir, to_branch):
1597
1480
        """Set the target reference of the branch in a_bzrdir.
1598
1481
 
1599
1482
        format probing must have been completed before calling
1601
1484
        in a_bzrdir is correct.
1602
1485
 
1603
1486
        :param a_bzrdir: The bzrdir to set the branch reference for.
1604
 
        :param name: Name of colocated branch to set, None for default
1605
1487
        :param to_branch: branch that the checkout is to reference
1606
1488
        """
1607
1489
        raise NotImplementedError(self.set_reference)
1614
1496
        """Return the short format description for this format."""
1615
1497
        raise NotImplementedError(self.get_format_description)
1616
1498
 
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
1499
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1626
1500
                           lock_type='metadir', set_format=True):
1627
1501
        """Initialize a branch in a bzrdir, with specified files
1635
1509
            elsewhere)
1636
1510
        :return: a branch in this format
1637
1511
        """
1638
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1512
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1639
1513
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1640
1514
        lock_map = {
1641
1515
            'metadir': ('lock', lockdir.LockDir),
1663
1537
        finally:
1664
1538
            if lock_taken:
1665
1539
                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
 
1540
        return self.open(a_bzrdir, name, _found=True)
1669
1541
 
1670
1542
    def initialize(self, a_bzrdir, name=None):
1671
1543
        """Create a branch of this format in a_bzrdir.
1721
1593
 
1722
1594
    @classmethod
1723
1595
    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
 
        """
 
1596
        """Register a metadir format."""
1729
1597
        klass._formats[format.get_format_string()] = format
1730
1598
        # 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__)
 
1599
        # registered as class factories.
 
1600
        network_format_registry.register(format.get_format_string(), format.__class__)
1737
1601
 
1738
1602
    @classmethod
1739
1603
    def set_default_format(klass, format):
1759
1623
        return False  # by default
1760
1624
 
1761
1625
 
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
1626
class BranchHooks(Hooks):
1791
1627
    """A dictionary mapping hook name to a list of callables for branch hooks.
1792
1628
 
1862
1698
            "all are called with the url returned from the previous hook."
1863
1699
            "The order is however undefined.", (1, 9), None))
1864
1700
        self.create_hook(HookPoint('automatic_tag_name',
1865
 
            "Called to determine an automatic tag name for a revision. "
 
1701
            "Called to determine an automatic tag name for a revision."
1866
1702
            "automatic_tag_name is called with (branch, revision_id) and "
1867
1703
            "should return a tag name or None if no tag name could be "
1868
1704
            "determined. The first non-None tag name returned will be used.",
1869
1705
            (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
1706
 
1881
1707
 
1882
1708
 
1922
1748
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1923
1749
 
1924
1750
 
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
1751
class BzrBranchFormat4(BranchFormat):
1999
1752
    """Bzr branch format 4.
2000
1753
 
2059
1812
            if format.__class__ != self.__class__:
2060
1813
                raise AssertionError("wrong format %r found for %r" %
2061
1814
                    (format, self))
2062
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2063
1815
        try:
 
1816
            transport = a_bzrdir.get_branch_transport(None, name=name)
2064
1817
            control_files = lockable_files.LockableFiles(transport, 'lock',
2065
1818
                                                         lockdir.LockDir)
2066
1819
            return self._branch_class()(_format=self,
2248
2001
        """See BranchFormat.get_format_description()."""
2249
2002
        return "Checkout reference format 1"
2250
2003
 
2251
 
    def get_reference(self, a_bzrdir, name=None):
 
2004
    def get_reference(self, a_bzrdir):
2252
2005
        """See BranchFormat.get_reference()."""
2253
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2006
        transport = a_bzrdir.get_branch_transport(None)
2254
2007
        return transport.get_bytes('location')
2255
2008
 
2256
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
2009
    def set_reference(self, a_bzrdir, to_branch):
2257
2010
        """See BranchFormat.set_reference()."""
2258
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2011
        transport = a_bzrdir.get_branch_transport(None)
2259
2012
        location = transport.put_bytes('location', to_branch.base)
2260
2013
 
2261
2014
    def initialize(self, a_bzrdir, name=None, target_branch=None):
2264
2017
            # this format does not implement branch itself, thus the implicit
2265
2018
            # creation contract must see it as uninitializable
2266
2019
            raise errors.UninitializableFormat(self)
2267
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2020
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
2268
2021
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2269
2022
        branch_transport.put_bytes('location',
2270
 
            target_branch.bzrdir.user_url)
 
2023
            target_branch.bzrdir.root_transport.base)
2271
2024
        branch_transport.put_bytes('format', self.get_format_string())
2272
 
        branch = self.open(
 
2025
        return self.open(
2273
2026
            a_bzrdir, name, _found=True,
2274
2027
            possible_transports=[target_branch.bzrdir.root_transport])
2275
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2276
 
        return branch
2277
2028
 
2278
2029
    def __init__(self):
2279
2030
        super(BranchReferenceFormat, self).__init__()
2312
2063
                raise AssertionError("wrong format %r found for %r" %
2313
2064
                    (format, self))
2314
2065
        if location is None:
2315
 
            location = self.get_reference(a_bzrdir, name)
 
2066
            location = self.get_reference(a_bzrdir)
2316
2067
        real_bzrdir = bzrdir.BzrDir.open(
2317
2068
            location, possible_transports=possible_transports)
2318
2069
        result = real_bzrdir.open_branch(name=name, 
2356
2107
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2357
2108
 
2358
2109
 
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
2110
class BzrBranch(Branch, _RelockDebugMixin):
2377
2111
    """A branch stored in the actual filesystem.
2378
2112
 
2412
2146
 
2413
2147
    def __str__(self):
2414
2148
        if self.name is None:
2415
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2149
            return '%s(%r)' % (self.__class__.__name__, self.base)
2416
2150
        else:
2417
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2418
 
                self.name)
 
2151
            return '%s(%r,%r)' % (self.__class__.__name__, self.base, self.name)
2419
2152
 
2420
2153
    __repr__ = __str__
2421
2154
 
2432
2165
        return self.control_files.is_locked()
2433
2166
 
2434
2167
    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
2168
        if not self.is_locked():
2442
2169
            self._note_lock('w')
2443
2170
        # All-in-one needs to always unlock/lock.
2449
2176
        else:
2450
2177
            took_lock = False
2451
2178
        try:
2452
 
            return BranchWriteLockResult(self.unlock,
2453
 
                self.control_files.lock_write(token=token))
 
2179
            return self.control_files.lock_write(token=token)
2454
2180
        except:
2455
2181
            if took_lock:
2456
2182
                self.repository.unlock()
2457
2183
            raise
2458
2184
 
2459
2185
    def lock_read(self):
2460
 
        """Lock the branch for read operations.
2461
 
 
2462
 
        :return: A bzrlib.lock.LogicalLockResult.
2463
 
        """
2464
2186
        if not self.is_locked():
2465
2187
            self._note_lock('r')
2466
2188
        # All-in-one needs to always unlock/lock.
2473
2195
            took_lock = False
2474
2196
        try:
2475
2197
            self.control_files.lock_read()
2476
 
            return LogicalLockResult(self.unlock)
2477
2198
        except:
2478
2199
            if took_lock:
2479
2200
                self.repository.unlock()
2648
2369
        return result
2649
2370
 
2650
2371
    def get_stacked_on_url(self):
2651
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2372
        raise errors.UnstackableBranchFormat(self._format, self.base)
2652
2373
 
2653
2374
    def set_push_location(self, location):
2654
2375
        """See Branch.set_push_location."""
2844
2565
        if _mod_revision.is_null(last_revision):
2845
2566
            return
2846
2567
        if last_revision not in self._lefthand_history(revision_id):
2847
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2568
            raise errors.AppendRevisionsOnlyViolation(self.base)
2848
2569
 
2849
2570
    def _gen_revision_history(self):
2850
2571
        """Generate the revision history from last revision
2950
2671
        if branch_location is None:
2951
2672
            return Branch.reference_parent(self, file_id, path,
2952
2673
                                           possible_transports)
2953
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2674
        branch_location = urlutils.join(self.base, branch_location)
2954
2675
        return Branch.open(branch_location,
2955
2676
                           possible_transports=possible_transports)
2956
2677
 
3002
2723
        return stacked_url
3003
2724
 
3004
2725
    def _get_append_revisions_only(self):
3005
 
        return self.get_config(
3006
 
            ).get_user_option_as_bool('append_revisions_only')
 
2726
        value = self.get_config().get_user_option('append_revisions_only')
 
2727
        return value == 'True'
3007
2728
 
3008
2729
    @needs_write_lock
3009
2730
    def generate_revision_history(self, revision_id, last_rev=None,
3071
2792
    """
3072
2793
 
3073
2794
    def get_stacked_on_url(self):
3074
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2795
        raise errors.UnstackableBranchFormat(self._format, self.base)
3075
2796
 
3076
2797
 
3077
2798
######################################################################
3164
2885
        :param verbose: Requests more detailed display of what was checked,
3165
2886
            if any.
3166
2887
        """
3167
 
        note('checked branch %s format %s', self.branch.user_url,
 
2888
        note('checked branch %s format %s', self.branch.base,
3168
2889
            self.branch._format)
3169
2890
        for error in self.errors:
3170
2891
            note('found error:%s', error)
3265
2986
    _optimisers = []
3266
2987
    """The available optimised InterBranch types."""
3267
2988
 
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)
 
2989
    @staticmethod
 
2990
    def _get_branch_formats_to_test():
 
2991
        """Return a tuple with the Branch formats to use when testing."""
 
2992
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3277
2993
 
3278
 
    @needs_write_lock
3279
2994
    def pull(self, overwrite=False, stop_revision=None,
3280
2995
             possible_transports=None, local=False):
3281
2996
        """Mirror source into target branch.
3286
3001
        """
3287
3002
        raise NotImplementedError(self.pull)
3288
3003
 
3289
 
    @needs_write_lock
3290
3004
    def update_revisions(self, stop_revision=None, overwrite=False,
3291
3005
                         graph=None):
3292
3006
        """Pull in new perfect-fit revisions.
3300
3014
        """
3301
3015
        raise NotImplementedError(self.update_revisions)
3302
3016
 
3303
 
    @needs_write_lock
3304
3017
    def push(self, overwrite=False, stop_revision=None,
3305
3018
             _override_hook_source_branch=None):
3306
3019
        """Mirror the source branch into the target branch.
3309
3022
        """
3310
3023
        raise NotImplementedError(self.push)
3311
3024
 
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
3025
 
3322
3026
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
 
3027
    """InterBranch implementation that uses public Branch functions.
 
3028
    """
 
3029
 
 
3030
    @staticmethod
 
3031
    def _get_branch_formats_to_test():
 
3032
        return BranchFormat._default_format, BranchFormat._default_format
 
3033
 
3361
3034
    def update_revisions(self, stop_revision=None, overwrite=False,
3362
3035
        graph=None):
3363
3036
        """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
 
3037
        self.source.lock_read()
 
3038
        try:
 
3039
            other_revno, other_last_revision = self.source.last_revision_info()
 
3040
            stop_revno = None # unknown
 
3041
            if stop_revision is None:
 
3042
                stop_revision = other_last_revision
 
3043
                if _mod_revision.is_null(stop_revision):
 
3044
                    # if there are no commits, we're done.
 
3045
                    return
 
3046
                stop_revno = other_revno
 
3047
 
 
3048
            # what's the current last revision, before we fetch [and change it
 
3049
            # possibly]
 
3050
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3051
            # we fetch here so that we don't process data twice in the common
 
3052
            # case of having something to pull, and so that the check for
 
3053
            # already merged can operate on the just fetched graph, which will
 
3054
            # be cached in memory.
 
3055
            self.target.fetch(self.source, stop_revision)
 
3056
            # Check to see if one is an ancestor of the other
 
3057
            if not overwrite:
 
3058
                if graph is None:
 
3059
                    graph = self.target.repository.get_graph()
 
3060
                if self.target._check_if_descendant_or_diverged(
 
3061
                        stop_revision, last_rev, graph, self.source):
 
3062
                    # stop_revision is a descendant of last_rev, but we aren't
 
3063
                    # overwriting, so we're done.
 
3064
                    return
 
3065
            if stop_revno is None:
 
3066
                if graph is None:
 
3067
                    graph = self.target.repository.get_graph()
 
3068
                this_revno, this_last_revision = \
 
3069
                        self.target.last_revision_info()
 
3070
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3071
                                [(other_last_revision, other_revno),
 
3072
                                 (this_last_revision, this_revno)])
 
3073
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
3074
        finally:
 
3075
            self.source.unlock()
 
3076
 
3401
3077
    def pull(self, overwrite=False, stop_revision=None,
3402
 
             possible_transports=None, run_hooks=True,
 
3078
             possible_transports=None, _hook_master=None, run_hooks=True,
3403
3079
             _override_hook_target=None, local=False):
3404
 
        """Pull from source into self, updating my master if any.
 
3080
        """See Branch.pull.
3405
3081
 
 
3082
        :param _hook_master: Private parameter - set the branch to
 
3083
            be supplied as the master to pull hooks.
3406
3084
        :param run_hooks: Private parameter - if false, this branch
3407
3085
            is being called because it's the master of the primary branch,
3408
3086
            so it should not run its hooks.
 
3087
        :param _override_hook_target: Private parameter - set the branch to be
 
3088
            supplied as the target_branch to pull hooks.
 
3089
        :param local: Only update the local branch, and not the bound branch.
3409
3090
        """
3410
 
        bound_location = self.target.get_bound_location()
3411
 
        if local and not bound_location:
 
3091
        # This type of branch can't be bound.
 
3092
        if local:
3412
3093
            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()
 
3094
        result = PullResult()
 
3095
        result.source_branch = self.source
 
3096
        if _override_hook_target is None:
 
3097
            result.target_branch = self.target
 
3098
        else:
 
3099
            result.target_branch = _override_hook_target
 
3100
        self.source.lock_read()
3418
3101
        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)
 
3102
            # We assume that during 'pull' the target repository is closer than
 
3103
            # the source one.
 
3104
            self.source.update_references(self.target)
 
3105
            graph = self.target.repository.get_graph(self.source.repository)
 
3106
            # TODO: Branch formats should have a flag that indicates 
 
3107
            # that revno's are expensive, and pull() should honor that flag.
 
3108
            # -- JRV20090506
 
3109
            result.old_revno, result.old_revid = \
 
3110
                self.target.last_revision_info()
 
3111
            self.target.update_revisions(self.source, stop_revision,
 
3112
                overwrite=overwrite, graph=graph)
 
3113
            # TODO: The old revid should be specified when merging tags, 
 
3114
            # so a tags implementation that versions tags can only 
 
3115
            # pull in the most recent changes. -- JRV20090506
 
3116
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3117
                overwrite)
 
3118
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3119
            if _hook_master:
 
3120
                result.master_branch = _hook_master
 
3121
                result.local_branch = result.target_branch
 
3122
            else:
 
3123
                result.master_branch = result.target_branch
 
3124
                result.local_branch = None
 
3125
            if run_hooks:
 
3126
                for hook in Branch.hooks['post_pull']:
 
3127
                    hook(result)
3427
3128
        finally:
3428
 
            if master_branch:
3429
 
                master_branch.unlock()
 
3129
            self.source.unlock()
 
3130
        return result
3430
3131
 
3431
3132
    def push(self, overwrite=False, stop_revision=None,
3432
3133
             _override_hook_source_branch=None):
3494
3195
            _run_hooks()
3495
3196
            return result
3496
3197
 
3497
 
    def _pull(self, overwrite=False, stop_revision=None,
3498
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3198
    @classmethod
 
3199
    def is_compatible(self, source, target):
 
3200
        # GenericBranch uses the public API, so always compatible
 
3201
        return True
 
3202
 
 
3203
 
 
3204
class InterToBranch5(GenericInterBranch):
 
3205
 
 
3206
    @staticmethod
 
3207
    def _get_branch_formats_to_test():
 
3208
        return BranchFormat._default_format, BzrBranchFormat5()
 
3209
 
 
3210
    def pull(self, overwrite=False, stop_revision=None,
 
3211
             possible_transports=None, run_hooks=True,
3499
3212
             _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.
 
3213
        """Pull from source into self, updating my master if any.
 
3214
 
3507
3215
        :param run_hooks: Private parameter - if false, this branch
3508
3216
            is being called because it's the master of the primary branch,
3509
3217
            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
3218
        """
3514
 
        # This type of branch can't be bound.
3515
 
        if local:
 
3219
        bound_location = self.target.get_bound_location()
 
3220
        if local and not bound_location:
3516
3221
            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()
 
3222
        master_branch = None
 
3223
        if not local and bound_location and self.source.base != bound_location:
 
3224
            # not pulling from master, so we need to update master.
 
3225
            master_branch = self.target.get_master_branch(possible_transports)
 
3226
            master_branch.lock_write()
3524
3227
        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)
 
3228
            if master_branch:
 
3229
                # pull from source into master.
 
3230
                master_branch.pull(self.source, overwrite, stop_revision,
 
3231
                    run_hooks=False)
 
3232
            return super(InterToBranch5, self).pull(overwrite,
 
3233
                stop_revision, _hook_master=master_branch,
 
3234
                run_hooks=run_hooks,
 
3235
                _override_hook_target=_override_hook_target)
3551
3236
        finally:
3552
 
            self.source.unlock()
3553
 
        return result
 
3237
            if master_branch:
 
3238
                master_branch.unlock()
3554
3239
 
3555
3240
 
3556
3241
InterBranch.register_optimiser(GenericInterBranch)
 
3242
InterBranch.register_optimiser(InterToBranch5)