~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: 2010-02-11 06:15:33 UTC
  • mfrom: (5025.1.6 331095-malloc)
  • Revision ID: pqm@pqm.ubuntu.com-20100211061533-5glf4faoutadhql9
(mbp) avoid malloc(0)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2011 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
24
24
from bzrlib import (
25
25
        bzrdir,
26
26
        cache_utf8,
27
 
        cleanup,
28
27
        config as _mod_config,
29
28
        debug,
30
29
        errors,
31
 
        fetch,
32
 
        graph as _mod_graph,
33
30
        lockdir,
34
31
        lockable_files,
35
 
        remote,
36
32
        repository,
37
33
        revision as _mod_revision,
38
34
        rio,
 
35
        symbol_versioning,
39
36
        transport,
 
37
        tsort,
40
38
        ui,
41
39
        urlutils,
42
40
        )
43
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
44
43
from bzrlib.tag import (
45
44
    BasicTags,
46
45
    DisabledTags,
47
46
    )
48
47
""")
49
48
 
50
 
from bzrlib import (
51
 
    controldir,
52
 
    )
53
 
from bzrlib.decorators import (
54
 
    needs_read_lock,
55
 
    needs_write_lock,
56
 
    only_raises,
57
 
    )
58
 
from bzrlib.hooks import Hooks
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
50
from bzrlib.hooks import HookPoint, Hooks
59
51
from bzrlib.inter import InterObject
60
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
61
53
from bzrlib import registry
62
54
from bzrlib.symbol_versioning import (
63
55
    deprecated_in,
71
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
72
64
 
73
65
 
74
 
class Branch(controldir.ControlComponent):
 
66
# TODO: Maybe include checks for common corruption of newlines, etc?
 
67
 
 
68
# TODO: Some operations like log might retrieve the same revisions
 
69
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
70
# cache in memory to make this faster.  In general anything can be
 
71
# cached in memory between lock and unlock operations. .. nb thats
 
72
# what the transaction identity map provides
 
73
 
 
74
 
 
75
######################################################################
 
76
# branch objects
 
77
 
 
78
class Branch(object):
75
79
    """Branch holding a history of revisions.
76
80
 
77
 
    :ivar base:
78
 
        Base directory/url of the branch; using control_url and
79
 
        control_transport is more standardized.
80
 
    :ivar hooks: An instance of BranchHooks.
81
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
82
 
        _clear_cached_state.
 
81
    base
 
82
        Base directory/url of the branch.
 
83
 
 
84
    hooks: An instance of BranchHooks.
83
85
    """
84
86
    # this is really an instance variable - FIXME move it there
85
87
    # - RBC 20060112
86
88
    base = None
87
89
 
88
 
    @property
89
 
    def control_transport(self):
90
 
        return self._transport
91
 
 
92
 
    @property
93
 
    def user_transport(self):
94
 
        return self.bzrdir.user_transport
95
 
 
96
90
    def __init__(self, *ignored, **ignored_too):
97
91
        self.tags = self._format.make_tags(self)
98
92
        self._revision_history_cache = None
99
93
        self._revision_id_to_revno_cache = None
100
94
        self._partial_revision_id_to_revno_cache = {}
101
95
        self._partial_revision_history_cache = []
102
 
        self._tags_bytes = None
103
96
        self._last_revision_info_cache = None
104
 
        self._master_branch_cache = None
105
97
        self._merge_sorted_revisions_cache = None
106
98
        self._open_hook()
107
99
        hooks = Branch.hooks['open']
113
105
 
114
106
    def _activate_fallback_location(self, url):
115
107
        """Activate the branch/repository from url as a fallback repository."""
116
 
        for existing_fallback_repo in self.repository._fallback_repositories:
117
 
            if existing_fallback_repo.user_url == url:
118
 
                # This fallback is already configured.  This probably only
119
 
                # happens because BzrDir.sprout is a horrible mess.  To avoid
120
 
                # confusing _unstack we don't add this a second time.
121
 
                mutter('duplicate activation of fallback %r on %r', url, self)
122
 
                return
123
108
        repo = self._get_fallback_repository(url)
124
109
        if repo.has_same_location(self.repository):
125
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
110
            raise errors.UnstackableLocationError(self.base, url)
126
111
        self.repository.add_fallback_repository(repo)
127
112
 
128
113
    def break_lock(self):
182
167
        """
183
168
        control = bzrdir.BzrDir.open(base, _unsupported,
184
169
                                     possible_transports=possible_transports)
185
 
        return control.open_branch(unsupported=_unsupported)
 
170
        return control.open_branch(_unsupported)
186
171
 
187
172
    @staticmethod
188
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
173
    def open_from_transport(transport, _unsupported=False):
189
174
        """Open the branch rooted at transport"""
190
175
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
191
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
176
        return control.open_branch(_unsupported)
192
177
 
193
178
    @staticmethod
194
179
    def open_containing(url, possible_transports=None):
215
200
        return self.supports_tags() and self.tags.get_tag_dict()
216
201
 
217
202
    def get_config(self):
218
 
        """Get a bzrlib.config.BranchConfig for this Branch.
219
 
 
220
 
        This can then be used to get and set configuration options for the
221
 
        branch.
222
 
 
223
 
        :return: A bzrlib.config.BranchConfig.
224
 
        """
225
203
        return BranchConfig(self)
226
204
 
227
205
    def _get_config(self):
239
217
    def _get_fallback_repository(self, url):
240
218
        """Get the repository we fallback to at url."""
241
219
        url = urlutils.join(self.base, url)
242
 
        a_branch = Branch.open(url,
 
220
        a_bzrdir = bzrdir.BzrDir.open(url,
243
221
            possible_transports=[self.bzrdir.root_transport])
244
 
        return a_branch.repository
 
222
        return a_bzrdir.open_branch().repository
245
223
 
246
 
    @needs_read_lock
247
224
    def _get_tags_bytes(self):
248
225
        """Get the bytes of a serialised tags dict.
249
226
 
256
233
        :return: The bytes of the tags file.
257
234
        :seealso: Branch._set_tags_bytes.
258
235
        """
259
 
        if self._tags_bytes is None:
260
 
            self._tags_bytes = self._transport.get_bytes('tags')
261
 
        return self._tags_bytes
 
236
        return self._transport.get_bytes('tags')
262
237
 
263
238
    def _get_nick(self, local=False, possible_transports=None):
264
239
        config = self.get_config()
266
241
        if not local and not config.has_explicit_nickname():
267
242
            try:
268
243
                master = self.get_master_branch(possible_transports)
269
 
                if master and self.user_url == master.user_url:
270
 
                    raise errors.RecursiveBind(self.user_url)
271
244
                if master is not None:
272
245
                    # return the master branch value
273
246
                    return master.nick
274
 
            except errors.RecursiveBind, e:
275
 
                raise e
276
247
            except errors.BzrError, e:
277
248
                # Silently fall back to local implicit nick if the master is
278
249
                # unavailable
315
286
        new_history.reverse()
316
287
        return new_history
317
288
 
318
 
    def lock_write(self, token=None):
319
 
        """Lock the branch for write operations.
320
 
 
321
 
        :param token: A token to permit reacquiring a previously held and
322
 
            preserved lock.
323
 
        :return: A BranchWriteLockResult.
324
 
        """
 
289
    def lock_write(self):
325
290
        raise NotImplementedError(self.lock_write)
326
291
 
327
292
    def lock_read(self):
328
 
        """Lock the branch for read operations.
329
 
 
330
 
        :return: A bzrlib.lock.LogicalLockResult.
331
 
        """
332
293
        raise NotImplementedError(self.lock_read)
333
294
 
334
295
    def unlock(self):
455
416
            after. If None, the rest of history is included.
456
417
        :param stop_rule: if stop_revision_id is not None, the precise rule
457
418
            to use for termination:
458
 
 
459
419
            * 'exclude' - leave the stop revision out of the result (default)
460
420
            * 'include' - the stop revision is the last item in the result
461
421
            * 'with-merges' - include the stop revision and all of its
462
422
              merged revisions in the result
463
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
464
 
              that are in both ancestries
465
423
        :param direction: either 'reverse' or 'forward':
466
 
 
467
424
            * reverse means return the start_revision_id first, i.e.
468
425
              start at the most recent revision and go backwards in history
469
426
            * forward returns tuples in the opposite order to reverse.
490
447
        # start_revision_id.
491
448
        if self._merge_sorted_revisions_cache is None:
492
449
            last_revision = self.last_revision()
493
 
            known_graph = self.repository.get_known_graph_ancestry(
494
 
                [last_revision])
 
450
            last_key = (last_revision,)
 
451
            known_graph = self.repository.revisions.get_known_graph_ancestry(
 
452
                [last_key])
495
453
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
496
 
                last_revision)
 
454
                last_key)
497
455
        filtered = self._filter_merge_sorted_revisions(
498
456
            self._merge_sorted_revisions_cache, start_revision_id,
499
457
            stop_revision_id, stop_rule)
500
 
        # Make sure we don't return revisions that are not part of the
501
 
        # start_revision_id ancestry.
502
 
        filtered = self._filter_start_non_ancestors(filtered)
503
458
        if direction == 'reverse':
504
459
            return filtered
505
460
        if direction == 'forward':
513
468
        rev_iter = iter(merge_sorted_revisions)
514
469
        if start_revision_id is not None:
515
470
            for node in rev_iter:
516
 
                rev_id = node.key
 
471
                rev_id = node.key[-1]
517
472
                if rev_id != start_revision_id:
518
473
                    continue
519
474
                else:
525
480
        if stop_revision_id is None:
526
481
            # Yield everything
527
482
            for node in rev_iter:
528
 
                rev_id = node.key
 
483
                rev_id = node.key[-1]
529
484
                yield (rev_id, node.merge_depth, node.revno,
530
485
                       node.end_of_merge)
531
486
        elif stop_rule == 'exclude':
532
487
            for node in rev_iter:
533
 
                rev_id = node.key
 
488
                rev_id = node.key[-1]
534
489
                if rev_id == stop_revision_id:
535
490
                    return
536
491
                yield (rev_id, node.merge_depth, node.revno,
537
492
                       node.end_of_merge)
538
493
        elif stop_rule == 'include':
539
494
            for node in rev_iter:
540
 
                rev_id = node.key
 
495
                rev_id = node.key[-1]
541
496
                yield (rev_id, node.merge_depth, node.revno,
542
497
                       node.end_of_merge)
543
498
                if rev_id == stop_revision_id:
544
499
                    return
545
 
        elif stop_rule == 'with-merges-without-common-ancestry':
546
 
            # We want to exclude all revisions that are already part of the
547
 
            # stop_revision_id ancestry.
548
 
            graph = self.repository.get_graph()
549
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
550
 
                                                    [stop_revision_id])
551
 
            for node in rev_iter:
552
 
                rev_id = node.key
553
 
                if rev_id not in ancestors:
554
 
                    continue
555
 
                yield (rev_id, node.merge_depth, node.revno,
556
 
                       node.end_of_merge)
557
500
        elif stop_rule == 'with-merges':
558
501
            stop_rev = self.repository.get_revision(stop_revision_id)
559
502
            if stop_rev.parent_ids:
565
508
            reached_stop_revision_id = False
566
509
            revision_id_whitelist = []
567
510
            for node in rev_iter:
568
 
                rev_id = node.key
 
511
                rev_id = node.key[-1]
569
512
                if rev_id == left_parent:
570
513
                    # reached the left parent after the stop_revision
571
514
                    return
582
525
        else:
583
526
            raise ValueError('invalid stop_rule %r' % stop_rule)
584
527
 
585
 
    def _filter_start_non_ancestors(self, rev_iter):
586
 
        # If we started from a dotted revno, we want to consider it as a tip
587
 
        # and don't want to yield revisions that are not part of its
588
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
589
 
        # uninteresting descendants of the first parent of our tip before the
590
 
        # tip itself.
591
 
        first = rev_iter.next()
592
 
        (rev_id, merge_depth, revno, end_of_merge) = first
593
 
        yield first
594
 
        if not merge_depth:
595
 
            # We start at a mainline revision so by definition, all others
596
 
            # revisions in rev_iter are ancestors
597
 
            for node in rev_iter:
598
 
                yield node
599
 
 
600
 
        clean = False
601
 
        whitelist = set()
602
 
        pmap = self.repository.get_parent_map([rev_id])
603
 
        parents = pmap.get(rev_id, [])
604
 
        if parents:
605
 
            whitelist.update(parents)
606
 
        else:
607
 
            # If there is no parents, there is nothing of interest left
608
 
 
609
 
            # FIXME: It's hard to test this scenario here as this code is never
610
 
            # called in that case. -- vila 20100322
611
 
            return
612
 
 
613
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
614
 
            if not clean:
615
 
                if rev_id in whitelist:
616
 
                    pmap = self.repository.get_parent_map([rev_id])
617
 
                    parents = pmap.get(rev_id, [])
618
 
                    whitelist.remove(rev_id)
619
 
                    whitelist.update(parents)
620
 
                    if merge_depth == 0:
621
 
                        # We've reached the mainline, there is nothing left to
622
 
                        # filter
623
 
                        clean = True
624
 
                else:
625
 
                    # A revision that is not part of the ancestry of our
626
 
                    # starting revision.
627
 
                    continue
628
 
            yield (rev_id, merge_depth, revno, end_of_merge)
629
 
 
630
528
    def leave_lock_in_place(self):
631
529
        """Tell this branch object not to release the physical lock when this
632
530
        object is unlocked.
649
547
        :param other: The branch to bind to
650
548
        :type other: Branch
651
549
        """
652
 
        raise errors.UpgradeRequired(self.user_url)
 
550
        raise errors.UpgradeRequired(self.base)
653
551
 
654
552
    def set_append_revisions_only(self, enabled):
655
553
        if not self._format.supports_set_append_revisions_only():
656
 
            raise errors.UpgradeRequired(self.user_url)
 
554
            raise errors.UpgradeRequired(self.base)
657
555
        if enabled:
658
556
            value = 'True'
659
557
        else:
670
568
        raise errors.UnsupportedOperation(self.get_reference_info, self)
671
569
 
672
570
    @needs_write_lock
673
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
571
    def fetch(self, from_branch, last_revision=None, pb=None):
