/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Neil Martinsen-Burrell
  • Date: 2010-09-26 02:27:37 UTC
  • mfrom: (5424 +trunk)
  • mto: This revision was merged to the branch mainline in revision 5461.
  • Revision ID: nmb@wartburg.edu-20100926022737-cj2qvebm2mhpjzak
mergeĀ fromĀ trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
 
1
# Copyright (C) 2005-2010 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,
28
29
        debug,
29
30
        errors,
30
31
        lockdir,
31
32
        lockable_files,
 
33
        remote,
32
34
        repository,
33
35
        revision as _mod_revision,
34
36
        rio,
49
51
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
50
52
from bzrlib.hooks import HookPoint, Hooks
51
53
from bzrlib.inter import InterObject
52
 
from bzrlib.lock import _RelockDebugMixin
 
54
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
53
55
from bzrlib import registry
54
56
from bzrlib.symbol_versioning import (
55
57
    deprecated_in,
63
65
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
64
66
 
65
67
 
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):
 
68
class Branch(controldir.ControlComponent):
79
69
    """Branch holding a history of revisions.
80
70
 
81
 
    base
82
 
        Base directory/url of the branch.
 
71
    :ivar base:
 
72
        Base directory/url of the branch; using control_url and
 
73
        control_transport is more standardized.
83
74
 
84
75
    hooks: An instance of BranchHooks.
85
76
    """
87
78
    # - RBC 20060112
88
79
    base = None
89
80
 
 
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
 
90
89
    def __init__(self, *ignored, **ignored_too):
91
90
        self.tags = self._format.make_tags(self)
92
91
        self._revision_history_cache = None
107
106
        """Activate the branch/repository from url as a fallback repository."""
108
107
        repo = self._get_fallback_repository(url)
109
108
        if repo.has_same_location(self.repository):
110
 
            raise errors.UnstackableLocationError(self.base, url)
 
109
            raise errors.UnstackableLocationError(self.user_url, url)
111
110
        self.repository.add_fallback_repository(repo)
112
111
 
113
112
    def break_lock(self):
167
166
        """
168
167
        control = bzrdir.BzrDir.open(base, _unsupported,
169
168
                                     possible_transports=possible_transports)
170
 
        return control.open_branch(_unsupported)
 
169
        return control.open_branch(unsupported=_unsupported)
171
170
 
172
171
    @staticmethod
173
 
    def open_from_transport(transport, _unsupported=False):
 
172
    def open_from_transport(transport, name=None, _unsupported=False):
174
173
        """Open the branch rooted at transport"""
175
174
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
176
 
        return control.open_branch(_unsupported)
 
175
        return control.open_branch(name=name, unsupported=_unsupported)
177
176
 
178
177
    @staticmethod
179
178
    def open_containing(url, possible_transports=None):
200
199
        return self.supports_tags() and self.tags.get_tag_dict()
201
200
 
202
201
    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
        """
203
209
        return BranchConfig(self)
204
210
 
205
211
    def _get_config(self):
217
223
    def _get_fallback_repository(self, url):
218
224
        """Get the repository we fallback to at url."""
219
225
        url = urlutils.join(self.base, url)
220
 
        a_bzrdir = bzrdir.BzrDir.open(url,
 
226
        a_branch = Branch.open(url,
221
227
            possible_transports=[self.bzrdir.root_transport])
222
 
        return a_bzrdir.open_branch().repository
 
228
        return a_branch.repository
223
229
 
224
230
    def _get_tags_bytes(self):
225
231
        """Get the bytes of a serialised tags dict.
241
247
        if not local and not config.has_explicit_nickname():
242
248
            try:
243
249
                master = self.get_master_branch(possible_transports)
 
250
                if master and self.user_url == master.user_url:
 
251
                    raise errors.RecursiveBind(self.user_url)
244
252
                if master is not None:
245
253
                    # return the master branch value
246
254
                    return master.nick
 
255
            except errors.RecursiveBind, e:
 
256
                raise e
247
257
            except errors.BzrError, e:
248
258
                # Silently fall back to local implicit nick if the master is
249
259
                # unavailable
286
296
        new_history.reverse()
287
297
        return new_history
288
298
 
289
 
    def lock_write(self):
 
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
        """
290
306
        raise NotImplementedError(self.lock_write)
291
307
 
292
308
    def lock_read(self):
 
309
        """Lock the branch for read operations.
 
310
 
 
311
        :return: A bzrlib.lock.LogicalLockResult.
 
312
        """
293
313
        raise NotImplementedError(self.lock_read)
294
314
 
295
315
    def unlock(self):
420
440
            * 'include' - the stop revision is the last item in the result
421
441
            * 'with-merges' - include the stop revision and all of its
422
442
              merged revisions in the result
 
443
            * 'with-merges-without-common-ancestry' - filter out revisions 
 
444
              that are in both ancestries
423
445
        :param direction: either 'reverse' or 'forward':
424
446
            * reverse means return the start_revision_id first, i.e.
425
447
              start at the most recent revision and go backwards in history
447
469
        # start_revision_id.
448
470
        if self._merge_sorted_revisions_cache is None:
449
471
            last_revision = self.last_revision()
450
 
            last_key = (last_revision,)
451
 
            known_graph = self.repository.revisions.get_known_graph_ancestry(
452
 
                [last_key])
 
472
            known_graph = self.repository.get_known_graph_ancestry(
 
473
                [last_revision])
453
474
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
454
 
                last_key)
 
475
                last_revision)
455
476
        filtered = self._filter_merge_sorted_revisions(
456
477
            self._merge_sorted_revisions_cache, start_revision_id,
457
478
            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)
458
482
        if direction == 'reverse':
459
483
            return filtered
460
484
        if direction == 'forward':
497
521
                       node.end_of_merge)
498
522
                if rev_id == stop_revision_id:
499
523
                    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)
500
536
        elif stop_rule == 'with-merges':
501
537
            stop_rev = self.repository.get_revision(stop_revision_id)
