~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-08-14 05:49:27 UTC
  • mfrom: (4476.3.86 inventory-delta)
  • Revision ID: pqm@pqm.ubuntu.com-20090814054927-k0k18dn46ax4b91f
(andrew) Add inventory-delta streaming for cross-format fetch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
29
29
        errors,
30
30
        lockdir,
31
31
        lockable_files,
32
 
        remote,
33
32
        repository,
34
33
        revision as _mod_revision,
35
34
        rio,
47
46
    )
48
47
""")
49
48
 
50
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
51
50
from bzrlib.hooks import HookPoint, Hooks
52
51
from bzrlib.inter import InterObject
53
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
54
52
from bzrlib import registry
55
53
from bzrlib.symbol_versioning import (
56
54
    deprecated_in,
64
62
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
65
63
 
66
64
 
67
 
class Branch(bzrdir.ControlComponent):
 
65
# TODO: Maybe include checks for common corruption of newlines, etc?
 
66
 
 
67
# TODO: Some operations like log might retrieve the same revisions
 
68
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
69
# cache in memory to make this faster.  In general anything can be
 
70
# cached in memory between lock and unlock operations. .. nb thats
 
71
# what the transaction identity map provides
 
72
 
 
73
 
 
74
######################################################################
 
75
# branch objects
 
76
 
 
77
class Branch(object):
68
78
    """Branch holding a history of revisions.
69
79
 
70
 
    :ivar base:
71
 
        Base directory/url of the branch; using control_url and
72
 
        control_transport is more standardized.
 
80
    base
 
81
        Base directory/url of the branch.
73
82
 
74
83
    hooks: An instance of BranchHooks.
75
84
    """
77
86
    # - RBC 20060112
78
87
    base = None
79
88
 
80
 
    @property
81
 
    def control_transport(self):
82
 
        return self._transport
83
 
 
84
 
    @property
85
 
    def user_transport(self):
86
 
        return self.bzrdir.user_transport
87
 
 
88
89
    def __init__(self, *ignored, **ignored_too):
89
90
        self.tags = self._format.make_tags(self)
90
91
        self._revision_history_cache = None
105
106
        """Activate the branch/repository from url as a fallback repository."""
106
107
        repo = self._get_fallback_repository(url)
107
108
        if repo.has_same_location(self.repository):
108
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
109
            raise errors.UnstackableLocationError(self.base, url)
109
110
        self.repository.add_fallback_repository(repo)
110
111
 
111
112
    def break_lock(self):
165
166
        """
166
167
        control = bzrdir.BzrDir.open(base, _unsupported,
167
168
                                     possible_transports=possible_transports)
168
 
        return control.open_branch(unsupported=_unsupported)
 
169
        return control.open_branch(_unsupported)
169
170
 
170
171
    @staticmethod
171
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
172
    def open_from_transport(transport, _unsupported=False):
172
173
        """Open the branch rooted at transport"""
173
174
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
174
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
175
        return control.open_branch(_unsupported)
175
176
 
176
177
    @staticmethod
177
178
    def open_containing(url, possible_transports=None):
198
199
        return self.supports_tags() and self.tags.get_tag_dict()
199
200
 
200
201
    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
202
        return BranchConfig(self)
209
203
 
210
204
    def _get_config(self):
222
216
    def _get_fallback_repository(self, url):
223
217
        """Get the repository we fallback to at url."""
224
218
        url = urlutils.join(self.base, url)
225
 
        a_branch = Branch.open(url,
 
219
        a_bzrdir = bzrdir.BzrDir.open(url,
226
220
            possible_transports=[self.bzrdir.root_transport])
227
 
        return a_branch.repository
 
221
        return a_bzrdir.open_branch().repository
228
222
 
229
223
    def _get_tags_bytes(self):
230
224
        """Get the bytes of a serialised tags dict.
246
240
        if not local and not config.has_explicit_nickname():
247
241
            try:
248
242
                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
243
                if master is not None:
252
244
                    # return the master branch value
253
245
                    return master.nick
254
 
            except errors.RecursiveBind, e:
255
 
                raise e
256
246
            except errors.BzrError, e:
257
247
                # Silently fall back to local implicit nick if the master is
258
248
                # unavailable
295
285
        new_history.reverse()
296
286
        return new_history
297
287
 
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
 
        """
 
288
    def lock_write(self):
305
289
        raise NotImplementedError(self.lock_write)
306
290
 
307
291
    def lock_read(self):
308
 
        """Lock the branch for read operations.
309
 
 
310
 
        :return: A bzrlib.lock.LogicalLockResult.
311
 
        """
312
292
        raise NotImplementedError(self.lock_read)
313
293
 
314
294
    def unlock(self):
439
419
            * 'include' - the stop revision is the last item in the result
440
420
            * 'with-merges' - include the stop revision and all of its
441
421
              merged revisions in the result
442
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
443
 
              that are in both ancestries
444
422
        :param direction: either 'reverse' or 'forward':
445
423
            * reverse means return the start_revision_id first, i.e.
446
424
              start at the most recent revision and go backwards in history
468
446
        # start_revision_id.
469
447
        if self._merge_sorted_revisions_cache is None:
470
448
            last_revision = self.last_revision()
471
 
            known_graph = self.repository.get_known_graph_ancestry(
472
 
                [last_revision])
473
 
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
474
 
                last_revision)
 
449
            graph = self.repository.get_graph()
 
450
            parent_map = dict(((key, value) for key, value in
 
451
                     graph.iter_ancestry([last_revision]) if value is not None))
 
452
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
453
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
454
                generate_revno=True)
 
455
            # Drop the sequence # before caching
 
456
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
457
 