674
572
        """Copy revisions from from_branch into this branch.
675
573
 
676
574
        :param from_branch: Where to copy from.
677
575
        :param last_revision: What revision to stop at (None for at the end
678
576
                              of the branch.
679
 
        :param limit: Optional rough limit of revisions to fetch
 
577
        :param pb: An optional progress bar to use.
680
578
        :return: None
681
579
        """
682
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
580
        if self.base == from_branch.base:
 
581
            return (0, [])
 
582
        if pb is not None:
 
583
            symbol_versioning.warn(
 
584
                symbol_versioning.deprecated_in((1, 14, 0))
 
585
                % "pb parameter to fetch()")
 
586
        from_branch.lock_read()
 
587
        try:
 
588
            if last_revision is None:
 
589
                last_revision = from_branch.last_revision()
 
590
                last_revision = _mod_revision.ensure_null(last_revision)
 
591
            return self.repository.fetch(from_branch.repository,
 
592
                                         revision_id=last_revision,
 
593
                                         pb=pb)
 
594
        finally:
 
595
            from_branch.unlock()
683
596
 
684
597
    def get_bound_location(self):
685
598
        """Return the URL of the branch we are bound to.
692
605
    def get_old_bound_location(self):
693
606
        """Return the URL of the branch we used to be bound to
694
607
        """
695
 
        raise errors.UpgradeRequired(self.user_url)
 
608
        raise errors.UpgradeRequired(self.base)
696
609
 
697
610
    def get_commit_builder(self, parents, config=None, timestamp=None,
698
611
                           timezone=None, committer=None, revprops=None,
699
 
                           revision_id=None, lossy=False):
 
612
                           revision_id=None):
700
613
        """Obtain a CommitBuilder for this branch.
701
614
 
702
615
        :param parents: Revision ids of the parents of the new revision.
706
619
        :param committer: Optional committer to set for commit.
707
620
        :param revprops: Optional dictionary of revision properties.
708
621
        :param revision_id: Optional revision id.
709
 
        :param lossy: Whether to discard data that can not be natively
710
 
            represented, when pushing to a foreign VCS 
711
622
        """
712
623
 
713
624
        if config is None:
714
625
            config = self.get_config()
715
626
 
716
627
        return self.repository.get_commit_builder(self, parents, config,
717
 
            timestamp, timezone, committer, revprops, revision_id,
718
 
            lossy)
 
628
            timestamp, timezone, committer, revprops, revision_id)
719
629
 
720
630
    def get_master_branch(self, possible_transports=None):
721
631
        """Return the branch we are bound to.
748
658
        """Print `file` to stdout."""
749
659
        raise NotImplementedError(self.print_file)
750
660
 
751
 
    @deprecated_method(deprecated_in((2, 4, 0)))
752
661
    def set_revision_history(self, rev_history):
753
 
        """See Branch.set_revision_history."""
754
 
        self._set_revision_history(rev_history)
755
 
 
756
 
    @needs_write_lock
757
 
    def _set_revision_history(self, rev_history):
758
 
        if len(rev_history) == 0:
759
 
            revid = _mod_revision.NULL_REVISION
760
 
        else:
761
 
            revid = rev_history[-1]
762
 
        if rev_history != self._lefthand_history(revid):
763
 
            raise errors.NotLefthandHistory(rev_history)
764
 
        self.set_last_revision_info(len(rev_history), revid)
765
 
        self._cache_revision_history(rev_history)
766
 
        for hook in Branch.hooks['set_rh']:
767
 
            hook(self, rev_history)
768
 
 
769
 
    @needs_write_lock
770
 
    def set_last_revision_info(self, revno, revision_id):
771
 
        """Set the last revision of this branch.
772
 
 
773
 
        The caller is responsible for checking that the revno is correct
774
 
        for this revision id.
775
 
 
776
 
        It may be possible to set the branch last revision to an id not
777
 
        present in the repository.  However, branches can also be
778
 
        configured to check constraints on history, in which case this may not
779
 
        be permitted.
780
 
        """
781
 
        raise NotImplementedError(self.set_last_revision_info)
782
 
 
783
 
    @needs_write_lock
784
 
    def generate_revision_history(self, revision_id, last_rev=None,
785
 
                                  other_branch=None):
786
 
        """See Branch.generate_revision_history"""
787
 
        graph = self.repository.get_graph()
788
 
        known_revision_ids = [
789
 
            self.last_revision_info(),
790
 
            (_mod_revision.NULL_REVISION, 0),
791
 
            ]
792
 
        if last_rev is not None:
793
 
            if not graph.is_ancestor(last_rev, revision_id):
794
 
                # our previous tip is not merged into stop_revision
795
 
                raise errors.DivergedBranches(self, other_branch)
796
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
797
 
        self.set_last_revision_info(revno, revision_id)
 
662
        raise NotImplementedError(self.set_revision_history)
798
663
 
799
664
    @needs_write_lock
800
665
    def set_parent(self, url):
824
689
            stacking.
825
690
        """
826
691
        if not self._format.supports_stacking():
827
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
692
            raise errors.UnstackableBranchFormat(self._format, self.base)
828
693
        # XXX: Changing from one fallback repository to another does not check
829
694
        # that all the data you need is present in the new fallback.
830
695
        # Possibly it should.
844
709
 
845
710
    def _unstack(self):
846
711
        """Change a branch to be unstacked, copying data as needed.
847
 
 
 
712
        
848
713
        Don't call this directly, use set_stacked_on_url(None).
849
714
        """
850
715
        pb = ui.ui_factory.nested_progress_bar()
859
724
            old_repository = self.repository
860
725
            if len(old_repository._fallback_repositories) != 1:
861
726
                raise AssertionError("can't cope with fallback repositories "
862
 
                    "of %r (fallbacks: %r)" % (old_repository,
863
 
                        old_repository._fallback_repositories))
864
 
            # Open the new repository object.
865
 
            # Repositories don't offer an interface to remove fallback
866
 
            # repositories today; take the conceptually simpler option and just
867
 
            # reopen it.  We reopen it starting from the URL so that we
868
 
            # get a separate connection for RemoteRepositories and can
869
 
            # stream from one of them to the other.  This does mean doing
870
 
            # separate SSH connection setup, but unstacking is not a
871
 
            # common operation so it's tolerable.
872
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
873
 
            new_repository = new_bzrdir.find_repository()
874
 
            if new_repository._fallback_repositories:
875
 
                raise AssertionError("didn't expect %r to have "
876
 
                    "fallback_repositories"
877
 
                    % (self.repository,))
878
 
            # Replace self.repository with the new repository.
879
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
880
 
            # lock count) of self.repository to the new repository.
881
 
            lock_token = old_repository.lock_write().repository_token
882
 
            self.repository = new_repository
883
 
            if isinstance(self, remote.RemoteBranch):
884
 
                # Remote branches can have a second reference to the old
885
 
                # repository that need to be replaced.
886
 
                if self._real_branch is not None:
887
 
                    self._real_branch.repository = new_repository
888
 
            self.repository.lock_write(token=lock_token)
889
 
            if lock_token is not None:
890
 
                old_repository.leave_lock_in_place()
 
727
                    "of %r" % (self.repository,))
 
728
            # unlock it, including unlocking the fallback
891
729
            old_repository.unlock()
892
 
            if lock_token is not None:
893
 
                # XXX: self.repository.leave_lock_in_place() before this
894
 
                # function will not be preserved.  Fortunately that doesn't
895
 
                # affect the current default format (2a), and would be a
896
 
                # corner-case anyway.
897
 
                #  - Andrew Bennetts, 2010/06/30
898
 
                self.repository.dont_leave_lock_in_place()
899
 
            old_lock_count = 0
900
 
            while True:
901
 
                try:
902
 
                    old_repository.unlock()
903
 
                except errors.LockNotHeld:
904
 
                    break
905
 
                old_lock_count += 1
906
 
            if old_lock_count == 0:
907
 
                raise AssertionError(
908
 
                    'old_repository should have been locked at least once.')
909
 
            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
910
749
                self.repository.lock_write()
911
 
            # Fetch from the old repository into the new.
912
 
            old_repository.lock_read()
913
 
            try:
914
750
                # XXX: If you unstack a branch while it has a working tree
915
751
                # with a pending merge, the pending-merged revisions will no
916
752
                # longer be present.  You can (probably) revert and remerge.
917
 
                try:
918
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
919
 
                except errors.TagsNotSupported:
920
 
                    tags_to_fetch = set()
921
 
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
922
 
                    old_repository, required_ids=[self.last_revision()],
923
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
924
 
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
753
                #
 
754
                # XXX: This only fetches up to the tip of the repository; it
 
755
                # doesn't bring across any tags.  That's fairly consistent
 
756
                # with how branch works, but perhaps not ideal.
 
757
                self.repository.fetch(old_repository,
 
758
                    revision_id=self.last_revision(),
 
759
                    find_ghosts=True)
925
760
            finally:
926
761
                old_repository.unlock()
927
762
        finally:
932
767
 
933
768
        :seealso: Branch._get_tags_bytes.
934
769
        """
935
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
936
 
        op.add_cleanup(self.lock_write().unlock)
937
 
        return op.run_simple(bytes)
938
 
 
939
 
    def _set_tags_bytes_locked(self, bytes):
940
 
        self._tags_bytes = bytes
941
 
        return self._transport.put_bytes('tags', bytes)
 
770
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
771
            'tags', bytes)
942
772
 
943
773
    def _cache_revision_history(self, rev_history):
944
774
        """Set the cached revision history to rev_history.
971
801
        self._revision_history_cache = None
972
802
        self._revision_id_to_revno_cache = None
973
803
        self._last_revision_info_cache = None
974
 
        self._master_branch_cache = None
975
804
        self._merge_sorted_revisions_cache = None
976
805
        self._partial_revision_history_cache = []
977
806
        self._partial_revision_id_to_revno_cache = {}
978
 
        self._tags_bytes = None
979
807
 
980
808
    def _gen_revision_history(self):
981
809
        """Return sequence of revision hashes on to this branch.
1018
846
 
1019
847
    def unbind(self):
1020
848
        """Older format branches cannot bind or unbind."""
1021
 
        raise errors.UpgradeRequired(self.user_url)
 
849
        raise errors.UpgradeRequired(self.base)
1022
850
 
1023
851
    def last_revision(self):
1024
852
        """Return last revision id, or NULL_REVISION."""
1031
859
        :return: A tuple (revno, revision_id).
1032
860
        """
1033
861
        if self._last_revision_info_cache is None:
1034
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
862
            self._last_revision_info_cache = self._last_revision_info()
1035
863
        return self._last_revision_info_cache
1036
864
 
1037
 
    def _read_last_revision_info(self):
1038
 
        raise NotImplementedError(self._read_last_revision_info)
1039
 
 
1040
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
865
    def _last_revision_info(self):
 
866
        rh = self.revision_history()
 
867
        revno = len(rh)
 
868
        if revno:
 
869
            return (revno, rh[-1])
 
870
        else:
 
871
            return (0, _mod_revision.NULL_REVISION)
 
872
 
 
873
    @deprecated_method(deprecated_in((1, 6, 0)))
 
874
    def missing_revisions(self, other, stop_revision=None):
 
875
        """Return a list of new revisions that would perfectly fit.
 
876
 
 
877
        If self and other have not diverged, return a list of the revisions
 
878
        present in other, but missing from self.
 
879
        """
 
880
        self_history = self.revision_history()
 
881
        self_len = len(self_history)
 
882
        other_history = other.revision_history()
 
883
        other_len = len(other_history)
 
884
        common_index = min(self_len, other_len) -1
 
885
        if common_index >= 0 and \
 
886
            self_history[common_index] != other_history[common_index]:
 
887
            raise errors.DivergedBranches(self, other)
 
888
 
 
889
        if stop_revision is None:
 
890
            stop_revision = other_len
 
891
        else:
 
892
            if stop_revision > other_len:
 
893
                raise errors.NoSuchRevision(self, stop_revision)
 
894
        return other_history[self_len:stop_revision]
 
895
 
 
896
    @needs_write_lock
 
897
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
898
                         graph=None):
 
899
        """Pull in new perfect-fit revisions.
 
900
 
 
901
        :param other: Another Branch to pull from
 
902
        :param stop_revision: Updated until the given revision
 
903
        :param overwrite: Always set the branch pointer, rather than checking
 
904
            to see if it is a proper descendant.
 
905
        :param graph: A Graph object that can be used to query history
 
906
            information. This can be None.
 
907
        :return: None
 
908
        """
 
909
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
910
            overwrite, graph)
 
911
 
1041
912
    def import_last_revision_info(self, source_repo, revno, revid):
1042
913
        """Set the last revision info, importing from another repo if necessary.
1043
914
 
 
915
        This is used by the bound branch code to upload a revision to
 
916
        the master branch first before updating the tip of the local branch.
 
917
 
1044
918
        :param source_repo: Source repository to optionally fetch from
1045
919
        :param revno: Revision number of the new tip
1046
920
        :param revid: Revision id of the new tip
1049
923
            self.repository.fetch(source_repo, revision_id=revid)
1050
924
        self.set_last_revision_info(revno, revid)
1051
925
 
1052
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1053
 
                                           lossy=False):
1054
 
        """Set the last revision info, importing from another repo if necessary.
1055
 
 
1056
 
        This is used by the bound branch code to upload a revision to
1057
 
        the master branch first before updating the tip of the local branch.
1058
 
        Revisions referenced by source's tags are also transferred.
1059
 
 
1060
 
        :param source: Source branch to optionally fetch from
1061
 
        :param revno: Revision number of the new tip
1062
 
        :param revid: Revision id of the new tip
1063
 
        :param lossy: Whether to discard metadata that can not be
1064
 
            natively represented
1065
 
        :return: Tuple with the new revision number and revision id
1066
 
            (should only be different from the arguments when lossy=True)
1067
 
        """
1068
 
        if not self.repository.has_same_location(source.repository):
1069
 
            self.fetch(source, revid)
1070
 
        self.set_last_revision_info(revno, revid)
1071
 
        return (revno, revid)
1072
 
 
1073
926
    def revision_id_to_revno(self, revision_id):
1074
927
        """Given a revision id, return its revno"""
1075
928
        if _mod_revision.is_null(revision_id):
1095
948
            self._extend_partial_history(distance_from_last)
1096
949
        return self._partial_revision_history_cache[distance_from_last]
