/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: Vincent Ladeuil
  • Date: 2010-03-01 09:02:18 UTC
  • mto: (5064.1.1 integration)
  • mto: This revision was merged to the branch mainline in revision 5065.
  • Revision ID: v.ladeuil+lp@free.fr-20100301090218-pq3ib5y07dx3wbp6
Delete spurious spaces.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
29
29
        errors,
30
30
        lockdir,
31
31
        lockable_files,
32
 
        remote,
33
32
        repository,
34
33
        revision as _mod_revision,
35
34
        rio,
50
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
51
50
from bzrlib.hooks import HookPoint, Hooks
52
51
from bzrlib.inter import InterObject
53
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
54
53
from bzrlib import registry
55
54
from bzrlib.symbol_versioning import (
56
55
    deprecated_in,
64
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
65
64
 
66
65
 
67
 
class Branch(bzrdir.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):
68
79
    """Branch holding a history of revisions.
69
80
 
70
 
    :ivar base:
71
 
        Base directory/url of the branch; using control_url and
72
 
        control_transport is more standardized.
 
81
    base
 
82
        Base directory/url of the branch.
73
83
 
74
84
    hooks: An instance of BranchHooks.
75
85
    """
77
87
    # - RBC 20060112
78
88
    base = None
79
89
 
80
 
    @property
81
 
    def control_transport(self):
82
 
        return self._transport
83
 
 
84
 
    @property
85
 
    def user_transport(self):
86
 
        return self.bzrdir.user_transport
87
 
 
88
90
    def __init__(self, *ignored, **ignored_too):
89
91
        self.tags = self._format.make_tags(self)
90
92
        self._revision_history_cache = None
105
107
        """Activate the branch/repository from url as a fallback repository."""
106
108
        repo = self._get_fallback_repository(url)
107
109
        if repo.has_same_location(self.repository):
108
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
110
            raise errors.UnstackableLocationError(self.base, url)
109
111
        self.repository.add_fallback_repository(repo)
110
112
 
111
113
    def break_lock(self):
165
167
        """
166
168
        control = bzrdir.BzrDir.open(base, _unsupported,
167
169
                                     possible_transports=possible_transports)
168
 
        return control.open_branch(unsupported=_unsupported)
 
170
        return control.open_branch(_unsupported)
169
171
 
170
172
    @staticmethod
171
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
173
    def open_from_transport(transport, _unsupported=False):
172
174
        """Open the branch rooted at transport"""
173
175
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
174
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
176
        return control.open_branch(_unsupported)
175
177
 
176
178
    @staticmethod
177
179
    def open_containing(url, possible_transports=None):
198
200
        return self.supports_tags() and self.tags.get_tag_dict()
199
201
 
200
202
    def get_config(self):
201
 
        """Get a bzrlib.config.BranchConfig for this Branch.
202
 
 
203
 
        This can then be used to get and set configuration options for the
204
 
        branch.
205
 
 
206
 
        :return: A bzrlib.config.BranchConfig.
207
 
        """
208
203
        return BranchConfig(self)
209
204
 
210
205
    def _get_config(self):
222
217
    def _get_fallback_repository(self, url):
223
218
        """Get the repository we fallback to at url."""
224
219
        url = urlutils.join(self.base, url)
225
 
        a_branch = Branch.open(url,
 
220
        a_bzrdir = bzrdir.BzrDir.open(url,
226
221
            possible_transports=[self.bzrdir.root_transport])
227
 
        return a_branch.repository
 
222
        return a_bzrdir.open_branch().repository
228
223
 
229
224
    def _get_tags_bytes(self):
230
225
        """Get the bytes of a serialised tags dict.
246
241
        if not local and not config.has_explicit_nickname():
247
242
            try:
248
243
                master = self.get_master_branch(possible_transports)
249
 
                if master and self.user_url == master.user_url:
250
 
                    raise errors.RecursiveBind(self.user_url)
251
244
                if master is not None:
252
245
                    # return the master branch value
253
246
                    return master.nick
254
 
            except errors.RecursiveBind, e:
255
 
                raise e
256
247
            except errors.BzrError, e:
257
248
                # Silently fall back to local implicit nick if the master is
258
249
                # unavailable
295
286
        new_history.reverse()
296
287
        return new_history
297
288
 
298
 
    def lock_write(self, token=None):
299
 
        """Lock the branch for write operations.
300
 
 
301
 
        :param token: A token to permit reacquiring a previously held and
302
 
            preserved lock.
303
 
        :return: A BranchWriteLockResult.
304
 
        """
 
289
    def lock_write(self):
305
290
        raise NotImplementedError(self.lock_write)
306
291
 
307
292
    def lock_read(self):
308
 
        """Lock the branch for read operations.
309
 
 
310
 
        :return: A bzrlib.lock.LogicalLockResult.
311
 
        """
312
293
        raise NotImplementedError(self.lock_read)
313
294
 
314
295
    def unlock(self):
439
420
            * 'include' - the stop revision is the last item in the result
440
421
            * 'with-merges' - include the stop revision and all of its
441
422
              merged revisions in the result
442
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
443
 
              that are in both ancestries
444
423
        :param direction: either 'reverse' or 'forward':
445
424
            * reverse means return the start_revision_id first, i.e.
446
425
              start at the most recent revision and go backwards in history
468
447
        # start_revision_id.
469
448
        if self._merge_sorted_revisions_cache is None:
470
449
            last_revision = self.last_revision()
471
 
            known_graph = self.repository.get_known_graph_ancestry(
472
 
                [last_revision])
 
450
            last_key = (last_revision,)
 
451
            known_graph = self.repository.revisions.get_known_graph_ancestry(
 
452
                [last_key])
473
453
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
474
 
                last_revision)
 
454
                last_key)
475
455
        filtered = self._filter_merge_sorted_revisions(
476
456
            self._merge_sorted_revisions_cache, start_revision_id,
477
457
            stop_revision_id, stop_rule)
478
 
        # Make sure we don't return revisions that are not part of the
479
 
        # start_revision_id ancestry.
480
 
        filtered = self._filter_start_non_ancestors(filtered)
481
458
        if direction == 'reverse':
482
459
            return filtered
483
460
        if direction == 'forward':
520
497
                       node.end_of_merge)
521
498
                if rev_id == stop_revision_id:
522
499
                    return
523
 
        elif stop_rule == 'with-merges-without-common-ancestry':
524
 
            # We want to exclude all revisions that are already part of the
525
 
            # stop_revision_id ancestry.
526
 
            graph = self.repository.get_graph()
527
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
528
 
                                                    [stop_revision_id])
529
 
            for node in rev_iter:
530
 
                rev_id = node.key[-1]
531
 
                if rev_id not in ancestors:
532
 
                    continue
533
 
                yield (rev_id, node.merge_depth, node.revno,
534
 
                       node.end_of_merge)
535
500
        elif stop_rule == 'with-merges':
536
501
            stop_rev = self.repository.get_revision(stop_revision_id)
537
502
            if stop_rev.parent_ids:
560
525
        else:
561
526
            raise ValueError('invalid stop_rule %r' % stop_rule)
562
527
 
563
 
    def _filter_start_non_ancestors(self, rev_iter):
564
 
        # If we started from a dotted revno, we want to consider it as a tip
565
 
        # and don't want to yield revisions that are not part of its
566
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
567
 
        # uninteresting descendants of the first parent of our tip before the
568
 
        # tip itself.
569
 
        first = rev_iter.next()
570
 
        (rev_id, merge_depth, revno, end_of_merge) = first
571
 
        yield first
572
 
        if not merge_depth:
573
 
            # We start at a mainline revision so by definition, all others
574
 
            # revisions in rev_iter are ancestors
575
 
            for node in rev_iter:
576
 
                yield node
577
 
 
578
 
        clean = False
579
 
        whitelist = set()
580
 
        pmap = self.repository.get_parent_map([rev_id])
581
 
        parents = pmap.get(rev_id, [])
582
 
        if parents:
583
 
            whitelist.update(parents)
584
 
        else:
585
 
            # If there is no parents, there is nothing of interest left
586
 
 
587
 
            # FIXME: It's hard to test this scenario here as this code is never
588
 
            # called in that case. -- vila 20100322
589
 
            return
590
 
 
591
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
592
 
            if not clean:
593
 
                if rev_id in whitelist:
594
 
                    pmap = self.repository.get_parent_map([rev_id])
595
 
                    parents = pmap.get(rev_id, [])
596
 
                    whitelist.remove(rev_id)
597
 
                    whitelist.update(parents)
598
 
                    if merge_depth == 0:
599
 
                        # We've reached the mainline, there is nothing left to
600
 
                        # filter
601
 
                        clean = True
602
 
                else:
603
 
                    # A revision that is not part of the ancestry of our
604
 
                    # starting revision.
605
 
                    continue
606
 
            yield (rev_id, merge_depth, revno, end_of_merge)
607
 
 
608
528
    def leave_lock_in_place(self):
609
529
        """Tell this branch object not to release the physical lock when this
610
530
        object is unlocked.
627
547
        :param other: The branch to bind to
628
548
        :type other: Branch
629
549
        """
630
 
        raise errors.UpgradeRequired(self.user_url)
 
550
        raise errors.UpgradeRequired(self.base)
631
551
 
632
552
    def set_append_revisions_only(self, enabled):
633
553
        if not self._format.supports_set_append_revisions_only():
634
 
            raise errors.UpgradeRequired(self.user_url)
 
554
            raise errors.UpgradeRequired(self.base)
635
555
        if enabled:
636
556
            value = 'True'
637
557
        else:
685
605
    def get_old_bound_location(self):
686
606
        """Return the URL of the branch we used to be bound to
687
607
        """
688
 
        raise errors.UpgradeRequired(self.user_url)
 
608
        raise errors.UpgradeRequired(self.base)
689
609
 
690
610
    def get_commit_builder(self, parents, config=None, timestamp=None,
691
611
                           timezone=None, committer=None, revprops=None,
769
689
            stacking.
770
690
        """
771
691
        if not self._format.supports_stacking():
772
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
692
            raise errors.UnstackableBranchFormat(self._format, self.base)
773
693
        # XXX: Changing from one fallback repository to another does not check
774
694
        # that all the data you need is present in the new fallback.
775
695
        # Possibly it should.
805
725
            if len(old_repository._fallback_repositories) != 1:
806
726
                raise AssertionError("can't cope with fallback repositories "
807
727
                    "of %r" % (self.repository,))
808
 
            # Open the new repository object.
809
 
            # Repositories don't offer an interface to remove fallback
810
 
            # repositories today; take the conceptually simpler option and just
811
 
            # reopen it.  We reopen it starting from the URL so that we
812
 
            # get a separate connection for RemoteRepositories and can
813
 
            # stream from one of them to the other.  This does mean doing
814
 
            # separate SSH connection setup, but unstacking is not a
815
 
            # common operation so it's tolerable.
816
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
817
 
            new_repository = new_bzrdir.find_repository()
818
 
            if new_repository._fallback_repositories:
819
 
                raise AssertionError("didn't expect %r to have "
820
 
                    "fallback_repositories"
821
 
                    % (self.repository,))
822
 
            # Replace self.repository with the new repository.
823
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
824
 
            # lock count) of self.repository to the new repository.
825
 
            lock_token = old_repository.lock_write().repository_token
826
 
            self.repository = new_repository
827
 
            if isinstance(self, remote.RemoteBranch):
828
 
                # Remote branches can have a second reference to the old
829
 
                # repository that need to be replaced.
830
 
                if self._real_branch is not None:
831
 
                    self._real_branch.repository = new_repository
832
 
            self.repository.lock_write(token=lock_token)
833
 
            if lock_token is not None:
834
 
                old_repository.leave_lock_in_place()
 
728
            # unlock it, including unlocking the fallback
835
729
            old_repository.unlock()
836
 
            if lock_token is not None:
837
 
                # XXX: self.repository.leave_lock_in_place() before this
838
 
                # function will not be preserved.  Fortunately that doesn't
839
 
                # affect the current default format (2a), and would be a
840
 
                # corner-case anyway.
841
 
                #  - Andrew Bennetts, 2010/06/30
842
 
                self.repository.dont_leave_lock_in_place()
843
 
            old_lock_count = 0
844
 
            while True:
845
 
                try:
846
 
                    old_repository.unlock()
847
 
                except errors.LockNotHeld:
848
 
                    break
849
 
                old_lock_count += 1
850
 
            if old_lock_count == 0:
851
 
                raise AssertionError(
852
 
                    'old_repository should have been locked at least once.')
853
 
            for i in range(old_lock_count-1):
 
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
854
749
                self.repository.lock_write()
855
 
            # Fetch from the old repository into the new.
856
 
            old_repository.lock_read()
857
 
            try:
858
750
                # XXX: If you unstack a branch while it has a working tree
859
751
                # with a pending merge, the pending-merged revisions will no
860
752
                # longer be present.  You can (probably) revert and remerge.
954
846
 
955
847
    def unbind(self):
956
848
        """Older format branches cannot bind or unbind."""
957
 
        raise errors.UpgradeRequired(self.user_url)
 
849
        raise errors.UpgradeRequired(self.base)
958
850
 
959
851
    def last_revision(self):
960
852
        """Return last revision id, or NULL_REVISION."""
1001
893
                raise errors.NoSuchRevision(self, stop_revision)
1002
894
        return other_history[self_len:stop_revision]
1003
895
 
 
896
    @needs_write_lock
1004
897
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1005
898
                         graph=None):
1006
899
        """Pull in new perfect-fit revisions.
1055
948
            self._extend_partial_history(distance_from_last)
1056
949
        return self._partial_revision_history_cache[distance_from_last]
1057
950
 
 
951
    @needs_write_lock
1058
952
    def pull(self, source, overwrite=False, stop_revision=None,
1059
953
             possible_transports=None, *args, **kwargs):
1060
954
        """Mirror source into this branch.
1118
1012
        try:
1119
1013
            return urlutils.join(self.base[:-1], parent)
1120
1014
        except errors.InvalidURLJoin, e:
1121
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
1015
            raise errors.InaccessibleParent(parent, self.base)
1122
1016
 
1123
1017
    def _get_parent_location(self):
1124
1018
        raise NotImplementedError(self._get_parent_location)
1303
1197
                revno = 1
1304
1198
        destination.set_last_revision_info(revno, revision_id)
1305
1199
 
 
1200
    @needs_read_lock
1306
1201
    def copy_content_into(self, destination, revision_id=None):
1307
1202
        """Copy the content of self into destination.
1308
1203
 
1309
1204
        revision_id: if not None, the revision history in the new branch will
1310
1205
                     be truncated to end with revision_id.
1311
1206
        """
1312
 
        return InterBranch.get(self, destination).copy_content_into(
1313
 
            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)
1314
1218
 
1315
1219
    def update_references(self, target):
1316
1220
        if not getattr(self._format, 'supports_reference_locations', False):
1384
1288
        """
1385
1289
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1386
1290
        # clone call. Or something. 20090224 RBC/spiv.
1387
 
        # XXX: Should this perhaps clone colocated branches as well, 
1388
 
        # rather than just the default branch? 20100319 JRV
1389
1291
        if revision_id is None:
1390
1292
            revision_id = self.last_revision()
1391
1293
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1415
1317
        if lightweight:
1416
1318
            format = self._get_checkout_format()
1417
1319
            checkout = format.initialize_on_transport(t)
1418
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1419
 
                target_branch=self)
 