475
458
        filtered = self._filter_merge_sorted_revisions(
476
459
            self._merge_sorted_revisions_cache, start_revision_id,
477
460
            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
461
        if direction == 'reverse':
482
462
            return filtered
483
463
        if direction == 'forward':
490
470
        """Iterate over an inclusive range of sorted revisions."""
491
471
        rev_iter = iter(merge_sorted_revisions)
492
472
        if start_revision_id is not None:
493
 
            for node in rev_iter:
494
 
                rev_id = node.key[-1]
 
473
            for rev_id, depth, revno, end_of_merge in rev_iter:
495
474
                if rev_id != start_revision_id:
496
475
                    continue
497
476
                else:
498
477
                    # The decision to include the start or not
499
478
                    # depends on the stop_rule if a stop is provided
500
 
                    # so pop this node back into the iterator
501
 
                    rev_iter = chain(iter([node]), rev_iter)
 
479
                    rev_iter = chain(
 
480
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
481
                        rev_iter)
502
482
                    break
503
483
        if stop_revision_id is None:
504
 
            # Yield everything
505
 
            for node in rev_iter:
506
 
                rev_id = node.key[-1]
507
 
                yield (rev_id, node.merge_depth, node.revno,
508
 
                       node.end_of_merge)
 
484
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
485
                yield rev_id, depth, revno, end_of_merge
509
486
        elif stop_rule == 'exclude':
510
 
            for node in rev_iter:
511
 
                rev_id = node.key[-1]
 
487
            for rev_id, depth, revno, end_of_merge in rev_iter:
512
488
                if rev_id == stop_revision_id:
513
489
                    return
514
 
                yield (rev_id, node.merge_depth, node.revno,
515
 
                       node.end_of_merge)
 
490
                yield rev_id, depth, revno, end_of_merge
516
491
        elif stop_rule == 'include':
517
 
            for node in rev_iter:
518
 
                rev_id = node.key[-1]
519
 
                yield (rev_id, node.merge_depth, node.revno,
520
 
                       node.end_of_merge)
 
492
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
493
                yield rev_id, depth, revno, end_of_merge
521
494
                if rev_id == stop_revision_id:
522
495
                    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
496
        elif stop_rule == 'with-merges':
536
497
            stop_rev = self.repository.get_revision(stop_revision_id)
537
498
            if stop_rev.parent_ids:
538
499
                left_parent = stop_rev.parent_ids[0]
539
500
            else:
540
501
                left_parent = _mod_revision.NULL_REVISION
541
 
            # left_parent is the actual revision we want to stop logging at,
542
 
            # since we want to show the merged revisions after the stop_rev too
543
 
            reached_stop_revision_id = False
544
 
            revision_id_whitelist = []
545
 
            for node in rev_iter:
546
 
                rev_id = node.key[-1]
 
502
            for rev_id, depth, revno, end_of_merge in rev_iter:
547
503
                if rev_id == left_parent:
548
 
                    # reached the left parent after the stop_revision
549
504
                    return
550
 
                if (not reached_stop_revision_id or
551
 
                        rev_id in revision_id_whitelist):
552
 
                    yield (rev_id, node.merge_depth, node.revno,
553
 
                       node.end_of_merge)
554
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
555
 
                        # only do the merged revs of rev_id from now on
556
 
                        rev = self.repository.get_revision(rev_id)
557
 
                        if rev.parent_ids:
558
 
                            reached_stop_revision_id = True
559
 
                            revision_id_whitelist.extend(rev.parent_ids)
 
505
                yield rev_id, depth, revno, end_of_merge
560
506
        else:
561
507
            raise ValueError('invalid stop_rule %r' % stop_rule)
562
508
 
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
509
    def leave_lock_in_place(self):
609
510
        """Tell this branch object not to release the physical lock when this
610
511
        object is unlocked.
627
528
        :param other: The branch to bind to
628
529
        :type other: Branch
629
530
        """
630
 
        raise errors.UpgradeRequired(self.user_url)
 
531
        raise errors.UpgradeRequired(self.base)
631
532
 
632
533
    def set_append_revisions_only(self, enabled):
633
534
        if not self._format.supports_set_append_revisions_only():
634
 
            raise errors.UpgradeRequired(self.user_url)
 
535
            raise errors.UpgradeRequired(self.base)
635
536
        if enabled:
636
537
            value = 'True'
637
538
        else:
685
586
    def get_old_bound_location(self):
686
587
        """Return the URL of the branch we used to be bound to
687
588
        """
688
 
        raise errors.UpgradeRequired(self.user_url)
 
589
        raise errors.UpgradeRequired(self.base)
689
590
 
690
591
    def get_commit_builder(self, parents, config=None, timestamp=None,
691
592
                           timezone=None, committer=None, revprops=None,
769
670
            stacking.
770
671
        """
771
672
        if not self._format.supports_stacking():
772
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
673
            raise errors.UnstackableBranchFormat(self._format, self.base)
773
674
        # XXX: Changing from one fallback repository to another does not check
774
675
        # that all the data you need is present in the new fallback.
775
676
        # Possibly it should.
805
706
            if len(old_repository._fallback_repositories) != 1:
806
707
                raise AssertionError("can't cope with fallback repositories "
807
708
                    "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()
 
709
            # unlock it, including unlocking the fallback
835
710
            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):
 
711
            old_repository.lock_read()
 
712
            try:
 
713
                # Repositories don't offer an interface to remove fallback
 
714
                # repositories today; take the conceptually simpler option and just
 
715
                # reopen it.  We reopen it starting from the URL so that we
 
716
                # get a separate connection for RemoteRepositories and can
 
717
                # stream from one of them to the other.  This does mean doing
 
718
                # separate SSH connection setup, but unstacking is not a
 
719
                # common operation so it's tolerable.
 
720
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
721
                new_repository = new_bzrdir.find_repository()
 
722
                self.repository = new_repository
 
723
                if self.repository._fallback_repositories:
 
724
                    raise AssertionError("didn't expect %r to have "
 
725
                        "fallback_repositories"
 
726
                        % (self.repository,))
 
727
                # this is not paired with an unlock because it's just restoring
 
728
                # the previous state; the lock's released when set_stacked_on_url
 
729
                # returns
854
730
                self.repository.lock_write()
855
 
            # Fetch from the old repository into the new.
856
 
            old_repository.lock_read()
857
 
            try:
858
731
                # XXX: If you unstack a branch while it has a working tree
859
732
                # with a pending merge, the pending-merged revisions will no
860
733
                # longer be present.  You can (probably) revert and remerge.
954
827
 
955
828
    def unbind(self):
956
829
        """Older format branches cannot bind or unbind."""
957
 
        raise errors.UpgradeRequired(self.user_url)
 
830
        raise errors.UpgradeRequired(self.base)
958
831
 
959
832
    def last_revision(self):
960
833
        """Return last revision id, or NULL_REVISION."""
1001
874
                raise errors.NoSuchRevision(self, stop_revision)
1002
875
        return other_history[self_len:stop_revision]
1003
876
 
 
877
    @needs_write_lock
1004
878
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1005
879
                         graph=None):
1006
880
        """Pull in new perfect-fit revisions.
1055
929
            self._extend_partial_history(distance_from_last)
1056
930
        return self._partial_revision_history_cache[distance_from_last]
1057
931
 
 
932
    @needs_write_lock
1058
933
    def pull(self, source, overwrite=False, stop_revision=None,
1059
934
             possible_transports=None, *args, **kwargs):
1060
935
        """Mirror source into this branch.
1118
993
        try:
1119
994
            return urlutils.join(self.base[:-1], parent)
1120
995
        except errors.InvalidURLJoin, e:
1121
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
996
            raise errors.InaccessibleParent(parent, self.base)
1122
997
 
1123
998
    def _get_parent_location(self):
1124
999
        raise NotImplementedError(self._get_parent_location)
1209
1084
        params = ChangeBranchTipParams(
1210
1085
            self, old_revno, new_revno, old_revid, new_revid)
1211
1086
        for hook in hooks:
1212
 
            hook(params)
 
1087
            try:
 
1088
                hook(params)
 
1089
            except errors.TipChangeRejected:
 
1090
                raise
 
1091
            except Exception:
 
1092
                exc_info = sys.exc_info()
 
1093
                hook_name = Branch.hooks.get_hook_name(hook)
 
1094
                raise errors.HookFailed(
 
1095
                    'pre_change_branch_tip', hook_name, exc_info)
1213
1096
 
1214
1097
    @needs_write_lock
1215
1098
    def update(self):
1264
1147
        revision_id: if not None, the revision history in the new branch will
1265
1148
                     be truncated to end with revision_id.
1266
1149
        """
1267
 
        if (repository_policy is not None and
1268
 
            repository_policy.requires_stacking()):
1269
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1270
1150
        result = to_bzrdir.create_branch()
1271
1151
        result.lock_write()
1272
1152
        try:
1303
1183
                revno = 1
1304
1184
        destination.set_last_revision_info(revno, revision_id)
1305
1185
 
 
1186
    @needs_read_lock
1306
1187
    def copy_content_into(self, destination, revision_id=None):
1307
1188
        """Copy the content of self into destination.
1308
1189
 
1309
1190
        revision_id: if not None, the revision history in the new branch will
1310
1191
                     be truncated to end with revision_id.
1311
1192
        """
1312
 
        return InterBranch.get(self, destination).copy_content_into(
1313
 
            revision_id=revision_id)
 
1193
        self.update_references(destination)
 
1194
        self._synchronize_history(destination, revision_id)
 
1195
        try:
 
1196
            parent = self.get_parent()
 
1197
        except errors.InaccessibleParent, e:
 
1198
            mutter('parent was not accessible to copy: %s', e)
 
1199
        else:
 
1200
            if parent:
 
1201
                destination.set_parent(parent)
 
1202
        if self._push_should_merge_tags():
 
1203
            self.tags.merge_to(destination.tags)
1314
1204
 
1315
1205
    def update_references(self, target):
1316
1206
        if not getattr(self._format, 'supports_reference_locations', False):
1384
1274
        """
1385
1275
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1386
1276
        # 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
1277
        if revision_id is None:
1390
1278
            revision_id = self.last_revision()
1391
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1392
 
            revision_id=revision_id, stacked_on=stacked_on,
1393
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1279
        try:
 
1280
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1281
                revision_id=revision_id, stacked_on=stacked_on,
 
1282
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1283
        except errors.FileExists:
 
1284
            if not use_existing_dir:
 
1285
                raise
 
1286
        except errors.NoSuchFile:
 
1287
            if not create_prefix:
 
1288
                raise
1394
1289
        return dir_to.open_branch()
1395
1290
 
1396
1291
    def create_checkout(self, to_location, revision_id=None,
1415
1310
        if lightweight:
1416
1311
            format = self._get_checkout_format()
1417
1312
            checkout = format.initialize_on_transport(t)
1418
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1419
 
                target_branch=self)
 
1313
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1420
1314
        else:
1421
1315
            format = self._get_checkout_format()
1422
1316
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1464
1358
    def supports_tags(self):
1465
1359
        return self._format.supports_tags()
1466
1360
 
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
1361
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1480
1362
                                         other_branch):
1481
1363
        """Ensure that revision_b is a descendant of revision_a.
1545
1427
        return not (self == other)
1546
1428
 
1547
1429
    @classmethod
1548
 
    def find_format(klass, a_bzrdir, name=None):
 
1430
    def find_format(klass, a_bzrdir):
1549
1431
        """Return the format for the branch object in a_bzrdir."""
1550
1432
        try:
1551
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1552
 
            format_string = transport.get_bytes("format")
1553
 
            format = klass._formats[format_string]
1554
 
            if isinstance(format, MetaDirBranchFormatFactory):
1555
 
                return format()
1556
 
            return format
 
1433
            transport = a_bzrdir.get_branch_transport(None)
 
1434
            format_string = transport.get("format").read()
 
1435
            return klass._formats[format_string]
1557
1436
        except errors.NoSuchFile:
1558
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1437
            raise errors.NotBranchError(path=transport.base)
1559
1438
        except KeyError:
1560
1439
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1561
1440
 
1564
1443
        """Return the current default format."""
1565
1444
        return klass._default_format
1566
1445
 
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):
 
1446
    def get_reference(self, a_bzrdir):
1582
1447
        """Get the target reference of the branch in a_bzrdir.
1583
1448
 
1584
1449
        format probing must have been completed before calling
1586
1451
        in a_bzrdir is correct.
1587
1452
 
1588
1453
        :param a_bzrdir: The bzrdir to get the branch data from.
1589
 
        :param name: Name of the colocated branch to fetch
1590
1454
        :return: None if the branch is not a reference branch.
1591
1455
        """
1592
1456
        return None
1593
1457
 
1594
1458
    @classmethod
1595
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1459
    def set_reference(self, a_bzrdir, to_branch):
1596
1460
        """Set the target reference of the branch in a_bzrdir.
1597
1461
 
1598
1462
        format probing must have been completed before calling
1600
1464
        in a_bzrdir is correct.
1601
1465
 
1602
1466
        :param a_bzrdir: The bzrdir to set the branch reference for.
1603
 
        :param name: Name of colocated branch to set, None for default
1604
1467
        :param to_branch: branch that the checkout is to reference
1605
1468
        """
1606
1469
        raise NotImplementedError(self.set_reference)
1613
1476
        """Return the short format description for this format."""
1614
1477
        raise NotImplementedError(self.get_format_description)
1615
1478
 
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):
 