1097
950
 
 
951
    @needs_write_lock
1098
952
    def pull(self, source, overwrite=False, stop_revision=None,
1099
953
             possible_transports=None, *args, **kwargs):
1100
954
        """Mirror source into this branch.
1107
961
            stop_revision=stop_revision,
1108
962
            possible_transports=possible_transports, *args, **kwargs)
1109
963
 
1110
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1111
 
            *args, **kwargs):
 
964
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
965
        **kwargs):
1112
966
        """Mirror this branch into target.
1113
967
 
1114
968
        This branch is considered to be 'local', having low latency.
1115
969
        """
1116
970
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1117
 
            lossy, *args, **kwargs)
 
971
            *args, **kwargs)
 
972
 
 
973
    def lossy_push(self, target, stop_revision=None):
 
974
        """Push deltas into another branch.
 
975
 
 
976
        :note: This does not, like push, retain the revision ids from 
 
977
            the source branch and will, rather than adding bzr-specific 
 
978
            metadata, push only those semantics of the revision that can be 
 
979
            natively represented by this branch' VCS.
 
980
 
 
981
        :param target: Target branch
 
982
        :param stop_revision: Revision to push, defaults to last revision.
 
983
        :return: BranchPushResult with an extra member revidmap: 
 
984
            A dictionary mapping revision ids from the target branch 
 
985
            to new revision ids in the target branch, for each 
 
986
            revision that was pushed.
 
987
        """
 
988
        inter = InterBranch.get(self, target)
 
989
        lossy_push = getattr(inter, "lossy_push", None)
 
990
        if lossy_push is None:
 
991
            raise errors.LossyPushToSameVCS(self, target)
 
992
        return lossy_push(stop_revision)
1118
993
 
1119
994
    def basis_tree(self):
1120
995
        """Return `Tree` object for last revision."""
1137
1012
        try:
1138
1013
            return urlutils.join(self.base[:-1], parent)
1139
1014
        except errors.InvalidURLJoin, e:
1140
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
1015
            raise errors.InaccessibleParent(parent, self.base)
1141
1016
 
1142
1017
    def _get_parent_location(self):
1143
1018
        raise NotImplementedError(self._get_parent_location)
1275
1150
        return result
1276
1151
 
1277
1152
    @needs_read_lock
1278
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1279
 
            repository=None):
 
1153
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1280
1154
        """Create a new line of development from the branch, into to_bzrdir.
1281
1155
 
1282
1156
        to_bzrdir controls the branch format.
1287
1161
        if (repository_policy is not None and
1288
1162
            repository_policy.requires_stacking()):
1289
1163
            to_bzrdir._format.require_stacking(_skip_repo=True)
1290
 
        result = to_bzrdir.create_branch(repository=repository)
 
1164
        result = to_bzrdir.create_branch()
1291
1165
        result.lock_write()
1292
1166
        try:
1293
1167
            if repository_policy is not None:
1294
1168
                repository_policy.configure_branch(result)
1295
1169
            self.copy_content_into(result, revision_id=revision_id)
1296
 
            master_branch = self.get_master_branch()
1297
 
            if master_branch is None:
1298
 
                result.set_parent(self.bzrdir.root_transport.base)
1299
 
            else:
1300
 
                result.set_parent(master_branch.bzrdir.root_transport.base)
 
1170
            result.set_parent(self.bzrdir.root_transport.base)
1301
1171
        finally:
1302
1172
            result.unlock()
1303
1173
        return result
1327
1197
                revno = 1
1328
1198
        destination.set_last_revision_info(revno, revision_id)
1329
1199
 
 
1200
    @needs_read_lock
1330
1201
    def copy_content_into(self, destination, revision_id=None):
1331
1202
        """Copy the content of self into destination.
1332
1203
 
1333
1204
        revision_id: if not None, the revision history in the new branch will
1334
1205
                     be truncated to end with revision_id.
1335
1206
        """
1336
 
        return InterBranch.get(self, destination).copy_content_into(
1337
 
            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)
1338
1218
 
1339
1219
    def update_references(self, target):
1340
1220
        if not getattr(self._format, 'supports_reference_locations', False):
1385
1265
        """Return the most suitable metadir for a checkout of this branch.
1386
1266
        Weaves are used if this branch's repository uses weaves.
1387
1267
        """
1388
 
        format = self.repository.bzrdir.checkout_metadir()
1389
 
        format.set_branch_format(self._format)
 
1268
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1269
            from bzrlib.repofmt import weaverepo
 
1270
            format = bzrdir.BzrDirMetaFormat1()
 
1271
            format.repository_format = weaverepo.RepositoryFormat7()
 
1272
        else:
 
1273
            format = self.repository.bzrdir.checkout_metadir()
 
1274
            format.set_branch_format(self._format)
1390
1275
        return format
1391
1276
 
1392
1277
    def create_clone_on_transport(self, to_transport, revision_id=None,
1393
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1394
 
        no_tree=None):
 
1278
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1395
1279
        """Create a clone of this branch and its bzrdir.
1396
1280
 
1397
1281
        :param to_transport: The transport to clone onto.
1404
1288
        """
1405
1289
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1406
1290
        # clone call. Or something. 20090224 RBC/spiv.
1407
 
        # XXX: Should this perhaps clone colocated branches as well, 
1408
 
        # rather than just the default branch? 20100319 JRV
1409
1291
        if revision_id is None:
1410
1292
            revision_id = self.last_revision()
1411
1293
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1412
1294
            revision_id=revision_id, stacked_on=stacked_on,
1413
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1414
 
            no_tree=no_tree)
 
1295
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
1415
1296
        return dir_to.open_branch()
1416
1297
 
1417
1298
    def create_checkout(self, to_location, revision_id=None,
1422
1303
        :param to_location: The url to produce the checkout at
1423
1304
        :param revision_id: The revision to check out
1424
1305
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1425
 
            produce a bound branch (heavyweight checkout)
 
1306
        produce a bound branch (heavyweight checkout)
1426
1307
        :param accelerator_tree: A tree which can be used for retrieving file
1427
1308
            contents more quickly than the revision tree, i.e. a workingtree.
1428
1309
            The revision tree will be used for cases where accelerator_tree's
1436
1317
        if lightweight:
1437
1318
            format = self._get_checkout_format()
1438
1319
            checkout = format.initialize_on_transport(t)
1439
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1440
 
                target_branch=self)
 
1320
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1441
1321
        else:
1442
1322
            format = self._get_checkout_format()
1443
1323
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1474
1354
 
1475
1355
    def reference_parent(self, file_id, path, possible_transports=None):
1476
1356
        """Return the parent branch for a tree-reference file_id
1477
 
 
1478
1357
        :param file_id: The file_id of the tree reference
1479
1358
        :param path: The path of the file_id in the tree
1480
1359
        :return: A branch associated with the file_id
1486
1365
    def supports_tags(self):
1487
1366
        return self._format.supports_tags()
1488
1367
 
1489
 
    def automatic_tag_name(self, revision_id):
1490
 
        """Try to automatically find the tag name for a revision.
1491
 
 
1492
 
        :param revision_id: Revision id of the revision.
1493
 
        :return: A tag name or None if no tag name could be determined.
1494
 
        """
1495
 
        for hook in Branch.hooks['automatic_tag_name']:
1496
 
            ret = hook(self, revision_id)
1497
 
            if ret is not None:
1498
 
                return ret
1499
 
        return None
1500
 
 
1501
1368
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1502
1369
                                         other_branch):
1503
1370
        """Ensure that revision_b is a descendant of revision_a.
1533
1400
        else:
1534
1401
            raise AssertionError("invalid heads: %r" % (heads,))
1535
1402
 
1536
 
    def heads_to_fetch(self):
1537
 
        """Return the heads that must and that should be fetched to copy this
1538
 
        branch into another repo.
1539
 
 
1540
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1541
 
            set of heads that must be fetched.  if_present_fetch is a set of
1542
 
            heads that must be fetched if present, but no error is necessary if
1543
 
            they are not present.
1544
 
        """
1545
 
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
1546
 
        # are the tags.
1547
 
        must_fetch = set([self.last_revision()])
1548
 
        try:
1549
 
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
1550
 
        except errors.TagsNotSupported:
1551
 
            if_present_fetch = set()
1552
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1553
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1554
 
        return must_fetch, if_present_fetch
1555
 
 
1556
 
 
1557
 
class BranchFormat(controldir.ControlComponentFormat):
 
1403
 
 
1404
class BranchFormat(object):
1558
1405
    """An encapsulation of the initialization and open routines for a format.
1559
1406
 
1560
1407
    Formats provide three things:
1563
1410
     * an open routine.
1564
1411
 
1565
1412
    Formats are placed in an dict by their format string for reference
1566
 
    during branch opening. It's not required that these be instances, they
 
1413
    during branch opening. Its not required that these be instances, they
1567
1414
    can be classes themselves with class methods - it simply depends on
1568
1415
    whether state is needed for a given format or not.
1569
1416
 
1572
1419
    object will be created every time regardless.
1573
1420
    """
1574
1421
 
 
1422
    _default_format = None
 
1423
    """The default format used for new branches."""
 
1424
 
 
1425
    _formats = {}
 
1426
    """The known formats."""
 
1427
 
1575
1428
    can_set_append_revisions_only = True
1576
1429
 
1577
1430
    def __eq__(self, other):
1581
1434
        return not (self == other)
1582
1435
 
1583
1436
    @classmethod
1584
 
    def find_format(klass, a_bzrdir, name=None):
 
1437
    def find_format(klass, a_bzrdir):
1585
1438
        """Return the format for the branch object in a_bzrdir."""
1586
1439
        try:
1587
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
 
1440
            transport = a_bzrdir.get_branch_transport(None)
1588
1441
            format_string = transport.get_bytes("format")
1589
 
            return format_registry.get(format_string)
 
1442
            return klass._formats[format_string]
1590
1443
        except errors.NoSuchFile:
1591
1444
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1592
1445
        except KeyError:
1593
1446
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1594
1447
 
1595
1448
    @classmethod
1596
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1597
1449
    def get_default_format(klass):
1598
1450
        """Return the current default format."""
1599
 
        return format_registry.get_default()
1600
 
 
1601
 
    @classmethod
1602
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1603
 
    def get_formats(klass):
1604
 
        """Get all the known formats.
1605
 
 
1606
 
        Warning: This triggers a load of all lazy registered formats: do not
1607
 
        use except when that is desireed.
1608
 
        """
1609
 
        return format_registry._get_all()
1610
 
 
1611
 
    def get_reference(self, a_bzrdir, name=None):
 
1451
        return klass._default_format
 
1452
 
 
1453
    def get_reference(self, a_bzrdir):
1612
1454
        """Get the target reference of the branch in a_bzrdir.
1613
1455
 
1614
1456
        format probing must have been completed before calling
1616
1458
        in a_bzrdir is correct.
1617
1459
 
1618
1460
        :param a_bzrdir: The bzrdir to get the branch data from.
1619
 
        :param name: Name of the colocated branch to fetch
1620
1461
        :return: None if the branch is not a reference branch.
1621
1462
        """
1622
1463
        return None
1623
1464
 
1624
1465
    @classmethod
1625
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1466
    def set_reference(self, a_bzrdir, to_branch):
1626
1467
        """Set the target reference of the branch in a_bzrdir.
1627
1468
 
1628
1469
        format probing must have been completed before calling
1630
1471
        in a_bzrdir is correct.
1631
1472
 
1632
1473
        :param a_bzrdir: The bzrdir to set the branch reference for.
1633
 
        :param name: Name of colocated branch to set, None for default
1634
1474
        :param to_branch: branch that the checkout is to reference
1635
1475
        """
1636
1476
        raise NotImplementedError(self.set_reference)
1643
1483
        """Return the short format description for this format."""
1644
1484
        raise NotImplementedError(self.get_format_description)
1645
1485
 
1646
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1647
 
        hooks = Branch.hooks['post_branch_init']
1648
 
        if not hooks:
1649
 
            return
1650
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1651
 
        for hook in hooks:
1652
 
            hook(params)
 
1486
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1487
                           set_format=True):
 
1488
        """Initialize a branch in a bzrdir, with specified files
1653
1489
 
1654
 
    def initialize(self, a_bzrdir, name=None, repository=None):
1655
 
        """Create a branch of this format in a_bzrdir.
1656
 
        
1657
 
        :param name: Name of the colocated branch to create.
 
1490
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1491
        :param utf8_files: The files to create as a list of
 
1492
            (filename, content) tuples
 
1493
        :param set_format: If True, set the format with
 
1494
            self.get_format_string.  (BzrBranch4 has its format set
 
1495
            elsewhere)
 
1496
        :return: a branch in this format
1658
1497
        """
 
1498
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1499
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1500
        lock_map = {
 
1501
            'metadir': ('lock', lockdir.LockDir),
 
1502
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1503
        }
 
1504
        lock_name, lock_class = lock_map[lock_type]
 
1505
        control_files = lockable_files.LockableFiles(branch_transport,
 
1506
            lock_name, lock_class)
 
1507
        control_files.create_lock()
 
1508
        try:
 
1509
            control_files.lock_write()
 
1510
        except errors.LockContention:
 
1511
            if lock_type != 'branch4':
 
1512
                raise
 
1513
            lock_taken = False
 
1514
        else:
 
1515
            lock_taken = True
 
1516
        if set_format:
 
1517
            utf8_files += [('format', self.get_format_string())]
 
1518
        try:
 
1519
            for (filename, content) in utf8_files:
 
1520
                branch_transport.put_bytes(
 
1521
                    filename, content,
 
1522
                    mode=a_bzrdir._get_file_mode())
 
1523
        finally:
 
1524
            if lock_taken:
 
1525
                control_files.unlock()
 
1526
        return self.open(a_bzrdir, _found=True)
 
1527
 
 
1528
    def initialize(self, a_bzrdir):
 
1529
        """Create a branch of this format in a_bzrdir."""
1659
1530
        raise NotImplementedError(self.initialize)
1660
1531
 
1661
1532
    def is_supported(self):
1691
1562
        """
1692
1563
        raise NotImplementedError(self.network_name)
1693
1564
 
1694
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1695
 
            found_repository=None):
 