502
538
            if stop_rev.parent_ids:
525
561
        else:
526
562
            raise ValueError('invalid stop_rule %r' % stop_rule)
527
563
 
 
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
 
528
609
    def leave_lock_in_place(self):
529
610
        """Tell this branch object not to release the physical lock when this
530
611
        object is unlocked.
547
628
        :param other: The branch to bind to
548
629
        :type other: Branch
549
630
        """
550
 
        raise errors.UpgradeRequired(self.base)
 
631
        raise errors.UpgradeRequired(self.user_url)
551
632
 
552
633
    def set_append_revisions_only(self, enabled):
553
634
        if not self._format.supports_set_append_revisions_only():
554
 
            raise errors.UpgradeRequired(self.base)
 
635
            raise errors.UpgradeRequired(self.user_url)
555
636
        if enabled:
556
637
            value = 'True'
557
638
        else:
605
686
    def get_old_bound_location(self):
606
687
        """Return the URL of the branch we used to be bound to
607
688
        """
608
 
        raise errors.UpgradeRequired(self.base)
 
689
        raise errors.UpgradeRequired(self.user_url)
609
690
 
610
691
    def get_commit_builder(self, parents, config=None, timestamp=None,
611
692
                           timezone=None, committer=None, revprops=None,
689
770
            stacking.
690
771
        """
691
772
        if not self._format.supports_stacking():
692
 
            raise errors.UnstackableBranchFormat(self._format, self.base)
 
773
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
693
774
        # XXX: Changing from one fallback repository to another does not check
694
775
        # that all the data you need is present in the new fallback.
695
776
        # Possibly it should.
725
806
            if len(old_repository._fallback_repositories) != 1:
726
807
                raise AssertionError("can't cope with fallback repositories "
727
808
                    "of %r" % (self.repository,))
728
 
            # unlock it, including unlocking the fallback
 
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()
729
836
            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):
 
855
                self.repository.lock_write()
 
856
            # Fetch from the old repository into the new.
730
857
            old_repository.lock_read()
731
858
            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
749
 
                self.repository.lock_write()
750
859
                # XXX: If you unstack a branch while it has a working tree
751
860
                # with a pending merge, the pending-merged revisions will no
752
861
                # longer be present.  You can (probably) revert and remerge.
846
955
 
847
956
    def unbind(self):
848
957
        """Older format branches cannot bind or unbind."""
849
 
        raise errors.UpgradeRequired(self.base)
 
958
        raise errors.UpgradeRequired(self.user_url)
850
959
 
851
960
    def last_revision(self):
852
961
        """Return last revision id, or NULL_REVISION."""
893
1002
                raise errors.NoSuchRevision(self, stop_revision)
894
1003
        return other_history[self_len:stop_revision]
895
1004
 
896
 
    @needs_write_lock
897
1005
    def update_revisions(self, other, stop_revision=None, overwrite=False,
898
1006
                         graph=None):
899
1007
        """Pull in new perfect-fit revisions.
948
1056
            self._extend_partial_history(distance_from_last)
949
1057
        return self._partial_revision_history_cache[distance_from_last]
950
1058
 
951
 
    @needs_write_lock
952
1059
    def pull(self, source, overwrite=False, stop_revision=None,
953
1060
             possible_transports=None, *args, **kwargs):
954
1061
        """Mirror source into this branch.
1012
1119
        try:
1013
1120
            return urlutils.join(self.base[:-1], parent)
1014
1121
        except errors.InvalidURLJoin, e:
1015
 
            raise errors.InaccessibleParent(parent, self.base)
 
1122
            raise errors.InaccessibleParent(parent, self.user_url)
1016
1123
 
1017
1124
    def _get_parent_location(self):
1018
1125
        raise NotImplementedError(self._get_parent_location)
1197
1304
                revno = 1
1198
1305
        destination.set_last_revision_info(revno, revision_id)
1199
1306
 
1200
 
    @needs_read_lock
1201
1307
    def copy_content_into(self, destination, revision_id=None):
1202
1308
        """Copy the content of self into destination.
1203
1309
 
1204
1310
        revision_id: if not None, the revision history in the new branch will
1205
1311
                     be truncated to end with revision_id.
1206
1312
        """
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)
 
1313
        return InterBranch.get(self, destination).copy_content_into(
 
1314
            revision_id=revision_id)
1218
1315
 
1219
1316
    def update_references(self, target):
1220
1317
        if not getattr(self._format, 'supports_reference_locations', False):
1288
1385
        """
1289
1386
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1290
1387
        # 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
1291
1390
        if revision_id is None:
1292
1391
            revision_id = self.last_revision()
1293
1392
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1317
1416
        if lightweight:
1318
1417
            format = self._get_checkout_format()
1319
1418
            checkout = format.initialize_on_transport(t)
1320
 
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
1419
            from_branch = BranchReferenceFormat().initialize(checkout, 
 
1420
                target_branch=self)
1321
1421
        else:
1322
1422
            format = self._get_checkout_format()
1323
1423
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1365
1465
    def supports_tags(self):
1366
1466
        return self._format.supports_tags()
1367
1467
 
 
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
 
1368
1480
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1369
1481
                                         other_branch):
1370
1482
        """Ensure that revision_b is a descendant of revision_a.
1434
1546
        return not (self == other)
1435
1547
 
1436
1548
    @classmethod
1437
 
    def find_format(klass, a_bzrdir):
 
1549
    def find_format(klass, a_bzrdir, name=None):
1438
1550
        """Return the format for the branch object in a_bzrdir."""
1439
1551
        try:
1440
 
            transport = a_bzrdir.get_branch_transport(None)
 
1552
            transport = a_bzrdir.get_branch_transport(None, name=name)
1441
1553
            format_string = transport.get_bytes("format")
1442
 
            return klass._formats[format_string]
 
1554
            format = klass._formats[format_string]
 
1555
            if isinstance(format, MetaDirBranchFormatFactory):
 
1556
                return format()
 
1557
            return format
1443
1558
        except errors.NoSuchFile:
1444
1559
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1445
1560
        except KeyError:
1450
1565
        """Return the current default format."""
1451
1566
        return klass._default_format
1452
1567
 
1453
 
    def get_reference(self, a_bzrdir):
 
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):
1454
1583
        """Get the target reference of the branch in a_bzrdir.