1479
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1480
                           set_format=True):
1626
1481
        """Initialize a branch in a bzrdir, with specified files
1627
1482
 
1628
1483
        :param a_bzrdir: The bzrdir to initialize the branch in
1629
1484
        :param utf8_files: The files to create as a list of
1630
1485
            (filename, content) tuples
1631
 
        :param name: Name of colocated branch to create, if any
1632
1486
        :param set_format: If True, set the format with
1633
1487
            self.get_format_string.  (BzrBranch4 has its format set
1634
1488
            elsewhere)
1635
1489
        :return: a branch in this format
1636
1490
        """
1637
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1638
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1491
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1492
        branch_transport = a_bzrdir.get_branch_transport(self)
1639
1493
        lock_map = {
1640
1494
            'metadir': ('lock', lockdir.LockDir),
1641
1495
            'branch4': ('branch-lock', lockable_files.TransportLock),
1662
1516
        finally:
1663
1517
            if lock_taken:
1664
1518
                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
 
1519
        return self.open(a_bzrdir, _found=True)
1668
1520
 
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
 
        """
 
1521
    def initialize(self, a_bzrdir):
 
1522
        """Create a branch of this format in a_bzrdir."""
1674
1523
        raise NotImplementedError(self.initialize)
1675
1524
 
1676
1525
    def is_supported(self):
1706
1555
        """
1707
1556
        raise NotImplementedError(self.network_name)
1708
1557
 
1709
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1558
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1710
1559
        """Return the branch object for a_bzrdir
1711
1560
 
1712
1561
        :param a_bzrdir: A BzrDir that contains a branch.
1713
 
        :param name: Name of colocated branch to open
1714
1562
        :param _found: a private parameter, do not use it. It is used to
1715
1563
            indicate if format probing has already be done.
1716
1564
        :param ignore_fallbacks: when set, no fallback branches will be opened
1720
1568
 
1721
1569
    @classmethod
1722
1570
    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
 
        """
 
1571
        """Register a metadir format."""
1728
1572
        klass._formats[format.get_format_string()] = format
1729
1573
        # 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__)
 
1574
        # registered as class factories.
 
1575
        network_format_registry.register(format.get_format_string(), format.__class__)
1736
1576
 
1737
1577
    @classmethod
1738
1578
    def set_default_format(klass, format):
1758
1598
        return False  # by default
1759
1599
 
1760
1600
 
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
1601
class BranchHooks(Hooks):
1790
1602
    """A dictionary mapping hook name to a list of callables for branch hooks.
1791
1603
 
1860
1672
            "multiple hooks installed for transform_fallback_location, "
1861
1673
            "all are called with the url returned from the previous hook."
1862
1674
            "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
1675
 
1881
1676
 
1882
1677
# install the default hooks into the Branch class.
1921
1716
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1922
1717
 
1923
1718
 
1924
 
class BranchInitHookParams(object):
1925
 
    """Object holding parameters passed to *_branch_init hooks.
1926
 
 
1927
 
    There are 4 fields that hooks may wish to access:
1928
 
 
1929
 
    :ivar format: the branch format
1930
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1931
 
    :ivar name: name of colocated branch, if any (or None)
1932
 
    :ivar branch: the branch created
1933
 
 
1934
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1935
 
    the checkout, hence they are different from the corresponding fields in
1936
 
    branch, which refer to the original branch.
1937
 
    """
1938
 
 
1939
 
    def __init__(self, format, a_bzrdir, name, branch):
1940
 
        """Create a group of BranchInitHook parameters.
1941
 
 
1942
 
        :param format: the branch format
1943
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1944
 
            initialized
1945
 
        :param name: name of colocated branch, if any (or None)
1946
 
        :param branch: the branch created
1947
 
 
1948
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1949
 
        to the checkout, hence they are different from the corresponding fields
1950
 
        in branch, which refer to the original branch.
1951
 
        """
1952
 
        self.format = format
1953
 
        self.bzrdir = a_bzrdir
1954
 
        self.name = name
1955
 
        self.branch = branch
1956
 
 
1957
 
    def __eq__(self, other):
1958
 
        return self.__dict__ == other.__dict__
1959
 
 
1960
 
    def __repr__(self):
1961
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1962
 
 
1963
 
 
1964
 
class SwitchHookParams(object):
1965
 
    """Object holding parameters passed to *_switch hooks.
1966
 
 
1967
 
    There are 4 fields that hooks may wish to access:
1968
 
 
1969
 
    :ivar control_dir: BzrDir of the checkout to change
1970
 
    :ivar to_branch: branch that the checkout is to reference
1971
 
    :ivar force: skip the check for local commits in a heavy checkout
1972
 
    :ivar revision_id: revision ID to switch to (or None)
1973
 
    """
1974
 
 
1975
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1976
 
        """Create a group of SwitchHook parameters.
1977
 
 
1978
 
        :param control_dir: BzrDir of the checkout to change
1979
 
        :param to_branch: branch that the checkout is to reference
1980
 
        :param force: skip the check for local commits in a heavy checkout
1981
 
        :param revision_id: revision ID to switch to (or None)
1982
 
        """
1983
 
        self.control_dir = control_dir
1984
 
        self.to_branch = to_branch
1985
 
        self.force = force
1986
 
        self.revision_id = revision_id
1987
 
 
1988
 
    def __eq__(self, other):
1989
 
        return self.__dict__ == other.__dict__
1990
 
 
1991
 
    def __repr__(self):
1992
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1993
 
            self.control_dir, self.to_branch,
1994
 
            self.revision_id)
1995
 
 
1996
 
 
1997
1719
class BzrBranchFormat4(BranchFormat):
1998
1720
    """Bzr branch format 4.
1999
1721
 
2006
1728
        """See BranchFormat.get_format_description()."""
2007
1729
        return "Branch format 4"
2008
1730
 
2009
 
    def initialize(self, a_bzrdir, name=None):
 
1731
    def initialize(self, a_bzrdir):
2010
1732
        """Create a branch of this format in a_bzrdir."""
2011
1733
        utf8_files = [('revision-history', ''),
2012
1734
                      ('branch-name', ''),
2013
1735
                      ]
2014
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1736
        return self._initialize_helper(a_bzrdir, utf8_files,
2015
1737
                                       lock_type='branch4', set_format=False)
2016
1738
 
2017
1739
    def __init__(self):
2022
1744
        """The network name for this format is the control dirs disk label."""
2023
1745
        return self._matchingbzrdir.get_format_string()
2024
1746
 
2025
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1747
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2026
1748
        """See BranchFormat.open()."""
2027
1749
        if not _found:
2028
1750
            # we are being called directly and must probe.
2030
1752
        return BzrBranch(_format=self,
2031
1753
                         _control_files=a_bzrdir._control_files,
2032
1754
                         a_bzrdir=a_bzrdir,
2033
 
                         name=name,
2034
1755
                         _repository=a_bzrdir.open_repository())
2035
1756
 
2036
1757
    def __str__(self):
2051
1772
        """
2052
1773
        return self.get_format_string()
2053
1774
 
2054
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1775
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2055
1776
        """See BranchFormat.open()."""
2056
1777
        if not _found:
2057
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1778
            format = BranchFormat.find_format(a_bzrdir)
2058
1779
            if format.__class__ != self.__class__:
2059
1780
                raise AssertionError("wrong format %r found for %r" %
2060
1781
                    (format, self))
2061
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2062
1782
        try:
 
1783
            transport = a_bzrdir.get_branch_transport(None)
2063
1784
            control_files = lockable_files.LockableFiles(transport, 'lock',
2064
1785
                                                         lockdir.LockDir)
2065
1786
            return self._branch_class()(_format=self,
2066
1787
                              _control_files=control_files,
2067
 
                              name=name,
2068
1788
                              a_bzrdir=a_bzrdir,
2069
1789
                              _repository=a_bzrdir.find_repository(),
2070
1790
                              ignore_fallbacks=ignore_fallbacks)
2071
1791
        except errors.NoSuchFile:
2072
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1792
            raise errors.NotBranchError(path=transport.base)
2073
1793
 
2074
1794
    def __init__(self):
2075
1795
        super(BranchFormatMetadir, self).__init__()
2104
1824
        """See BranchFormat.get_format_description()."""
2105
1825
        return "Branch format 5"
2106
1826
 
2107
 
    def initialize(self, a_bzrdir, name=None):
 
1827
    def initialize(self, a_bzrdir):
2108
1828
        """Create a branch of this format in a_bzrdir."""
2109
1829
        utf8_files = [('revision-history', ''),
2110
1830
                      ('branch-name', ''),
2111
1831
                      ]
2112
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1832
        return self._initialize_helper(a_bzrdir, utf8_files)
2113
1833
 
2114
1834
    def supports_tags(self):
2115
1835
        return False
2137
1857
        """See BranchFormat.get_format_description()."""
2138
1858
        return "Branch format 6"
2139
1859
 
2140
 
    def initialize(self, a_bzrdir, name=None):
 
1860
    def initialize(self, a_bzrdir):
2141
1861
        """Create a branch of this format in a_bzrdir."""
2142
1862
        utf8_files = [('last-revision', '0 null:\n'),
2143
1863
                      ('branch.conf', ''),
2144
1864
                      ('tags', ''),
2145
1865
                      ]
2146
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1866
        return self._initialize_helper(a_bzrdir, utf8_files)
2147
1867
 
2148
1868
    def make_tags(self, branch):
2149
1869
        """See bzrlib.branch.BranchFormat.make_tags()."""
2167
1887
        """See BranchFormat.get_format_description()."""
2168
1888
        return "Branch format 8"
2169
1889
 
2170
 
    def initialize(self, a_bzrdir, name=None):
 
1890
    def initialize(self, a_bzrdir):
2171
1891
        """Create a branch of this format in a_bzrdir."""
2172
1892
        utf8_files = [('last-revision', '0 null:\n'),
2173
1893
                      ('branch.conf', ''),
2174
1894
                      ('tags', ''),
2175
1895
                      ('references', '')
2176
1896
                      ]
2177
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1897
        return self._initialize_helper(a_bzrdir, utf8_files)
2178
1898
 
2179
1899
    def __init__(self):
2180
1900
        super(BzrBranchFormat8, self).__init__()
2203
1923
    This format was introduced in bzr 1.6.
2204
1924
    """
2205
1925
 
2206
 
    def initialize(self, a_bzrdir, name=None):
 
1926
    def initialize(self, a_bzrdir):
2207
1927
        """Create a branch of this format in a_bzrdir."""
2208
1928
        utf8_files = [('last-revision', '0 null:\n'),
2209
1929
                      ('branch.conf', ''),
2210
1930
                      ('tags', ''),
2211
1931
                      ]
2212
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1932
        return self._initialize_helper(a_bzrdir, utf8_files)
2213
1933
 
2214
1934
    def _branch_class(self):
2215
1935
        return BzrBranch7
2247
1967
        """See BranchFormat.get_format_description()."""
2248
1968
        return "Checkout reference format 1"
2249
1969
 
2250
 
    def get_reference(self, a_bzrdir, name=None):
 
1970
    def get_reference(self, a_bzrdir):
2251
1971
        """See BranchFormat.get_reference()."""
2252
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2253
 
        return transport.get_bytes('location')
 
1972
        transport = a_bzrdir.get_branch_transport(None)
 
1973
        return transport.get('location').read()
2254
1974
 
2255
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1975
    def set_reference(self, a_bzrdir, to_branch):
2256
1976
        """See BranchFormat.set_reference()."""
2257
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1977
        transport = a_bzrdir.get_branch_transport(None)
2258
1978
        location = transport.put_bytes('location', to_branch.base)
2259
1979
 
2260
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1980
    def initialize(self, a_bzrdir, target_branch=None):
2261
1981
        """Create a branch of this format in a_bzrdir."""
2262
1982
        if target_branch is None:
2263
1983
            # this format does not implement branch itself, thus the implicit
2264
1984
            # creation contract must see it as uninitializable
2265
1985
            raise errors.UninitializableFormat(self)
2266
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2267
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1986
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1987
        branch_transport = a_bzrdir.get_branch_transport(self)
2268
1988
        branch_transport.put_bytes('location',
2269
 
            target_branch.bzrdir.user_url)
 
1989
            target_branch.bzrdir.root_transport.base)