1320
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1420
1321
        else:
1421
1322
            format = self._get_checkout_format()
1422
1323
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1464
1365
    def supports_tags(self):
1465
1366
        return self._format.supports_tags()
1466
1367
 
1467
 
    def automatic_tag_name(self, revision_id):
1468
 
        """Try to automatically find the tag name for a revision.
1469
 
 
1470
 
        :param revision_id: Revision id of the revision.
1471
 
        :return: A tag name or None if no tag name could be determined.
1472
 
        """
1473
 
        for hook in Branch.hooks['automatic_tag_name']:
1474
 
            ret = hook(self, revision_id)
1475
 
            if ret is not None:
1476
 
                return ret
1477
 
        return None
1478
 
 
1479
1368
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1480
1369
                                         other_branch):
1481
1370
        """Ensure that revision_b is a descendant of revision_a.
1545
1434
        return not (self == other)
1546
1435
 
1547
1436
    @classmethod
1548
 
    def find_format(klass, a_bzrdir, name=None):
 
1437
    def find_format(klass, a_bzrdir):
1549
1438
        """Return the format for the branch object in a_bzrdir."""
1550
1439
        try:
1551
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
 
1440
            transport = a_bzrdir.get_branch_transport(None)
1552
1441
            format_string = transport.get_bytes("format")
1553
 
            format = klass._formats[format_string]
1554
 
            if isinstance(format, MetaDirBranchFormatFactory):
1555
 
                return format()
1556
 
            return format
 
1442
            return klass._formats[format_string]
1557
1443
        except errors.NoSuchFile:
1558
1444
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1559
1445
        except KeyError:
1564
1450
        """Return the current default format."""
1565
1451
        return klass._default_format
1566
1452
 
1567
 
    @classmethod
1568
 
    def get_formats(klass):
1569
 
        """Get all the known formats.
1570
 
 
1571
 
        Warning: This triggers a load of all lazy registered formats: do not
1572
 
        use except when that is desireed.
1573
 
        """
1574
 
        result = []
1575
 
        for fmt in klass._formats.values():
1576
 
            if isinstance(fmt, MetaDirBranchFormatFactory):
1577
 
                fmt = fmt()
1578
 
            result.append(fmt)
1579
 
        return result
1580
 
 
1581
 
    def get_reference(self, a_bzrdir, name=None):
 
1453
    def get_reference(self, a_bzrdir):
1582
1454
        """Get the target reference of the branch in a_bzrdir.
1583
1455
 
1584
1456
        format probing must have been completed before calling
1586
1458
        in a_bzrdir is correct.
1587
1459
 
1588
1460
        :param a_bzrdir: The bzrdir to get the branch data from.
1589
 
        :param name: Name of the colocated branch to fetch
1590
1461
        :return: None if the branch is not a reference branch.
1591
1462
        """
1592
1463
        return None
1593
1464
 
1594
1465
    @classmethod
1595
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1466
    def set_reference(self, a_bzrdir, to_branch):
1596
1467
        """Set the target reference of the branch in a_bzrdir.
1597
1468
 
1598
1469
        format probing must have been completed before calling
1600
1471
        in a_bzrdir is correct.
1601
1472
 
1602
1473
        :param a_bzrdir: The bzrdir to set the branch reference for.
1603
 
        :param name: Name of colocated branch to set, None for default
1604
1474
        :param to_branch: branch that the checkout is to reference
1605
1475
        """
1606
1476
        raise NotImplementedError(self.set_reference)
1613
1483
        """Return the short format description for this format."""
1614
1484
        raise NotImplementedError(self.get_format_description)
1615
1485
 
1616
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1617
 
        hooks = Branch.hooks['post_branch_init']
1618
 
        if not hooks:
1619
 
            return
1620
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1621
 
        for hook in hooks:
1622
 
            hook(params)
1623
 
 
1624
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1625
 
                           lock_type='metadir', set_format=True):
 
1486
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1487
                           set_format=True):
1626
1488
        """Initialize a branch in a bzrdir, with specified files
1627
1489
 
1628
1490
        :param a_bzrdir: The bzrdir to initialize the branch in
1629
1491
        :param utf8_files: The files to create as a list of
1630
1492
            (filename, content) tuples