1455
1584
 
1456
1585
        format probing must have been completed before calling
1458
1587
        in a_bzrdir is correct.
1459
1588
 
1460
1589
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1590
        :param name: Name of the colocated branch to fetch
1461
1591
        :return: None if the branch is not a reference branch.
1462
1592
        """
1463
1593
        return None
1464
1594
 
1465
1595
    @classmethod
1466
 
    def set_reference(self, a_bzrdir, to_branch):
 
1596
    def set_reference(self, a_bzrdir, name, to_branch):
1467
1597
        """Set the target reference of the branch in a_bzrdir.
1468
1598
 
1469
1599
        format probing must have been completed before calling
1471
1601
        in a_bzrdir is correct.
1472
1602
 
1473
1603
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1604
        :param name: Name of colocated branch to set, None for default
1474
1605
        :param to_branch: branch that the checkout is to reference
1475
1606
        """
1476
1607
        raise NotImplementedError(self.set_reference)
1483
1614
        """Return the short format description for this format."""
1484
1615
        raise NotImplementedError(self.get_format_description)
1485
1616
 
1486
 
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1487
 
                           set_format=True):
 
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):
1488
1627
        """Initialize a branch in a bzrdir, with specified files
1489
1628
 
1490
1629
        :param a_bzrdir: The bzrdir to initialize the branch in
1491
1630
        :param utf8_files: The files to create as a list of
1492
1631
            (filename, content) tuples
 
1632
        :param name: Name of colocated branch to create, if any
1493
1633
        :param set_format: If True, set the format with
1494
1634
            self.get_format_string.  (BzrBranch4 has its format set
1495
1635
            elsewhere)
1496
1636
        :return: a branch in this format
1497
1637
        """
1498
 
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1499
 
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1638
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1639
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1500
1640
        lock_map = {
1501
1641
            'metadir': ('lock', lockdir.LockDir),
1502
1642
            'branch4': ('branch-lock', lockable_files.TransportLock),
1523
1663
        finally:
1524
1664
            if lock_taken:
1525
1665
                control_files.unlock()
1526
 
        return self.open(a_bzrdir, _found=True)
 
1666
        branch = self.open(a_bzrdir, name, _found=True)
 
1667
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1668
        return branch
1527
1669
 
1528
 
    def initialize(self, a_bzrdir):
1529
 
        """Create a branch of this format in a_bzrdir."""
 
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
        """
1530
1675
        raise NotImplementedError(self.initialize)
1531
1676
 
1532
1677
    def is_supported(self):
1562
1707
        """
1563
1708
        raise NotImplementedError(self.network_name)
1564
1709
 
1565
 
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1710
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1566
1711
        """Return the branch object for a_bzrdir
1567
1712
 
1568
1713
        :param a_bzrdir: A BzrDir that contains a branch.
 
1714
        :param name: Name of colocated branch to open
1569
1715
        :param _found: a private parameter, do not use it. It is used to
1570
1716
            indicate if format probing has already be done.
1571
1717
        :param ignore_fallbacks: when set, no fallback branches will be opened
1575
1721
 
1576
1722
    @classmethod
1577
1723
    def register_format(klass, format):
1578
 
        """Register a metadir 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
        """
1579
1729
        klass._formats[format.get_format_string()] = format
1580
1730
        # Metadir formats have a network name of their format string, and get
1581
 
        # registered as class factories.
1582
 
        network_format_registry.register(format.get_format_string(), format.__class__)
 
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__)
1583
1737
 
1584
1738
    @classmethod
1585
1739
    def set_default_format(klass, format):
1605
1759
        return False  # by default
1606
1760
 
1607
1761
 
 
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
 
1608
1790
class BranchHooks(Hooks):
1609
1791
    """A dictionary mapping hook name to a list of callables for branch hooks.
1610
1792
 
1679
1861
            "multiple hooks installed for transform_fallback_location, "
1680
1862
            "all are called with the url returned from the previous hook."
1681
1863
            "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
 
1682
1881
 
1683
1882
 
1684
1883
# install the default hooks into the Branch class.
1723
1922
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1724
1923
 
1725
1924
 
 
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
 
1726
1998
class BzrBranchFormat4(BranchFormat):
1727
1999
    """Bzr branch format 4.
1728
2000
 
1735
2007
        """See BranchFormat.get_format_description()."""
1736
2008
        return "Branch format 4"
1737
2009
 
1738
 
    def initialize(self, a_bzrdir):
 
2010
    def initialize(self, a_bzrdir, name=None):
1739
2011
        """Create a branch of this format in a_bzrdir."""
1740
2012
        utf8_files = [('revision-history', ''),
1741
2013
                      ('branch-name', ''),
1742
2014
                      ]
1743
 
        return self._initialize_helper(a_bzrdir, utf8_files,
 
2015
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1744
2016
                                       lock_type='branch4', set_format=False)
1745
2017
 
1746
2018
    def __init__(self):
1751
2023
        """The network name for this format is the control dirs disk label."""
1752
2024
        return self._matchingbzrdir.get_format_string()
1753
2025
 
1754
 
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
2026
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1755
2027
        """See BranchFormat.open()."""
1756
2028
        if not _found:
1757
2029
            # we are being called directly and must probe.
1759
2031
        return BzrBranch(_format=self,
1760
2032
                         _control_files=a_bzrdir._control_files,
1761
2033
                         a_bzrdir=a_bzrdir,
 
2034
                         name=name,
1762
2035
                         _repository=a_bzrdir.open_repository())
1763
2036
 
1764
2037
    def __str__(self):