2270
1990
        branch_transport.put_bytes('format', self.get_format_string())
2271
 
        branch = self.open(
2272
 
            a_bzrdir, name, _found=True,
 
1991
        return self.open(
 
1992
            a_bzrdir, _found=True,
2273
1993
            possible_transports=[target_branch.bzrdir.root_transport])
2274
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2275
 
        return branch
2276
1994
 
2277
1995
    def __init__(self):
2278
1996
        super(BranchReferenceFormat, self).__init__()
2284
2002
        def clone(to_bzrdir, revision_id=None,
2285
2003
            repository_policy=None):
2286
2004
            """See Branch.clone()."""
2287
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2005
            return format.initialize(to_bzrdir, a_branch)
2288
2006
            # cannot obey revision_id limits when cloning a reference ...
2289
2007
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2290
2008
            # emit some sort of warning/error to the caller ?!
2291
2009
        return clone
2292
2010
 
2293
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2011
    def open(self, a_bzrdir, _found=False, location=None,
2294
2012
             possible_transports=None, ignore_fallbacks=False):
2295
2013
        """Return the branch that the branch reference in a_bzrdir points at.
2296
2014
 
2297
2015
        :param a_bzrdir: A BzrDir that contains a branch.
2298
 
        :param name: Name of colocated branch to open, if any
2299
2016
        :param _found: a private parameter, do not use it. It is used to
2300
2017
            indicate if format probing has already be done.
2301
2018
        :param ignore_fallbacks: when set, no fallback branches will be opened
2306
2023
        :param possible_transports: An optional reusable transports list.
2307
2024
        """
2308
2025
        if not _found:
2309
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2026
            format = BranchFormat.find_format(a_bzrdir)
2310
2027
            if format.__class__ != self.__class__:
2311
2028
                raise AssertionError("wrong format %r found for %r" %
2312
2029
                    (format, self))
2313
2030
        if location is None:
2314
 
            location = self.get_reference(a_bzrdir, name)
 
2031
            location = self.get_reference(a_bzrdir)
2315
2032
        real_bzrdir = bzrdir.BzrDir.open(
2316
2033
            location, possible_transports=possible_transports)
2317
 
        result = real_bzrdir.open_branch(name=name, 
2318
 
            ignore_fallbacks=ignore_fallbacks)
 
2034
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2319
2035
        # this changes the behaviour of result.clone to create a new reference
2320
2036
        # rather than a copy of the content of the branch.
2321
2037
        # I did not use a proxy object because that needs much more extensive
2348
2064
BranchFormat.register_format(__format6)
2349
2065
BranchFormat.register_format(__format7)
2350
2066
BranchFormat.register_format(__format8)
2351
 
BranchFormat.set_default_format(__format7)
 
2067
BranchFormat.set_default_format(__format6)
2352
2068
_legacy_formats = [BzrBranchFormat4(),
2353
2069
    ]
2354
2070
network_format_registry.register(
2355
2071
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2356
2072
 
2357
2073
 
2358
 
class BranchWriteLockResult(LogicalLockResult):
2359
 
    """The result of write locking a branch.
2360
 
 
2361
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2362
 
        None.
2363
 
    :ivar unlock: A callable which will unlock the lock.
2364
 
    """
2365
 
 
2366
 
    def __init__(self, unlock, branch_token):
2367
 
        LogicalLockResult.__init__(self, unlock)
2368
 
        self.branch_token = branch_token
2369
 
 
2370
 
    def __repr__(self):
2371
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2372
 
            self.unlock)
2373
 
 
2374
 
 
2375
 
class BzrBranch(Branch, _RelockDebugMixin):
 
2074
class BzrBranch(Branch):
2376
2075
    """A branch stored in the actual filesystem.
2377
2076
 
2378
2077
    Note that it's "local" in the context of the filesystem; it doesn't
2384
2083
    :ivar repository: Repository for this branch.
2385
2084
    :ivar base: The url of the base directory for this branch; the one
2386
2085
        containing the .bzr directory.
2387
 
    :ivar name: Optional colocated branch name as it exists in the control
2388
 
        directory.
2389
2086
    """
2390
2087
 
2391
2088
    def __init__(self, _format=None,
2392
 
                 _control_files=None, a_bzrdir=None, name=None,
2393
 
                 _repository=None, ignore_fallbacks=False):
 
2089
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2090
                 ignore_fallbacks=False):