1631
 
        :param name: Name of colocated branch to create, if any
1632
1493
        :param set_format: If True, set the format with
1633
1494
            self.get_format_string.  (BzrBranch4 has its format set
1634
1495
            elsewhere)
1635
1496
        :return: a branch in this format
1636
1497
        """
1637
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1638
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1498
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1499
        branch_transport = a_bzrdir.get_branch_transport(self)
1639
1500
        lock_map = {
1640
1501
            'metadir': ('lock', lockdir.LockDir),
1641
1502
            'branch4': ('branch-lock', lockable_files.TransportLock),
1662
1523
        finally:
1663
1524
            if lock_taken:
1664
1525
                control_files.unlock()
1665
 
        branch = self.open(a_bzrdir, name, _found=True)
1666
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1667
 
        return branch
 
1526
        return self.open(a_bzrdir, _found=True)
1668
1527
 
1669
 
    def initialize(self, a_bzrdir, name=None):
1670
 
        """Create a branch of this format in a_bzrdir.
1671
 
        
1672
 
        :param name: Name of the colocated branch to create.
1673
 
        """
 
1528
    def initialize(self, a_bzrdir):
 
1529
        """Create a branch of this format in a_bzrdir."""
1674
1530
        raise NotImplementedError(self.initialize)
1675
1531
 
1676
1532
    def is_supported(self):
1706
1562
        """
1707
1563
        raise NotImplementedError(self.network_name)
1708
1564
 
1709
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1565
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1710
1566
        """Return the branch object for a_bzrdir
1711
1567
 
1712
1568
        :param a_bzrdir: A BzrDir that contains a branch.
1713
 
        :param name: Name of colocated branch to open
1714
1569
        :param _found: a private parameter, do not use it. It is used to
1715
1570
            indicate if format probing has already be done.
1716
1571
        :param ignore_fallbacks: when set, no fallback branches will be opened
1720
1575
 
1721
1576
    @classmethod
1722
1577
    def register_format(klass, format):
1723
 
        """Register a metadir format.
1724
 
        
1725
 
        See MetaDirBranchFormatFactory for the ability to register a format
1726
 
        without loading the code the format needs until it is actually used.
1727
 
        """
 
1578
        """Register a metadir format."""
1728
1579
        klass._formats[format.get_format_string()] = format
1729
1580
        # Metadir formats have a network name of their format string, and get
1730
 
        # registered as factories.
1731
 
        if isinstance(format, MetaDirBranchFormatFactory):
1732
 
            network_format_registry.register(format.get_format_string(), format)
1733
 
        else:
1734
 
            network_format_registry.register(format.get_format_string(),
1735
 
                format.__class__)
 
1581
        # registered as class factories.
 
1582
        network_format_registry.register(format.get_format_string(), format.__class__)
1736
1583
 
1737
1584
    @classmethod
1738
1585
    def set_default_format(klass, format):
1758
1605
        return False  # by default
1759
1606
 
1760
1607
 
1761
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1762
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1763
 
    
1764
 
    While none of the built in BranchFormats are lazy registered yet,
1765
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1766
 
    use it, and the bzr-loom plugin uses it as well (see
1767
 
    bzrlib.plugins.loom.formats).
1768
 
    """
1769
 
 
1770
 
    def __init__(self, format_string, module_name, member_name):
1771
 
        """Create a MetaDirBranchFormatFactory.
1772
 
 
1773
 
        :param format_string: The format string the format has.
1774
 
        :param module_name: Module to load the format class from.
1775
 
        :param member_name: Attribute name within the module for the format class.
1776
 
        """
1777
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1778
 
        self._format_string = format_string
1779
 
        
1780
 
    def get_format_string(self):
1781
 
        """See BranchFormat.get_format_string."""
1782
 
        return self._format_string
1783
 
 
1784
 
    def __call__(self):
1785
 
        """Used for network_format_registry support."""
1786
 
        return self.get_obj()()
1787
 
 
1788
 
 
1789
1608
class BranchHooks(Hooks):
1790
1609
    """A dictionary mapping hook name to a list of callables for branch hooks.
1791
1610
 
1860
1679
            "multiple hooks installed for transform_fallback_location, "
1861
1680
            "all are called with the url returned from the previous hook."
1862
1681
            "The order is however undefined.", (1, 9), None))
1863
 
        self.create_hook(HookPoint('automatic_tag_name',
1864
 
            "Called to determine an automatic tag name for a revision. "
1865
 
            "automatic_tag_name is called with (branch, revision_id) and "
1866
 
            "should return a tag name or None if no tag name could be "
1867
 
            "determined. The first non-None tag name returned will be used.",
1868
 
            (2, 2), None))
1869
 
        self.create_hook(HookPoint('post_branch_init',
1870
 
            "Called after new branch initialization completes. "
1871
 
            "post_branch_init is called with a "
1872
 
            "bzrlib.branch.BranchInitHookParams. "
1873
 
            "Note that init, branch and checkout (both heavyweight and "
1874
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1875
 
        self.create_hook(HookPoint('post_switch',
1876
 
            "Called after a checkout switches branch. "
1877
 
            "post_switch is called with a "
1878
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1879
 
 
1880
1682
 
1881
1683
 
1882
1684
# install the default hooks into the Branch class.
1921
1723
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1922
1724
 
1923
1725
 
1924
 
class BranchInitHookParams(object):
1925
 
    """Object holding parameters passed to *_branch_init hooks.
1926
 
 
1927
 
    There are 4 fields that hooks may wish to access:
1928
 
 
1929
 
    :ivar format: the branch format
1930
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1931
 
    :ivar name: name of colocated branch, if any (or None)
1932
 
    :ivar branch: the branch created
1933
 
 
1934
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1935
 
    the checkout, hence they are different from the corresponding fields in
1936
 
    branch, which refer to the original branch.
1937
 
    """
1938
 
 
1939
 
    def __init__(self, format, a_bzrdir, name, branch):
1940
 
        """Create a group of BranchInitHook parameters.
1941
 
 
1942
 
        :param format: the branch format
1943
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1944
 
            initialized
1945
 
        :param name: name of colocated branch, if any (or None)
1946
 
        :param branch: the branch created
1947
 
 
1948
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1949
 
        to the checkout, hence they are different from the corresponding fields
1950
 
        in branch, which refer to the original branch.