1565
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1696
1566
        """Return the branch object for a_bzrdir
1697
1567
 
1698
1568
        :param a_bzrdir: A BzrDir that contains a branch.
1699
 
        :param name: Name of colocated branch to open
1700
1569
        :param _found: a private parameter, do not use it. It is used to
1701
1570
            indicate if format probing has already be done.
1702
1571
        :param ignore_fallbacks: when set, no fallback branches will be opened
1705
1574
        raise NotImplementedError(self.open)
1706
1575
 
1707
1576
    @classmethod
1708
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1709
1577
    def register_format(klass, format):
1710
 
        """Register a metadir format.
1711
 
 
1712
 
        See MetaDirBranchFormatFactory for the ability to register a format
1713
 
        without loading the code the format needs until it is actually used.
1714
 
        """
1715
 
        format_registry.register(format)
 
1578
        """Register a metadir format."""
 
1579
        klass._formats[format.get_format_string()] = format
 
1580
        # Metadir formats have a network name of their format string, and get
 
1581
        # registered as class factories.
 
1582
        network_format_registry.register(format.get_format_string(), format.__class__)
1716
1583
 
1717
1584
    @classmethod
1718
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1719
1585
    def set_default_format(klass, format):
1720
 
        format_registry.set_default(format)
 
1586
        klass._default_format = format
1721
1587
 
1722
1588
    def supports_set_append_revisions_only(self):
1723
1589
        """True if this format supports set_append_revisions_only."""
1727
1593
        """True if this format records a stacked-on branch."""
1728
1594
        return False
1729
1595
 
1730
 
    def supports_leaving_lock(self):
1731
 
        """True if this format supports leaving locks in place."""
1732
 
        return False # by default
1733
 
 
1734
1596
    @classmethod
1735
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1736
1597
    def unregister_format(klass, format):
1737
 
        format_registry.remove(format)
 
1598
        del klass._formats[format.get_format_string()]
1738
1599
 
1739
1600
    def __str__(self):
1740
1601
        return self.get_format_description().rstrip()
1744
1605
        return False  # by default
1745
1606
 
1746
1607
 
1747
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1748
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1749
 
    
1750
 
    While none of the built in BranchFormats are lazy registered yet,
1751
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1752
 
    use it, and the bzr-loom plugin uses it as well (see
1753
 
    bzrlib.plugins.loom.formats).
1754
 
    """
1755
 
 
1756
 
    def __init__(self, format_string, module_name, member_name):
1757
 
        """Create a MetaDirBranchFormatFactory.
1758
 
 
1759
 
        :param format_string: The format string the format has.
1760
 
        :param module_name: Module to load the format class from.
1761
 
        :param member_name: Attribute name within the module for the format class.
1762
 
        """
1763
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1764
 
        self._format_string = format_string
1765
 
        
1766
 
    def get_format_string(self):
1767
 
        """See BranchFormat.get_format_string."""
1768
 
        return self._format_string
1769
 
 
1770
 
    def __call__(self):
1771
 
        """Used for network_format_registry support."""
1772
 
        return self.get_obj()()
1773
 
 
1774
 
 
1775
1608
class BranchHooks(Hooks):
1776
1609
    """A dictionary mapping hook name to a list of callables for branch hooks.
1777
1610
 
1785
1618
        These are all empty initially, because by default nothing should get
1786
1619
        notified.
1787
1620
        """