2394
2091
        """Create new branch object at a particular location."""
2395
2092
        if a_bzrdir is None:
2396
2093
            raise ValueError('a_bzrdir must be supplied')
2397
2094
        else:
2398
2095
            self.bzrdir = a_bzrdir
2399
2096
        self._base = self.bzrdir.transport.clone('..').base
2400
 
        self.name = name
2401
2097
        # XXX: We should be able to just do
2402
2098
        #   self.base = self.bzrdir.root_transport.base
2403
2099
        # but this does not quite work yet -- mbp 20080522
2410
2106
        Branch.__init__(self)
2411
2107
 
2412
2108
    def __str__(self):
2413
 
        if self.name is None:
2414
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2415
 
        else:
2416
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2417
 
                self.name)
 
2109
        return '%s(%r)' % (self.__class__.__name__, self.base)
2418
2110
 
2419
2111
    __repr__ = __str__
2420
2112
 
2431
2123
        return self.control_files.is_locked()
2432
2124
 
2433
2125
    def lock_write(self, token=None):
2434
 
        """Lock the branch for write operations.
2435
 
 
2436
 
        :param token: A token to permit reacquiring a previously held and
2437
 
            preserved lock.
2438
 
        :return: A BranchWriteLockResult.
2439
 
        """
2440
 
        if not self.is_locked():