1779
2052
        """
1780
2053
        return self.get_format_string()
1781
2054
 
1782
 
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
2055
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1783
2056
        """See BranchFormat.open()."""
1784
2057
        if not _found:
1785
 
            format = BranchFormat.find_format(a_bzrdir)
 
2058
            format = BranchFormat.find_format(a_bzrdir, name=name)
1786
2059
            if format.__class__ != self.__class__:
1787
2060
                raise AssertionError("wrong format %r found for %r" %
1788
2061
                    (format, self))
 
2062
        transport = a_bzrdir.get_branch_transport(None, name=name)
1789
2063
        try:
1790
 
            transport = a_bzrdir.get_branch_transport(None)
1791
2064
            control_files = lockable_files.LockableFiles(transport, 'lock',
1792
2065
                                                         lockdir.LockDir)
1793
2066
            return self._branch_class()(_format=self,
1794
2067
                              _control_files=control_files,
 
2068
                              name=name,
1795
2069
                              a_bzrdir=a_bzrdir,
1796
2070
                              _repository=a_bzrdir.find_repository(),
1797
2071
                              ignore_fallbacks=ignore_fallbacks)
1831
2105
        """See BranchFormat.get_format_description()."""
1832
2106
        return "Branch format 5"
1833
2107
 
1834
 
    def initialize(self, a_bzrdir):
 
2108
    def initialize(self, a_bzrdir, name=None):
1835
2109
        """Create a branch of this format in a_bzrdir."""
1836
2110
        utf8_files = [('revision-history', ''),
1837
2111
                      ('branch-name', ''),
1838
2112
                      ]
1839
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2113
        return self._initialize_helper(a_bzrdir, utf8_files, name)
1840
2114
 
1841
2115
    def supports_tags(self):
1842
2116
        return False
1864
2138
        """See BranchFormat.get_format_description()."""
1865
2139
        return "Branch format 6"
1866
2140
 
1867
 
    def initialize(self, a_bzrdir):
 
2141
    def initialize(self, a_bzrdir, name=None):
1868
2142
        """Create a branch of this format in a_bzrdir."""
1869
2143
        utf8_files = [('last-revision', '0 null:\n'),
1870
2144
                      ('branch.conf', ''),
1871
2145
                      ('tags', ''),
1872
2146
                      ]
1873
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2147
        return self._initialize_helper(a_bzrdir, utf8_files, name)
1874
2148
 
1875
2149
    def make_tags(self, branch):
1876
2150
        """See bzrlib.branch.BranchFormat.make_tags()."""
1894
2168
        """See BranchFormat.get_format_description()."""
1895
2169
        return "Branch format 8"
1896
2170
 
1897
 
    def initialize(self, a_bzrdir):
 
2171
    def initialize(self, a_bzrdir, name=None):
1898
2172
        """Create a branch of this format in a_bzrdir."""
1899
2173
        utf8_files = [('last-revision', '0 null:\n'),
1900
2174
                      ('branch.conf', ''),
1901
2175
                      ('tags', ''),
1902
2176
                      ('references', '')
1903
2177
                      ]
1904
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2178
        return self._initialize_helper(a_bzrdir, utf8_files, name)
1905
2179
 
1906
2180
    def __init__(self):
1907
2181
        super(BzrBranchFormat8, self).__init__()
1930
2204
    This format was introduced in bzr 1.6.
1931
2205
    """
1932
2206
 
1933
 
    def initialize(self, a_bzrdir):
 
2207
    def initialize(self, a_bzrdir, name=None):
1934
2208
        """Create a branch of this format in a_bzrdir."""
1935
2209
        utf8_files = [('last-revision', '0 null:\n'),
1936
2210
                      ('branch.conf', ''),
1937
2211
                      ('tags', ''),
1938
2212
                      ]
1939
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2213
        return self._initialize_helper(a_bzrdir, utf8_files, name)
1940
2214
 
1941
2215
    def _branch_class(self):
1942
2216
        return BzrBranch7
1974
2248
        """See BranchFormat.get_format_description()."""
1975
2249
        return "Checkout reference format 1"
1976
2250
 
1977
 
    def get_reference(self, a_bzrdir):
 
2251
    def get_reference(self, a_bzrdir, name=None):
1978
2252
        """See BranchFormat.get_reference()."""
1979
 
        transport = a_bzrdir.get_branch_transport(None)
 
2253
        transport = a_bzrdir.get_branch_transport(None, name=name)
1980
2254
        return transport.get_bytes('location')
1981
2255
 
1982
 
    def set_reference(self, a_bzrdir, to_branch):
 
2256
    def set_reference(self, a_bzrdir, name, to_branch):
1983
2257
        """See BranchFormat.set_reference()."""
1984
 
        transport = a_bzrdir.get_branch_transport(None)
 
2258
        transport = a_bzrdir.get_branch_transport(None, name=name)
1985
2259
        location = transport.put_bytes('location', to_branch.base)
1986
2260
 
1987
 
    def initialize(self, a_bzrdir, target_branch=None):
 
2261
    def initialize(self, a_bzrdir, name=None, target_branch=None):
1988
2262
        """Create a branch of this format in a_bzrdir."""
1989
2263
        if target_branch is None:
1990
2264
            # this format does not implement branch itself, thus the implicit
1991
2265
            # creation contract must see it as uninitializable
1992
2266
            raise errors.UninitializableFormat(self)
1993
 
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
1994
 
        branch_transport = a_bzrdir.get_branch_transport(self)
 
2267
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2268
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1995
2269
        branch_transport.put_bytes('location',
1996
 
            target_branch.bzrdir.root_transport.base)
 
2270
            target_branch.bzrdir.user_url)
1997
2271
        branch_transport.put_bytes('format', self.get_format_string())