1951
 
        """
1952
 
        self.format = format
1953
 
        self.bzrdir = a_bzrdir
1954
 
        self.name = name
1955
 
        self.branch = branch
1956
 
 
1957
 
    def __eq__(self, other):
1958
 
        return self.__dict__ == other.__dict__
1959
 
 
1960
 
    def __repr__(self):
1961
 
        if self.branch:
1962
 
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
1963
 
        else:
1964
 
            return "<%s of format:%s bzrdir:%s>" % (
1965
 
                self.__class__.__name__, self.branch,
1966
 
                self.format, self.bzrdir)
1967
 
 
1968
 
 
1969
 
class SwitchHookParams(object):
1970
 
    """Object holding parameters passed to *_switch hooks.
1971
 
 
1972
 
    There are 4 fields that hooks may wish to access:
1973
 
 
1974
 
    :ivar control_dir: BzrDir of the checkout to change
1975
 
    :ivar to_branch: branch that the checkout is to reference
1976
 
    :ivar force: skip the check for local commits in a heavy checkout
1977
 
    :ivar revision_id: revision ID to switch to (or None)
1978
 
    """
1979
 
 
1980
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1981
 
        """Create a group of SwitchHook parameters.
1982
 
 
1983
 
        :param control_dir: BzrDir of the checkout to change
1984
 
        :param to_branch: branch that the checkout is to reference
1985
 
        :param force: skip the check for local commits in a heavy checkout
1986
 
        :param revision_id: revision ID to switch to (or None)
1987
 
        """
1988
 
        self.control_dir = control_dir
1989
 
        self.to_branch = to_branch
1990
 
        self.force = force
1991
 
        self.revision_id = revision_id
1992
 
 
1993
 
    def __eq__(self, other):
1994
 
        return self.__dict__ == other.__dict__
1995
 
 
1996
 
    def __repr__(self):
1997
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1998
 
            self.control_dir, self.to_branch,
1999
 
            self.revision_id)
2000
 
 
2001
 
 
2002
1726
class BzrBranchFormat4(BranchFormat):
2003
1727
    """Bzr branch format 4.
2004
1728
 
2011
1735
        """See BranchFormat.get_format_description()."""
2012
1736
        return "Branch format 4"
2013
1737
 
2014
 
    def initialize(self, a_bzrdir, name=None):
 
1738
    def initialize(self, a_bzrdir):
2015
1739
        """Create a branch of this format in a_bzrdir."""
2016
1740
        utf8_files = [('revision-history', ''),
2017
1741
                      ('branch-name', ''),
2018
1742
                      ]
2019
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1743
        return self._initialize_helper(a_bzrdir, utf8_files,
2020
1744
                                       lock_type='branch4', set_format=False)
2021
1745
 
2022
1746
    def __init__(self):
2027
1751
        """The network name for this format is the control dirs disk label."""
2028
1752
        return self._matchingbzrdir.get_format_string()
2029
1753
 
2030
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1754
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2031
1755
        """See BranchFormat.open()."""
2032
1756
        if not _found:
2033
1757
            # we are being called directly and must probe.
2035
1759
        return BzrBranch(_format=self,
2036
1760
                         _control_files=a_bzrdir._control_files,
2037
1761
                         a_bzrdir=a_bzrdir,
2038
 
                         name=name,
2039
1762
                         _repository=a_bzrdir.open_repository())
2040
1763
 
2041
1764
    def __str__(self):
2056
1779
        """
2057
1780
        return self.get_format_string()
2058
1781
 
2059
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1782
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2060
1783
        """See BranchFormat.open()."""
2061
1784
        if not _found:
2062
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1785
            format = BranchFormat.find_format(a_bzrdir)
2063
1786
            if format.__class__ != self.__class__:
2064
1787
                raise AssertionError("wrong format %r found for %r" %
2065
1788
                    (format, self))
2066
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2067
1789
        try:
 
1790
            transport = a_bzrdir.get_branch_transport(None)
2068
1791
            control_files = lockable_files.LockableFiles(transport, 'lock',
2069
1792
                                                         lockdir.LockDir)
2070
1793
            return self._branch_class()(_format=self,
2071
1794
                              _control_files=control_files,
2072
 
                              name=name,
2073
1795
                              a_bzrdir=a_bzrdir,
2074
1796
                              _repository=a_bzrdir.find_repository(),
2075
1797
                              ignore_fallbacks=ignore_fallbacks)
2109
1831
        """See BranchFormat.get_format_description()."""
2110
1832
        return "Branch format 5"
2111
1833
 
2112
 
    def initialize(self, a_bzrdir, name=None):
 
1834
    def initialize(self, a_bzrdir):
2113
1835
        """Create a branch of this format in a_bzrdir."""
2114
1836
        utf8_files = [('revision-history', ''),
2115
1837
                      ('branch-name', ''),
2116
1838
                      ]
2117
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1839
        return self._initialize_helper(a_bzrdir, utf8_files)
2118
1840
 
2119
1841
    def supports_tags(self):
2120
1842
        return False
2142
1864
        """See BranchFormat.get_format_description()."""
2143
1865
        return "Branch format 6"
2144
1866
 
2145
 
    def initialize(self, a_bzrdir, name=None):
 
1867
    def initialize(self, a_bzrdir):
2146
1868
        """Create a branch of this format in a_bzrdir."""
2147
1869
        utf8_files = [('last-revision', '0 null:\n'),
2148
1870
                      ('branch.conf', ''),
2149
1871
                      ('tags', ''),
2150
1872
                      ]
2151
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1873
        return self._initialize_helper(a_bzrdir, utf8_files)
2152
1874
 
2153
1875
    def make_tags(self, branch):
2154
1876
        """See bzrlib.branch.BranchFormat.make_tags()."""
2172
1894
        """See BranchFormat.get_format_description()."""
2173
1895
        return "Branch format 8"
2174
1896
 
2175
 
    def initialize(self, a_bzrdir, name=None):
 
1897
    def initialize(self, a_bzrdir):
2176
1898
        """Create a branch of this format in a_bzrdir."""
2177
1899
        utf8_files = [('last-revision', '0 null:\n'),
2178
1900
                      ('branch.conf', ''),
2179
1901
                      ('tags', ''),
2180
1902
                      ('references', '')
2181
1903
                      ]
2182
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1904
        return self._initialize_helper(a_bzrdir, utf8_files)
2183
1905
 
2184
1906
    def __init__(self):
2185
1907
        super(BzrBranchFormat8, self).__init__()
2208
1930
    This format was introduced in bzr 1.6.
2209
1931
    """
2210
1932
 
2211
 
    def initialize(self, a_bzrdir, name=None):
 
1933
    def initialize(self, a_bzrdir):
2212
1934
        """Create a branch of this format in a_bzrdir."""
2213
1935
        utf8_files = [('last-revision', '0 null:\n'),
2214
1936
                      ('branch.conf', ''),
2215
1937
                      ('tags', ''),
2216
1938
                      ]