2441
 
            self._note_lock('w')
2442
2126
        # All-in-one needs to always unlock/lock.
2443
2127
        repo_control = getattr(self.repository, 'control_files', None)
2444
2128
        if self.control_files == repo_control or not self.is_locked():
2445
 
            self.repository._warn_if_deprecated(self)
2446
2129
            self.repository.lock_write()
2447
2130
            took_lock = True
2448
2131
        else:
2449
2132
            took_lock = False
2450
2133
        try:
2451
 
            return BranchWriteLockResult(self.unlock,
2452
 
                self.control_files.lock_write(token=token))
 
2134
            return self.control_files.lock_write(token=token)
2453
2135
        except:
2454
2136
            if took_lock:
2455
2137
                self.repository.unlock()
2456
2138
            raise
2457
2139
 
2458
2140
    def lock_read(self):
2459
 
        """Lock the branch for read operations.
2460
 
 
2461
 
        :return: A bzrlib.lock.LogicalLockResult.
2462
 
        """
2463
 
        if not self.is_locked():
2464
 
            self._note_lock('r')
2465
2141
        # All-in-one needs to always unlock/lock.
2466
2142
        repo_control = getattr(self.repository, 'control_files', None)
2467
2143
        if self.control_files == repo_control or not self.is_locked():
2468
 
            self.repository._warn_if_deprecated(self)
2469
2144
            self.repository.lock_read()
2470
2145
            took_lock = True
2471
2146
        else:
2472
2147
            took_lock = False
2473
2148
        try:
2474
2149
            self.control_files.lock_read()
2475
 
            return LogicalLockResult(self.unlock)
2476
2150
        except:
2477
2151
            if took_lock:
2478
2152
                self.repository.unlock()
2479
2153
            raise
2480
2154
 
2481
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2482
2155
    def unlock(self):
2483
2156
        try:
2484
2157
            self.control_files.unlock()
2647
2320
        return result
2648
2321
 
2649
2322
    def get_stacked_on_url(self):
2650
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2323
        raise errors.UnstackableBranchFormat(self._format, self.base)
2651
2324
 
2652
2325
    def set_push_location(self, location):
2653
2326
        """See Branch.set_push_location."""
2843
2516
        if _mod_revision.is_null(last_revision):
2844
2517
            return
2845
2518
        if last_revision not in self._lefthand_history(revision_id):
2846
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2519
            raise errors.AppendRevisionsOnlyViolation(self.base)
2847
2520
 
2848
2521
    def _gen_revision_history(self):
2849
2522
        """Generate the revision history from last revision
2949
2622
        if branch_location is None:
2950
2623
            return Branch.reference_parent(self, file_id, path,
2951
2624
                                           possible_transports)
2952
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2625
        branch_location = urlutils.join(self.base, branch_location)
2953
2626
        return Branch.open(branch_location,
2954
2627
                           possible_transports=possible_transports)
2955
2628
 
3001
2674
        return stacked_url
3002
2675
 
3003
2676
    def _get_append_revisions_only(self):
3004
 
        return self.get_config(
3005
 
            ).get_user_option_as_bool('append_revisions_only')
 
2677
        value = self.get_config().get_user_option('append_revisions_only')
 
2678
        return value == 'True'
3006
2679
 
3007
2680
    @needs_write_lock
3008
2681
    def generate_revision_history(self, revision_id, last_rev=None,
3070
2743
    """
3071
2744
 
3072
2745
    def get_stacked_on_url(self):
3073
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2746
        raise errors.UnstackableBranchFormat(self._format, self.base)
3074
2747
 
3075
2748
 
3076
2749
######################################################################
3163
2836
        :param verbose: Requests more detailed display of what was checked,
3164
2837
            if any.
3165
2838
        """
3166
 
        note('checked branch %s format %s', self.branch.user_url,
 
2839
        note('checked branch %s format %s', self.branch.base,
3167
2840
            self.branch._format)
3168
2841
        for error in self.errors:
3169
2842
            note('found error:%s', error)
3264
2937
    _optimisers = []
3265
2938
    """The available optimised InterBranch types."""
3266
2939
 
3267
 
    @classmethod
3268
 
    def _get_branch_formats_to_test(klass):
3269
 
        """Return an iterable of format tuples for testing.
3270
 
        
3271
 
        :return: An iterable of (from_format, to_format) to use when testing
3272
 
            this InterBranch class. Each InterBranch class should define this
3273
 
            method itself.
3274
 
        """
3275
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2940
    @staticmethod
 
2941
    def _get_branch_formats_to_test():
 
2942
        """Return a tuple with the Branch formats to use when testing."""
 
2943
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3276
2944
 
3277
 
    @needs_write_lock
3278
2945
    def pull(self, overwrite=False, stop_revision=None,
3279
2946
             possible_transports=None, local=False):
3280
2947
        """Mirror source into target branch.
3285
2952
        """
3286
2953
        raise NotImplementedError(self.pull)
3287
2954
 
3288
 
    @needs_write_lock
3289
2955
    def update_revisions(self, stop_revision=None, overwrite=False,
3290
2956
                         graph=None):
3291
2957
        """Pull in new perfect-fit revisions.