1788
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1789
 
        self.add_hook('set_rh',
 
1621
        Hooks.__init__(self)
 
1622
        self.create_hook(HookPoint('set_rh',
1790
1623
            "Invoked whenever the revision history has been set via "
1791
1624
            "set_revision_history. The api signature is (branch, "
1792
1625
            "revision_history), and the branch will be write-locked. "
1793
1626
            "The set_rh hook can be expensive for bzr to trigger, a better "
1794
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1795
 
        self.add_hook('open',
 
1627
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1628
        self.create_hook(HookPoint('open',
1796
1629
            "Called with the Branch object that has been opened after a "
1797
 
            "branch is opened.", (1, 8))
1798
 
        self.add_hook('post_push',
 
1630
            "branch is opened.", (1, 8), None))
 
1631
        self.create_hook(HookPoint('post_push',
1799
1632
            "Called after a push operation completes. post_push is called "
1800
1633
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1801
 
            "bzr client.", (0, 15))
1802
 
        self.add_hook('post_pull',
 
1634
            "bzr client.", (0, 15), None))
 
1635
        self.create_hook(HookPoint('post_pull',
1803
1636
            "Called after a pull operation completes. post_pull is called "
1804
1637
            "with a bzrlib.branch.PullResult object and only runs in the "
1805
 
            "bzr client.", (0, 15))
1806
 
        self.add_hook('pre_commit',
1807
 
            "Called after a commit is calculated but before it is "
 
1638
            "bzr client.", (0, 15), None))
 
1639
        self.create_hook(HookPoint('pre_commit',
 
1640
            "Called after a commit is calculated but before it is is "
1808
1641
            "completed. pre_commit is called with (local, master, old_revno, "
1809
1642
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1810
1643
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1812
1645
            "basis revision. hooks MUST NOT modify this delta. "
1813
1646
            " future_tree is an in-memory tree obtained from "
1814
1647
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1815
 
            "tree.", (0,91))
1816
 
        self.add_hook('post_commit',
 
1648
            "tree.", (0,91), None))
 
1649
        self.create_hook(HookPoint('post_commit',
1817
1650
            "Called in the bzr client after a commit has completed. "
1818
1651
            "post_commit is called with (local, master, old_revno, old_revid, "
1819
1652
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1820
 
            "commit to a branch.", (0, 15))
1821
 
        self.add_hook('post_uncommit',
 
1653
            "commit to a branch.", (0, 15), None))
 
1654
        self.create_hook(HookPoint('post_uncommit',
1822
1655
            "Called in the bzr client after an uncommit completes. "
1823
1656
            "post_uncommit is called with (local, master, old_revno, "
1824
1657
            "old_revid, new_revno, new_revid) where local is the local branch "
1825
1658
            "or None, master is the target branch, and an empty branch "
1826
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1827
 
        self.add_hook('pre_change_branch_tip',
 
1659
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1660
        self.create_hook(HookPoint('pre_change_branch_tip',
1828
1661
            "Called in bzr client and server before a change to the tip of a "
1829
1662
            "branch is made. pre_change_branch_tip is called with a "
1830
1663
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1831
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1832
 
        self.add_hook('post_change_branch_tip',
 
1664
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1665
        self.create_hook(HookPoint('post_change_branch_tip',
1833
1666
            "Called in bzr client and server after a change to the tip of a "
1834
1667
            "branch is made. post_change_branch_tip is called with a "
1835
1668
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1836
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1837
 
        self.add_hook('transform_fallback_location',
 
1669
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1670
        self.create_hook(HookPoint('transform_fallback_location',
1838
1671
            "Called when a stacked branch is activating its fallback "
1839
1672
            "locations. transform_fallback_location is called with (branch, "
1840
1673
            "url), and should return a new url. Returning the same url "
1845
1678
            "fallback locations have not been activated. When there are "
1846
1679
            "multiple hooks installed for transform_fallback_location, "
1847
1680
            "all are called with the url returned from the previous hook."
1848
 
            "The order is however undefined.", (1, 9))
1849
 
        self.add_hook('automatic_tag_name',
1850
 
            "Called to determine an automatic tag name for a revision. "
1851
 
            "automatic_tag_name is called with (branch, revision_id) and "
1852
 
            "should return a tag name or None if no tag name could be "
1853
 
            "determined. The first non-None tag name returned will be used.",
1854
 
            (2, 2))
1855
 
        self.add_hook('post_branch_init',
1856
 
            "Called after new branch initialization completes. "
1857
 
            "post_branch_init is called with a "
1858
 
            "bzrlib.branch.BranchInitHookParams. "
1859
 
            "Note that init, branch and checkout (both heavyweight and "
1860
 
            "lightweight) will all trigger this hook.", (2, 2))
1861
 
        self.add_hook('post_switch',
1862
 
            "Called after a checkout switches branch. "
1863
 
            "post_switch is called with a "
1864
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1865
 
 
 
1681
            "The order is however undefined.", (1, 9), None))
1866
1682
 
1867
1683
 
1868
1684
# install the default hooks into the Branch class.
1870
1686
 
1871
1687
 
1872
1688
class ChangeBranchTipParams(object):
1873
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1689
    """Object holding parameters passed to *_change_branch_tip hooks.
1874
1690
 
1875
1691
    There are 5 fields that hooks may wish to access:
1876
1692
 
1907
1723
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1908
1724
 
1909
1725
 
1910
 
class BranchInitHookParams(object):
1911
 
    """Object holding parameters passed to `*_branch_init` hooks.
1912
 
 
1913
 
    There are 4 fields that hooks may wish to access:
1914
 
 
1915
 
    :ivar format: the branch format
1916
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1917
 
    :ivar name: name of colocated branch, if any (or None)
1918
 
    :ivar branch: the branch created
1919
 
 
1920
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1921
 
    the checkout, hence they are different from the corresponding fields in
1922
 
    branch, which refer to the original branch.
1923
 
    """
1924
 
 
1925
 
    def __init__(self, format, a_bzrdir, name, branch):
1926
 
        """Create a group of BranchInitHook parameters.
1927
 
 
1928
 
        :param format: the branch format
1929
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1930
 
            initialized
1931
 
        :param name: name of colocated branch, if any (or None)
1932
 
        :param branch: the branch created
1933
 
 
1934
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1935
 
        to the checkout, hence they are different from the corresponding fields
1936
 
        in branch, which refer to the original branch.
1937
 
        """
1938
 
        self.format = format
1939
 
        self.bzrdir = a_bzrdir
1940
 
        self.name = name
1941
 
        self.branch = branch
1942
 
 
1943
 
    def __eq__(self, other):
1944
 
        return self.__dict__ == other.__dict__
1945
 
 
1946
 
    def __repr__(self):
1947
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1948
 
 
1949
 
 
1950
 
class SwitchHookParams(object):
1951
 
    """Object holding parameters passed to `*_switch` hooks.
1952
 
 
1953
 
    There are 4 fields that hooks may wish to access:
1954
 
 
1955
 
    :ivar control_dir: BzrDir of the checkout to change
1956
 
    :ivar to_branch: branch that the checkout is to reference
1957
 
    :ivar force: skip the check for local commits in a heavy checkout
1958
 
    :ivar revision_id: revision ID to switch to (or None)
1959
 
    """
1960
 
 
1961
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1962
 
        """Create a group of SwitchHook parameters.
1963
 
 
1964
 
        :param control_dir: BzrDir of the checkout to change
1965
 
        :param to_branch: branch that the checkout is to reference
1966
 
        :param force: skip the check for local commits in a heavy checkout
1967
 
        :param revision_id: revision ID to switch to (or None)
1968
 
        """
1969
 
        self.control_dir = control_dir
1970
 
        self.to_branch = to_branch
1971
 
        self.force = force
1972
 
        self.revision_id = revision_id
1973
 
 
1974
 
    def __eq__(self, other):
1975
 
        return self.__dict__ == other.__dict__
1976
 
 
1977
 
    def __repr__(self):
1978
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1979
 
            self.control_dir, self.to_branch,
1980
 
            self.revision_id)
 
1726
class BzrBranchFormat4(BranchFormat):
 
1727
    """Bzr branch format 4.
 
1728
 
 
1729
    This format has:
 
1730
     - a revision-history file.
 
1731
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1732
    """
 
1733
 
 
1734
    def get_format_description(self):
 
1735
        """See BranchFormat.get_format_description()."""
 
1736
        return "Branch format 4"
 
1737
 
 
1738
    def initialize(self, a_bzrdir):
 
1739
        """Create a branch of this format in a_bzrdir."""
 
1740
        utf8_files = [('revision-history', ''),
 
1741
                      ('branch-name', ''),
 
1742
                      ]
 
1743
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1744
                                       lock_type='branch4', set_format=False)
 
1745
 
 
1746
    def __init__(self):
 
1747
        super(BzrBranchFormat4, self).__init__()
 
1748
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1749
 
 
1750
    def network_name(self):
 
1751
        """The network name for this format is the control dirs disk label."""
 
1752
        return self._matchingbzrdir.get_format_string()
 
1753
 
 
1754
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1755
        """See BranchFormat.open()."""
 
1756
        if not _found:
 
1757
            # we are being called directly and must probe.
 
1758
            raise NotImplementedError
 
1759
        return BzrBranch(_format=self,
 
1760
                         _control_files=a_bzrdir._control_files,
 
1761
                         a_bzrdir=a_bzrdir,
 
1762
                         _repository=a_bzrdir.open_repository())
 
1763
 
 
1764
    def __str__(self):
 
1765
        return "Bazaar-NG branch format 4"
1981
1766
 
1982
1767
 
1983
1768
class BranchFormatMetadir(BranchFormat):
1987
1772
        """What class to instantiate on open calls."""
1988
1773
        raise NotImplementedError(self._branch_class)
1989
1774
 
1990
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1991
 
                           repository=None):
1992
 
        """Initialize a branch in a bzrdir, with specified files
1993
 
 
1994
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1995
 
        :param utf8_files: The files to create as a list of
1996
 
            (filename, content) tuples
1997
 
        :param name: Name of colocated branch to create, if any
1998
 
        :return: a branch in this format
1999
 
        """
2000
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2001
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2002
 
        control_files = lockable_files.LockableFiles(branch_transport,
2003
 
            'lock', lockdir.LockDir)
2004
 
        control_files.create_lock()
2005
 
        control_files.lock_write()
2006
 
        try:
2007
 
            utf8_files += [('format', self.get_format_string())]
2008
 
            for (filename, content) in utf8_files:
2009
 
                branch_transport.put_bytes(
2010
 
                    filename, content,
2011
 
                    mode=a_bzrdir._get_file_mode())
2012
 
        finally:
2013
 
            control_files.unlock()
2014
 
        branch = self.open(a_bzrdir, name, _found=True,
2015
 
                found_repository=repository)
2016
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2017
 
        return branch
2018
 
 
2019
1775
    def network_name(self):
2020
1776
        """A simple byte string uniquely identifying this format for RPC calls.
2021
1777
 
2023
1779
        """
2024
1780
        return self.get_format_string()
2025
1781
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2027
 
            found_repository=None):
 
1782
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2028
1783
        """See BranchFormat.open()."""
2029
1784
        if not _found:
2030
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1785
            format = BranchFormat.find_format(a_bzrdir)
2031
1786
            if format.__class__ != self.__class__:
2032
1787
                raise AssertionError("wrong format %r found for %r" %
2033
1788
                    (format, self))
2034
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2035
1789
        try:
 
1790
            transport = a_bzrdir.get_branch_transport(None)
2036
1791
            control_files = lockable_files.LockableFiles(transport, 'lock',
2037
1792
                                                         lockdir.LockDir)
2038
 
            if found_repository is None:
2039
 
                found_repository = a_bzrdir.find_repository()
2040
1793
            return self._branch_class()(_format=self,
2041
1794
                              _control_files=control_files,
2042
 
                              name=name,
2043
1795
                              a_bzrdir=a_bzrdir,
2044
 
                              _repository=found_repository,
 
1796
                              _repository=a_bzrdir.find_repository(),
2045
1797
                              ignore_fallbacks=ignore_fallbacks)
2046
1798
        except errors.NoSuchFile:
2047
1799
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2054
1806
    def supports_tags(self):
2055
1807
        return True
2056
1808
 
2057
 
    def supports_leaving_lock(self):
2058
 
        return True
2059
 
 
2060
1809
 
2061
1810
class BzrBranchFormat5(BranchFormatMetadir):
2062
1811
    """Bzr branch format 5.
2082
1831
        """See BranchFormat.get_format_description()."""
2083
1832
        return "Branch format 5"
2084
1833
 
2085
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1834
    def initialize(self, a_bzrdir):
2086
1835
        """Create a branch of this format in a_bzrdir."""
2087
1836
        utf8_files = [('revision-history', ''),
2088
1837
                      ('branch-name', ''),
2089
1838
                      ]
2090
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1839
        return self._initialize_helper(a_bzrdir, utf8_files)
2091
1840
 
2092
1841
    def supports_tags(self):
2093
1842
        return False
2115
1864
        """See BranchFormat.get_format_description()."""
2116
1865
        return "Branch format 6"
2117
1866
 
2118
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1867
    def initialize(self, a_bzrdir):
2119
1868
        """Create a branch of this format in a_bzrdir."""
2120
1869
        utf8_files = [('last-revision', '0 null:\n'),
2121
1870
                      ('branch.conf', ''),
2122
1871
                      ('tags', ''),
2123
1872
                      ]
2124
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1873
        return self._initialize_helper(a_bzrdir, utf8_files)
2125
1874
 
2126
1875
    def make_tags(self, branch):
2127
1876
        """See bzrlib.branch.BranchFormat.make_tags()."""
2145
1894
        """See BranchFormat.get_format_description()."""
2146
1895
        return "Branch format 8"
2147
1896
 
2148
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1897
    def initialize(self, a_bzrdir):
2149
1898
        """Create a branch of this format in a_bzrdir."""
2150
1899
        utf8_files = [('last-revision', '0 null:\n'),
2151
1900
                      ('branch.conf', ''),
2152
1901
                      ('tags', ''),
2153
1902
                      ('references', '')
2154
1903
                      ]
2155
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1904
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1905
 
 
1906
    def __init__(self):
 
1907
        super(BzrBranchFormat8, self).__init__()
 
1908
        self._matchingbzrdir.repository_format = \
 
1909
            RepositoryFormatKnitPack5RichRoot()
2156
1910
 
2157
1911
    def make_tags(self, branch):
2158
1912
        """See bzrlib.branch.BranchFormat.make_tags()."""
2167
1921
    supports_reference_locations = True
2168
1922
 
2169
1923
 
2170
 
class BzrBranchFormat7(BranchFormatMetadir):
 
1924
class BzrBranchFormat7(BzrBranchFormat8):
2171
1925
    """Branch format with last-revision, tags, and a stacked location pointer.
2172
1926
 
2173
1927
    The stacked location pointer is passed down to the repository and requires
2176
1930
    This format was introduced in bzr 1.6.
2177
1931
    """
2178
1932
 
2179
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1933
    def initialize(self, a_bzrdir):
2180
1934
        """Create a branch of this format in a_bzrdir."""
2181
1935
        utf8_files = [('last-revision', '0 null:\n'),
2182
1936
                      ('branch.conf', ''),
2183
1937
                      ('tags', ''),
2184
1938
                      ]
2185
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1939
        return self._initialize_helper(a_bzrdir, utf8_files)
2186
1940
 
2187
1941
    def _branch_class(self):
2188
1942
        return BzrBranch7
2198
1952
    def supports_set_append_revisions_only(self):
2199
1953
        return True
2200
1954
 
2201
 
    def supports_stacking(self):
2202
 
        return True
2203
 
 
2204
 
    def make_tags(self, branch):
2205
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2206
 
        return BasicTags(branch)
2207
 
 
2208
1955
    supports_reference_locations = False
2209
1956
 
2210
1957
 
2227
1974
        """See BranchFormat.get_format_description()."""
2228
1975
        return "Checkout reference format 1"
2229
1976
 
2230
 
    def get_reference(self, a_bzrdir, name=None):
 
1977
    def get_reference(self, a_bzrdir):
2231
1978
        """See BranchFormat.get_reference()."""
2232
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1979
        transport = a_bzrdir.get_branch_transport(None)
2233
1980
        return transport.get_bytes('location')
2234
1981
 
2235
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1982
    def set_reference(self, a_bzrdir, to_branch):
2236
1983
        """See BranchFormat.set_reference()."""
2237
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1984
        transport = a_bzrdir.get_branch_transport(None)
2238
1985
        location = transport.put_bytes('location', to_branch.base)
2239
1986
 
2240
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2241
 
            repository=None):
 
1987
    def initialize(self, a_bzrdir, target_branch=None):
2242
1988
        """Create a branch of this format in a_bzrdir."""
2243
1989
        if target_branch is None:
2244
1990
            # this format does not implement branch itself, thus the implicit
2245
1991
            # creation contract must see it as uninitializable
2246
1992
            raise errors.UninitializableFormat(self)
2247
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2248
 
        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)
2249
1995
        branch_transport.put_bytes('location',
2250
 
            target_branch.bzrdir.user_url)
 
1996
            target_branch.bzrdir.root_transport.base)
2251
1997
        branch_transport.put_bytes('format', self.get_format_string())
2252
 
        branch = self.open(
2253
 
            a_bzrdir, name, _found=True,
 
1998
        return self.open(
 
1999
            a_bzrdir, _found=True,
2254
2000
            possible_transports=[target_branch.bzrdir.root_transport])
2255
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2256
 
        return branch
2257
2001
 
2258
2002
    def __init__(self):
2259
2003
        super(BranchReferenceFormat, self).__init__()
2265
2009
        def clone(to_bzrdir, revision_id=None,
2266
2010
            repository_policy=None):
2267
2011
            """See Branch.clone()."""
2268
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2012
            return format.initialize(to_bzrdir, a_branch)
2269
2013
            # cannot obey revision_id limits when cloning a reference ...
2270
2014
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2271
2015
            # emit some sort of warning/error to the caller ?!
2272
2016
        return clone
2273
2017
 
2274
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2275
 
             possible_transports=None, ignore_fallbacks=False,
2276
 
             found_repository=None):
 
2018
    def open(self, a_bzrdir, _found=False, location=None,
 
2019
             possible_transports=None, ignore_fallbacks=False):
2277
2020
        """Return the branch that the branch reference in a_bzrdir points at.
2278
2021
 
2279
2022
        :param a_bzrdir: A BzrDir that contains a branch.
2280
 
        :param name: Name of colocated branch to open, if any
2281
2023
        :param _found: a private parameter, do not use it. It is used to
2282
2024
            indicate if format probing has already be done.
2283
2025
        :param ignore_fallbacks: when set, no fallback branches will be opened
2288
2030
        :param possible_transports: An optional reusable transports list.
2289
2031
        """
2290
2032
        if not _found:
2291
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
2033
            format = BranchFormat.find_format(a_bzrdir)
2292
2034
            if format.__class__ != self.__class__:
2293
2035
                raise AssertionError("wrong format %r found for %r" %
2294
2036
                    (format, self))
2295
2037
        if location is None:
2296
 
            location = self.get_reference(a_bzrdir, name)
 
2038
            location = self.get_reference(a_bzrdir)
2297
2039
        real_bzrdir = bzrdir.BzrDir.open(
2298
2040
            location, possible_transports=possible_transports)
2299
 
        result = real_bzrdir.open_branch(name=name, 
2300
 
            ignore_fallbacks=ignore_fallbacks)
 
2041
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2301
2042
        # this changes the behaviour of result.clone to create a new reference
2302
2043
        # rather than a copy of the content of the branch.
2303
2044
        # I did not use a proxy object because that needs much more extensive
2310
2051
        return result
2311
2052
 
2312
2053
 
2313
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2314
 
    """Branch format registry."""
2315
 
 
2316
 
    def __init__(self, other_registry=None):
2317
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2318
 
        self._default_format = None
2319
 
 
2320
 
    def set_default(self, format):
2321
 
        self._default_format = format
2322
 
 
2323
 
    def get_default(self):
2324
 
        return self._default_format
2325
 
 
2326
 
 
2327
2054
network_format_registry = registry.FormatRegistry()
2328
2055
"""Registry of formats indexed by their network name.
2329
2056
 
2332
2059
BranchFormat.network_name() for more detail.
2333
2060
"""
2334
2061
 
2335
 
format_registry = BranchFormatRegistry(network_format_registry)
2336
 
 
2337
2062
 
2338
2063
# formats which have no format string are not discoverable
2339
2064
# and not independently creatable, so are not registered.
2341
2066
__format6 = BzrBranchFormat6()
2342
2067
__format7 = BzrBranchFormat7()
2343
2068
__format8 = BzrBranchFormat8()
2344
 
format_registry.register(__format5)
2345
 
format_registry.register(BranchReferenceFormat())
2346
 
format_registry.register(__format6)
2347
 
format_registry.register(__format7)
2348
 
format_registry.register(__format8)
2349
 
format_registry.set_default(__format7)
2350
 
 
2351
 
 
2352
 
class BranchWriteLockResult(LogicalLockResult):
2353
 
    """The result of write locking a branch.
2354
 
 
2355
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2356
 
        None.
2357
 
    :ivar unlock: A callable which will unlock the lock.
2358
 
    """
2359
 
 
2360
 
    def __init__(self, unlock, branch_token):
2361
 
        LogicalLockResult.__init__(self, unlock)
2362
 
        self.branch_token = branch_token
2363
 
 
2364
 
    def __repr__(self):
2365
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2366
 
            self.unlock)
 
2069
BranchFormat.register_format(__format5)
 
2070
BranchFormat.register_format(BranchReferenceFormat())
 
2071
BranchFormat.register_format(__format6)
 
2072
BranchFormat.register_format(__format7)
 
2073
BranchFormat.register_format(__format8)
 
2074
BranchFormat.set_default_format(__format7)
 
2075
_legacy_formats = [BzrBranchFormat4(),
 
2076
    ]
 
2077
network_format_registry.register(
 
2078
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2367
2079
 
2368
2080
 
2369
2081
class BzrBranch(Branch, _RelockDebugMixin):
2378
2090
    :ivar repository: Repository for this branch.
2379
2091
    :ivar base: The url of the base directory for this branch; the one
2380
2092
        containing the .bzr directory.
2381
 
    :ivar name: Optional colocated branch name as it exists in the control
2382
 
        directory.
2383
2093
    """
2384
2094
 
2385
2095
    def __init__(self, _format=None,
2386
 
                 _control_files=None, a_bzrdir=None, name=None,
2387
 
                 _repository=None, ignore_fallbacks=False):
 
2096
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2097
                 ignore_fallbacks=False):
2388
2098
        """Create new branch object at a particular location."""
2389
2099
        if a_bzrdir is None:
2390
2100
            raise ValueError('a_bzrdir must be supplied')
2391
2101
        else:
2392
2102
            self.bzrdir = a_bzrdir
2393
2103
        self._base = self.bzrdir.transport.clone('..').base
2394
 
        self.name = name
2395
2104
        # XXX: We should be able to just do
2396
2105
        #   self.base = self.bzrdir.root_transport.base
2397
2106
        # but this does not quite work yet -- mbp 20080522
2404
2113
        Branch.__init__(self)
2405
2114
 
2406
2115
    def __str__(self):
2407
 
        if self.name is None:
2408
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2409
 
        else:
2410
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2411
 
                self.name)
 
2116
        return '%s(%r)' % (self.__class__.__name__, self.base)
2412
2117
 
2413
2118
    __repr__ = __str__
2414
2119
 
2425
2130
        return self.control_files.is_locked()
2426
2131
 
2427
2132
    def lock_write(self, token=None):
2428
 
        """Lock the branch for write operations.
2429
 
 
2430
 
        :param token: A token to permit reacquiring a previously held and
2431
 
            preserved lock.
2432
 
        :return: A BranchWriteLockResult.
2433
 
        """
2434
2133
        if not self.is_locked():
2435
2134
            self._note_lock('w')
2436
2135
        # All-in-one needs to always unlock/lock.
2442
2141
        else:
2443
2142
            took_lock = False
2444
2143
        try:
2445
 
            return BranchWriteLockResult(self.unlock,
2446
 
                self.control_files.lock_write(token=token))
 
2144
            return self.control_files.lock_write(token=token)
2447
2145
        except:
2448
2146
            if took_lock:
2449
2147
                self.repository.unlock()
2450
2148
            raise
2451
2149
 
2452
2150
    def lock_read(self):
2453
 
        """Lock the branch for read operations.
2454
 
 
2455
 
        :return: A bzrlib.lock.LogicalLockResult.
2456
 
        """
2457
2151
        if not self.is_locked():
2458
2152
            self._note_lock('r')
2459
2153
        # All-in-one needs to always unlock/lock.
2466
2160
            took_lock = False
2467
2161
        try:
2468
2162
            self.control_files.lock_read()
2469
 
            return LogicalLockResult(self.unlock)
2470
2163
        except:
2471
2164
            if took_lock:
2472
2165
                self.repository.unlock()
2500
2193
        """See Branch.print_file."""
2501
2194
        return self.repository.print_file(file, revision_id)
2502
2195
 
 
2196
    def _write_revision_history(self, history):
 
2197
        """Factored out of set_revision_history.
 
2198
 
 
2199
        This performs the actual writing to disk.
 
2200
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2201
        self._transport.put_bytes(
 
2202
            'revision-history', '\n'.join(history),
 
2203
            mode=self.bzrdir._get_file_mode())
 
2204
 
 
2205
    @needs_write_lock
 
2206
    def set_revision_history(self, rev_history):
 
2207
        """See Branch.set_revision_history."""
 
2208
        if 'evil' in debug.debug_flags:
 
2209
            mutter_callsite(3, "set_revision_history scales with history.")
 
2210
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2211
        for rev_id in rev_history:
 
2212
            check_not_reserved_id(rev_id)
 
2213
        if Branch.hooks['post_change_branch_tip']:
 
2214
            # Don't calculate the last_revision_info() if there are no hooks
 
2215
            # that will use it.
 
2216
            old_revno, old_revid = self.last_revision_info()
 
2217
        if len(rev_history) == 0:
 
2218
            revid = _mod_revision.NULL_REVISION
 
2219
        else:
 
2220
            revid = rev_history[-1]
 
2221
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2222
        self._write_revision_history(rev_history)
 
2223
        self._clear_cached_state()
 
2224
        self._cache_revision_history(rev_history)
 
2225
        for hook in Branch.hooks['set_rh']:
 
2226
            hook(self, rev_history)
 
2227
        if Branch.hooks['post_change_branch_tip']:
 
2228
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2229
 
 
2230
    def _synchronize_history(self, destination, revision_id):
 
2231
        """Synchronize last revision and revision history between branches.
 
2232
 
 
2233
        This version is most efficient when the destination is also a
 
2234
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2235
        history is the true lefthand parent history, and all of the revisions
 
2236
        are in the destination's repository.  If not, set_revision_history
 
2237
        will fail.
 
2238
 
 
2239
        :param destination: The branch to copy the history into
 
2240
        :param revision_id: The revision-id to truncate history at.  May
 
2241
          be None to copy complete history.
 
2242
        """
 
2243
        if not isinstance(destination._format, BzrBranchFormat5):
 
2244
            super(BzrBranch, self)._synchronize_history(
 
2245
                destination, revision_id)
 
2246
            return
 
2247
        if revision_id == _mod_revision.NULL_REVISION:
 
2248
            new_history = []
 
2249
        else:
 
2250
            new_history = self.revision_history()
 
2251
        if revision_id is not None and new_history != []:
 
2252
            try:
 
2253
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2254
            except ValueError:
 
2255
                rev = self.repository.get_revision(revision_id)
 
2256
                new_history = rev.get_history(self.repository)[1:]
 
2257
        destination.set_revision_history(new_history)
 
2258
 
2503
2259
    @needs_write_lock
2504
2260
    def set_last_revision_info(self, revno, revision_id):
2505
 
        if not revision_id or not isinstance(revision_id, basestring):
2506
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2261
        """Set the last revision of this branch.
 
2262
 
 
2263
        The caller is responsible for checking that the revno is correct
 
2264
        for this revision id.
 
2265
 
 
2266
        It may be possible to set the branch last revision to an id not
 
2267
        present in the repository.  However, branches can also be
 
2268
        configured to check constraints on history, in which case this may not
 
2269
        be permitted.
 
2270
        """
2507
2271
        revision_id = _mod_revision.ensure_null(revision_id)
2508
 
        old_revno, old_revid = self.last_revision_info()
2509
 
        if self._get_append_revisions_only():
2510
 
            self._check_history_violation(revision_id)
2511
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2512
 
        self._write_last_revision_info(revno, revision_id)
2513
 
        self._clear_cached_state()
2514
 
        self._last_revision_info_cache = revno, revision_id
2515
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2272
        # this old format stores the full history, but this api doesn't
 
2273
        # provide it, so we must generate, and might as well check it's
 
2274
        # correct
 
2275
        history = self._lefthand_history(revision_id)
 
2276
        if len(history) != revno:
 
2277
            raise AssertionError('%d != %d' % (len(history), revno))
 
2278
        self.set_revision_history(history)
 
2279
 
 
2280
    def _gen_revision_history(self):
 
2281
        history = self._transport.get_bytes('revision-history').split('\n')
 
2282
        if history[-1:] == ['']:
 
2283
            # There shouldn't be a trailing newline, but just in case.
 
2284
            history.pop()
 
2285
        return history
 
2286
 
 
2287
    @needs_write_lock
 
2288
    def generate_revision_history(self, revision_id, last_rev=None,
 
2289
        other_branch=None):
 
2290
        """Create a new revision history that will finish with revision_id.
 
2291
 
 
2292
        :param revision_id: the new tip to use.
 
2293
        :param last_rev: The previous last_revision. If not None, then this
 
2294
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2295
        :param other_branch: The other branch that DivergedBranches should
 
2296
            raise with respect to.
 
2297
        """
 
2298
        self.set_revision_history(self._lefthand_history(revision_id,
 
2299
            last_rev, other_branch))
2516
2300
 
2517
2301
    def basis_tree(self):
2518
2302
        """See Branch.basis_tree."""
2527
2311
                pass
2528
2312
        return None
2529
2313
 
 
2314
    def _basic_push(self, target, overwrite, stop_revision):
 
2315
        """Basic implementation of push without bound branches or hooks.
 
2316
 
 
2317
        Must be called with source read locked and target write locked.
 
2318
        """
 
2319
        result = BranchPushResult()
 
2320
        result.source_branch = self
 
2321
        result.target_branch = target
 
2322
        result.old_revno, result.old_revid = target.last_revision_info()
 
2323
        self.update_references(target)
 
2324
        if result.old_revid != self.last_revision():
 
2325
            # We assume that during 'push' this repository is closer than
 
2326
            # the target.
 
2327
            graph = self.repository.get_graph(target.repository)
 
2328
            target.update_revisions(self, stop_revision,
 
2329
                overwrite=overwrite, graph=graph)
 
2330
        if self._push_should_merge_tags():
 
2331
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2332
                overwrite)
 
2333
        result.new_revno, result.new_revid = target.last_revision_info()
 
2334
        return result
 
2335
 
2530
2336
    def get_stacked_on_url(self):
2531
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2337
        raise errors.UnstackableBranchFormat(self._format, self.base)
2532
2338
 
2533
2339
    def set_push_location(self, location):
2534
2340
        """See Branch.set_push_location."""
2543
2349
            self._transport.put_bytes('parent', url + '\n',
2544
2350
                mode=self.bzrdir._get_file_mode())
2545
2351
 
 
2352
 
 
2353
class BzrBranch5(BzrBranch):
 
2354
    """A format 5 branch. This supports new features over plain branches.
 
2355
 
 
2356
    It has support for a master_branch which is the data for bound branches.
 
2357
    """
 
2358
 
 
2359
    def get_bound_location(self):
 
2360
        try:
 
2361
            return self._transport.get_bytes('bound')[:-1]
 
2362
        except errors.NoSuchFile:
 
2363
            return None
 
2364
 
 
2365
    @needs_read_lock
 
2366
    def get_master_branch(self, possible_transports=None):
 
2367
        """Return the branch we are bound to.
 
2368
 
 
2369
        :return: Either a Branch, or None
 
2370
 
 
2371
        This could memoise the branch, but if thats done
 
2372
        it must be revalidated on each new lock.
 
2373
        So for now we just don't memoise it.
 
2374
        # RBC 20060304 review this decision.
 
2375
        """
 
2376
        bound_loc = self.get_bound_location()
 
2377
        if not bound_loc:
 
2378
            return None
 
2379
        try:
 
2380
            return Branch.open(bound_loc,
 
2381
                               possible_transports=possible_transports)
 
2382
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2383
            raise errors.BoundBranchConnectionFailure(
 
2384
                    self, bound_loc, e)
 
2385
 
2546
2386
    @needs_write_lock
2547
 
    def unbind(self):
2548
 
        """If bound, unbind"""
2549
 
        return self.set_bound_location(None)
 
2387
    def set_bound_location(self, location):
 
2388
        """Set the target where this branch is bound to.
 
2389
 
 
2390
        :param location: URL to the target branch
 
2391
        """
 
2392
        if location:
 
2393
            self._transport.put_bytes('bound', location+'\n',
 
2394
                mode=self.bzrdir._get_file_mode())
 
2395
        else:
 
2396
            try:
 
2397
                self._transport.delete('bound')
 
2398
            except errors.NoSuchFile:
 
2399
                return False
 
2400
            return True
2550
2401
 
2551
2402
    @needs_write_lock
2552
2403
    def bind(self, other):
2574
2425
        # history around
2575
2426
        self.set_bound_location(other.base)
2576
2427
 
2577
 
    def get_bound_location(self):
2578
 
        try:
2579
 
            return self._transport.get_bytes('bound')[:-1]
2580
 
        except errors.NoSuchFile:
2581
 
            return None
2582
 
 
2583
 
    @needs_read_lock
2584
 
    def get_master_branch(self, possible_transports=None):
2585
 
        """Return the branch we are bound to.
2586
 
 
2587
 
        :return: Either a Branch, or None
2588
 
        """
2589
 
        if self._master_branch_cache is None:
2590
 
            self._master_branch_cache = self._get_master_branch(
2591
 
                possible_transports)
2592
 
        return self._master_branch_cache
2593
 
 
2594
 
    def _get_master_branch(self, possible_transports):
2595
 
        bound_loc = self.get_bound_location()
2596
 
        if not bound_loc:
2597
 
            return None
2598
 
        try:
2599
 
            return Branch.open(bound_loc,
2600
 
                               possible_transports=possible_transports)
2601
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2602
 
            raise errors.BoundBranchConnectionFailure(
2603
 
                    self, bound_loc, e)
2604
 
 
2605
2428
    @needs_write_lock
2606
 
    def set_bound_location(self, location):
2607
 
        """Set the target where this branch is bound to.
2608
 
 
2609
 
        :param location: URL to the target branch
2610
 
        """
2611
 
        self._master_branch_cache = None
2612
 
        if location:
2613
 
            self._transport.put_bytes('bound', location+'\n',
2614
 
                mode=self.bzrdir._get_file_mode())
2615
 
        else:
2616
 
            try:
2617
 
                self._transport.delete('bound')
2618
 
            except errors.NoSuchFile:
2619
 
                return False
2620
 
            return True
 
2429
    def unbind(self):
 
2430
        """If bound, unbind"""
 
2431
        return self.set_bound_location(None)
2621
2432
 
2622
2433
    @needs_write_lock
2623
2434
    def update(self, possible_transports=None):
2636
2447
            return old_tip
2637
2448
        return None
2638
2449
 
2639
 
    def _read_last_revision_info(self):
2640
 
        revision_string = self._transport.get_bytes('last-revision')
2641
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2642
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2643
 
        revno = int(revno)
2644
 
        return revno, revision_id
2645
 
 
2646
 
    def _write_last_revision_info(self, revno, revision_id):
2647
 
        """Simply write out the revision id, with no checks.
2648
 
 
2649
 
        Use set_last_revision_info to perform this safely.
2650
 
 
2651
 
        Does not update the revision_history cache.
2652
 
        """
2653
 
        revision_id = _mod_revision.ensure_null(revision_id)
2654
 
        out_string = '%d %s\n' % (revno, revision_id)
2655
 
        self._transport.put_bytes('last-revision', out_string,
2656
 
            mode=self.bzrdir._get_file_mode())
2657
 
 
2658
 
 
2659
 
class FullHistoryBzrBranch(BzrBranch):
2660
 
    """Bzr branch which contains the full revision history."""
2661
 
 
2662
 
    @needs_write_lock
2663
 
    def set_last_revision_info(self, revno, revision_id):
2664
 
        if not revision_id or not isinstance(revision_id, basestring):
2665
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2666
 
        revision_id = _mod_revision.ensure_null(revision_id)
2667
 
        # this old format stores the full history, but this api doesn't
2668
 
        # provide it, so we must generate, and might as well check it's
2669
 
        # correct
2670
 
        history = self._lefthand_history(revision_id)
2671
 
        if len(history) != revno:
2672
 
            raise AssertionError('%d != %d' % (len(history), revno))
2673
 
        self._set_revision_history(history)
2674
 
 
2675
 
    def _read_last_revision_info(self):
2676
 
        rh = self.revision_history()
2677
 
        revno = len(rh)
2678
 
        if revno:
2679
 
            return (revno, rh[-1])
2680
 
        else:
2681
 
            return (0, _mod_revision.NULL_REVISION)
2682
 
 
2683
 
    @deprecated_method(deprecated_in((2, 4, 0)))
2684
 
    @needs_write_lock
2685
 
    def set_revision_history(self, rev_history):
2686
 
        """See Branch.set_revision_history."""
2687
 
        self._set_revision_history(rev_history)
2688
 
 
2689
 
    def _set_revision_history(self, rev_history):
2690
 
        if 'evil' in debug.debug_flags:
2691
 
            mutter_callsite(3, "set_revision_history scales with history.")
2692
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2693
 
        for rev_id in rev_history:
2694
 
            check_not_reserved_id(rev_id)
2695
 
        if Branch.hooks['post_change_branch_tip']:
2696
 
            # Don't calculate the last_revision_info() if there are no hooks
2697
 
            # that will use it.
2698
 
            old_revno, old_revid = self.last_revision_info()
2699
 
        if len(rev_history) == 0:
2700
 
            revid = _mod_revision.NULL_REVISION
2701
 
        else:
2702
 
            revid = rev_history[-1]
2703
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2704
 
        self._write_revision_history(rev_history)
2705
 
        self._clear_cached_state()
2706
 
        self._cache_revision_history(rev_history)
2707
 
        for hook in Branch.hooks['set_rh']:
2708
 
            hook(self, rev_history)
2709
 
        if Branch.hooks['post_change_branch_tip']:
2710
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2711
 
 
2712
 
    def _write_revision_history(self, history):
2713
 
        """Factored out of set_revision_history.
2714
 
 
2715
 
        This performs the actual writing to disk.
2716
 
        It is intended to be called by set_revision_history."""
2717
 
        self._transport.put_bytes(
2718
 
            'revision-history', '\n'.join(history),
2719
 
            mode=self.bzrdir._get_file_mode())
2720
 
 
2721
 
    def _gen_revision_history(self):
2722
 
        history = self._transport.get_bytes('revision-history').split('\n')
2723
 
        if history[-1:] == ['']:
2724
 
            # There shouldn't be a trailing newline, but just in case.
2725
 
            history.pop()
2726
 
        return history
2727
 
 
2728
 
    def _synchronize_history(self, destination, revision_id):
2729
 
        if not isinstance(destination, FullHistoryBzrBranch):
2730
 
            super(BzrBranch, self)._synchronize_history(
2731
 
                destination, revision_id)
2732
 
            return
2733
 
        if revision_id == _mod_revision.NULL_REVISION:
2734
 
            new_history = []
2735
 
        else:
2736
 
            new_history = self.revision_history()
2737
 
        if revision_id is not None and new_history != []:
2738
 
            try:
2739
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2740
 
            except ValueError:
2741
 
                rev = self.repository.get_revision(revision_id)
2742
 
                new_history = rev.get_history(self.repository)[1:]
2743
 
        destination._set_revision_history(new_history)
2744
 
 
2745
 
    @needs_write_lock
2746
 
    def generate_revision_history(self, revision_id, last_rev=None,
2747
 
        other_branch=None):
2748
 
        """Create a new revision history that will finish with revision_id.
2749
 
 
2750
 
        :param revision_id: the new tip to use.
2751
 
        :param last_rev: The previous last_revision. If not None, then this
2752
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2753
 
        :param other_branch: The other branch that DivergedBranches should
2754
 
            raise with respect to.
2755
 
        """
2756
 
        self._set_revision_history(self._lefthand_history(revision_id,
2757
 
            last_rev, other_branch))
2758
 
 
2759
 
 
2760
 
class BzrBranch5(FullHistoryBzrBranch):
2761
 
    """A format 5 branch. This supports new features over plain branches.
2762
 
 
2763
 
    It has support for a master_branch which is the data for bound branches.
2764
 
    """
2765
 
 
2766
 
 
2767
 
class BzrBranch8(BzrBranch):
 
2450
 
 
2451
class BzrBranch8(BzrBranch5):
2768
2452
    """A branch that stores tree-reference locations."""
2769
2453
 
2770
2454
    def _open_hook(self):
2796
2480
        self._last_revision_info_cache = None
2797
2481
        self._reference_info = None
2798
2482
 
 
2483
    def _last_revision_info(self):
 
2484
        revision_string = self._transport.get_bytes('last-revision')
 
2485
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2486
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2487
        revno = int(revno)
 
2488
        return revno, revision_id
 
2489
 
 
2490
    def _write_last_revision_info(self, revno, revision_id):
 
2491
        """Simply write out the revision id, with no checks.
 
2492
 
 
2493
        Use set_last_revision_info to perform this safely.
 
2494
 
 
2495
        Does not update the revision_history cache.
 
2496
        Intended to be called by set_last_revision_info and
 
2497
        _write_revision_history.
 
2498
        """
 
2499
        revision_id = _mod_revision.ensure_null(revision_id)
 
2500
        out_string = '%d %s\n' % (revno, revision_id)
 
2501
        self._transport.put_bytes('last-revision', out_string,
 
2502
            mode=self.bzrdir._get_file_mode())
 
2503
 
 
2504
    @needs_write_lock
 
2505
    def set_last_revision_info(self, revno, revision_id):
 
2506
        revision_id = _mod_revision.ensure_null(revision_id)
 
2507
        old_revno, old_revid = self.last_revision_info()
 
2508
        if self._get_append_revisions_only():
 
2509
            self._check_history_violation(revision_id)
 
2510
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2511
        self._write_last_revision_info(revno, revision_id)
 
2512
        self._clear_cached_state()
 
2513
        self._last_revision_info_cache = revno, revision_id
 
2514
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2515
 
 
2516
    def _synchronize_history(self, destination, revision_id):
 
2517
        """Synchronize last revision and revision history between branches.
 
2518
 
 
2519
        :see: Branch._synchronize_history
 
2520
        """
 
2521
        # XXX: The base Branch has a fast implementation of this method based
 
2522
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2523
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2524
        # but wants the fast implementation, so it calls
 
2525
        # Branch._synchronize_history directly.
 
2526
        Branch._synchronize_history(self, destination, revision_id)
 
2527
 
2799
2528
    def _check_history_violation(self, revision_id):
2800
 
        current_revid = self.last_revision()
2801
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2529
        last_revision = _mod_revision.ensure_null(self.last_revision())
2802
2530
        if _mod_revision.is_null(last_revision):
2803
2531
            return
2804
 
        graph = self.repository.get_graph()
2805
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2806
 
            if lh_ancestor == current_revid:
2807
 
                return
2808
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2532
        if last_revision not in self._lefthand_history(revision_id):
 
2533
            raise errors.AppendRevisionsOnlyViolation(self.base)
2809
2534
 
2810
2535
    def _gen_revision_history(self):
2811
2536
        """Generate the revision history from last revision
2814
2539
        self._extend_partial_history(stop_index=last_revno-1)
2815
2540
        return list(reversed(self._partial_revision_history_cache))
2816
2541
 
 
2542
    def _write_revision_history(self, history):
 
2543
        """Factored out of set_revision_history.
 
2544
 
 
2545
        This performs the actual writing to disk, with format-specific checks.
 
2546
        It is intended to be called by BzrBranch5.set_revision_history.
 
2547
        """
 
2548
        if len(history) == 0:
 
2549
            last_revision = 'null:'
 
2550
        else:
 
2551
            if history != self._lefthand_history(history[-1]):
 
2552
                raise errors.NotLefthandHistory(history)
 
2553
            last_revision = history[-1]
 
2554
        if self._get_append_revisions_only():
 
2555
            self._check_history_violation(last_revision)
 
2556
        self._write_last_revision_info(len(history), last_revision)
 
2557
 
2817
2558
    @needs_write_lock
2818
2559
    def _set_parent_location(self, url):
2819
2560
        """Set the parent branch"""
2895
2636
        if branch_location is None:
2896
2637
            return Branch.reference_parent(self, file_id, path,
2897
2638
                                           possible_transports)
2898
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2639
        branch_location = urlutils.join(self.base, branch_location)
2899
2640
        return Branch.open(branch_location,
2900
2641
                           possible_transports=possible_transports)
2901
2642
 
2905
2646
 
2906
2647
    def set_bound_location(self, location):
2907
2648
        """See Branch.set_push_location."""
2908
 
        self._master_branch_cache = None
2909
2649
        result = None
2910
2650
        config = self.get_config()
2911
2651
        if location is None:
2942
2682
        # you can always ask for the URL; but you might not be able to use it
2943
2683
        # if the repo can't support stacking.
2944
2684
        ## self._check_stackable_repo()
2945
 
        # stacked_on_location is only ever defined in branch.conf, so don't
2946
 
        # waste effort reading the whole stack of config files.
2947
 
        config = self.get_config()._get_branch_data_config()
2948
 
        stacked_url = self._get_config_location('stacked_on_location',
2949
 
            config=config)
 
2685
        stacked_url = self._get_config_location('stacked_on_location')
2950
2686
        if stacked_url is None:
2951
2687
            raise errors.NotStacked(self)
2952
2688
        return stacked_url
2953
2689
 
2954
2690
    def _get_append_revisions_only(self):
2955
 
        return self.get_config(
2956
 
            ).get_user_option_as_bool('append_revisions_only')
 
2691
        value = self.get_config().get_user_option('append_revisions_only')
 
2692
        return value == 'True'
 
2693
 
 
2694
    @needs_write_lock
 
2695
    def generate_revision_history(self, revision_id, last_rev=None,
 
2696
                                  other_branch=None):
 
2697
        """See BzrBranch5.generate_revision_history"""
 
2698
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2699
        revno = len(history)
 
2700
        self.set_last_revision_info(revno, revision_id)
2957
2701
 
2958
2702
    @needs_read_lock
2959
2703
    def get_rev_id(self, revno, history=None):
2984
2728
        try:
2985
2729
            index = self._partial_revision_history_cache.index(revision_id)
2986
2730
        except ValueError:
2987
 
            try:
2988
 
                self._extend_partial_history(stop_revision=revision_id)
2989
 
            except errors.RevisionNotPresent, e:
2990
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2731
            self._extend_partial_history(stop_revision=revision_id)
2991
2732
            index = len(self._partial_revision_history_cache) - 1
2992
2733
            if self._partial_revision_history_cache[index] != revision_id:
2993
2734
                raise errors.NoSuchRevision(self, revision_id)
3016
2757
    """
3017
2758
 
3018
2759
    def get_stacked_on_url(self):
3019
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2760
        raise errors.UnstackableBranchFormat(self._format, self.base)
3020
2761
 
3021
2762
 
3022
2763
######################################################################
3048
2789
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3049
2790
    """
3050
2791
 
3051
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3052
2792
    def __int__(self):
3053
 
        """Return the relative change in revno.
3054
 
 
3055
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3056
 
        """
 
2793
        # DEPRECATED: pull used to return the change in revno
3057
2794
        return self.new_revno - self.old_revno
3058
2795
 
3059
2796
    def report(self, to_file):
3084
2821
        target, otherwise it will be None.
3085
2822
    """
3086
2823
 
3087
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3088
2824
    def __int__(self):
3089
 
        """Return the relative change in revno.
3090
 
 
3091
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3092
 
        """
 
2825
        # DEPRECATED: push used to return the change in revno
3093
2826
        return self.new_revno - self.old_revno
3094
2827
 
3095
2828
    def report(self, to_file):
3117
2850
        :param verbose: Requests more detailed display of what was checked,
3118
2851
            if any.
3119
2852
        """
3120
 
        note('checked branch %s format %s', self.branch.user_url,
 
2853
        note('checked branch %s format %s', self.branch.base,
3121
2854
            self.branch._format)
3122
2855
        for error in self.errors:
3123
2856
            note('found error:%s', error)
3174
2907
        branch._transport.put_bytes('format', format.get_format_string())
3175
2908
 
3176
2909
 
 
2910
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
2911
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
2912
    duration.
 
2913
 
 
2914
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
2915
 
 
2916
    If an exception is raised by callable, then that exception *will* be
 
2917
    propagated, even if the unlock attempt raises its own error.  Thus
 
2918
    _run_with_write_locked_target should be preferred to simply doing::
 
2919
 
 
2920
        target.lock_write()
 
2921
        try:
 
2922
            return callable(*args, **kwargs)
 
2923
        finally:
 
2924
            target.unlock()
 
2925
 
 
2926
    """
 
2927
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
2928
    # should share code?
 
2929
    target.lock_write()
 
2930
    try:
 
2931
        result = callable(*args, **kwargs)
 
2932
    except:
 
2933
        exc_info = sys.exc_info()
 
2934
        try:
 
2935
            target.unlock()
 
2936
        finally:
 
2937
            raise exc_info[0], exc_info[1], exc_info[2]
 
2938
    else:
 
2939
        target.unlock()
 
2940
        return result
 
2941
 
 
2942
 
3177
2943
class InterBranch(InterObject):
3178
2944
    """This class represents operations taking place between two branches.
3179
2945
 
3185
2951
    _optimisers = []
3186
2952
    """The available optimised InterBranch types."""
3187
2953
 
3188
 
    @classmethod
3189
 
    def _get_branch_formats_to_test(klass):
3190
 
        """Return an iterable of format tuples for testing.
3191
 
        
3192
 
        :return: An iterable of (from_format, to_format) to use when testing
3193
 
            this InterBranch class. Each InterBranch class should define this
3194
 
            method itself.
3195
 
        """
3196
 
        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)
3197
2958
 
3198
 
    @needs_write_lock
3199
2959
    def pull(self, overwrite=False, stop_revision=None,
3200
2960
             possible_transports=None, local=False):
3201
2961
        """Mirror source into target branch.
3206
2966
        """
3207
2967
        raise NotImplementedError(self.pull)
3208
2968
 
3209
 
    @needs_write_lock
3210
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2969
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2970
                         graph=None):
 
2971
        """Pull in new perfect-fit revisions.
 
2972
 
 
2973
        :param stop_revision: Updated until the given revision
 
2974
        :param overwrite: Always set the branch pointer, rather than checking
 
2975
            to see if it is a proper descendant.
 
2976
        :param graph: A Graph object that can be used to query history
 
2977
            information. This can be None.
 
2978
        :return: None
 
2979
        """
 
2980
        raise NotImplementedError(self.update_revisions)
 
2981
 
 
2982
    def push(self, overwrite=False, stop_revision=None,
3211
2983
             _override_hook_source_branch=None):
3212
2984
        """Mirror the source branch into the target branch.
3213
2985
 
3215
2987
        """
3216
2988
        raise NotImplementedError(self.push)
3217
2989
 
3218
 
    @needs_write_lock
3219
 
    def copy_content_into(self, revision_id=None):
3220
 
        """Copy the content of source into target
3221
 
 
3222
 
        revision_id: if not None, the revision history in the new branch will
3223
 
                     be truncated to end with revision_id.
3224
 
        """
3225
 
        raise NotImplementedError(self.copy_content_into)
3226
 
 
3227
 
    @needs_write_lock
3228
 
    def fetch(self, stop_revision=None, limit=None):
3229
 
        """Fetch revisions.
3230
 
 
3231
 
        :param stop_revision: Last revision to fetch
3232
 
        :param limit: Optional rough limit of revisions to fetch
3233
 
        """
3234
 
        raise NotImplementedError(self.fetch)
3235
 
 
3236
2990
 
3237
2991
class GenericInterBranch(InterBranch):
3238
 
    """InterBranch implementation that uses public Branch functions."""
3239
 
 
3240
 
    @classmethod
3241
 
    def is_compatible(klass, source, target):
3242
 
        # GenericBranch uses the public API, so always compatible
3243
 
        return True
3244
 
 
3245
 
    @classmethod
3246
 
    def _get_branch_formats_to_test(klass):
3247
 
        return [(format_registry.get_default(), format_registry.get_default())]
3248
 
 
3249
 
    @classmethod
3250
 
    def unwrap_format(klass, format):
3251
 
        if isinstance(format, remote.RemoteBranchFormat):
3252
 
            format._ensure_real()
3253
 
            return format._custom_format
3254
 
        return format
3255
 
 
3256
 
    @needs_write_lock
3257
 
    def copy_content_into(self, revision_id=None):
3258
 
        """Copy the content of source into target
3259
 
 
3260
 
        revision_id: if not None, the revision history in the new branch will
3261
 
                     be truncated to end with revision_id.
3262
 
        """
3263
 
        self.source.update_references(self.target)
3264
 
        self.source._synchronize_history(self.target, revision_id)
3265
 
        try:
3266
 
            parent = self.source.get_parent()
3267
 
        except errors.InaccessibleParent, e:
3268
 
            mutter('parent was not accessible to copy: %s', e)
3269
 
        else:
3270
 
            if parent:
3271
 
                self.target.set_parent(parent)
3272
 
        if self.source._push_should_merge_tags():
3273
 
            self.source.tags.merge_to(self.target.tags)
3274
 
 
3275
 
    @needs_write_lock
3276
 
    def fetch(self, stop_revision=None, limit=None):
3277
 
        if self.target.base == self.source.base:
3278
 
            return (0, [])
 
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
 
 
2999
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3000
        graph=None):
 
3001
        """See InterBranch.update_revisions()."""
3279
3002
        self.source.lock_read()
3280
3003
        try:
3281
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3282
 
            fetch_spec_factory.source_branch = self.source
3283
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3284
 
            fetch_spec_factory.source_repo = self.source.repository
3285
 
            fetch_spec_factory.target_repo = self.target.repository
3286
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3287
 
            fetch_spec_factory.limit = limit
3288
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3289
 
            return self.target.repository.fetch(self.source.repository,
3290
 
                fetch_spec=fetch_spec)
 
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)
3291
3039
        finally:
3292
3040
            self.source.unlock()
3293
3041
 
3294
 
    @needs_write_lock
3295
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3296
 
            graph=None):
3297
 
        other_revno, other_last_revision = self.source.last_revision_info()
3298
 
        stop_revno = None # unknown
3299
 
        if stop_revision is None:
3300
 
            stop_revision = other_last_revision
3301
 
            if _mod_revision.is_null(stop_revision):
3302
 
                # if there are no commits, we're done.
3303
 
                return
3304
 
            stop_revno = other_revno
3305
 
 
3306
 
        # what's the current last revision, before we fetch [and change it
3307
 
        # possibly]
3308
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3309
 
        # we fetch here so that we don't process data twice in the common
3310
 
        # case of having something to pull, and so that the check for
3311
 
        # already merged can operate on the just fetched graph, which will
3312
 
        # be cached in memory.
3313
 
        self.fetch(stop_revision=stop_revision)
3314
 
        # Check to see if one is an ancestor of the other
3315
 
        if not overwrite:
3316
 
            if graph is None:
3317
 
                graph = self.target.repository.get_graph()
3318
 
            if self.target._check_if_descendant_or_diverged(
3319
 
                    stop_revision, last_rev, graph, self.source):
3320
 
                # stop_revision is a descendant of last_rev, but we aren't
3321
 
                # overwriting, so we're done.
3322
 
                return
3323
 
        if stop_revno is None:
3324
 
            if graph is None:
3325
 
                graph = self.target.repository.get_graph()
3326
 
            this_revno, this_last_revision = \
3327
 
                    self.target.last_revision_info()
3328
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3329
 
                            [(other_last_revision, other_revno),
3330
 
                             (this_last_revision, this_revno)])
3331
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3332
 
 
3333
 
    @needs_write_lock
3334
3042
    def pull(self, overwrite=False, stop_revision=None,
3335
 
             possible_transports=None, run_hooks=True,
3336
 
             _override_hook_target=None, local=False):
3337
 
        """Pull from source into self, updating my master if any.
3338
 
 
3339
 
        :param run_hooks: Private parameter - if false, this branch
3340
 
            is being called because it's the master of the primary branch,
3341
 
            so it should not run its hooks.
3342
 
        """
3343
 
        bound_location = self.target.get_bound_location()
3344
 
        if local and not bound_location:
3345
 
            raise errors.LocalRequiresBoundBranch()
3346
 
        master_branch = None
3347
 
        source_is_master = (self.source.user_url == bound_location)
3348
 
        if not local and bound_location and not source_is_master:
3349
 
            # not pulling from master, so we need to update master.
3350
 
            master_branch = self.target.get_master_branch(possible_transports)
3351
 
            master_branch.lock_write()
3352
 
        try:
3353
 
            if master_branch:
3354
 
                # pull from source into master.
3355
 
                master_branch.pull(self.source, overwrite, stop_revision,
3356
 
                    run_hooks=False)
3357
 
            return self._pull(overwrite,
3358
 
                stop_revision, _hook_master=master_branch,
3359
 
                run_hooks=run_hooks,
3360
 
                _override_hook_target=_override_hook_target,
3361
 
                merge_tags_to_master=not source_is_master)
3362
 
        finally:
3363
 
            if master_branch:
3364
 
                master_branch.unlock()
3365
 
 
3366
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3367
 
             _override_hook_source_branch=None):
3368
 
        """See InterBranch.push.
3369
 
 
3370
 
        This is the basic concrete implementation of push()
3371
 
 
3372
 
        :param _override_hook_source_branch: If specified, run the hooks
3373
 
            passing this Branch as the source, rather than self.  This is for
3374
 
            use of RemoteBranch, where push is delegated to the underlying
3375
 
            vfs-based Branch.
3376
 
        """
3377
 
        if lossy:
3378
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3379
 
        # TODO: Public option to disable running hooks - should be trivial but
3380
 
        # needs tests.
3381
 
 
3382
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3383
 
        op.add_cleanup(self.source.lock_read().unlock)
3384
 
        op.add_cleanup(self.target.lock_write().unlock)
3385
 
        return op.run(overwrite, stop_revision,
3386
 
            _override_hook_source_branch=_override_hook_source_branch)
3387
 
 
3388
 
    def _basic_push(self, overwrite, stop_revision):
3389
 
        """Basic implementation of push without bound branches or hooks.
3390
 
 
3391
 
        Must be called with source read locked and target write locked.
3392
 
        """
3393
 
        result = BranchPushResult()
3394
 
        result.source_branch = self.source
3395
 
        result.target_branch = self.target
3396
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3397
 
        self.source.update_references(self.target)
3398
 
        if result.old_revid != stop_revision:
3399
 
            # We assume that during 'push' this repository is closer than
3400
 
            # the target.
3401
 
            graph = self.source.repository.get_graph(self.target.repository)
3402
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3403
 
                    graph=graph)
3404
 
        if self.source._push_should_merge_tags():
3405
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3406
 
                overwrite)
3407
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3408
 
        return result
3409
 
 
3410
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3411
 
            _override_hook_source_branch=None):
3412
 
        """Push from source into target, and into target's master if any.
3413
 
        """
3414
 
        def _run_hooks():
3415
 
            if _override_hook_source_branch:
3416
 
                result.source_branch = _override_hook_source_branch
3417
 
            for hook in Branch.hooks['post_push']:
3418
 
                hook(result)
3419
 
 
3420
 
        bound_location = self.target.get_bound_location()
3421
 
        if bound_location and self.target.base != bound_location:
3422
 
            # there is a master branch.
3423
 
            #
3424
 
            # XXX: Why the second check?  Is it even supported for a branch to
3425
 
            # be bound to itself? -- mbp 20070507
3426
 
            master_branch = self.target.get_master_branch()
3427
 
            master_branch.lock_write()
3428
 
            operation.add_cleanup(master_branch.unlock)
3429
 
            # push into the master from the source branch.
3430
 
            master_inter = InterBranch.get(self.source, master_branch)
3431
 
            master_inter._basic_push(overwrite, stop_revision)
3432
 
            # and push into the target branch from the source. Note that
3433
 
            # we push from the source branch again, because it's considered
3434
 
            # the highest bandwidth repository.
3435
 
            result = self._basic_push(overwrite, stop_revision)
3436
 
            result.master_branch = master_branch
3437
 
            result.local_branch = self.target
3438
 
        else:
3439
 
            master_branch = None
3440
 
            # no master branch
3441
 
            result = self._basic_push(overwrite, stop_revision)
3442
 
            # TODO: Why set master_branch and local_branch if there's no
3443
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3444
 
            # 20070504
3445
 
            result.master_branch = self.target
3446
 
            result.local_branch = None
3447
 
        _run_hooks()
3448
 
        return result
3449
 
 
3450
 
    def _pull(self, overwrite=False, stop_revision=None,
3451
3043
             possible_transports=None, _hook_master=None, run_hooks=True,
3452
 
             _override_hook_target=None, local=False,
3453
 
             merge_tags_to_master=True):
 
3044
             _override_hook_target=None, local=False):
3454
3045
        """See Branch.pull.
3455
3046
 
3456
 
        This function is the core worker, used by GenericInterBranch.pull to
3457
 
        avoid duplication when pulling source->master and source->local.
3458
 
 
3459
3047
        :param _hook_master: Private parameter - set the branch to
3460
3048
            be supplied as the master to pull hooks.
3461
3049
        :param run_hooks: Private parameter - if false, this branch
3462
3050
            is being called because it's the master of the primary branch,
3463
3051
            so it should not run its hooks.
3464
 
            is being called because it's the master of the primary branch,
3465
 
            so it should not run its hooks.
3466
3052
        :param _override_hook_target: Private parameter - set the branch to be
3467
3053
            supplied as the target_branch to pull hooks.
3468
3054
        :param local: Only update the local branch, and not the bound branch.
3487
3073
            # -- JRV20090506
3488
3074
            result.old_revno, result.old_revid = \
3489
3075
                self.target.last_revision_info()
3490
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3491
 
                graph=graph)
 
3076
            self.target.update_revisions(self.source, stop_revision,
 
3077
                overwrite=overwrite, graph=graph)
3492
3078
            # TODO: The old revid should be specified when merging tags, 
3493
3079
            # so a tags implementation that versions tags can only 
3494
3080
            # pull in the most recent changes. -- JRV20090506
3495
3081
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3496
 
                overwrite, ignore_master=not merge_tags_to_master)
 
3082
                overwrite)
3497
3083
            result.new_revno, result.new_revid = self.target.last_revision_info()
3498
3084
            if _hook_master:
3499
3085
                result.master_branch = _hook_master
3508
3094
            self.source.unlock()
3509
3095
        return result
3510
3096
 
 
3097
    def push(self, overwrite=False, stop_revision=None,
 
3098
             _override_hook_source_branch=None):
 
3099
        """See InterBranch.push.
 
3100
 
 
3101
        This is the basic concrete implementation of push()
 
3102
 
 
3103
        :param _override_hook_source_branch: If specified, run
 
3104
        the hooks passing this Branch as the source, rather than self.
 
3105
        This is for use of RemoteBranch, where push is delegated to the
 
3106
        underlying vfs-based Branch.
 
3107
        """
 
3108
        # TODO: Public option to disable running hooks - should be trivial but
 
3109
        # needs tests.
 
3110
        self.source.lock_read()
 
3111
        try:
 
3112
            return _run_with_write_locked_target(
 
3113
                self.target, self._push_with_bound_branches, overwrite,
 
3114
                stop_revision,
 
3115
                _override_hook_source_branch=_override_hook_source_branch)
 
3116
        finally:
 
3117
            self.source.unlock()
 
3118
 
 
3119
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3120
            _override_hook_source_branch=None):
 
3121
        """Push from source into target, and into target's master if any.
 
3122
        """
 
3123
        def _run_hooks():
 
3124
            if _override_hook_source_branch:
 
3125
                result.source_branch = _override_hook_source_branch
 
3126
            for hook in Branch.hooks['post_push']:
 
3127
                hook(result)
 
3128
 
 
3129
        bound_location = self.target.get_bound_location()
 
3130
        if bound_location and self.target.base != bound_location:
 
3131
            # there is a master branch.
 
3132
            #
 
3133
            # XXX: Why the second check?  Is it even supported for a branch to
 
3134
            # be bound to itself? -- mbp 20070507
 
3135
            master_branch = self.target.get_master_branch()
 
3136
            master_branch.lock_write()
 
3137
            try:
 
3138
                # push into the master from the source branch.
 
3139
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3140
                # and push into the target branch from the source. Note that we
 
3141
                # push from the source branch again, because its considered the
 
3142
                # highest bandwidth repository.
 
3143
                result = self.source._basic_push(self.target, overwrite,
 
3144
                    stop_revision)
 
3145
                result.master_branch = master_branch
 
3146
                result.local_branch = self.target
 
3147
                _run_hooks()
 
3148
                return result
 
3149
            finally:
 
3150
                master_branch.unlock()
 
3151
        else:
 
3152
            # no master branch
 
3153
            result = self.source._basic_push(self.target, overwrite,
 
3154
                stop_revision)
 
3155
            # TODO: Why set master_branch and local_branch if there's no
 
3156
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3157
            # 20070504
 
3158
            result.master_branch = self.target
 
3159
            result.local_branch = None
 
3160
            _run_hooks()
 
3161
            return result
 
3162
 
 
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,
 
3177
             _override_hook_target=None, local=False):
 
3178
        """Pull from source into self, updating my master if any.
 
3179
 
 
3180
        :param run_hooks: Private parameter - if false, this branch
 
3181
            is being called because it's the master of the primary branch,
 
3182
            so it should not run its hooks.
 
3183
        """
 
3184
        bound_location = self.target.get_bound_location()
 
3185
        if local and not bound_location:
 
3186
            raise errors.LocalRequiresBoundBranch()
 
3187
        master_branch = None
 
3188
        if not local and bound_location and self.source.base != bound_location:
 
3189
            # not pulling from master, so we need to update master.
 
3190
            master_branch = self.target.get_master_branch(possible_transports)
 
3191
            master_branch.lock_write()
 
3192
        try:
 
3193
            if master_branch:
 
3194
                # pull from source into master.
 
3195
                master_branch.pull(self.source, overwrite, stop_revision,
 
3196
                    run_hooks=False)
 
3197
            return super(InterToBranch5, self).pull(overwrite,
 
3198
                stop_revision, _hook_master=master_branch,
 
3199
                run_hooks=run_hooks,
 
3200
                _override_hook_target=_override_hook_target)
 
3201
        finally:
 
3202
            if master_branch:
 
3203
                master_branch.unlock()
 
3204
 
3511
3205
 
3512
3206
InterBranch.register_optimiser(GenericInterBranch)
 
3207
InterBranch.register_optimiser(InterToBranch5)