2217
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1939
        return self._initialize_helper(a_bzrdir, utf8_files)
2218
1940
 
2219
1941
    def _branch_class(self):
2220
1942
        return BzrBranch7
2252
1974
        """See BranchFormat.get_format_description()."""
2253
1975
        return "Checkout reference format 1"
2254
1976
 
2255
 
    def get_reference(self, a_bzrdir, name=None):
 
1977
    def get_reference(self, a_bzrdir):
2256
1978
        """See BranchFormat.get_reference()."""
2257
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1979
        transport = a_bzrdir.get_branch_transport(None)
2258
1980
        return transport.get_bytes('location')
2259
1981
 
2260
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1982
    def set_reference(self, a_bzrdir, to_branch):
2261
1983
        """See BranchFormat.set_reference()."""
2262
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1984
        transport = a_bzrdir.get_branch_transport(None)
2263
1985
        location = transport.put_bytes('location', to_branch.base)
2264
1986
 
2265
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1987
    def initialize(self, a_bzrdir, target_branch=None):
2266
1988
        """Create a branch of this format in a_bzrdir."""
2267
1989
        if target_branch is None:
2268
1990
            # this format does not implement branch itself, thus the implicit
2269
1991
            # creation contract must see it as uninitializable
2270
1992
            raise errors.UninitializableFormat(self)
2271
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2272
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1993
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1994
        branch_transport = a_bzrdir.get_branch_transport(self)
2273
1995
        branch_transport.put_bytes('location',
2274
 
            target_branch.bzrdir.user_url)
 
1996
            target_branch.bzrdir.root_transport.base)
2275
1997
        branch_transport.put_bytes('format', self.get_format_string())
2276
 
        branch = self.open(
2277
 
            a_bzrdir, name, _found=True,
 
1998
        return self.open(
 
1999
            a_bzrdir, _found=True,
2278
2000
            possible_transports=[target_branch.bzrdir.root_transport])
2279
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2280
 
        return branch
2281
2001
 
2282
2002
    def __init__(self):
2283
2003
        super(BranchReferenceFormat, self).__init__()
2289
2009
        def clone(to_bzrdir, revision_id=None,
2290
2010
            repository_policy=None):
2291
2011
            """See Branch.clone()."""
2292
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2012
            return format.initialize(to_bzrdir, a_branch)
2293
2013
            # cannot obey revision_id limits when cloning a reference ...
2294
2014
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2295
2015
            # emit some sort of warning/error to the caller ?!
2296
2016
        return clone
2297
2017
 
2298
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2018
    def open(self, a_bzrdir, _found=False, location=None,
2299
2019
             possible_transports=None, ignore_fallbacks=False):
2300
2020
        """Return the branch that the branch reference in a_bzrdir points at.
2301
2021
 
2302
2022
        :param a_bzrdir: A BzrDir that contains a branch.
2303
 
        :param name: Name of colocated branch to open, if any
2304
2023
        :param _found: a private parameter, do not use it. It is used to
2305
2024
            indicate if format probing has already be done.
2306
2025
        :param ignore_fallbacks: when set, no fallback branches will be opened
2311
2030
        :param possible_transports: An optional reusable transports list.
2312
2031
        """
2313
2032
        if not _found:
2314
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2033
            format = BranchFormat.find_format(a_bzrdir)
2315
2034
            if format.__class__ != self.__class__:
2316
2035
                raise AssertionError("wrong format %r found for %r" %
2317
2036
                    (format, self))
2318
2037
        if location is None:
2319
 
            location = self.get_reference(a_bzrdir, name)
 
2038
            location = self.get_reference(a_bzrdir)
2320
2039
        real_bzrdir = bzrdir.BzrDir.open(
2321
2040
            location, possible_transports=possible_transports)
2322
 
        result = real_bzrdir.open_branch(name=name, 
2323
 
            ignore_fallbacks=ignore_fallbacks)
 
2041
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2324
2042
        # this changes the behaviour of result.clone to create a new reference
2325
2043
        # rather than a copy of the content of the branch.
2326
2044
        # I did not use a proxy object because that needs much more extensive
2360
2078
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2361
2079
 
2362
2080
 
2363
 
class BranchWriteLockResult(LogicalLockResult):
2364
 
    """The result of write locking a branch.
2365
 
 
2366
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2367
 
        None.
2368
 
    :ivar unlock: A callable which will unlock the lock.
2369
 
    """
2370
 
 
2371
 
    def __init__(self, unlock, branch_token):
2372
 
        LogicalLockResult.__init__(self, unlock)
2373
 
        self.branch_token = branch_token
2374
 
 
2375
 
    def __repr__(self):
2376
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2377
 
            self.unlock)
2378
 
 
2379
 
 
2380
2081
class BzrBranch(Branch, _RelockDebugMixin):
2381
2082
    """A branch stored in the actual filesystem.
2382
2083
 
2389
2090
    :ivar repository: Repository for this branch.
2390
2091
    :ivar base: The url of the base directory for this branch; the one
2391
2092
        containing the .bzr directory.
2392
 
    :ivar name: Optional colocated branch name as it exists in the control
2393
 
        directory.
2394
2093
    """
2395
2094
 
2396
2095
    def __init__(self, _format=None,
2397
 
                 _control_files=None, a_bzrdir=None, name=None,
2398
 
                 _repository=None, ignore_fallbacks=False):
 
2096
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2097
                 ignore_fallbacks=False):
2399
2098
        """Create new branch object at a particular location."""
2400
2099
        if a_bzrdir is None:
2401
2100
            raise ValueError('a_bzrdir must be supplied')
2402
2101
        else:
2403
2102
            self.bzrdir = a_bzrdir
2404
2103
        self._base = self.bzrdir.transport.clone('..').base
2405
 
        self.name = name
2406
2104
        # XXX: We should be able to just do
2407
2105
        #   self.base = self.bzrdir.root_transport.base
2408
2106
        # but this does not quite work yet -- mbp 20080522
2415
2113
        Branch.__init__(self)
2416
2114
 
2417
2115
    def __str__(self):
2418
 
        if self.name is None:
2419
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2420
 
        else:
2421
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2422
 
                self.name)
 
2116
        return '%s(%r)' % (self.__class__.__name__, self.base)
2423
2117
 
2424
2118
    __repr__ = __str__
2425
2119
 
2436
2130
        return self.control_files.is_locked()
2437
2131
 
2438
2132
    def lock_write(self, token=None):
2439
 
        """Lock the branch for write operations.
2440
 
 
2441
 
        :param token: A token to permit reacquiring a previously held and
2442
 
            preserved lock.
2443
 
        :return: A BranchWriteLockResult.
2444
 
        """