3299
2965
        """
3300
2966
        raise NotImplementedError(self.update_revisions)
3301
2967
 
3302
 
    @needs_write_lock
3303
2968
    def push(self, overwrite=False, stop_revision=None,
3304
2969
             _override_hook_source_branch=None):
3305
2970
        """Mirror the source branch into the target branch.
3308
2973
        """
3309
2974
        raise NotImplementedError(self.push)
3310
2975
 
3311
 
    @needs_write_lock
3312
 
    def copy_content_into(self, revision_id=None):
3313
 
        """Copy the content of source into target
3314
 
 
3315
 
        revision_id: if not None, the revision history in the new branch will
3316
 
                     be truncated to end with revision_id.
3317
 
        """
3318
 
        raise NotImplementedError(self.copy_content_into)
3319
 
 
3320
2976
 
3321
2977
class GenericInterBranch(InterBranch):
3322
 
    """InterBranch implementation that uses public Branch functions."""
3323
 
 
3324
 
    @classmethod
3325
 
    def is_compatible(klass, source, target):
3326
 
        # GenericBranch uses the public API, so always compatible
3327
 
        return True
3328
 
 
3329
 
    @classmethod
3330
 
    def _get_branch_formats_to_test(klass):
3331
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3332
 
 
3333
 
    @classmethod
3334
 
    def unwrap_format(klass, format):
3335
 
        if isinstance(format, remote.RemoteBranchFormat):
3336
 
            format._ensure_real()
3337
 
            return format._custom_format
3338
 
        return format                                                                                                  
3339
 
 
3340
 
    @needs_write_lock
3341
 
    def copy_content_into(self, revision_id=None):
3342
 
        """Copy the content of source into target
3343
 
 
3344
 
        revision_id: if not None, the revision history in the new branch will
3345
 
                     be truncated to end with revision_id.
3346
 
        """
3347
 
        self.source.update_references(self.target)
3348
 
        self.source._synchronize_history(self.target, revision_id)
3349
 
        try:
3350
 
            parent = self.source.get_parent()
3351
 
        except errors.InaccessibleParent, e:
3352
 
            mutter('parent was not accessible to copy: %s', e)
3353
 
        else:
3354
 
            if parent:
3355
 
                self.target.set_parent(parent)
3356
 
        if self.source._push_should_merge_tags():
3357
 
            self.source.tags.merge_to(self.target.tags)
3358
 
 
3359
 
    @needs_write_lock
 
2978
    """InterBranch implementation that uses public Branch functions.
 
2979
    """
 
2980
 
 
2981
    @staticmethod
 
2982
    def _get_branch_formats_to_test():
 
2983
        return BranchFormat._default_format, BranchFormat._default_format
 
2984
 
3360
2985
    def update_revisions(self, stop_revision=None, overwrite=False,
3361
2986
        graph=None):
3362
2987
        """See InterBranch.update_revisions()."""
3363
 
        other_revno, other_last_revision = self.source.last_revision_info()
3364
 
        stop_revno = None # unknown
3365
 
        if stop_revision is None:
3366
 
            stop_revision = other_last_revision
3367
 
            if _mod_revision.is_null(stop_revision):
3368
 
                # if there are no commits, we're done.
3369
 
                return
3370
 
            stop_revno = other_revno
3371
 
 
3372
 
        # what's the current last revision, before we fetch [and change it
3373
 
        # possibly]
3374
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3375
 
        # we fetch here so that we don't process data twice in the common
3376
 
        # case of having something to pull, and so that the check for
3377
 
        # already merged can operate on the just fetched graph, which will
3378
 
        # be cached in memory.
3379
 
        self.target.fetch(self.source, stop_revision)
3380
 
        # Check to see if one is an ancestor of the other
3381
 
        if not overwrite:
3382
 
            if graph is None:
3383
 
                graph = self.target.repository.get_graph()
3384
 
            if self.target._check_if_descendant_or_diverged(
3385
 
                    stop_revision, last_rev, graph, self.source):
3386
 
                # stop_revision is a descendant of last_rev, but we aren't
3387
 
                # overwriting, so we're done.
3388
 
                return
3389
 
        if stop_revno is None:
3390
 
            if graph is None:
3391
 
                graph = self.target.repository.get_graph()
3392
 
            this_revno, this_last_revision = \
3393
 
                    self.target.last_revision_info()
3394
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3395
 
                            [(other_last_revision, other_revno),
3396
 
                             (this_last_revision, this_revno)])
3397
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3398
 
 
3399
 
    @needs_write_lock
 
2988
        self.source.lock_read()
 
2989
        try:
 
2990
            other_revno, other_last_revision = self.source.last_revision_info()
 
2991
            stop_revno = None # unknown
 
2992
            if stop_revision is None:
 
2993
                stop_revision = other_last_revision
 
2994
                if _mod_revision.is_null(stop_revision):
 
2995
                    # if there are no commits, we're done.
 
2996
                    return
 
2997
                stop_revno = other_revno
 
2998
 
 
2999
            # what's the current last revision, before we fetch [and change it
 
3000
            # possibly]
 
3001
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3002
            # we fetch here so that we don't process data twice in the common
 
3003
            # case of having something to pull, and so that the check for
 
3004
            # already merged can operate on the just fetched graph, which will
 
3005
            # be cached in memory.
 
3006
            self.target.fetch(self.source, stop_revision)
 
3007
            # Check to see if one is an ancestor of the other
 
3008
            if not overwrite:
 
3009
                if graph is None:
 
3010
                    graph = self.target.repository.get_graph()
 
3011
                if self.target._check_if_descendant_or_diverged(
 
3012
                        stop_revision, last_rev, graph, self.source):
 
3013
                    # stop_revision is a descendant of last_rev, but we aren't
 
3014
                    # overwriting, so we're done.
 
3015
                    return
 
3016
            if stop_revno is None:
 
3017
                if graph is None:
 
3018
                    graph = self.target.repository.get_graph()
 
3019
                this_revno, this_last_revision = \
 
3020
                        self.target.last_revision_info()
 
3021
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3022
                                [(other_last_revision, other_revno),
 
3023
                                 (this_last_revision, this_revno)])
 
3024
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
3025
        finally:
 
3026
            self.source.unlock()
 
3027
 
3400
3028
    def pull(self, overwrite=False, stop_revision=None,
3401
 
             possible_transports=None, run_hooks=True,
 
3029
             possible_transports=None, _hook_master=None, run_hooks=True,
3402
3030
             _override_hook_target=None, local=False):
3403
 
        """Pull from source into self, updating my master if any.
 
3031
        """See Branch.pull.
3404
3032
 
 
3033
        :param _hook_master: Private parameter - set the branch to
 
3034
            be supplied as the master to pull hooks.
3405
3035
        :param run_hooks: Private parameter - if false, this branch
3406
3036
            is being called because it's the master of the primary branch,
3407
3037
            so it should not run its hooks.
 
3038
        :param _override_hook_target: Private parameter - set the branch to be
 
3039
            supplied as the target_branch to pull hooks.
 
3040
        :param local: Only update the local branch, and not the bound branch.
3408
3041
        """
3409
 
        bound_location = self.target.get_bound_location()
