~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2009-12-16 22:29:31 UTC
  • mto: This revision was merged to the branch mainline in revision 4920.
  • Revision ID: robertc@robertcollins.net-20091216222931-wbbn5ey4mwmpatwd
Review feedback.

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