1998
 
        return self.open(
1999
 
            a_bzrdir, _found=True,
 
2272
        branch = self.open(
 
2273
            a_bzrdir, name, _found=True,
2000
2274
            possible_transports=[target_branch.bzrdir.root_transport])
 
2275
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2276
        return branch
2001
2277
 
2002
2278
    def __init__(self):
2003
2279
        super(BranchReferenceFormat, self).__init__()
2009
2285
        def clone(to_bzrdir, revision_id=None,
2010
2286
            repository_policy=None):
2011
2287
            """See Branch.clone()."""
2012
 
            return format.initialize(to_bzrdir, a_branch)
 
2288
            return format.initialize(to_bzrdir, target_branch=a_branch)
2013
2289
            # cannot obey revision_id limits when cloning a reference ...
2014
2290
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2015
2291
            # emit some sort of warning/error to the caller ?!
2016
2292
        return clone
2017
2293
 
2018
 
    def open(self, a_bzrdir, _found=False, location=None,
 
2294
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2019
2295
             possible_transports=None, ignore_fallbacks=False):
2020
2296
        """Return the branch that the branch reference in a_bzrdir points at.
2021
2297
 
2022
2298
        :param a_bzrdir: A BzrDir that contains a branch.
 
2299
        :param name: Name of colocated branch to open, if any
2023
2300
        :param _found: a private parameter, do not use it. It is used to
2024
2301
            indicate if format probing has already be done.
2025
2302
        :param ignore_fallbacks: when set, no fallback branches will be opened
2030
2307
        :param possible_transports: An optional reusable transports list.
2031
2308
        """
2032
2309
        if not _found:
2033
 
            format = BranchFormat.find_format(a_bzrdir)
 
2310
            format = BranchFormat.find_format(a_bzrdir, name=name)
2034
2311
            if format.__class__ != self.__class__:
2035
2312
                raise AssertionError("wrong format %r found for %r" %
2036
2313
                    (format, self))
2037
2314
        if location is None:
2038
 
            location = self.get_reference(a_bzrdir)
 
2315
            location = self.get_reference(a_bzrdir, name)
2039
2316
        real_bzrdir = bzrdir.BzrDir.open(
2040
2317
            location, possible_transports=possible_transports)
2041
 
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
 
2318
        result = real_bzrdir.open_branch(name=name, 
 
2319
            ignore_fallbacks=ignore_fallbacks)
2042
2320
        # this changes the behaviour of result.clone to create a new reference
2043
2321
        # rather than a copy of the content of the branch.
2044
2322
        # I did not use a proxy object because that needs much more extensive
2078
2356
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2079
2357
 
2080
2358
 
 
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
 
2081
2376
class BzrBranch(Branch, _RelockDebugMixin):
2082
2377
    """A branch stored in the actual filesystem.
2083
2378
 
2090
2385
    :ivar repository: Repository for this branch.
2091
2386
    :ivar base: The url of the base directory for this branch; the one
2092
2387
        containing the .bzr directory.
 
2388
    :ivar name: Optional colocated branch name as it exists in the control
 
2389
        directory.
2093
2390
    """
2094
2391
 
2095
2392
    def __init__(self, _format=None,
2096
 
                 _control_files=None, a_bzrdir=None, _repository=None,
2097
 
                 ignore_fallbacks=False):
 
2393
                 _control_files=None, a_bzrdir=None, name=None,
 
2394
                 _repository=None, ignore_fallbacks=False):
2098
2395
        """Create new branch object at a particular location."""
2099
2396
        if a_bzrdir is None:
2100
2397
            raise ValueError('a_bzrdir must be supplied')
2101
2398
        else:
2102
2399
            self.bzrdir = a_bzrdir
2103
2400
        self._base = self.bzrdir.transport.clone('..').base
 
2401
        self.name = name
2104
2402
        # XXX: We should be able to just do
2105
2403
        #   self.base = self.bzrdir.root_transport.base
2106
2404
        # but this does not quite work yet -- mbp 20080522
2113
2411
        Branch.__init__(self)
2114
2412
 
2115
2413
    def __str__(self):
2116
 
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
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)
2117
2419
 
2118
2420
    __repr__ = __str__
2119
2421
 
2130
2432
        return self.control_files.is_locked()
2131
2433
 
2132
2434
    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
        """
2133
2441
        if not self.is_locked():
2134
2442
            self._note_lock('w')
2135
2443
        # All-in-one needs to always unlock/lock.
2141
2449
        else:
2142
2450
            took_lock = False
2143
2451
        try:
2144
 
            return self.control_files.lock_write(token=token)
 
2452
            return BranchWriteLockResult(self.unlock,
 
2453
                self.control_files.lock_write(token=token))
2145
2454
        except:
2146
2455
            if took_lock:
2147
2456
                self.repository.unlock()
2148
2457
            raise
2149
2458
 
2150
2459
    def lock_read(self):
 
2460
        """Lock the branch for read operations.
 
2461
 
 
2462
        :return: A bzrlib.lock.LogicalLockResult.
 
2463
        """
2151
2464
        if not self.is_locked():
2152
2465
            self._note_lock('r')
2153
2466
        # All-in-one needs to always unlock/lock.
2160
2473
            took_lock = False
2161
2474
        try:
2162
2475
            self.control_files.lock_read()
 
2476
            return LogicalLockResult(self.unlock)
2163
2477
        except:
2164
2478
            if took_lock:
2165
2479
                self.repository.unlock()
2334
2648
        return result
2335
2649
 
2336
2650
    def get_stacked_on_url(self):
2337
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2651
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2338
2652
 
2339
2653
    def set_push_location(self, location):
2340
2654
        """See Branch.set_push_location."""
2530
2844
        if _mod_revision.is_null(last_revision):
2531
2845
            return
2532
2846
        if last_revision not in self._lefthand_history(revision_id):
2533
 
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
2847
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2534
2848
 
2535
2849
    def _gen_revision_history(self):
2536
2850
        """Generate the revision history from last revision
2636
2950
        if branch_location is None:
2637
2951
            return Branch.reference_parent(self, file_id, path,
2638
2952
                                           possible_transports)
2639
 
        branch_location = urlutils.join(self.base, branch_location)
 