2445
2133
        if not self.is_locked():
2446
2134
            self._note_lock('w')
2447
2135
        # All-in-one needs to always unlock/lock.
2453
2141
        else:
2454
2142
            took_lock = False
2455
2143
        try:
2456
 
            return BranchWriteLockResult(self.unlock,
2457
 
                self.control_files.lock_write(token=token))
 
2144
            return self.control_files.lock_write(token=token)
2458
2145
        except:
2459
2146
            if took_lock:
2460
2147
                self.repository.unlock()
2461
2148
            raise
2462
2149
 
2463
2150
    def lock_read(self):
2464
 
        """Lock the branch for read operations.
2465
 
 
2466
 
        :return: A bzrlib.lock.LogicalLockResult.
2467
 
        """
2468
2151
        if not self.is_locked():
2469
2152
            self._note_lock('r')
2470
2153
        # All-in-one needs to always unlock/lock.
2477
2160
            took_lock = False
2478
2161
        try:
2479
2162
            self.control_files.lock_read()
2480
 
            return LogicalLockResult(self.unlock)
2481
2163
        except:
2482
2164
            if took_lock:
2483
2165
                self.repository.unlock()
2652
2334
        return result
2653
2335
 
2654
2336
    def get_stacked_on_url(self):
2655
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2337
        raise errors.UnstackableBranchFormat(self._format, self.base)
2656
2338
 
2657
2339
    def set_push_location(self, location):
2658
2340
        """See Branch.set_push_location."""
2848
2530
        if _mod_revision.is_null(last_revision):
2849
2531
            return
2850
2532
        if last_revision not in self._lefthand_history(revision_id):
2851
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2533
            raise errors.AppendRevisionsOnlyViolation(self.base)
2852
2534
 
2853
2535
    def _gen_revision_history(self):
2854
2536
        """Generate the revision history from last revision
2954
2636
        if branch_location is None:
2955
2637
            return Branch.reference_parent(self, file_id, path,
2956
2638
                                           possible_transports)
2957
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2639
        branch_location = urlutils.join(self.base, branch_location)
2958
2640
        return Branch.open(branch_location,
2959
2641
                           possible_transports=possible_transports)
2960
2642
 
3006
2688
        return stacked_url
3007
2689
 
3008
2690
    def _get_append_revisions_only(self):
3009
 
        return self.get_config(
3010
 
            ).get_user_option_as_bool('append_revisions_only')
 
2691
        value = self.get_config().get_user_option('append_revisions_only')
 
2692
        return value == 'True'
3011
2693
 
3012
2694
    @needs_write_lock
3013
2695
    def generate_revision_history(self, revision_id, last_rev=None,
3075
2757
    """
3076
2758
 
3077
2759
    def get_stacked_on_url(self):
3078
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2760
        raise errors.UnstackableBranchFormat(self._format, self.base)
3079
2761
 
3080
2762
 
3081
2763
######################################################################
3168
2850
        :param verbose: Requests more detailed display of what was checked,
3169
2851
            if any.
3170
2852
        """
3171
 
        note('checked branch %s format %s', self.branch.user_url,
 
2853
        note('checked branch %s format %s', self.branch.base,
3172
2854
            self.branch._format)
3173
2855
        for error in self.errors:
3174
2856
            note('found error:%s', error)
3269
2951
    _optimisers = []
3270
2952
    """The available optimised InterBranch types."""
3271
2953
 
3272
 
    @classmethod
3273
 
    def _get_branch_formats_to_test(klass):
3274
 
        """Return an iterable of format tuples for testing.
3275
 
        
3276
 
        :return: An iterable of (from_format, to_format) to use when testing
3277
 
            this InterBranch class. Each InterBranch class should define this
3278
 
            method itself.
3279
 
        """
3280
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
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)
3281
2958
 
3282
 
    @needs_write_lock
3283
2959
    def pull(self, overwrite=False, stop_revision=None,
3284
2960
             possible_transports=None, local=False):
3285
2961
        """Mirror source into target branch.
3290
2966
        """
3291
2967
        raise NotImplementedError(self.pull)
3292
2968
 
3293
 
    @needs_write_lock
3294
2969
    def update_revisions(self, stop_revision=None, overwrite=False,
3295
2970
                         graph=None):
3296
2971
        """Pull in new perfect-fit revisions.
3304
2979
        """
3305
2980
        raise NotImplementedError(self.update_revisions)
3306
2981
 
3307
 
    @needs_write_lock
3308
2982
    def push(self, overwrite=False, stop_revision=None,
3309
2983
             _override_hook_source_branch=None):
3310
2984
        """Mirror the source branch into the target branch.
3315
2989
 
3316
2990
 
3317
2991
class GenericInterBranch(InterBranch):
3318
 
    """InterBranch implementation that uses public Branch functions."""
3319
 
 
3320
 
    @classmethod
3321
 
    def is_compatible(klass, source, target):
3322
 
        # GenericBranch uses the public API, so always compatible
3323
 
        return True
3324
 
 
3325
 
    @classmethod
3326
 
    def _get_branch_formats_to_test(klass):
3327
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3328
 
 
3329
 
    @classmethod
3330
 
    def unwrap_format(klass, format):
3331
 
        if isinstance(format, remote.RemoteBranchFormat):
3332
 
            format._ensure_real()
3333
 
            return format._custom_format
3334
 
        return format                                                                                                  
3335
 
 
3336
 
    @needs_write_lock
3337
 
    def copy_content_into(self, revision_id=None):
3338
 
        """Copy the content of source into target
3339
 
 
3340
 
        revision_id: if not None, the revision history in the new branch will
3341
 
                     be truncated to end with revision_id.
3342
 
        """
3343
 
        self.source.update_references(self.target)
3344
 
        self.source._synchronize_history(self.target, revision_id)
3345
 
        try:
3346
 
            parent = self.source.get_parent()
3347
 
        except errors.InaccessibleParent, e:
3348
 
            mutter('parent was not accessible to copy: %s', e)
3349
 
        else:
3350
 
            if parent:
3351
 
                self.target.set_parent(parent)
3352
 
        if self.source._push_should_merge_tags():
3353
 
            self.source.tags.merge_to(self.target.tags)
3354
 
 
3355
 
    @needs_write_lock
 
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
 
3356
2999
    def update_revisions(self, stop_revision=None, overwrite=False,
3357
3000
        graph=None):
3358
3001
        """See InterBranch.update_revisions()."""
3359
 
        other_revno, other_last_revision = self.source.last_revision_info()
3360
 
        stop_revno = None # unknown