3410
 
        if local and not bound_location:
 
3042
        # This type of branch can't be bound.
 
3043
        if local:
3411
3044
            raise errors.LocalRequiresBoundBranch()
3412
 
        master_branch = None
3413
 
        if not local and bound_location and self.source.user_url != bound_location:
3414
 
            # not pulling from master, so we need to update master.
3415
 
            master_branch = self.target.get_master_branch(possible_transports)
3416
 
            master_branch.lock_write()
 
3045
        result = PullResult()
 
3046
        result.source_branch = self.source
 
3047
        if _override_hook_target is None:
 
3048
            result.target_branch = self.target
 
3049
        else:
 
3050
            result.target_branch = _override_hook_target
 
3051
        self.source.lock_read()
3417
3052
        try:
3418
 
            if master_branch:
3419
 
                # pull from source into master.
3420
 
                master_branch.pull(self.source, overwrite, stop_revision,
3421
 
                    run_hooks=False)
3422
 
            return self._pull(overwrite,
3423
 
                stop_revision, _hook_master=master_branch,
3424
 
                run_hooks=run_hooks,
3425
 
                _override_hook_target=_override_hook_target)
 
3053
            # We assume that during 'pull' the target repository is closer than
 
3054
            # the source one.
 
3055
            self.source.update_references(self.target)
 
3056
            graph = self.target.repository.get_graph(self.source.repository)
 
3057
            # TODO: Branch formats should have a flag that indicates 
 
3058
            # that revno's are expensive, and pull() should honor that flag.
 
3059
            # -- JRV20090506
 
3060
            result.old_revno, result.old_revid = \
 
3061
                self.target.last_revision_info()
 
3062
            self.target.update_revisions(self.source, stop_revision,
 
3063
                overwrite=overwrite, graph=graph)
 
3064
            # TODO: The old revid should be specified when merging tags, 
 
3065
            # so a tags implementation that versions tags can only 
 
3066
            # pull in the most recent changes. -- JRV20090506
 
3067
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3068
                overwrite)
 
3069
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3070
            if _hook_master:
 
3071
                result.master_branch = _hook_master
 
3072
                result.local_branch = result.target_branch
 
3073
            else:
 
3074
                result.master_branch = result.target_branch
 
3075
                result.local_branch = None
 
3076
            if run_hooks:
 
3077
                for hook in Branch.hooks['post_pull']:
 
3078
                    hook(result)
3426
3079
        finally:
3427
 
            if master_branch:
3428
 
                master_branch.unlock()
 
3080
            self.source.unlock()
 
3081
        return result
3429
3082
 
3430
3083
    def push(self, overwrite=False, stop_revision=None,
3431
3084
             _override_hook_source_branch=None):
3493
3146
            _run_hooks()
3494
3147
            return result
3495
3148
 
3496
 
    def _pull(self, overwrite=False, stop_revision=None,
3497
 
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3149
    @classmethod
 
3150
    def is_compatible(self, source, target):
 
3151
        # GenericBranch uses the public API, so always compatible
 
3152
        return True
 
3153
 
 
3154
 
 
3155
class InterToBranch5(GenericInterBranch):
 
3156
 
 
3157
    @staticmethod
 
3158
    def _get_branch_formats_to_test():
 
3159
        return BranchFormat._default_format, BzrBranchFormat5()
 
3160
 
 
3161
    def pull(self, overwrite=False, stop_revision=None,
 
3162
             possible_transports=None, run_hooks=True,
3498
3163
             _override_hook_target=None, local=False):
3499
 
        """See Branch.pull.
3500
 
 
3501
 
        This function is the core worker, used by GenericInterBranch.pull to
3502
 
        avoid duplication when pulling source->master and source->local.
3503
 
 
3504
 
        :param _hook_master: Private parameter - set the branch to
3505
 
            be supplied as the master to pull hooks.
 
3164
        """Pull from source into self, updating my master if any.
 
3165
 
3506
3166
        :param run_hooks: Private parameter - if false, this branch
3507
3167
            is being called because it's the master of the primary branch,
3508
3168
            so it should not run its hooks.
3509
 
        :param _override_hook_target: Private parameter - set the branch to be
3510
 
            supplied as the target_branch to pull hooks.
3511
 
        :param local: Only update the local branch, and not the bound branch.
3512
3169
        """
3513
 
        # This type of branch can't be bound.
3514
 
        if local:
 
3170
        bound_location = self.target.get_bound_location()
 
3171
        if local and not bound_location:
3515
3172
            raise errors.LocalRequiresBoundBranch()
3516
 
        result = PullResult()
3517
 
        result.source_branch = self.source
3518
 
        if _override_hook_target is None:
3519
 
            result.target_branch = self.target
3520
 
        else:
3521
 
            result.target_branch = _override_hook_target
3522
 
        self.source.lock_read()
 
3173
        master_branch = None
 
3174
        if not local and bound_location and self.source.base != bound_location:
 
3175
            # not pulling from master, so we need to update master.
 
3176
            master_branch = self.target.get_master_branch(possible_transports)
 
3177
            master_branch.lock_write()
3523
3178
        try:
3524
 
            # We assume that during 'pull' the target repository is closer than
3525
 
            # the source one.
3526
 
            self.source.update_references(self.target)
3527
 
            graph = self.target.repository.get_graph(self.source.repository)
3528
 
            # TODO: Branch formats should have a flag that indicates 
3529
 
            # that revno's are expensive, and pull() should honor that flag.
3530
 
            # -- JRV20090506
3531
 
            result.old_revno, result.old_revid = \
3532
 
                self.target.last_revision_info()
3533
 
            self.target.update_revisions(self.source, stop_revision,
3534
 
                overwrite=overwrite, graph=graph)
3535
 
            # TODO: The old revid should be specified when merging tags, 
3536
 
            # so a tags implementation that versions tags can only 
3537
 
            # pull in the most recent changes. -- JRV20090506
3538
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3539
 
                overwrite)
3540
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3541
 
            if _hook_master:
3542
 
                result.master_branch = _hook_master
3543
 
                result.local_branch = result.target_branch
3544
 
            else:
3545
 
                result.master_branch = result.target_branch
3546
 
                result.local_branch = None
3547
 
            if run_hooks:
3548
 
                for hook in Branch.hooks['post_pull']:
3549
 
                    hook(result)
 
3179
            if master_branch:
 
3180
                # pull from source into master.
 
3181
                master_branch.pull(self.source, overwrite, stop_revision,
 
3182
                    run_hooks=False)
 
3183
            return super(InterToBranch5, self).pull(overwrite,
 
3184
                stop_revision, _hook_master=master_branch,
 
3185
                run_hooks=run_hooks,
 
3186
                _override_hook_target=_override_hook_target)
3550
3187
        finally:
3551
 
            self.source.unlock()
3552
 
        return result
 
3188
            if master_branch:
 
3189
                master_branch.unlock()
3553
3190
 
3554
3191
 
3555
3192
InterBranch.register_optimiser(GenericInterBranch)
 
3193
InterBranch.register_optimiser(InterToBranch5)