2953
        branch_location = urlutils.join(self.user_url, branch_location)
2640
2954
        return Branch.open(branch_location,
2641
2955
                           possible_transports=possible_transports)
2642
2956
 
2688
3002
        return stacked_url
2689
3003
 
2690
3004
    def _get_append_revisions_only(self):
2691
 
        value = self.get_config().get_user_option('append_revisions_only')
2692
 
        return value == 'True'
 
3005
        return self.get_config(
 
3006
            ).get_user_option_as_bool('append_revisions_only')
2693
3007
 
2694
3008
    @needs_write_lock
2695
3009
    def generate_revision_history(self, revision_id, last_rev=None,
2757
3071
    """
2758
3072
 
2759
3073
    def get_stacked_on_url(self):
2760
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
3074
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2761
3075
 
2762
3076
 
2763
3077
######################################################################
2789
3103
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2790
3104
    """
2791
3105
 
 
3106
    @deprecated_method(deprecated_in((2, 3, 0)))
2792
3107
    def __int__(self):
2793
 
        # DEPRECATED: pull used to return the change in revno
 
3108
        """Return the relative change in revno.
 
3109
 
 
3110
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3111
        """
2794
3112
        return self.new_revno - self.old_revno
2795
3113
 
2796
3114
    def report(self, to_file):
2821
3139
        target, otherwise it will be None.
2822
3140
    """
2823
3141
 
 
3142
    @deprecated_method(deprecated_in((2, 3, 0)))
2824
3143
    def __int__(self):
2825
 
        # DEPRECATED: push used to return the change in revno
 
3144
        """Return the relative change in revno.
 
3145
 
 
3146
        :deprecated: Use `new_revno` and `old_revno` instead.
 
3147
        """
2826
3148
        return self.new_revno - self.old_revno
2827
3149
 
2828
3150
    def report(self, to_file):
2850
3172
        :param verbose: Requests more detailed display of what was checked,
2851
3173
            if any.
2852
3174
        """
2853
 
        note('checked branch %s format %s', self.branch.base,
 
3175
        note('checked branch %s format %s', self.branch.user_url,
2854
3176
            self.branch._format)
2855
3177
        for error in self.errors:
2856
3178
            note('found error:%s', error)
2951
3273
    _optimisers = []
2952
3274
    """The available optimised InterBranch types."""
2953
3275
 
2954
 
    @staticmethod
2955
 
    def _get_branch_formats_to_test():
2956
 
        """Return a tuple with the Branch formats to use when testing."""
2957
 
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3276
    @classmethod
 
3277
    def _get_branch_formats_to_test(klass):
 
3278
        """Return an iterable of format tuples for testing.
 
3279
        
 
3280
        :return: An iterable of (from_format, to_format) to use when testing
 
3281
            this InterBranch class. Each InterBranch class should define this
 
3282
            method itself.
 
3283
        """
 
3284
        raise NotImplementedError(klass._get_branch_formats_to_test)
2958
3285
 
 
3286
    @needs_write_lock
2959
3287
    def pull(self, overwrite=False, stop_revision=None,
2960
3288
             possible_transports=None, local=False):
2961
3289
        """Mirror source into target branch.
2966
3294
        """
2967
3295
        raise NotImplementedError(self.pull)
2968
3296
 
 
3297
    @needs_write_lock
2969
3298
    def update_revisions(self, stop_revision=None, overwrite=False,
2970
3299
                         graph=None):
2971
3300
        """Pull in new perfect-fit revisions.
2979
3308
        """
2980
3309
        raise NotImplementedError(self.update_revisions)
2981
3310
 
 
3311
    @needs_write_lock
2982
3312
    def push(self, overwrite=False, stop_revision=None,
2983
3313
             _override_hook_source_branch=None):
2984
3314
        """Mirror the source branch into the target branch.
2987
3317
        """
2988
3318
        raise NotImplementedError(self.push)
2989
3319
 
 
3320
    @needs_write_lock
 
3321
    def copy_content_into(self, revision_id=None):
 
3322
        """Copy the content of source into target
 
3323
 
 
3324
        revision_id: if not None, the revision history in the new branch will
 
3325
                     be truncated to end with revision_id.
 
3326
        """
 
3327
        raise NotImplementedError(self.copy_content_into)
 
3328
 
2990
3329
 
2991
3330
class GenericInterBranch(InterBranch):
2992
 
    """InterBranch implementation that uses public Branch functions.
2993
 
    """
2994
 
 
2995
 
    @staticmethod
2996
 
    def _get_branch_formats_to_test():
2997
 
        return BranchFormat._default_format, BranchFormat._default_format
2998
 
 
 
3331
    """InterBranch implementation that uses public Branch functions."""
 
3332
 
 
3333
    @classmethod
 
3334
    def is_compatible(klass, source, target):
 
3335
        # GenericBranch uses the public API, so always compatible
 
3336
        return True
 
3337
 
 
3338
    @classmethod
 
3339
    def _get_branch_formats_to_test(klass):
 
3340
        return [(BranchFormat._default_format, BranchFormat._default_format)]
 
3341
 
 
3342
    @classmethod
 
3343
    def unwrap_format(klass, format):
 
3344
        if isinstance(format, remote.RemoteBranchFormat):
 
3345
            format._ensure_real()
 
3346
            return format._custom_format
 
3347
        return format                                                                                                  
 
3348
 
 
3349
    @needs_write_lock
 
3350
    def copy_content_into(self, revision_id=None):
 
3351
        """Copy the content of source into target
 
3352
 
 
3353
        revision_id: if not None, the revision history in the new branch will
 
3354
                     be truncated to end with revision_id.
 
3355
        """
 
3356
        self.source.update_references(self.target)
 
3357
        self.source._synchronize_history(self.target, revision_id)
 
3358
        try:
 
3359
            parent = self.source.get_parent()
 
3360
        except errors.InaccessibleParent, e:
 
3361
            mutter('parent was not accessible to copy: %s', e)
 
3362
        else:
 
3363
            if parent:
 
3364
                self.target.set_parent(parent)
 
3365
        if self.source._push_should_merge_tags():
 
3366
            self.source.tags.merge_to(self.target.tags)
 
3367
 
 
3368
    @needs_write_lock
2999
3369
    def update_revisions(self, stop_revision=None, overwrite=False,
3000
3370
        graph=None):
3001
3371
        """See InterBranch.update_revisions()."""
3002
 
        self.source.lock_read()
3003
 
        try:
3004
 
            other_revno, other_last_revision = self.source.last_revision_info()
3005
 
            stop_revno = None # unknown
3006
 
            if stop_revision is None:
3007
 
                stop_revision = other_last_revision
3008
 
                if _mod_revision.is_null(stop_revision):
3009
 
                    # if there are no commits, we're done.
3010
 
                    return
3011
 
                stop_revno = other_revno
3012
 
 
3013
 
            # what's the current last revision, before we fetch [and change it
3014
 
            # possibly]
3015
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
3016
 
            # we fetch here so that we don't process data twice in the common
3017
 
            # case of having something to pull, and so that the check for
3018
 
            # already merged can operate on the just fetched graph, which will
3019
 
            # be cached in memory.
3020
 
            self.target.fetch(self.source, stop_revision)
3021
 
            # Check to see if one is an ancestor of the other
3022
 
            if not overwrite:
3023
 
                if graph is None:
3024
 
                    graph = self.target.repository.get_graph()
3025
 
                if self.target._check_if_descendant_or_diverged(
3026
 
                        stop_revision, last_rev, graph, self.source):
3027
 
                    # stop_revision is a descendant of last_rev, but we aren't
3028
 
                    # overwriting, so we're done.
3029
 
                    return
3030
 
            if stop_revno is None:
3031
 
                if graph is None:
3032
 
                    graph = self.target.repository.get_graph()
3033
 
                this_revno, this_last_revision = \
3034
 
                        self.target.last_revision_info()
3035
 
                stop_revno = graph.find_distance_to_null(stop_revision,
3036
 
                                [(other_last_revision, other_revno),
3037
 
                                 (this_last_revision, this_revno)])
3038
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
3039
 
        finally:
3040
 
            self.source.unlock()
3041
 
 
 
3372
        other_revno, other_last_revision = self.source.last_revision_info()
 
3373
        stop_revno = None # unknown
 
3374
        if stop_revision is None:
 
3375
            stop_revision = other_last_revision
 
3376
            if _mod_revision.is_null(stop_revision):
 
3377
                # if there are no commits, we're done.
 
3378
                return
 
3379
            stop_revno = other_revno
 
3380
 
 
3381
        # what's the current last revision, before we fetch [and change it
 
3382
        # possibly]
 
3383
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3384
        # we fetch here so that we don't process data twice in the common
 
3385
        # case of having something to pull, and so that the check for
 
3386
        # already merged can operate on the just fetched graph, which will
 
3387
        # be cached in memory.
 
3388
        self.target.fetch(self.source, stop_revision)
 
3389
        # Check to see if one is an ancestor of the other
 
3390
        if not overwrite:
 
3391
            if graph is None:
 
3392
                graph = self.target.repository.get_graph()
 
3393
            if self.target._check_if_descendant_or_diverged(
 
3394
                    stop_revision, last_rev, graph, self.source):
 
3395
                # stop_revision is a descendant of last_rev, but we aren't
 
3396
                # overwriting, so we're done.
 
3397
                return
 
3398
        if stop_revno is None:
 
3399
            if graph is None:
 
3400
                graph = self.target.repository.get_graph()
 
3401
            this_revno, this_last_revision = \
 
3402
                    self.target.last_revision_info()
 
3403
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3404
                            [(other_last_revision, other_revno),
 
3405
                             (this_last_revision, this_revno)])
 
3406
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3407
 
 
3408
    @needs_write_lock
3042
3409
    def pull(self, overwrite=False, stop_revision=None,
3043
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3410
             possible_transports=None, run_hooks=True,
3044
3411
             _override_hook_target=None, local=False):
3045
 
        """See Branch.pull.
 
3412
        """Pull from source into self, updating my master if any.
3046
3413
 
3047
 
        :param _hook_master: Private parameter - set the branch to
3048
 
            be supplied as the master to pull hooks.
3049
3414
        :param run_hooks: Private parameter - if false, this branch
3050
3415
            is being called because it's the master of the primary branch,
3051
3416
            so it should not run its hooks.
3052
 
        :param _override_hook_target: Private parameter - set the branch to be
3053
 
            supplied as the target_branch to pull hooks.
3054
 
        :param local: Only update the local branch, and not the bound branch.
3055
3417
        """
3056
 
        # This type of branch can't be bound.
3057
 
        if local:
 
3418
        bound_location = self.target.get_bound_location()
 
3419
        if local and not bound_location:
3058
3420
            raise errors.LocalRequiresBoundBranch()
3059
 
        result = PullResult()
3060
 
        result.source_branch = self.source
3061
 
        if _override_hook_target is None:
3062
 
            result.target_branch = self.target
3063
 
        else:
3064
 
            result.target_branch = _override_hook_target
3065
 
        self.source.lock_read()
 
3421
        master_branch = None
 
3422
        if not local and bound_location and self.source.user_url != bound_location:
 
3423
            # not pulling from master, so we need to update master.
 
3424
            master_branch = self.target.get_master_branch(possible_transports)
 
3425
            master_branch.lock_write()
3066
3426
        try:
3067
 
            # We assume that during 'pull' the target repository is closer than
3068
 
            # the source one.
3069
 
            self.source.update_references(self.target)
3070
 
            graph = self.target.repository.get_graph(self.source.repository)
3071
 
            # TODO: Branch formats should have a flag that indicates 
3072
 
            # that revno's are expensive, and pull() should honor that flag.
3073
 
            # -- JRV20090506
3074
 
            result.old_revno, result.old_revid = \
3075
 
                self.target.last_revision_info()
3076
 
            self.target.update_revisions(self.source, stop_revision,
3077
 
                overwrite=overwrite, graph=graph)
3078
 
            # TODO: The old revid should be specified when merging tags, 
3079
 
            # so a tags implementation that versions tags can only 
3080
 
            # pull in the most recent changes. -- JRV20090506
3081
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3082
 
                overwrite)
3083
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3084
 
            if _hook_master:
3085
 
                result.master_branch = _hook_master
3086
 
                result.local_branch = result.target_branch
3087
 
            else:
3088
 
                result.master_branch = result.target_branch
3089
 
                result.local_branch = None
3090
 
            if run_hooks:
3091
 
                for hook in Branch.hooks['post_pull']:
3092
 
                    hook(result)
 
3427
            if master_branch:
 
3428
                # pull from source into master.
 
3429
                master_branch.pull(self.source, overwrite, stop_revision,
 
3430
                    run_hooks=False)
 
3431
            return self._pull(overwrite,
 
3432
                stop_revision, _hook_master=master_branch,
 
3433
                run_hooks=run_hooks,
 
3434
                _override_hook_target=_override_hook_target)
3093
3435
        finally:
3094
 
            self.source.unlock()
3095
 
        return result
 
3436
            if master_branch:
 
3437
                master_branch.unlock()
3096
3438
 
3097
3439
    def push(self, overwrite=False, stop_revision=None,
3098
3440
             _override_hook_source_branch=None):
3160
3502
            _run_hooks()
3161
3503
            return result
3162
3504
 
3163
 
    @classmethod
3164
 
    def is_compatible(self, source, target):
3165
 
        # GenericBranch uses the public API, so always compatible
3166
 
        return True
3167
 
 
3168
 
 
3169
 
class InterToBranch5(GenericInterBranch):
3170
 
 
3171
 
    @staticmethod
3172
 
    def _get_branch_formats_to_test():
3173
 
        return BranchFormat._default_format, BzrBranchFormat5()
3174
 
 
3175
 
    def pull(self, overwrite=False, stop_revision=None,
3176
 
             possible_transports=None, run_hooks=True,
 
3505
    def _pull(self, overwrite=False, stop_revision=None,
 
3506
             possible_transports=None, _hook_master=None, run_hooks=True,
3177
3507
             _override_hook_target=None, local=False):
3178
 
        """Pull from source into self, updating my master if any.
3179
 
 
 
3508
        """See Branch.pull.
 
3509
 
 
3510
        This function is the core worker, used by GenericInterBranch.pull to
 
3511
        avoid duplication when pulling source->master and source->local.
 
3512
 
 
3513
        :param _hook_master: Private parameter - set the branch to
 
3514
            be supplied as the master to pull hooks.
3180
3515
        :param run_hooks: Private parameter - if false, this branch
3181
3516
            is being called because it's the master of the primary branch,
3182
3517
            so it should not run its hooks.
 
3518
        :param _override_hook_target: Private parameter - set the branch to be
 
3519
            supplied as the target_branch to pull hooks.
 
3520
        :param local: Only update the local branch, and not the bound branch.
3183
3521
        """
3184
 
        bound_location = self.target.get_bound_location()
3185
 
        if local and not bound_location:
 
3522
        # This type of branch can't be bound.
 
3523
        if local:
3186
3524
            raise errors.LocalRequiresBoundBranch()
3187
 
        master_branch = None
3188
 
        if not local and bound_location and self.source.base != bound_location:
3189
 
            # not pulling from master, so we need to update master.
3190
 
            master_branch = self.target.get_master_branch(possible_transports)
3191
 
            master_branch.lock_write()
 
3525
        result = PullResult()
 
3526
        result.source_branch = self.source
 
3527
        if _override_hook_target is None:
 
3528
            result.target_branch = self.target
 
3529
        else:
 
3530
            result.target_branch = _override_hook_target
 
3531
        self.source.lock_read()
3192
3532
        try:
3193
 
            if master_branch:
3194
 
                # pull from source into master.
3195
 
                master_branch.pull(self.source, overwrite, stop_revision,
3196
 
                    run_hooks=False)
3197
 
            return super(InterToBranch5, self).pull(overwrite,
3198
 
                stop_revision, _hook_master=master_branch,
3199
 
                run_hooks=run_hooks,
3200
 
                _override_hook_target=_override_hook_target)
 
3533
            # We assume that during 'pull' the target repository is closer than
 
3534
            # the source one.
 
3535
            self.source.update_references(self.target)
 
3536
            graph = self.target.repository.get_graph(self.source.repository)
 
3537
            # TODO: Branch formats should have a flag that indicates 
 
3538
            # that revno's are expensive, and pull() should honor that flag.
 
3539
            # -- JRV20090506
 
3540
            result.old_revno, result.old_revid = \
 
3541
                self.target.last_revision_info()
 
3542
            self.target.update_revisions(self.source, stop_revision,
 
3543
                overwrite=overwrite, graph=graph)
 
3544
            # TODO: The old revid should be specified when merging tags, 
 
3545
            # so a tags implementation that versions tags can only 
 
3546
            # pull in the most recent changes. -- JRV20090506
 
3547
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3548
                overwrite)
 
3549
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3550
            if _hook_master:
 
3551
                result.master_branch = _hook_master
 
3552
                result.local_branch = result.target_branch
 
3553
            else:
 
3554
                result.master_branch = result.target_branch
 
3555
                result.local_branch = None
 
3556
            if run_hooks:
 
3557
                for hook in Branch.hooks['post_pull']:
 
3558
                    hook(result)
3201
3559
        finally:
3202
 
            if master_branch:
3203
 
                master_branch.unlock()
 
3560
            self.source.unlock()
 
3561
        return result
3204
3562
 
3205
3563
 
3206
3564
InterBranch.register_optimiser(GenericInterBranch)
3207
 
InterBranch.register_optimiser(InterToBranch5)