3361
 
        if stop_revision is None:
3362
 
            stop_revision = other_last_revision
3363
 
            if _mod_revision.is_null(stop_revision):
3364
 
                # if there are no commits, we're done.
3365
 
                return
3366
 
            stop_revno = other_revno
3367
 
 
3368
 
        # what's the current last revision, before we fetch [and change it
3369
 
        # possibly]
3370
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3371
 
        # we fetch here so that we don't process data twice in the common
3372
 
        # case of having something to pull, and so that the check for
3373
 
        # already merged can operate on the just fetched graph, which will
3374
 
        # be cached in memory.
3375
 
        self.target.fetch(self.source, stop_revision)
3376
 
        # Check to see if one is an ancestor of the other
3377
 
        if not overwrite:
3378
 
            if graph is None:
3379
 
                graph = self.target.repository.get_graph()
3380
 
            if self.target._check_if_descendant_or_diverged(
3381
 
                    stop_revision, last_rev, graph, self.source):
3382
 
                # stop_revision is a descendant of last_rev, but we aren't
3383
 
                # overwriting, so we're done.
3384
 
                return
3385
 
        if stop_revno is None:
3386
 
            if graph is None:
3387
 
                graph = self.target.repository.get_graph()
3388
 
            this_revno, this_last_revision = \
3389
 
                    self.target.last_revision_info()
3390
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3391
 
                            [(other_last_revision, other_revno),
3392
 
                             (this_last_revision, this_revno)])
3393
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3394
 
 
3395
 
    @needs_write_lock
 
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
 
3396
3042
    def pull(self, overwrite=False, stop_revision=None,
3397
 
             possible_transports=None, run_hooks=True,
 
3043
             possible_transports=None, _hook_master=None, run_hooks=True,
3398
3044
             _override_hook_target=None, local=False):
3399
 
        """Pull from source into self, updating my master if any.
 
3045
        """See Branch.pull.
3400
3046
 
 
3047
        :param _hook_master: Private parameter - set the branch to
 
3048
            be supplied as the master to pull hooks.
3401
3049
        :param run_hooks: Private parameter - if false, this branch
3402
3050
            is being called because it's the master of the primary branch,
3403
3051
            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.
3404
3055
        """
3405
 
        bound_location = self.target.get_bound_location()
3406
 
        if local and not bound_location:
 
3056
        # This type of branch can't be bound.
 
3057
        if local:
3407
3058
            raise errors.LocalRequiresBoundBranch()
3408
 
        master_branch = None
3409
 
        if not local and bound_location and self.source.user_url != bound_location:
3410
 
            # not pulling from master, so we need to update master.
3411
 
            master_branch = self.target.get_master_branch(possible_transports)
3412
 
            master_branch.lock_write()
 
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()
3413
3066
        try:
3414
 
            if master_branch:
3415
 
                # pull from source into master.
3416
 
                master_branch.pull(self.source, overwrite, stop_revision,
3417
 
                    run_hooks=False)
3418
 
            return self._pull(overwrite,
3419
 
                stop_revision, _hook_master=master_branch,
3420
 
                run_hooks=run_hooks,
3421
 
                _override_hook_target=_override_hook_target)
 
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)
3422
3093
        finally:
3423
 
            if master_branch:
3424
 
                master_branch.unlock()
 
3094
            self.source.unlock()
 
3095
        return result
3425
3096
 
3426
3097
    def push(self, overwrite=False, stop_revision=None,
3427
3098
             _override_hook_source_branch=None):
3489
3160
            _run_hooks()
3490
3161
            return result
3491
3162
 
3492
 
    def _pull(self, overwrite=False, stop_revision=None,
3493
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
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,
3494
3177
             _override_hook_target=None, local=False):
3495
 
        """See Branch.pull.
3496
 
 
3497
 
        This function is the core worker, used by GenericInterBranch.pull to
3498
 
        avoid duplication when pulling source->master and source->local.
3499
 
 
3500
 
        :param _hook_master: Private parameter - set the branch to
3501
 
            be supplied as the master to pull hooks.
 
3178
        """Pull from source into self, updating my master if any.
 
3179
 
3502
3180
        :param run_hooks: Private parameter - if false, this branch
3503
3181
            is being called because it's the master of the primary branch,
3504
3182
            so it should not run its hooks.
3505
 
        :param _override_hook_target: Private parameter - set the branch to be
3506
 
            supplied as the target_branch to pull hooks.
3507
 
        :param local: Only update the local branch, and not the bound branch.
3508
3183
        """
3509
 
        # This type of branch can't be bound.
3510
 
        if local:
 
3184
        bound_location = self.target.get_bound_location()
 
3185
        if local and not bound_location:
3511
3186
            raise errors.LocalRequiresBoundBranch()
3512
 
        result = PullResult()
3513
 
        result.source_branch = self.source
3514
 
        if _override_hook_target is None:
3515
 
            result.target_branch = self.target
3516
 
        else:
3517
 
            result.target_branch = _override_hook_target
3518
 
        self.source.lock_read()
 
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()
3519
3192
        try:
3520
 
            # We assume that during 'pull' the target repository is closer than
3521
 
            # the source one.
3522
 
            self.source.update_references(self.target)
3523
 
            graph = self.target.repository.get_graph(self.source.repository)
3524
 
            # TODO: Branch formats should have a flag that indicates 
3525
 
            # that revno's are expensive, and pull() should honor that flag.
3526
 
            # -- JRV20090506
3527
 
            result.old_revno, result.old_revid = \
3528
 
                self.target.last_revision_info()
3529
 
            self.target.update_revisions(self.source, stop_revision,
3530
 
                overwrite=overwrite, graph=graph)
3531
 
            # TODO: The old revid should be specified when merging tags, 
3532
 
            # so a tags implementation that versions tags can only 
3533
 
            # pull in the most recent changes. -- JRV20090506
3534
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3535
 
                overwrite)
3536
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3537
 
            if _hook_master:
3538
 
                result.master_branch = _hook_master
3539
 
                result.local_branch = result.target_branch
3540
 
            else:
3541
 
                result.master_branch = result.target_branch
3542
 
                result.local_branch = None
3543
 
            if run_hooks:
3544
 
                for hook in Branch.hooks['post_pull']:
3545
 
                    hook(result)
 
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)
3546
3201
        finally:
3547
 
            self.source.unlock()
3548
 
        return result
 
3202
            if master_branch:
 
3203
                master_branch.unlock()
3549
3204
 
3550
3205
 
3551
3206
InterBranch.register_optimiser(GenericInterBranch)
 
3207
InterBranch.register_optimiser(InterToBranch5)