~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Robert Collins
  • Date: 2009-04-24 05:08:51 UTC
  • mto: This revision was merged to the branch mainline in revision 4304.
  • Revision ID: robertc@robertcollins.net-20090424050851-sdfonaqerfs386t0
Reduce round trips pushing new branches substantially.

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
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
 
from cStringIO import StringIO
19
18
import sys
20
19
 
21
20
from bzrlib.lazy_import import lazy_import
24
23
from bzrlib import (
25
24
        bzrdir,
26
25
        cache_utf8,
27
 
        cleanup,
28
26
        config as _mod_config,
29
27
        debug,
30
28
        errors,
31
 
        fetch,
32
 
        graph as _mod_graph,
33
29
        lockdir,
34
30
        lockable_files,
35
 
        remote,
36
31
        repository,
37
32
        revision as _mod_revision,
38
 
        rio,
 
33
        symbol_versioning,
39
34
        transport,
 
35
        tsort,
40
36
        ui,
41
37
        urlutils,
42
38
        )
43
39
from bzrlib.config import BranchConfig, TransportConfig
 
40
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
44
41
from bzrlib.tag import (
45
42
    BasicTags,
46
43
    DisabledTags,
47
44
    )
48
45
""")
49
46
 
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
 
47
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
48
from bzrlib.hooks import HookPoint, Hooks
59
49
from bzrlib.inter import InterObject
60
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
61
50
from bzrlib import registry
62
51
from bzrlib.symbol_versioning import (
63
52
    deprecated_in,
71
60
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
72
61
 
73
62
 
74
 
class Branch(controldir.ControlComponent):
 
63
# TODO: Maybe include checks for common corruption of newlines, etc?
 
64
 
 
65
# TODO: Some operations like log might retrieve the same revisions
 
66
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
67
# cache in memory to make this faster.  In general anything can be
 
68
# cached in memory between lock and unlock operations. .. nb thats
 
69
# what the transaction identity map provides
 
70
 
 
71
 
 
72
######################################################################
 
73
# branch objects
 
74
 
 
75
class Branch(object):
75
76
    """Branch holding a history of revisions.
76
77
 
77
 
    :ivar base:
78
 
        Base directory/url of the branch; using control_url and
79
 
        control_transport is more standardized.
80
 
    :ivar hooks: An instance of BranchHooks.
81
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
82
 
        _clear_cached_state.
 
78
    base
 
79
        Base directory/url of the branch.
 
80
 
 
81
    hooks: An instance of BranchHooks.
83
82
    """
84
83
    # this is really an instance variable - FIXME move it there
85
84
    # - RBC 20060112
86
85
    base = None
87
86
 
88
 
    @property
89
 
    def control_transport(self):
90
 
        return self._transport
91
 
 
92
 
    @property
93
 
    def user_transport(self):
94
 
        return self.bzrdir.user_transport
95
 
 
96
87
    def __init__(self, *ignored, **ignored_too):
97
88
        self.tags = self._format.make_tags(self)
98
89
        self._revision_history_cache = None
99
90
        self._revision_id_to_revno_cache = None
100
91
        self._partial_revision_id_to_revno_cache = {}
101
 
        self._partial_revision_history_cache = []
102
 
        self._tags_bytes = None
103
92
        self._last_revision_info_cache = None
104
 
        self._master_branch_cache = None
105
93
        self._merge_sorted_revisions_cache = None
106
94
        self._open_hook()
107
95
        hooks = Branch.hooks['open']
111
99
    def _open_hook(self):
112
100
        """Called by init to allow simpler extension of the base class."""
113
101
 
114
 
    def _activate_fallback_location(self, url):
 
102
    def _activate_fallback_location(self, url, lock_style):
115
103
        """Activate the branch/repository from url as a fallback repository."""
116
 
        for existing_fallback_repo in self.repository._fallback_repositories:
117
 
            if existing_fallback_repo.user_url == url:
118
 
                # This fallback is already configured.  This probably only
119
 
                # happens because BzrDir.sprout is a horrible mess.  To avoid
120
 
                # confusing _unstack we don't add this a second time.
121
 
                mutter('duplicate activation of fallback %r on %r', url, self)
122
 
                return
123
104
        repo = self._get_fallback_repository(url)
124
 
        if repo.has_same_location(self.repository):
125
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
105
        if lock_style == 'write':
 
106
            repo.lock_write()
 
107
        elif lock_style == 'read':
 
108
            repo.lock_read()
126
109
        self.repository.add_fallback_repository(repo)
127
110
 
128
111
    def break_lock(self):
144
127
            raise errors.UnstackableRepositoryFormat(self.repository._format,
145
128
                self.repository.base)
146
129
 
147
 
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
148
 
        """Extend the partial history to include a given index
149
 
 
150
 
        If a stop_index is supplied, stop when that index has been reached.
151
 
        If a stop_revision is supplied, stop when that revision is
152
 
        encountered.  Otherwise, stop when the beginning of history is
153
 
        reached.
154
 
 
155
 
        :param stop_index: The index which should be present.  When it is
156
 
            present, history extension will stop.
157
 
        :param stop_revision: The revision id which should be present.  When
158
 
            it is encountered, history extension will stop.
159
 
        """
160
 
        if len(self._partial_revision_history_cache) == 0:
161
 
            self._partial_revision_history_cache = [self.last_revision()]
162
 
        repository._iter_for_revno(
163
 
            self.repository, self._partial_revision_history_cache,
164
 
            stop_index=stop_index, stop_revision=stop_revision)
165
 
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
166
 
            self._partial_revision_history_cache.pop()
167
 
 
168
 
    def _get_check_refs(self):
169
 
        """Get the references needed for check().
170
 
 
171
 
        See bzrlib.check.
172
 
        """
173
 
        revid = self.last_revision()
174
 
        return [('revision-existence', revid), ('lefthand-distance', revid)]
175
 
 
176
130
    @staticmethod
177
131
    def open(base, _unsupported=False, possible_transports=None):
178
132
        """Open the branch rooted at base.
182
136
        """
183
137
        control = bzrdir.BzrDir.open(base, _unsupported,
184
138
                                     possible_transports=possible_transports)
185
 
        return control.open_branch(unsupported=_unsupported)
 
139
        return control.open_branch(_unsupported)
186
140
 
187
141
    @staticmethod
188
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
142
    def open_from_transport(transport, _unsupported=False):
189
143
        """Open the branch rooted at transport"""
190
144
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
191
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
145
        return control.open_branch(_unsupported)
192
146
 
193
147
    @staticmethod
194
148
    def open_containing(url, possible_transports=None):
215
169
        return self.supports_tags() and self.tags.get_tag_dict()
216
170
 
217
171
    def get_config(self):
218
 
        """Get a bzrlib.config.BranchConfig for this Branch.
219
 
 
220
 
        This can then be used to get and set configuration options for the
221
 
        branch.
222
 
 
223
 
        :return: A bzrlib.config.BranchConfig.
224
 
        """
225
172
        return BranchConfig(self)
226
173
 
227
174
    def _get_config(self):
239
186
    def _get_fallback_repository(self, url):
240
187
        """Get the repository we fallback to at url."""
241
188
        url = urlutils.join(self.base, url)
242
 
        a_branch = Branch.open(url,
 
189
        a_bzrdir = bzrdir.BzrDir.open(url,
243
190
            possible_transports=[self.bzrdir.root_transport])
244
 
        return a_branch.repository
 
191
        return a_bzrdir.open_branch().repository
245
192
 
246
 
    @needs_read_lock
247
193
    def _get_tags_bytes(self):
248
194
        """Get the bytes of a serialised tags dict.
249
195
 
256
202
        :return: The bytes of the tags file.
257
203
        :seealso: Branch._set_tags_bytes.
258
204
        """
259
 
        if self._tags_bytes is None:
260
 
            self._tags_bytes = self._transport.get_bytes('tags')
261
 
        return self._tags_bytes
 
205
        return self._transport.get_bytes('tags')
262
206
 
263
207
    def _get_nick(self, local=False, possible_transports=None):
264
208
        config = self.get_config()
266
210
        if not local and not config.has_explicit_nickname():
267
211
            try:
268
212
                master = self.get_master_branch(possible_transports)
269
 
                if master and self.user_url == master.user_url:
270
 
                    raise errors.RecursiveBind(self.user_url)
271
213
                if master is not None:
272
214
                    # return the master branch value
273
215
                    return master.nick
274
 
            except errors.RecursiveBind, e:
275
 
                raise e
276
216
            except errors.BzrError, e:
277
217
                # Silently fall back to local implicit nick if the master is
278
218
                # unavailable
315
255
        new_history.reverse()
316
256
        return new_history
317
257
 
318
 
    def lock_write(self, token=None):
319
 
        """Lock the branch for write operations.
320
 
 
321
 
        :param token: A token to permit reacquiring a previously held and
322
 
            preserved lock.
323
 
        :return: A BranchWriteLockResult.
324
 
        """
 
258
    def lock_write(self):
325
259
        raise NotImplementedError(self.lock_write)
326
260
 
327
261
    def lock_read(self):
328
 
        """Lock the branch for read operations.
329
 
 
330
 
        :return: A bzrlib.lock.LogicalLockResult.
331
 
        """
332
262
        raise NotImplementedError(self.lock_read)
333
263
 
334
264
    def unlock(self):
455
385
            after. If None, the rest of history is included.
456
386
        :param stop_rule: if stop_revision_id is not None, the precise rule
457
387
            to use for termination:
458
 
 
459
388
            * 'exclude' - leave the stop revision out of the result (default)
460
389
            * 'include' - the stop revision is the last item in the result
461
390
            * 'with-merges' - include the stop revision and all of its
462
391
              merged revisions in the result
463
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
464
 
              that are in both ancestries
465
392
        :param direction: either 'reverse' or 'forward':
466
 
 
467
393
            * reverse means return the start_revision_id first, i.e.
468
394
              start at the most recent revision and go backwards in history
469
395
            * forward returns tuples in the opposite order to reverse.
490
416
        # start_revision_id.
491
417
        if self._merge_sorted_revisions_cache is None:
492
418
            last_revision = self.last_revision()
493
 
            known_graph = self.repository.get_known_graph_ancestry(
494
 
                [last_revision])
495
 
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
496
 
                last_revision)
 
419
            graph = self.repository.get_graph()
 
420
            parent_map = dict(((key, value) for key, value in
 
421
                     graph.iter_ancestry([last_revision]) if value is not None))
 
422
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
423
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
424
                generate_revno=True)
 
425
            # Drop the sequence # before caching
 
426
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
427
 
497
428
        filtered = self._filter_merge_sorted_revisions(
498
429
            self._merge_sorted_revisions_cache, start_revision_id,
499
430
            stop_revision_id, stop_rule)
500
 
        # Make sure we don't return revisions that are not part of the
501
 
        # start_revision_id ancestry.
502
 
        filtered = self._filter_start_non_ancestors(filtered)
503
431
        if direction == 'reverse':
504
432
            return filtered
505
433
        if direction == 'forward':
512
440
        """Iterate over an inclusive range of sorted revisions."""
513
441
        rev_iter = iter(merge_sorted_revisions)
514
442
        if start_revision_id is not None:
515
 
            for node in rev_iter:
516
 
                rev_id = node.key
 
443
            for rev_id, depth, revno, end_of_merge in rev_iter:
517
444
                if rev_id != start_revision_id:
518
445
                    continue
519
446
                else:
520
447
                    # The decision to include the start or not
521
448
                    # depends on the stop_rule if a stop is provided
522
 
                    # so pop this node back into the iterator
523
 
                    rev_iter = chain(iter([node]), rev_iter)
 
449
                    rev_iter = chain(
 
450
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
451
                        rev_iter)
524
452
                    break
525
453
        if stop_revision_id is None:
526
 
            # Yield everything
527
 
            for node in rev_iter:
528
 
                rev_id = node.key
529
 
                yield (rev_id, node.merge_depth, node.revno,
530
 
                       node.end_of_merge)
 
454
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
455
                yield rev_id, depth, revno, end_of_merge
531
456
        elif stop_rule == 'exclude':
532
 
            for node in rev_iter:
533
 
                rev_id = node.key
 
457
            for rev_id, depth, revno, end_of_merge in rev_iter:
534
458
                if rev_id == stop_revision_id:
535
459
                    return
536
 
                yield (rev_id, node.merge_depth, node.revno,
537
 
                       node.end_of_merge)
 
460
                yield rev_id, depth, revno, end_of_merge
538
461
        elif stop_rule == 'include':
539
 
            for node in rev_iter:
540
 
                rev_id = node.key
541
 
                yield (rev_id, node.merge_depth, node.revno,
542
 
                       node.end_of_merge)
 
462
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
463
                yield rev_id, depth, revno, end_of_merge
543
464
                if rev_id == stop_revision_id:
544
465
                    return
545
 
        elif stop_rule == 'with-merges-without-common-ancestry':
546
 
            # We want to exclude all revisions that are already part of the
547
 
            # stop_revision_id ancestry.
548
 
            graph = self.repository.get_graph()
549
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
550
 
                                                    [stop_revision_id])
551
 
            for node in rev_iter:
552
 
                rev_id = node.key
553
 
                if rev_id not in ancestors:
554
 
                    continue
555
 
                yield (rev_id, node.merge_depth, node.revno,
556
 
                       node.end_of_merge)
557
466
        elif stop_rule == 'with-merges':
558
467
            stop_rev = self.repository.get_revision(stop_revision_id)
559
468
            if stop_rev.parent_ids:
560
469
                left_parent = stop_rev.parent_ids[0]
561
470
            else:
562
471
                left_parent = _mod_revision.NULL_REVISION
563
 
            # left_parent is the actual revision we want to stop logging at,
564
 
            # since we want to show the merged revisions after the stop_rev too
565
 
            reached_stop_revision_id = False
566
 
            revision_id_whitelist = []
567
 
            for node in rev_iter:
568
 
                rev_id = node.key
 
472
            for rev_id, depth, revno, end_of_merge in rev_iter:
569
473
                if rev_id == left_parent:
570
 
                    # reached the left parent after the stop_revision
571
474
                    return
572
 
                if (not reached_stop_revision_id or
573
 
                        rev_id in revision_id_whitelist):
574
 
                    yield (rev_id, node.merge_depth, node.revno,
575
 
                       node.end_of_merge)
576
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
577
 
                        # only do the merged revs of rev_id from now on
578
 
                        rev = self.repository.get_revision(rev_id)
579
 
                        if rev.parent_ids:
580
 
                            reached_stop_revision_id = True
581
 
                            revision_id_whitelist.extend(rev.parent_ids)
 
475
                yield rev_id, depth, revno, end_of_merge
582
476
        else:
583
477
            raise ValueError('invalid stop_rule %r' % stop_rule)
584
478
 
585
 
    def _filter_start_non_ancestors(self, rev_iter):
586
 
        # If we started from a dotted revno, we want to consider it as a tip
587
 
        # and don't want to yield revisions that are not part of its
588
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
589
 
        # uninteresting descendants of the first parent of our tip before the
590
 
        # tip itself.
591
 
        first = rev_iter.next()
592
 
        (rev_id, merge_depth, revno, end_of_merge) = first
593
 
        yield first
594
 
        if not merge_depth:
595
 
            # We start at a mainline revision so by definition, all others
596
 
            # revisions in rev_iter are ancestors
597
 
            for node in rev_iter:
598
 
                yield node
599
 
 
600
 
        clean = False
601
 
        whitelist = set()
602
 
        pmap = self.repository.get_parent_map([rev_id])
603
 
        parents = pmap.get(rev_id, [])
604
 
        if parents:
605
 
            whitelist.update(parents)
606
 
        else:
607
 
            # If there is no parents, there is nothing of interest left
608
 
 
609
 
            # FIXME: It's hard to test this scenario here as this code is never
610
 
            # called in that case. -- vila 20100322
611
 
            return
612
 
 
613
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
614
 
            if not clean:
615
 
                if rev_id in whitelist:
616
 
                    pmap = self.repository.get_parent_map([rev_id])
617
 
                    parents = pmap.get(rev_id, [])
618
 
                    whitelist.remove(rev_id)
619
 
                    whitelist.update(parents)
620
 
                    if merge_depth == 0:
621
 
                        # We've reached the mainline, there is nothing left to
622
 
                        # filter
623
 
                        clean = True
624
 
                else:
625
 
                    # A revision that is not part of the ancestry of our
626
 
                    # starting revision.
627
 
                    continue
628
 
            yield (rev_id, merge_depth, revno, end_of_merge)
629
 
 
630
479
    def leave_lock_in_place(self):
631
480
        """Tell this branch object not to release the physical lock when this
632
481
        object is unlocked.
649
498
        :param other: The branch to bind to
650
499
        :type other: Branch
651
500
        """
652
 
        raise errors.UpgradeRequired(self.user_url)
653
 
 
654
 
    def set_append_revisions_only(self, enabled):
655
 
        if not self._format.supports_set_append_revisions_only():
656
 
            raise errors.UpgradeRequired(self.user_url)
657
 
        if enabled:
658
 
            value = 'True'
659
 
        else:
660
 
            value = 'False'
661
 
        self.get_config().set_user_option('append_revisions_only', value,
662
 
            warn_masked=True)
663
 
 
664
 
    def set_reference_info(self, file_id, tree_path, branch_location):
665
 
        """Set the branch location to use for a tree reference."""
666
 
        raise errors.UnsupportedOperation(self.set_reference_info, self)
667
 
 
668
 
    def get_reference_info(self, file_id):
669
 
        """Get the tree_path and branch_location for a tree reference."""
670
 
        raise errors.UnsupportedOperation(self.get_reference_info, self)
 
501
        raise errors.UpgradeRequired(self.base)
671
502
 
672
503
    @needs_write_lock
673
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
504
    def fetch(self, from_branch, last_revision=None, pb=None):
674
505
        """Copy revisions from from_branch into this branch.
675
506
 
676
507
        :param from_branch: Where to copy from.
677
508
        :param last_revision: What revision to stop at (None for at the end
678
509
                              of the branch.
679
 
        :param limit: Optional rough limit of revisions to fetch
 
510
        :param pb: An optional progress bar to use.
680
511
        :return: None
681
512
        """
682
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
513
        if self.base == from_branch.base:
 
514
            return (0, [])
 
515
        if pb is not None:
 
516
            symbol_versioning.warn(
 
517
                symbol_versioning.deprecated_in((1, 14, 0))
 
518
                % "pb parameter to fetch()")
 
519
        from_branch.lock_read()
 
520
        try:
 
521
            if last_revision is None:
 
522
                last_revision = from_branch.last_revision()
 
523
                last_revision = _mod_revision.ensure_null(last_revision)
 
524
            return self.repository.fetch(from_branch.repository,
 
525
                                         revision_id=last_revision,
 
526
                                         pb=pb)
 
527
        finally:
 
528
            from_branch.unlock()
683
529
 
684
530
    def get_bound_location(self):
685
531
        """Return the URL of the branch we are bound to.
692
538
    def get_old_bound_location(self):
693
539
        """Return the URL of the branch we used to be bound to
694
540
        """
695
 
        raise errors.UpgradeRequired(self.user_url)
 
541
        raise errors.UpgradeRequired(self.base)
696
542
 
697
543
    def get_commit_builder(self, parents, config=None, timestamp=None,
698
544
                           timezone=None, committer=None, revprops=None,
699
 
                           revision_id=None, lossy=False):
 
545
                           revision_id=None):
700
546
        """Obtain a CommitBuilder for this branch.
701
547
 
702
548
        :param parents: Revision ids of the parents of the new revision.
706
552
        :param committer: Optional committer to set for commit.
707
553
        :param revprops: Optional dictionary of revision properties.
708
554
        :param revision_id: Optional revision id.
709
 
        :param lossy: Whether to discard data that can not be natively
710
 
            represented, when pushing to a foreign VCS 
711
555
        """
712
556
 
713
557
        if config is None:
714
558
            config = self.get_config()
715
559
 
716
560
        return self.repository.get_commit_builder(self, parents, config,
717
 
            timestamp, timezone, committer, revprops, revision_id,
718
 
            lossy)
 
561
            timestamp, timezone, committer, revprops, revision_id)
719
562
 
720
563
    def get_master_branch(self, possible_transports=None):
721
564
        """Return the branch we are bound to.
748
591
        """Print `file` to stdout."""
749
592
        raise NotImplementedError(self.print_file)
750
593
 
751
 
    @deprecated_method(deprecated_in((2, 4, 0)))
752
594
    def set_revision_history(self, rev_history):
753
 
        """See Branch.set_revision_history."""
754
 
        self._set_revision_history(rev_history)
755
 
 
756
 
    @needs_write_lock
757
 
    def _set_revision_history(self, rev_history):
758
 
        if len(rev_history) == 0:
759
 
            revid = _mod_revision.NULL_REVISION
760
 
        else:
761
 
            revid = rev_history[-1]
762
 
        if rev_history != self._lefthand_history(revid):
763
 
            raise errors.NotLefthandHistory(rev_history)
764
 
        self.set_last_revision_info(len(rev_history), revid)
765
 
        self._cache_revision_history(rev_history)
766
 
        for hook in Branch.hooks['set_rh']:
767
 
            hook(self, rev_history)
768
 
 
769
 
    @needs_write_lock
770
 
    def set_last_revision_info(self, revno, revision_id):
771
 
        """Set the last revision of this branch.
772
 
 
773
 
        The caller is responsible for checking that the revno is correct
774
 
        for this revision id.
775
 
 
776
 
        It may be possible to set the branch last revision to an id not
777
 
        present in the repository.  However, branches can also be
778
 
        configured to check constraints on history, in which case this may not
779
 
        be permitted.
780
 
        """
781
 
        raise NotImplementedError(self.set_last_revision_info)
782
 
 
783
 
    @needs_write_lock
784
 
    def generate_revision_history(self, revision_id, last_rev=None,
785
 
                                  other_branch=None):
786
 
        """See Branch.generate_revision_history"""
787
 
        graph = self.repository.get_graph()
788
 
        known_revision_ids = [
789
 
            self.last_revision_info(),
790
 
            (_mod_revision.NULL_REVISION, 0),
791
 
            ]
792
 
        if last_rev is not None:
793
 
            if not graph.is_ancestor(last_rev, revision_id):
794
 
                # our previous tip is not merged into stop_revision
795
 
                raise errors.DivergedBranches(self, other_branch)
796
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
797
 
        self.set_last_revision_info(revno, revision_id)
 
595
        raise NotImplementedError(self.set_revision_history)
798
596
 
799
597
    @needs_write_lock
800
598
    def set_parent(self, url):
824
622
            stacking.
825
623
        """
826
624
        if not self._format.supports_stacking():
827
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
828
 
        # XXX: Changing from one fallback repository to another does not check
829
 
        # that all the data you need is present in the new fallback.
830
 
        # Possibly it should.
 
625
            raise errors.UnstackableBranchFormat(self._format, self.base)
831
626
        self._check_stackable_repo()
832
627
        if not url:
833
628
            try:
835
630
            except (errors.NotStacked, errors.UnstackableBranchFormat,
836
631
                errors.UnstackableRepositoryFormat):
837
632
                return
838
 
            self._unstack()
 
633
            url = ''
 
634
            # XXX: Lock correctness - should unlock our old repo if we were
 
635
            # locked.
 
636
            # repositories don't offer an interface to remove fallback
 
637
            # repositories today; take the conceptually simpler option and just
 
638
            # reopen it.
 
639
            self.repository = self.bzrdir.find_repository()
 
640
            self.repository.lock_write()
 
641
            # for every revision reference the branch has, ensure it is pulled
 
642
            # in.
 
643
            source_repository = self._get_fallback_repository(old_url)
 
644
            for revision_id in chain([self.last_revision()],
 
645
                self.tags.get_reverse_tag_dict()):
 
646
                self.repository.fetch(source_repository, revision_id,
 
647
                    find_ghosts=True)
839
648
        else:
840
 
            self._activate_fallback_location(url)
 
649
            self._activate_fallback_location(url, 'write')
841
650
        # write this out after the repository is stacked to avoid setting a
842
651
        # stacked config that doesn't work.
843
652
        self._set_config_location('stacked_on_location', url)
844
653
 
845
 
    def _unstack(self):
846
 
        """Change a branch to be unstacked, copying data as needed.
847
 
 
848
 
        Don't call this directly, use set_stacked_on_url(None).
849
 
        """
850
 
        pb = ui.ui_factory.nested_progress_bar()
851
 
        try:
852
 
            pb.update("Unstacking")
853
 
            # The basic approach here is to fetch the tip of the branch,
854
 
            # including all available ghosts, from the existing stacked
855
 
            # repository into a new repository object without the fallbacks. 
856
 
            #
857
 
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
858
 
            # correct for CHKMap repostiories
859
 
            old_repository = self.repository
860
 
            if len(old_repository._fallback_repositories) != 1:
861
 
                raise AssertionError("can't cope with fallback repositories "
862
 
                    "of %r (fallbacks: %r)" % (old_repository,
863
 
                        old_repository._fallback_repositories))
864
 
            # Open the new repository object.
865
 
            # Repositories don't offer an interface to remove fallback
866
 
            # repositories today; take the conceptually simpler option and just
867
 
            # reopen it.  We reopen it starting from the URL so that we
868
 
            # get a separate connection for RemoteRepositories and can
869
 
            # stream from one of them to the other.  This does mean doing
870
 
            # separate SSH connection setup, but unstacking is not a
871
 
            # common operation so it's tolerable.
872
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
873
 
            new_repository = new_bzrdir.find_repository()
874
 
            if new_repository._fallback_repositories:
875
 
                raise AssertionError("didn't expect %r to have "
876
 
                    "fallback_repositories"
877
 
                    % (self.repository,))
878
 
            # Replace self.repository with the new repository.
879
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
880
 
            # lock count) of self.repository to the new repository.
881
 
            lock_token = old_repository.lock_write().repository_token
882
 
            self.repository = new_repository
883
 
            if isinstance(self, remote.RemoteBranch):
884
 
                # Remote branches can have a second reference to the old
885
 
                # repository that need to be replaced.
886
 
                if self._real_branch is not None:
887
 
                    self._real_branch.repository = new_repository
888
 
            self.repository.lock_write(token=lock_token)
889
 
            if lock_token is not None:
890
 
                old_repository.leave_lock_in_place()
891
 
            old_repository.unlock()
892
 
            if lock_token is not None:
893
 
                # XXX: self.repository.leave_lock_in_place() before this
894
 
                # function will not be preserved.  Fortunately that doesn't
895
 
                # affect the current default format (2a), and would be a
896
 
                # corner-case anyway.
897
 
                #  - Andrew Bennetts, 2010/06/30
898
 
                self.repository.dont_leave_lock_in_place()
899
 
            old_lock_count = 0
900
 
            while True:
901
 
                try:
902
 
                    old_repository.unlock()
903
 
                except errors.LockNotHeld:
904
 
                    break
905
 
                old_lock_count += 1
906
 
            if old_lock_count == 0:
907
 
                raise AssertionError(
908
 
                    'old_repository should have been locked at least once.')
909
 
            for i in range(old_lock_count-1):
910
 
                self.repository.lock_write()
911
 
            # Fetch from the old repository into the new.
912
 
            old_repository.lock_read()
913
 
            try:
914
 
                # XXX: If you unstack a branch while it has a working tree
915
 
                # with a pending merge, the pending-merged revisions will no
916
 
                # longer be present.  You can (probably) revert and remerge.
917
 
                try:
918
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
919
 
                except errors.TagsNotSupported:
920
 
                    tags_to_fetch = set()
921
 
                fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
922
 
                    old_repository, required_ids=[self.last_revision()],
923
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
924
 
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
925
 
            finally:
926
 
                old_repository.unlock()
927
 
        finally:
928
 
            pb.finished()
929
654
 
930
655
    def _set_tags_bytes(self, bytes):
931
656
        """Mirror method for _get_tags_bytes.
932
657
 
933
658
        :seealso: Branch._get_tags_bytes.
934
659
        """
935
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
936
 
        op.add_cleanup(self.lock_write().unlock)
937
 
        return op.run_simple(bytes)
938
 
 
939
 
    def _set_tags_bytes_locked(self, bytes):
940
 
        self._tags_bytes = bytes
941
 
        return self._transport.put_bytes('tags', bytes)
 
660
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
661
            'tags', bytes)
942
662
 
943
663
    def _cache_revision_history(self, rev_history):
944
664
        """Set the cached revision history to rev_history.
971
691
        self._revision_history_cache = None
972
692
        self._revision_id_to_revno_cache = None
973
693
        self._last_revision_info_cache = None
974
 
        self._master_branch_cache = None
975
694
        self._merge_sorted_revisions_cache = None
976
 
        self._partial_revision_history_cache = []
977
 
        self._partial_revision_id_to_revno_cache = {}
978
 
        self._tags_bytes = None
979
695
 
980
696
    def _gen_revision_history(self):
981
697
        """Return sequence of revision hashes on to this branch.
1018
734
 
1019
735
    def unbind(self):
1020
736
        """Older format branches cannot bind or unbind."""
1021
 
        raise errors.UpgradeRequired(self.user_url)
 
737
        raise errors.UpgradeRequired(self.base)
 
738
 
 
739
    def set_append_revisions_only(self, enabled):
 
740
        """Older format branches are never restricted to append-only"""
 
741
        raise errors.UpgradeRequired(self.base)
1022
742
 
1023
743
    def last_revision(self):
1024
744
        """Return last revision id, or NULL_REVISION."""
1031
751
        :return: A tuple (revno, revision_id).
1032
752
        """
1033
753
        if self._last_revision_info_cache is None:
1034
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
754
            self._last_revision_info_cache = self._last_revision_info()
1035
755
        return self._last_revision_info_cache
1036
756
 
1037
 
    def _read_last_revision_info(self):
1038
 
        raise NotImplementedError(self._read_last_revision_info)
1039
 
 
1040
 
    @deprecated_method(deprecated_in((2, 4, 0)))
 
757
    def _last_revision_info(self):
 
758
        rh = self.revision_history()
 
759
        revno = len(rh)
 
760
        if revno:
 
761
            return (revno, rh[-1])
 
762
        else:
 
763
            return (0, _mod_revision.NULL_REVISION)
 
764
 
 
765
    @deprecated_method(deprecated_in((1, 6, 0)))
 
766
    def missing_revisions(self, other, stop_revision=None):
 
767
        """Return a list of new revisions that would perfectly fit.
 
768
 
 
769
        If self and other have not diverged, return a list of the revisions
 
770
        present in other, but missing from self.
 
771
        """
 
772
        self_history = self.revision_history()
 
773
        self_len = len(self_history)
 
774
        other_history = other.revision_history()
 
775
        other_len = len(other_history)
 
776
        common_index = min(self_len, other_len) -1
 
777
        if common_index >= 0 and \
 
778
            self_history[common_index] != other_history[common_index]:
 
779
            raise errors.DivergedBranches(self, other)
 
780
 
 
781
        if stop_revision is None:
 
782
            stop_revision = other_len
 
783
        else:
 
784
            if stop_revision > other_len:
 
785
                raise errors.NoSuchRevision(self, stop_revision)
 
786
        return other_history[self_len:stop_revision]
 
787
 
 
788
    @needs_write_lock
 
789
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
790
                         graph=None):
 
791
        """Pull in new perfect-fit revisions.
 
792
 
 
793
        :param other: Another Branch to pull from
 
794
        :param stop_revision: Updated until the given revision
 
795
        :param overwrite: Always set the branch pointer, rather than checking
 
796
            to see if it is a proper descendant.
 
797
        :param graph: A Graph object that can be used to query history
 
798
            information. This can be None.
 
799
        :return: None
 
800
        """
 
801
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
802
            overwrite, graph)
 
803
 
1041
804
    def import_last_revision_info(self, source_repo, revno, revid):
1042
805
        """Set the last revision info, importing from another repo if necessary.
1043
806
 
 
807
        This is used by the bound branch code to upload a revision to
 
808
        the master branch first before updating the tip of the local branch.
 
809
 
1044
810
        :param source_repo: Source repository to optionally fetch from
1045
811
        :param revno: Revision number of the new tip
1046
812
        :param revid: Revision id of the new tip
1049
815
            self.repository.fetch(source_repo, revision_id=revid)
1050
816
        self.set_last_revision_info(revno, revid)
1051
817
 
1052
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1053
 
                                           lossy=False):
1054
 
        """Set the last revision info, importing from another repo if necessary.
1055
 
 
1056
 
        This is used by the bound branch code to upload a revision to
1057
 
        the master branch first before updating the tip of the local branch.
1058
 
        Revisions referenced by source's tags are also transferred.
1059
 
 
1060
 
        :param source: Source branch to optionally fetch from
1061
 
        :param revno: Revision number of the new tip
1062
 
        :param revid: Revision id of the new tip
1063
 
        :param lossy: Whether to discard metadata that can not be
1064
 
            natively represented
1065
 
        :return: Tuple with the new revision number and revision id
1066
 
            (should only be different from the arguments when lossy=True)
1067
 
        """
1068
 
        if not self.repository.has_same_location(source.repository):
1069
 
            self.fetch(source, revid)
1070
 
        self.set_last_revision_info(revno, revid)
1071
 
        return (revno, revid)
1072
 
 
1073
818
    def revision_id_to_revno(self, revision_id):
1074
819
        """Given a revision id, return its revno"""
1075
820
        if _mod_revision.is_null(revision_id):
1080
825
        except ValueError:
1081
826
            raise errors.NoSuchRevision(self, revision_id)
1082
827
 
1083
 
    @needs_read_lock
1084
828
    def get_rev_id(self, revno, history=None):
1085
829
        """Find the revision id of the specified revno."""
1086
830
        if revno == 0:
1087
831
            return _mod_revision.NULL_REVISION
1088
 
        last_revno, last_revid = self.last_revision_info()
1089
 
        if revno == last_revno:
1090
 
            return last_revid
1091
 
        if revno <= 0 or revno > last_revno:
 
832
        if history is None:
 
833
            history = self.revision_history()
 
834
        if revno <= 0 or revno > len(history):
1092
835
            raise errors.NoSuchRevision(self, revno)
1093
 
        distance_from_last = last_revno - revno
1094
 
        if len(self._partial_revision_history_cache) <= distance_from_last:
1095
 
            self._extend_partial_history(distance_from_last)
1096
 
        return self._partial_revision_history_cache[distance_from_last]
 
836
        return history[revno - 1]
1097
837
 
1098
838
    def pull(self, source, overwrite=False, stop_revision=None,
1099
 
             possible_transports=None, *args, **kwargs):
 
839
             possible_transports=None, _override_hook_target=None):
1100
840
        """Mirror source into this branch.
1101
841
 
1102
842
        This branch is considered to be 'local', having low latency.
1103
843
 
1104
844
        :returns: PullResult instance
1105
845
        """
1106
 
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1107
 
            stop_revision=stop_revision,
1108
 
            possible_transports=possible_transports, *args, **kwargs)
 
846
        raise NotImplementedError(self.pull)
1109
847
 
1110
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1111
 
            *args, **kwargs):
 
848
    def push(self, target, overwrite=False, stop_revision=None):
1112
849
        """Mirror this branch into target.
1113
850
 
1114
851
        This branch is considered to be 'local', having low latency.
1115
852
        """
1116
 
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1117
 
            lossy, *args, **kwargs)
 
853
        raise NotImplementedError(self.push)
1118
854
 
1119
855
    def basis_tree(self):
1120
856
        """Return `Tree` object for last revision."""
1137
873
        try:
1138
874
            return urlutils.join(self.base[:-1], parent)
1139
875
        except errors.InvalidURLJoin, e:
1140
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
876
            raise errors.InaccessibleParent(parent, self.base)
1141
877
 
1142
878
    def _get_parent_location(self):
1143
879
        raise NotImplementedError(self._get_parent_location)
1160
896
            location = None
1161
897
        return location
1162
898
 
1163
 
    def get_child_submit_format(self):
1164
 
        """Return the preferred format of submissions to this branch."""
1165
 
        return self.get_config().get_user_option("child_submit_format")
1166
 
 
1167
899
    def get_submit_branch(self):
1168
900
        """Return the submit location of the branch.
1169
901
 
1228
960
        params = ChangeBranchTipParams(
1229
961
            self, old_revno, new_revno, old_revid, new_revid)
1230
962
        for hook in hooks:
1231
 
            hook(params)
 
963
            try:
 
964
                hook(params)
 
965
            except errors.TipChangeRejected:
 
966
                raise
 
967
            except Exception:
 
968
                exc_info = sys.exc_info()
 
969
                hook_name = Branch.hooks.get_hook_name(hook)
 
970
                raise errors.HookFailed(
 
971
                    'pre_change_branch_tip', hook_name, exc_info)
1232
972
 
1233
973
    @needs_write_lock
1234
974
    def update(self):
1275
1015
        return result
1276
1016
 
1277
1017
    @needs_read_lock
1278
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1279
 
            repository=None):
 
1018
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1280
1019
        """Create a new line of development from the branch, into to_bzrdir.
1281
1020
 
1282
1021
        to_bzrdir controls the branch format.
1284
1023
        revision_id: if not None, the revision history in the new branch will
1285
1024
                     be truncated to end with revision_id.
1286
1025
        """
1287
 
        if (repository_policy is not None and
1288
 
            repository_policy.requires_stacking()):
1289
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1290
 
        result = to_bzrdir.create_branch(repository=repository)
 
1026
        result = to_bzrdir.create_branch()
1291
1027
        result.lock_write()
1292
1028
        try:
1293
1029
            if repository_policy is not None:
1294
1030
                repository_policy.configure_branch(result)
1295
1031
            self.copy_content_into(result, revision_id=revision_id)
1296
 
            master_branch = self.get_master_branch()
1297
 
            if master_branch is None:
1298
 
                result.set_parent(self.bzrdir.root_transport.base)
1299
 
            else:
1300
 
                result.set_parent(master_branch.bzrdir.root_transport.base)
 
1032
            result.set_parent(self.bzrdir.root_transport.base)
1301
1033
        finally:
1302
1034
            result.unlock()
1303
1035
        return result
1317
1049
        source_revno, source_revision_id = self.last_revision_info()
1318
1050
        if revision_id is None:
1319
1051
            revno, revision_id = source_revno, source_revision_id
 
1052
        elif source_revision_id == revision_id:
 
1053
            # we know the revno without needing to walk all of history
 
1054
            revno = source_revno
1320
1055
        else:
1321
 
            graph = self.repository.get_graph()
1322
 
            try:
1323
 
                revno = graph.find_distance_to_null(revision_id, 
1324
 
                    [(source_revision_id, source_revno)])
1325
 
            except errors.GhostRevisionsHaveNoRevno:
1326
 
                # Default to 1, if we can't find anything else
1327
 
                revno = 1
 
1056
            # To figure out the revno for a random revision, we need to build
 
1057
            # the revision history, and count its length.
 
1058
            # We don't care about the order, just how long it is.
 
1059
            # Alternatively, we could start at the current location, and count
 
1060
            # backwards. But there is no guarantee that we will find it since
 
1061
            # it may be a merged revision.
 
1062
            revno = len(list(self.repository.iter_reverse_revision_history(
 
1063
                                                                revision_id)))
1328
1064
        destination.set_last_revision_info(revno, revision_id)
1329
1065
 
 
1066
    @needs_read_lock
1330
1067
    def copy_content_into(self, destination, revision_id=None):
1331
1068
        """Copy the content of self into destination.
1332
1069
 
1333
1070
        revision_id: if not None, the revision history in the new branch will
1334
1071
                     be truncated to end with revision_id.
1335
1072
        """
1336
 
        return InterBranch.get(self, destination).copy_content_into(
1337
 
            revision_id=revision_id)
1338
 
 
1339
 
    def update_references(self, target):
1340
 
        if not getattr(self._format, 'supports_reference_locations', False):
1341
 
            return
1342
 
        reference_dict = self._get_all_reference_info()
1343
 
        if len(reference_dict) == 0:
1344
 
            return
1345
 
        old_base = self.base
1346
 
        new_base = target.base
1347
 
        target_reference_dict = target._get_all_reference_info()
1348
 
        for file_id, (tree_path, branch_location) in (
1349
 
            reference_dict.items()):
1350
 
            branch_location = urlutils.rebase_url(branch_location,
1351
 
                                                  old_base, new_base)
1352
 
            target_reference_dict.setdefault(
1353
 
                file_id, (tree_path, branch_location))
1354
 
        target._set_all_reference_info(target_reference_dict)
 
1073
        self._synchronize_history(destination, revision_id)
 
1074
        try:
 
1075
            parent = self.get_parent()
 
1076
        except errors.InaccessibleParent, e:
 
1077
            mutter('parent was not accessible to copy: %s', e)
 
1078
        else:
 
1079
            if parent:
 
1080
                destination.set_parent(parent)
 
1081
        if self._push_should_merge_tags():
 
1082
            self.tags.merge_to(destination.tags)
1355
1083
 
1356
1084
    @needs_read_lock
1357
 
    def check(self, refs):
 
1085
    def check(self):
1358
1086
        """Check consistency of the branch.
1359
1087
 
1360
1088
        In particular this checks that revisions given in the revision-history
1363
1091
 
1364
1092
        Callers will typically also want to check the repository.
1365
1093
 
1366
 
        :param refs: Calculated refs for this branch as specified by
1367
 
            branch._get_check_refs()
1368
1094
        :return: A BranchCheckResult.
1369
1095
        """
1370
 
        result = BranchCheckResult(self)
 
1096
        mainline_parent_id = None
1371
1097
        last_revno, last_revision_id = self.last_revision_info()
1372
 
        actual_revno = refs[('lefthand-distance', last_revision_id)]
1373
 
        if actual_revno != last_revno:
1374
 
            result.errors.append(errors.BzrCheckError(
1375
 
                'revno does not match len(mainline) %s != %s' % (
1376
 
                last_revno, actual_revno)))
1377
 
        # TODO: We should probably also check that self.revision_history
1378
 
        # matches the repository for older branch formats.
1379
 
        # If looking for the code that cross-checks repository parents against
1380
 
        # the iter_reverse_revision_history output, that is now a repository
1381
 
        # specific check.
1382
 
        return result
 
1098
        real_rev_history = list(self.repository.iter_reverse_revision_history(
 
1099
                                last_revision_id))
 
1100
        real_rev_history.reverse()
 
1101
        if len(real_rev_history) != last_revno:
 
1102
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
1103
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
1104
        # TODO: We should probably also check that real_rev_history actually
 
1105
        #       matches self.revision_history()
 
1106
        for revision_id in real_rev_history:
 
1107
            try:
 
1108
                revision = self.repository.get_revision(revision_id)
 
1109
            except errors.NoSuchRevision, e:
 
1110
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1111
                            % revision_id)
 
1112
            # In general the first entry on the revision history has no parents.
 
1113
            # But it's not illegal for it to have parents listed; this can happen
 
1114
            # in imports from Arch when the parents weren't reachable.
 
1115
            if mainline_parent_id is not None:
 
1116
                if mainline_parent_id not in revision.parent_ids:
 
1117
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1118
                                        "parents of {%s}"
 
1119
                                        % (mainline_parent_id, revision_id))
 
1120
            mainline_parent_id = revision_id
 
1121
        return BranchCheckResult(self)
1383
1122
 
1384
1123
    def _get_checkout_format(self):
1385
1124
        """Return the most suitable metadir for a checkout of this branch.
1386
1125
        Weaves are used if this branch's repository uses weaves.
1387
1126
        """
1388
 
        format = self.repository.bzrdir.checkout_metadir()
1389
 
        format.set_branch_format(self._format)
 
1127
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1128
            from bzrlib.repofmt import weaverepo
 
1129
            format = bzrdir.BzrDirMetaFormat1()
 
1130
            format.repository_format = weaverepo.RepositoryFormat7()
 
1131
        else:
 
1132
            format = self.repository.bzrdir.checkout_metadir()
 
1133
            format.set_branch_format(self._format)
1390
1134
        return format
1391
1135
 
1392
1136
    def create_clone_on_transport(self, to_transport, revision_id=None,
1393
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1394
 
        no_tree=None):
 
1137
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1395
1138
        """Create a clone of this branch and its bzrdir.
1396
1139
 
1397
1140
        :param to_transport: The transport to clone onto.
1404
1147
        """
1405
1148
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1406
1149
        # clone call. Or something. 20090224 RBC/spiv.
1407
 
        # XXX: Should this perhaps clone colocated branches as well, 
1408
 
        # rather than just the default branch? 20100319 JRV
1409
1150
        if revision_id is None:
1410
1151
            revision_id = self.last_revision()
1411
 
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1412
 
            revision_id=revision_id, stacked_on=stacked_on,
1413
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1414
 
            no_tree=no_tree)
 
1152
        try:
 
1153
            dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1154
                revision_id=revision_id, stacked_on=stacked_on,
 
1155
                create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1156
        except errors.FileExists:
 
1157
            if not use_existing_dir:
 
1158
                raise
 
1159
        except errors.NoSuchFile:
 
1160
            if not create_prefix:
 
1161
                raise
1415
1162
        return dir_to.open_branch()
1416
1163
 
1417
1164
    def create_checkout(self, to_location, revision_id=None,
1422
1169
        :param to_location: The url to produce the checkout at
1423
1170
        :param revision_id: The revision to check out
1424
1171
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1425
 
            produce a bound branch (heavyweight checkout)
 
1172
        produce a bound branch (heavyweight checkout)
1426
1173
        :param accelerator_tree: A tree which can be used for retrieving file
1427
1174
            contents more quickly than the revision tree, i.e. a workingtree.
1428
1175
            The revision tree will be used for cases where accelerator_tree's
1436
1183
        if lightweight:
1437
1184
            format = self._get_checkout_format()
1438
1185
            checkout = format.initialize_on_transport(t)
1439
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1440
 
                target_branch=self)
 
1186
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1441
1187
        else:
1442
1188
            format = self._get_checkout_format()
1443
1189
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1472
1218
        reconciler.reconcile()
1473
1219
        return reconciler
1474
1220
 
1475
 
    def reference_parent(self, file_id, path, possible_transports=None):
 
1221
    def reference_parent(self, file_id, path):
1476
1222
        """Return the parent branch for a tree-reference file_id
1477
 
 
1478
1223
        :param file_id: The file_id of the tree reference
1479
1224
        :param path: The path of the file_id in the tree
1480
1225
        :return: A branch associated with the file_id
1481
1226
        """
1482
1227
        # FIXME should provide multiple branches, based on config
1483
 
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
1484
 
                           possible_transports=possible_transports)
 
1228
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
1485
1229
 
1486
1230
    def supports_tags(self):
1487
1231
        return self._format.supports_tags()
1488
1232
 
1489
 
    def automatic_tag_name(self, revision_id):
1490
 
        """Try to automatically find the tag name for a revision.
1491
 
 
1492
 
        :param revision_id: Revision id of the revision.
1493
 
        :return: A tag name or None if no tag name could be determined.
1494
 
        """
1495
 
        for hook in Branch.hooks['automatic_tag_name']:
1496
 
            ret = hook(self, revision_id)
1497
 
            if ret is not None:
1498
 
                return ret
1499
 
        return None
1500
 
 
1501
1233
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1502
1234
                                         other_branch):
1503
1235
        """Ensure that revision_b is a descendant of revision_a.
1533
1265
        else:
1534
1266
            raise AssertionError("invalid heads: %r" % (heads,))
1535
1267
 
1536
 
    def heads_to_fetch(self):
1537
 
        """Return the heads that must and that should be fetched to copy this
1538
 
        branch into another repo.
1539
 
 
1540
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1541
 
            set of heads that must be fetched.  if_present_fetch is a set of
1542
 
            heads that must be fetched if present, but no error is necessary if
1543
 
            they are not present.
1544
 
        """
1545
 
        # For bzr native formats must_fetch is just the tip, and if_present_fetch
1546
 
        # are the tags.
1547
 
        must_fetch = set([self.last_revision()])
1548
 
        try:
1549
 
            if_present_fetch = set(self.tags.get_reverse_tag_dict())
1550
 
        except errors.TagsNotSupported:
1551
 
            if_present_fetch = set()
1552
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1553
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1554
 
        return must_fetch, if_present_fetch
1555
 
 
1556
 
 
1557
 
class BranchFormat(controldir.ControlComponentFormat):
 
1268
 
 
1269
class BranchFormat(object):
1558
1270
    """An encapsulation of the initialization and open routines for a format.
1559
1271
 
1560
1272
    Formats provide three things:
1563
1275
     * an open routine.
1564
1276
 
1565
1277
    Formats are placed in an dict by their format string for reference
1566
 
    during branch opening. It's not required that these be instances, they
 
1278
    during branch opening. Its not required that these be instances, they
1567
1279
    can be classes themselves with class methods - it simply depends on
1568
1280
    whether state is needed for a given format or not.
1569
1281
 
1572
1284
    object will be created every time regardless.
1573
1285
    """
1574
1286
 
1575
 
    can_set_append_revisions_only = True
 
1287
    _default_format = None
 
1288
    """The default format used for new branches."""
 
1289
 
 
1290
    _formats = {}
 
1291
    """The known formats."""
1576
1292
 
1577
1293
    def __eq__(self, other):
1578
1294
        return self.__class__ is other.__class__
1581
1297
        return not (self == other)
1582
1298
 
1583
1299
    @classmethod
1584
 
    def find_format(klass, a_bzrdir, name=None):
 
1300
    def find_format(klass, a_bzrdir):
1585
1301
        """Return the format for the branch object in a_bzrdir."""
1586
1302
        try:
1587
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1588
 
            format_string = transport.get_bytes("format")
1589
 
            return format_registry.get(format_string)
 
1303
            transport = a_bzrdir.get_branch_transport(None)
 
1304
            format_string = transport.get("format").read()
 
1305
            return klass._formats[format_string]
1590
1306
        except errors.NoSuchFile:
1591
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1307
            raise errors.NotBranchError(path=transport.base)
1592
1308
        except KeyError:
1593
1309
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1594
1310
 
1595
1311
    @classmethod
1596
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1597
1312
    def get_default_format(klass):
1598
1313
        """Return the current default format."""
1599
 
        return format_registry.get_default()
1600
 
 
1601
 
    @classmethod
1602
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1603
 
    def get_formats(klass):
1604
 
        """Get all the known formats.
1605
 
 
1606
 
        Warning: This triggers a load of all lazy registered formats: do not
1607
 
        use except when that is desireed.
1608
 
        """
1609
 
        return format_registry._get_all()
1610
 
 
1611
 
    def get_reference(self, a_bzrdir, name=None):
 
1314
        return klass._default_format
 
1315
 
 
1316
    def get_reference(self, a_bzrdir):
1612
1317
        """Get the target reference of the branch in a_bzrdir.
1613
1318
 
1614
1319
        format probing must have been completed before calling
1616
1321
        in a_bzrdir is correct.
1617
1322
 
1618
1323
        :param a_bzrdir: The bzrdir to get the branch data from.
1619
 
        :param name: Name of the colocated branch to fetch
1620
1324
        :return: None if the branch is not a reference branch.
1621
1325
        """
1622
1326
        return None
1623
1327
 
1624
1328
    @classmethod
1625
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1329
    def set_reference(self, a_bzrdir, to_branch):
1626
1330
        """Set the target reference of the branch in a_bzrdir.
1627
1331
 
1628
1332
        format probing must have been completed before calling
1630
1334
        in a_bzrdir is correct.
1631
1335
 
1632
1336
        :param a_bzrdir: The bzrdir to set the branch reference for.
1633
 
        :param name: Name of colocated branch to set, None for default
1634
1337
        :param to_branch: branch that the checkout is to reference
1635
1338
        """
1636
1339
        raise NotImplementedError(self.set_reference)
1643
1346
        """Return the short format description for this format."""
1644
1347
        raise NotImplementedError(self.get_format_description)
1645
1348
 
1646
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1647
 
        hooks = Branch.hooks['post_branch_init']
1648
 
        if not hooks:
1649
 
            return
1650
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1651
 
        for hook in hooks:
1652
 
            hook(params)
 
1349
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1350
                           set_format=True):
 
1351
        """Initialize a branch in a bzrdir, with specified files
1653
1352
 
1654
 
    def initialize(self, a_bzrdir, name=None, repository=None):
1655
 
        """Create a branch of this format in a_bzrdir.
1656
 
        
1657
 
        :param name: Name of the colocated branch to create.
 
1353
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1354
        :param utf8_files: The files to create as a list of
 
1355
            (filename, content) tuples
 
1356
        :param set_format: If True, set the format with
 
1357
            self.get_format_string.  (BzrBranch4 has its format set
 
1358
            elsewhere)
 
1359
        :return: a branch in this format
1658
1360
        """
 
1361
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1362
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1363
        lock_map = {
 
1364
            'metadir': ('lock', lockdir.LockDir),
 
1365
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1366
        }
 
1367
        lock_name, lock_class = lock_map[lock_type]
 
1368
        control_files = lockable_files.LockableFiles(branch_transport,
 
1369
            lock_name, lock_class)
 
1370
        control_files.create_lock()
 
1371
        control_files.lock_write()
 
1372
        if set_format:
 
1373
            utf8_files += [('format', self.get_format_string())]
 
1374
        try:
 
1375
            for (filename, content) in utf8_files:
 
1376
                branch_transport.put_bytes(
 
1377
                    filename, content,
 
1378
                    mode=a_bzrdir._get_file_mode())
 
1379
        finally:
 
1380
            control_files.unlock()
 
1381
        return self.open(a_bzrdir, _found=True)
 
1382
 
 
1383
    def initialize(self, a_bzrdir):
 
1384
        """Create a branch of this format in a_bzrdir."""
1659
1385
        raise NotImplementedError(self.initialize)
1660
1386
 
1661
1387
    def is_supported(self):
1691
1417
        """
1692
1418
        raise NotImplementedError(self.network_name)
1693
1419
 
1694
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1695
 
            found_repository=None):
 
1420
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1696
1421
        """Return the branch object for a_bzrdir
1697
1422
 
1698
1423
        :param a_bzrdir: A BzrDir that contains a branch.
1699
 
        :param name: Name of colocated branch to open
1700
1424
        :param _found: a private parameter, do not use it. It is used to
1701
1425
            indicate if format probing has already be done.
1702
1426
        :param ignore_fallbacks: when set, no fallback branches will be opened
1705
1429
        raise NotImplementedError(self.open)
1706
1430
 
1707
1431
    @classmethod
1708
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1709
1432
    def register_format(klass, format):
1710
 
        """Register a metadir format.
1711
 
 
1712
 
        See MetaDirBranchFormatFactory for the ability to register a format
1713
 
        without loading the code the format needs until it is actually used.
1714
 
        """
1715
 
        format_registry.register(format)
 
1433
        """Register a metadir format."""
 
1434
        klass._formats[format.get_format_string()] = format
 
1435
        # Metadir formats have a network name of their format string, and get
 
1436
        # registered as class factories.
 
1437
        network_format_registry.register(format.get_format_string(), format.__class__)
1716
1438
 
1717
1439
    @classmethod
1718
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1719
1440
    def set_default_format(klass, format):
1720
 
        format_registry.set_default(format)
1721
 
 
1722
 
    def supports_set_append_revisions_only(self):
1723
 
        """True if this format supports set_append_revisions_only."""
1724
 
        return False
 
1441
        klass._default_format = format
1725
1442
 
1726
1443
    def supports_stacking(self):
1727
1444
        """True if this format records a stacked-on branch."""
1728
1445
        return False
1729
1446
 
1730
 
    def supports_leaving_lock(self):
1731
 
        """True if this format supports leaving locks in place."""
1732
 
        return False # by default
1733
 
 
1734
1447
    @classmethod
1735
 
    @deprecated_method(deprecated_in((2, 4, 0)))
1736
1448
    def unregister_format(klass, format):
1737
 
        format_registry.remove(format)
 
1449
        del klass._formats[format.get_format_string()]
1738
1450
 
1739
1451
    def __str__(self):
1740
1452
        return self.get_format_description().rstrip()
1744
1456
        return False  # by default
1745
1457
 
1746
1458
 
1747
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1748
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1749
 
    
1750
 
    While none of the built in BranchFormats are lazy registered yet,
1751
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1752
 
    use it, and the bzr-loom plugin uses it as well (see
1753
 
    bzrlib.plugins.loom.formats).
1754
 
    """
1755
 
 
1756
 
    def __init__(self, format_string, module_name, member_name):
1757
 
        """Create a MetaDirBranchFormatFactory.
1758
 
 
1759
 
        :param format_string: The format string the format has.
1760
 
        :param module_name: Module to load the format class from.
1761
 
        :param member_name: Attribute name within the module for the format class.
1762
 
        """
1763
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1764
 
        self._format_string = format_string
1765
 
        
1766
 
    def get_format_string(self):
1767
 
        """See BranchFormat.get_format_string."""
1768
 
        return self._format_string
1769
 
 
1770
 
    def __call__(self):
1771
 
        """Used for network_format_registry support."""
1772
 
        return self.get_obj()()
1773
 
 
1774
 
 
1775
1459
class BranchHooks(Hooks):
1776
1460
    """A dictionary mapping hook name to a list of callables for branch hooks.
1777
1461
 
1785
1469
        These are all empty initially, because by default nothing should get
1786
1470
        notified.
1787
1471
        """
1788
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1789
 
        self.add_hook('set_rh',
 
1472
        Hooks.__init__(self)
 
1473
        self.create_hook(HookPoint('set_rh',
1790
1474
            "Invoked whenever the revision history has been set via "
1791
1475
            "set_revision_history. The api signature is (branch, "
1792
1476
            "revision_history), and the branch will be write-locked. "
1793
1477
            "The set_rh hook can be expensive for bzr to trigger, a better "
1794
 
            "hook to use is Branch.post_change_branch_tip.", (0, 15))
1795
 
        self.add_hook('open',
 
1478
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1479
        self.create_hook(HookPoint('open',
1796
1480
            "Called with the Branch object that has been opened after a "
1797
 
            "branch is opened.", (1, 8))
1798
 
        self.add_hook('post_push',
 
1481
            "branch is opened.", (1, 8), None))
 
1482
        self.create_hook(HookPoint('post_push',
1799
1483
            "Called after a push operation completes. post_push is called "
1800
1484
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1801
 
            "bzr client.", (0, 15))
1802
 
        self.add_hook('post_pull',
 
1485
            "bzr client.", (0, 15), None))
 
1486
        self.create_hook(HookPoint('post_pull',
1803
1487
            "Called after a pull operation completes. post_pull is called "
1804
1488
            "with a bzrlib.branch.PullResult object and only runs in the "
1805
 
            "bzr client.", (0, 15))
1806
 
        self.add_hook('pre_commit',
1807
 
            "Called after a commit is calculated but before it is "
 
1489
            "bzr client.", (0, 15), None))
 
1490
        self.create_hook(HookPoint('pre_commit',
 
1491
            "Called after a commit is calculated but before it is is "
1808
1492
            "completed. pre_commit is called with (local, master, old_revno, "
1809
1493
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1810
1494
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1812
1496
            "basis revision. hooks MUST NOT modify this delta. "
1813
1497
            " future_tree is an in-memory tree obtained from "
1814
1498
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1815
 
            "tree.", (0,91))
1816
 
        self.add_hook('post_commit',
 
1499
            "tree.", (0,91), None))
 
1500
        self.create_hook(HookPoint('post_commit',
1817
1501
            "Called in the bzr client after a commit has completed. "
1818
1502
            "post_commit is called with (local, master, old_revno, old_revid, "
1819
1503
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1820
 
            "commit to a branch.", (0, 15))
1821
 
        self.add_hook('post_uncommit',
 
1504
            "commit to a branch.", (0, 15), None))
 
1505
        self.create_hook(HookPoint('post_uncommit',
1822
1506
            "Called in the bzr client after an uncommit completes. "
1823
1507
            "post_uncommit is called with (local, master, old_revno, "
1824
1508
            "old_revid, new_revno, new_revid) where local is the local branch "
1825
1509
            "or None, master is the target branch, and an empty branch "
1826
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1827
 
        self.add_hook('pre_change_branch_tip',
 
1510
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1511
        self.create_hook(HookPoint('pre_change_branch_tip',
1828
1512
            "Called in bzr client and server before a change to the tip of a "
1829
1513
            "branch is made. pre_change_branch_tip is called with a "
1830
1514
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1831
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1832
 
        self.add_hook('post_change_branch_tip',
 
1515
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1516
        self.create_hook(HookPoint('post_change_branch_tip',
1833
1517
            "Called in bzr client and server after a change to the tip of a "
1834
1518
            "branch is made. post_change_branch_tip is called with a "
1835
1519
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1836
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1837
 
        self.add_hook('transform_fallback_location',
 
1520
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1521
        self.create_hook(HookPoint('transform_fallback_location',
1838
1522
            "Called when a stacked branch is activating its fallback "
1839
1523
            "locations. transform_fallback_location is called with (branch, "
1840
1524
            "url), and should return a new url. Returning the same url "
1845
1529
            "fallback locations have not been activated. When there are "
1846
1530
            "multiple hooks installed for transform_fallback_location, "
1847
1531
            "all are called with the url returned from the previous hook."
1848
 
            "The order is however undefined.", (1, 9))
1849
 
        self.add_hook('automatic_tag_name',
1850
 
            "Called to determine an automatic tag name for a revision. "
1851
 
            "automatic_tag_name is called with (branch, revision_id) and "
1852
 
            "should return a tag name or None if no tag name could be "
1853
 
            "determined. The first non-None tag name returned will be used.",
1854
 
            (2, 2))
1855
 
        self.add_hook('post_branch_init',
1856
 
            "Called after new branch initialization completes. "
1857
 
            "post_branch_init is called with a "
1858
 
            "bzrlib.branch.BranchInitHookParams. "
1859
 
            "Note that init, branch and checkout (both heavyweight and "
1860
 
            "lightweight) will all trigger this hook.", (2, 2))
1861
 
        self.add_hook('post_switch',
1862
 
            "Called after a checkout switches branch. "
1863
 
            "post_switch is called with a "
1864
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1865
 
 
 
1532
            "The order is however undefined.", (1, 9), None))
1866
1533
 
1867
1534
 
1868
1535
# install the default hooks into the Branch class.
1870
1537
 
1871
1538
 
1872
1539
class ChangeBranchTipParams(object):
1873
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1540
    """Object holding parameters passed to *_change_branch_tip hooks.
1874
1541
 
1875
1542
    There are 5 fields that hooks may wish to access:
1876
1543
 
1907
1574
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1908
1575
 
1909
1576
 
1910
 
class BranchInitHookParams(object):
1911
 
    """Object holding parameters passed to `*_branch_init` hooks.
1912
 
 
1913
 
    There are 4 fields that hooks may wish to access:
1914
 
 
1915
 
    :ivar format: the branch format
1916
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1917
 
    :ivar name: name of colocated branch, if any (or None)
1918
 
    :ivar branch: the branch created
1919
 
 
1920
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1921
 
    the checkout, hence they are different from the corresponding fields in
1922
 
    branch, which refer to the original branch.
1923
 
    """
1924
 
 
1925
 
    def __init__(self, format, a_bzrdir, name, branch):
1926
 
        """Create a group of BranchInitHook parameters.
1927
 
 
1928
 
        :param format: the branch format
1929
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1930
 
            initialized
1931
 
        :param name: name of colocated branch, if any (or None)
1932
 
        :param branch: the branch created
1933
 
 
1934
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1935
 
        to the checkout, hence they are different from the corresponding fields
1936
 
        in branch, which refer to the original branch.
1937
 
        """
1938
 
        self.format = format
1939
 
        self.bzrdir = a_bzrdir
1940
 
        self.name = name
1941
 
        self.branch = branch
1942
 
 
1943
 
    def __eq__(self, other):
1944
 
        return self.__dict__ == other.__dict__
1945
 
 
1946
 
    def __repr__(self):
1947
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1948
 
 
1949
 
 
1950
 
class SwitchHookParams(object):
1951
 
    """Object holding parameters passed to `*_switch` hooks.
1952
 
 
1953
 
    There are 4 fields that hooks may wish to access:
1954
 
 
1955
 
    :ivar control_dir: BzrDir of the checkout to change
1956
 
    :ivar to_branch: branch that the checkout is to reference
1957
 
    :ivar force: skip the check for local commits in a heavy checkout
1958
 
    :ivar revision_id: revision ID to switch to (or None)
1959
 
    """
1960
 
 
1961
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1962
 
        """Create a group of SwitchHook parameters.
1963
 
 
1964
 
        :param control_dir: BzrDir of the checkout to change
1965
 
        :param to_branch: branch that the checkout is to reference
1966
 
        :param force: skip the check for local commits in a heavy checkout
1967
 
        :param revision_id: revision ID to switch to (or None)
1968
 
        """
1969
 
        self.control_dir = control_dir
1970
 
        self.to_branch = to_branch
1971
 
        self.force = force
1972
 
        self.revision_id = revision_id
1973
 
 
1974
 
    def __eq__(self, other):
1975
 
        return self.__dict__ == other.__dict__
1976
 
 
1977
 
    def __repr__(self):
1978
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1979
 
            self.control_dir, self.to_branch,
1980
 
            self.revision_id)
 
1577
class BzrBranchFormat4(BranchFormat):
 
1578
    """Bzr branch format 4.
 
1579
 
 
1580
    This format has:
 
1581
     - a revision-history file.
 
1582
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1583
    """
 
1584
 
 
1585
    def get_format_description(self):
 
1586
        """See BranchFormat.get_format_description()."""
 
1587
        return "Branch format 4"
 
1588
 
 
1589
    def initialize(self, a_bzrdir):
 
1590
        """Create a branch of this format in a_bzrdir."""
 
1591
        utf8_files = [('revision-history', ''),
 
1592
                      ('branch-name', ''),
 
1593
                      ]
 
1594
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1595
                                       lock_type='branch4', set_format=False)
 
1596
 
 
1597
    def __init__(self):
 
1598
        super(BzrBranchFormat4, self).__init__()
 
1599
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1600
 
 
1601
    def network_name(self):
 
1602
        """The network name for this format is the control dirs disk label."""
 
1603
        return self._matchingbzrdir.get_format_string()
 
1604
 
 
1605
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1606
        """See BranchFormat.open()."""
 
1607
        if not _found:
 
1608
            # we are being called directly and must probe.
 
1609
            raise NotImplementedError
 
1610
        return BzrBranch(_format=self,
 
1611
                         _control_files=a_bzrdir._control_files,
 
1612
                         a_bzrdir=a_bzrdir,
 
1613
                         _repository=a_bzrdir.open_repository())
 
1614
 
 
1615
    def __str__(self):
 
1616
        return "Bazaar-NG branch format 4"
1981
1617
 
1982
1618
 
1983
1619
class BranchFormatMetadir(BranchFormat):
1987
1623
        """What class to instantiate on open calls."""
1988
1624
        raise NotImplementedError(self._branch_class)
1989
1625
 
1990
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1991
 
                           repository=None):
1992
 
        """Initialize a branch in a bzrdir, with specified files
1993
 
 
1994
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1995
 
        :param utf8_files: The files to create as a list of
1996
 
            (filename, content) tuples
1997
 
        :param name: Name of colocated branch to create, if any
1998
 
        :return: a branch in this format
1999
 
        """
2000
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2001
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2002
 
        control_files = lockable_files.LockableFiles(branch_transport,
2003
 
            'lock', lockdir.LockDir)
2004
 
        control_files.create_lock()
2005
 
        control_files.lock_write()
2006
 
        try:
2007
 
            utf8_files += [('format', self.get_format_string())]
2008
 
            for (filename, content) in utf8_files:
2009
 
                branch_transport.put_bytes(
2010
 
                    filename, content,
2011
 
                    mode=a_bzrdir._get_file_mode())
2012
 
        finally:
2013
 
            control_files.unlock()
2014
 
        branch = self.open(a_bzrdir, name, _found=True,
2015
 
                found_repository=repository)
2016
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2017
 
        return branch
2018
 
 
2019
1626
    def network_name(self):
2020
1627
        """A simple byte string uniquely identifying this format for RPC calls.
2021
1628
 
2023
1630
        """
2024
1631
        return self.get_format_string()
2025
1632
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2027
 
            found_repository=None):
 
1633
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2028
1634
        """See BranchFormat.open()."""
2029
1635
        if not _found:
2030
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1636
            format = BranchFormat.find_format(a_bzrdir)
2031
1637
            if format.__class__ != self.__class__:
2032
1638
                raise AssertionError("wrong format %r found for %r" %
2033
1639
                    (format, self))
2034
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2035
1640
        try:
 
1641
            transport = a_bzrdir.get_branch_transport(None)
2036
1642
            control_files = lockable_files.LockableFiles(transport, 'lock',
2037
1643
                                                         lockdir.LockDir)
2038
 
            if found_repository is None:
2039
 
                found_repository = a_bzrdir.find_repository()
2040
1644
            return self._branch_class()(_format=self,
2041
1645
                              _control_files=control_files,
2042
 
                              name=name,
2043
1646
                              a_bzrdir=a_bzrdir,
2044
 
                              _repository=found_repository,
 
1647
                              _repository=a_bzrdir.find_repository(),
2045
1648
                              ignore_fallbacks=ignore_fallbacks)
2046
1649
        except errors.NoSuchFile:
2047
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1650
            raise errors.NotBranchError(path=transport.base)
2048
1651
 
2049
1652
    def __init__(self):
2050
1653
        super(BranchFormatMetadir, self).__init__()
2054
1657
    def supports_tags(self):
2055
1658
        return True
2056
1659
 
2057
 
    def supports_leaving_lock(self):
2058
 
        return True
2059
 
 
2060
1660
 
2061
1661
class BzrBranchFormat5(BranchFormatMetadir):
2062
1662
    """Bzr branch format 5.
2082
1682
        """See BranchFormat.get_format_description()."""
2083
1683
        return "Branch format 5"
2084
1684
 
2085
 
    def initialize(self, a_bzrdir, name=None, repository=None):
 
1685
    def initialize(self, a_bzrdir):
2086
1686
        """Create a branch of this format in a_bzrdir."""
2087
1687
        utf8_files = [('revision-history', ''),
2088
1688
                      ('branch-name', ''),
2089
1689
                      ]
2090
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1690
        return self._initialize_helper(a_bzrdir, utf8_files)
2091
1691
 
2092
1692
    def supports_tags(self):
2093
1693
        return False
2115
1715
        """See BranchFormat.get_format_description()."""
2116
1716
        return "Branch format 6"
2117
1717
 
2118
 
    def initialize(self, a_bzrdir, name=None, repository=None):
2119
 
        """Create a branch of this format in a_bzrdir."""
2120
 
        utf8_files = [('last-revision', '0 null:\n'),
2121
 
                      ('branch.conf', ''),
2122
 
                      ('tags', ''),
2123
 
                      ]
2124
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2125
 
 
2126
 
    def make_tags(self, branch):
2127
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2128
 
        return BasicTags(branch)
2129
 
 
2130
 
    def supports_set_append_revisions_only(self):
2131
 
        return True
2132
 
 
2133
 
 
2134
 
class BzrBranchFormat8(BranchFormatMetadir):
2135
 
    """Metadir format supporting storing locations of subtree branches."""
2136
 
 
2137
 
    def _branch_class(self):
2138
 
        return BzrBranch8
2139
 
 
2140
 
    def get_format_string(self):
2141
 
        """See BranchFormat.get_format_string()."""
2142
 
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2143
 
 
2144
 
    def get_format_description(self):
2145
 
        """See BranchFormat.get_format_description()."""
2146
 
        return "Branch format 8"
2147
 
 
2148
 
    def initialize(self, a_bzrdir, name=None, repository=None):
2149
 
        """Create a branch of this format in a_bzrdir."""
2150
 
        utf8_files = [('last-revision', '0 null:\n'),
2151
 
                      ('branch.conf', ''),
2152
 
                      ('tags', ''),
2153
 
                      ('references', '')
2154
 
                      ]
2155
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2156
 
 
2157
 
    def make_tags(self, branch):
2158
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2159
 
        return BasicTags(branch)
2160
 
 
2161
 
    def supports_set_append_revisions_only(self):
2162
 
        return True
2163
 
 
2164
 
    def supports_stacking(self):
2165
 
        return True
2166
 
 
2167
 
    supports_reference_locations = True
 
1718
    def initialize(self, a_bzrdir):
 
1719
        """Create a branch of this format in a_bzrdir."""
 
1720
        utf8_files = [('last-revision', '0 null:\n'),
 
1721
                      ('branch.conf', ''),
 
1722
                      ('tags', ''),
 
1723
                      ]
 
1724
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1725
 
 
1726
    def make_tags(self, branch):
 
1727
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1728
        return BasicTags(branch)
 
1729
 
2168
1730
 
2169
1731
 
2170
1732
class BzrBranchFormat7(BranchFormatMetadir):
2176
1738
    This format was introduced in bzr 1.6.
2177
1739
    """
2178
1740
 
2179
 
    def initialize(self, a_bzrdir, name=None, repository=None):
2180
 
        """Create a branch of this format in a_bzrdir."""
2181
 
        utf8_files = [('last-revision', '0 null:\n'),
2182
 
                      ('branch.conf', ''),
2183
 
                      ('tags', ''),
2184
 
                      ]
2185
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2186
 
 
2187
1741
    def _branch_class(self):
2188
1742
        return BzrBranch7
2189
1743
 
2195
1749
        """See BranchFormat.get_format_description()."""
2196
1750
        return "Branch format 7"
2197
1751
 
2198
 
    def supports_set_append_revisions_only(self):
2199
 
        return True
 
1752
    def initialize(self, a_bzrdir):
 
1753
        """Create a branch of this format in a_bzrdir."""
 
1754
        utf8_files = [('last-revision', '0 null:\n'),
 
1755
                      ('branch.conf', ''),
 
1756
                      ('tags', ''),
 
1757
                      ]
 
1758
        return self._initialize_helper(a_bzrdir, utf8_files)
2200
1759
 
2201
 
    def supports_stacking(self):
2202
 
        return True
 
1760
    def __init__(self):
 
1761
        super(BzrBranchFormat7, self).__init__()
 
1762
        self._matchingbzrdir.repository_format = \
 
1763
            RepositoryFormatKnitPack5RichRoot()
2203
1764
 
2204
1765
    def make_tags(self, branch):
2205
1766
        """See bzrlib.branch.BranchFormat.make_tags()."""
2206
1767
        return BasicTags(branch)
2207
1768
 
2208
 
    supports_reference_locations = False
 
1769
    def supports_stacking(self):
 
1770
        return True
2209
1771
 
2210
1772
 
2211
1773
class BranchReferenceFormat(BranchFormat):
2227
1789
        """See BranchFormat.get_format_description()."""
2228
1790
        return "Checkout reference format 1"
2229
1791
 
2230
 
    def get_reference(self, a_bzrdir, name=None):
 
1792
    def get_reference(self, a_bzrdir):
2231
1793
        """See BranchFormat.get_reference()."""
2232
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2233
 
        return transport.get_bytes('location')
 
1794
        transport = a_bzrdir.get_branch_transport(None)
 
1795
        return transport.get('location').read()
2234
1796
 
2235
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1797
    def set_reference(self, a_bzrdir, to_branch):
2236
1798
        """See BranchFormat.set_reference()."""
2237
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1799
        transport = a_bzrdir.get_branch_transport(None)
2238
1800
        location = transport.put_bytes('location', to_branch.base)
2239
1801
 
2240
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2241
 
            repository=None):
 
1802
    def initialize(self, a_bzrdir, target_branch=None):
2242
1803
        """Create a branch of this format in a_bzrdir."""
2243
1804
        if target_branch is None:
2244
1805
            # this format does not implement branch itself, thus the implicit
2245
1806
            # creation contract must see it as uninitializable
2246
1807
            raise errors.UninitializableFormat(self)
2247
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2248
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1808
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1809
        branch_transport = a_bzrdir.get_branch_transport(self)
2249
1810
        branch_transport.put_bytes('location',
2250
 
            target_branch.bzrdir.user_url)
 
1811
            target_branch.bzrdir.root_transport.base)
2251
1812
        branch_transport.put_bytes('format', self.get_format_string())
2252
 
        branch = self.open(
2253
 
            a_bzrdir, name, _found=True,
 
1813
        return self.open(
 
1814
            a_bzrdir, _found=True,
2254
1815
            possible_transports=[target_branch.bzrdir.root_transport])
2255
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2256
 
        return branch
2257
1816
 
2258
1817
    def __init__(self):
2259
1818
        super(BranchReferenceFormat, self).__init__()
2265
1824
        def clone(to_bzrdir, revision_id=None,
2266
1825
            repository_policy=None):
2267
1826
            """See Branch.clone()."""
2268
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
1827
            return format.initialize(to_bzrdir, a_branch)
2269
1828
            # cannot obey revision_id limits when cloning a reference ...
2270
1829
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2271
1830
            # emit some sort of warning/error to the caller ?!
2272
1831
        return clone
2273
1832
 
2274
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2275
 
             possible_transports=None, ignore_fallbacks=False,
2276
 
             found_repository=None):
 
1833
    def open(self, a_bzrdir, _found=False, location=None,
 
1834
             possible_transports=None, ignore_fallbacks=False):
2277
1835
        """Return the branch that the branch reference in a_bzrdir points at.
2278
1836
 
2279
1837
        :param a_bzrdir: A BzrDir that contains a branch.
2280
 
        :param name: Name of colocated branch to open, if any
2281
1838
        :param _found: a private parameter, do not use it. It is used to
2282
1839
            indicate if format probing has already be done.
2283
1840
        :param ignore_fallbacks: when set, no fallback branches will be opened
2288
1845
        :param possible_transports: An optional reusable transports list.
2289
1846
        """
2290
1847
        if not _found:
2291
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1848
            format = BranchFormat.find_format(a_bzrdir)
2292
1849
            if format.__class__ != self.__class__:
2293
1850
                raise AssertionError("wrong format %r found for %r" %
2294
1851
                    (format, self))
2295
1852
        if location is None:
2296
 
            location = self.get_reference(a_bzrdir, name)
 
1853
            location = self.get_reference(a_bzrdir)
2297
1854
        real_bzrdir = bzrdir.BzrDir.open(
2298
1855
            location, possible_transports=possible_transports)
2299
 
        result = real_bzrdir.open_branch(name=name, 
2300
 
            ignore_fallbacks=ignore_fallbacks)
 
1856
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2301
1857
        # this changes the behaviour of result.clone to create a new reference
2302
1858
        # rather than a copy of the content of the branch.
2303
1859
        # I did not use a proxy object because that needs much more extensive
2310
1866
        return result
2311
1867
 
2312
1868
 
2313
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2314
 
    """Branch format registry."""
2315
 
 
2316
 
    def __init__(self, other_registry=None):
2317
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2318
 
        self._default_format = None
2319
 
 
2320
 
    def set_default(self, format):
2321
 
        self._default_format = format
2322
 
 
2323
 
    def get_default(self):
2324
 
        return self._default_format
2325
 
 
2326
 
 
2327
1869
network_format_registry = registry.FormatRegistry()
2328
1870
"""Registry of formats indexed by their network name.
2329
1871
 
2332
1874
BranchFormat.network_name() for more detail.
2333
1875
"""
2334
1876
 
2335
 
format_registry = BranchFormatRegistry(network_format_registry)
2336
 
 
2337
1877
 
2338
1878
# formats which have no format string are not discoverable
2339
1879
# and not independently creatable, so are not registered.
2340
1880
__format5 = BzrBranchFormat5()
2341
1881
__format6 = BzrBranchFormat6()
2342
1882
__format7 = BzrBranchFormat7()
2343
 
__format8 = BzrBranchFormat8()
2344
 
format_registry.register(__format5)
2345
 
format_registry.register(BranchReferenceFormat())
2346
 
format_registry.register(__format6)
2347
 
format_registry.register(__format7)
2348
 
format_registry.register(__format8)
2349
 
format_registry.set_default(__format7)
2350
 
 
2351
 
 
2352
 
class BranchWriteLockResult(LogicalLockResult):
2353
 
    """The result of write locking a branch.
2354
 
 
2355
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2356
 
        None.
2357
 
    :ivar unlock: A callable which will unlock the lock.
2358
 
    """
2359
 
 
2360
 
    def __init__(self, unlock, branch_token):
2361
 
        LogicalLockResult.__init__(self, unlock)
2362
 
        self.branch_token = branch_token
2363
 
 
2364
 
    def __repr__(self):
2365
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2366
 
            self.unlock)
2367
 
 
2368
 
 
2369
 
class BzrBranch(Branch, _RelockDebugMixin):
 
1883
BranchFormat.register_format(__format5)
 
1884
BranchFormat.register_format(BranchReferenceFormat())
 
1885
BranchFormat.register_format(__format6)
 
1886
BranchFormat.register_format(__format7)
 
1887
BranchFormat.set_default_format(__format6)
 
1888
_legacy_formats = [BzrBranchFormat4(),
 
1889
    ]
 
1890
network_format_registry.register(
 
1891
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
1892
 
 
1893
 
 
1894
class BzrBranch(Branch):
2370
1895
    """A branch stored in the actual filesystem.
2371
1896
 
2372
1897
    Note that it's "local" in the context of the filesystem; it doesn't
2378
1903
    :ivar repository: Repository for this branch.
2379
1904
    :ivar base: The url of the base directory for this branch; the one
2380
1905
        containing the .bzr directory.
2381
 
    :ivar name: Optional colocated branch name as it exists in the control
2382
 
        directory.
2383
1906
    """
2384
1907
 
2385
1908
    def __init__(self, _format=None,
2386
 
                 _control_files=None, a_bzrdir=None, name=None,
2387
 
                 _repository=None, ignore_fallbacks=False):
 
1909
                 _control_files=None, a_bzrdir=None, _repository=None,
 
1910
                 ignore_fallbacks=False):
2388
1911
        """Create new branch object at a particular location."""
2389
1912
        if a_bzrdir is None:
2390
1913
            raise ValueError('a_bzrdir must be supplied')
2391
1914
        else:
2392
1915
            self.bzrdir = a_bzrdir
2393
1916
        self._base = self.bzrdir.transport.clone('..').base
2394
 
        self.name = name
2395
1917
        # XXX: We should be able to just do
2396
1918
        #   self.base = self.bzrdir.root_transport.base
2397
1919
        # but this does not quite work yet -- mbp 20080522
2404
1926
        Branch.__init__(self)
2405
1927
 
2406
1928
    def __str__(self):
2407
 
        if self.name is None:
2408
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2409
 
        else:
2410
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2411
 
                self.name)
 
1929
        return '%s(%r)' % (self.__class__.__name__, self.base)
2412
1930
 
2413
1931
    __repr__ = __str__
2414
1932
 
2425
1943
        return self.control_files.is_locked()
2426
1944
 
2427
1945
    def lock_write(self, token=None):
2428
 
        """Lock the branch for write operations.
2429
 
 
2430
 
        :param token: A token to permit reacquiring a previously held and
2431
 
            preserved lock.
2432
 
        :return: A BranchWriteLockResult.
2433
 
        """
2434
 
        if not self.is_locked():
2435
 
            self._note_lock('w')
2436
1946
        # All-in-one needs to always unlock/lock.
2437
1947
        repo_control = getattr(self.repository, 'control_files', None)
2438
1948
        if self.control_files == repo_control or not self.is_locked():
2439
 
            self.repository._warn_if_deprecated(self)
2440
1949
            self.repository.lock_write()
2441
1950
            took_lock = True
2442
1951
        else:
2443
1952
            took_lock = False
2444
1953
        try:
2445
 
            return BranchWriteLockResult(self.unlock,
2446
 
                self.control_files.lock_write(token=token))
 
1954
            return self.control_files.lock_write(token=token)
2447
1955
        except:
2448
1956
            if took_lock:
2449
1957
                self.repository.unlock()
2450
1958
            raise
2451
1959
 
2452
1960
    def lock_read(self):
2453
 
        """Lock the branch for read operations.
2454
 
 
2455
 
        :return: A bzrlib.lock.LogicalLockResult.
2456
 
        """
2457
 
        if not self.is_locked():
2458
 
            self._note_lock('r')
2459
1961
        # All-in-one needs to always unlock/lock.
2460
1962
        repo_control = getattr(self.repository, 'control_files', None)
2461
1963
        if self.control_files == repo_control or not self.is_locked():
2462
 
            self.repository._warn_if_deprecated(self)
2463
1964
            self.repository.lock_read()
2464
1965
            took_lock = True
2465
1966
        else:
2466
1967
            took_lock = False
2467
1968
        try:
2468
1969
            self.control_files.lock_read()
2469
 
            return LogicalLockResult(self.unlock)
2470
1970
        except:
2471
1971
            if took_lock:
2472
1972
                self.repository.unlock()
2473
1973
            raise
2474
1974
 
2475
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2476
1975
    def unlock(self):
2477
1976
        try:
2478
1977
            self.control_files.unlock()
2500
1999
        """See Branch.print_file."""
2501
2000
        return self.repository.print_file(file, revision_id)
2502
2001
 
 
2002
    def _write_revision_history(self, history):
 
2003
        """Factored out of set_revision_history.
 
2004
 
 
2005
        This performs the actual writing to disk.
 
2006
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2007
        self._transport.put_bytes(
 
2008
            'revision-history', '\n'.join(history),
 
2009
            mode=self.bzrdir._get_file_mode())
 
2010
 
 
2011
    @needs_write_lock
 
2012
    def set_revision_history(self, rev_history):
 
2013
        """See Branch.set_revision_history."""
 
2014
        if 'evil' in debug.debug_flags:
 
2015
            mutter_callsite(3, "set_revision_history scales with history.")
 
2016
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2017
        for rev_id in rev_history:
 
2018
            check_not_reserved_id(rev_id)
 
2019
        if Branch.hooks['post_change_branch_tip']:
 
2020
            # Don't calculate the last_revision_info() if there are no hooks
 
2021
            # that will use it.
 
2022
            old_revno, old_revid = self.last_revision_info()
 
2023
        if len(rev_history) == 0:
 
2024
            revid = _mod_revision.NULL_REVISION
 
2025
        else:
 
2026
            revid = rev_history[-1]
 
2027
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2028
        self._write_revision_history(rev_history)
 
2029
        self._clear_cached_state()
 
2030
        self._cache_revision_history(rev_history)
 
2031
        for hook in Branch.hooks['set_rh']:
 
2032
            hook(self, rev_history)
 
2033
        if Branch.hooks['post_change_branch_tip']:
 
2034
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2035
 
 
2036
    def _synchronize_history(self, destination, revision_id):
 
2037
        """Synchronize last revision and revision history between branches.
 
2038
 
 
2039
        This version is most efficient when the destination is also a
 
2040
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2041
        history is the true lefthand parent history, and all of the revisions
 
2042
        are in the destination's repository.  If not, set_revision_history
 
2043
        will fail.
 
2044
 
 
2045
        :param destination: The branch to copy the history into
 
2046
        :param revision_id: The revision-id to truncate history at.  May
 
2047
          be None to copy complete history.
 
2048
        """
 
2049
        if not isinstance(destination._format, BzrBranchFormat5):
 
2050
            super(BzrBranch, self)._synchronize_history(
 
2051
                destination, revision_id)
 
2052
            return
 
2053
        if revision_id == _mod_revision.NULL_REVISION:
 
2054
            new_history = []
 
2055
        else:
 
2056
            new_history = self.revision_history()
 
2057
        if revision_id is not None and new_history != []:
 
2058
            try:
 
2059
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2060
            except ValueError:
 
2061
                rev = self.repository.get_revision(revision_id)
 
2062
                new_history = rev.get_history(self.repository)[1:]
 
2063
        destination.set_revision_history(new_history)
 
2064
 
2503
2065
    @needs_write_lock
2504
2066
    def set_last_revision_info(self, revno, revision_id):
2505
 
        if not revision_id or not isinstance(revision_id, basestring):
2506
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2067
        """Set the last revision of this branch.
 
2068
 
 
2069
        The caller is responsible for checking that the revno is correct
 
2070
        for this revision id.
 
2071
 
 
2072
        It may be possible to set the branch last revision to an id not
 
2073
        present in the repository.  However, branches can also be
 
2074
        configured to check constraints on history, in which case this may not
 
2075
        be permitted.
 
2076
        """
2507
2077
        revision_id = _mod_revision.ensure_null(revision_id)
2508
 
        old_revno, old_revid = self.last_revision_info()
2509
 
        if self._get_append_revisions_only():
2510
 
            self._check_history_violation(revision_id)
2511
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2512
 
        self._write_last_revision_info(revno, revision_id)
2513
 
        self._clear_cached_state()
2514
 
        self._last_revision_info_cache = revno, revision_id
2515
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2078
        # this old format stores the full history, but this api doesn't
 
2079
        # provide it, so we must generate, and might as well check it's
 
2080
        # correct
 
2081
        history = self._lefthand_history(revision_id)
 
2082
        if len(history) != revno:
 
2083
            raise AssertionError('%d != %d' % (len(history), revno))
 
2084
        self.set_revision_history(history)
 
2085
 
 
2086
    def _gen_revision_history(self):
 
2087
        history = self._transport.get_bytes('revision-history').split('\n')
 
2088
        if history[-1:] == ['']:
 
2089
            # There shouldn't be a trailing newline, but just in case.
 
2090
            history.pop()
 
2091
        return history
 
2092
 
 
2093
    @needs_write_lock
 
2094
    def generate_revision_history(self, revision_id, last_rev=None,
 
2095
        other_branch=None):
 
2096
        """Create a new revision history that will finish with revision_id.
 
2097
 
 
2098
        :param revision_id: the new tip to use.
 
2099
        :param last_rev: The previous last_revision. If not None, then this
 
2100
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2101
        :param other_branch: The other branch that DivergedBranches should
 
2102
            raise with respect to.
 
2103
        """
 
2104
        self.set_revision_history(self._lefthand_history(revision_id,
 
2105
            last_rev, other_branch))
2516
2106
 
2517
2107
    def basis_tree(self):
2518
2108
        """See Branch.basis_tree."""
2519
2109
        return self.repository.revision_tree(self.last_revision())
2520
2110
 
 
2111
    @needs_write_lock
 
2112
    def pull(self, source, overwrite=False, stop_revision=None,
 
2113
             _hook_master=None, run_hooks=True, possible_transports=None,
 
2114
             _override_hook_target=None):
 
2115
        """See Branch.pull.
 
2116
 
 
2117
        :param _hook_master: Private parameter - set the branch to
 
2118
            be supplied as the master to pull hooks.
 
2119
        :param run_hooks: Private parameter - if false, this branch
 
2120
            is being called because it's the master of the primary branch,
 
2121
            so it should not run its hooks.
 
2122
        :param _override_hook_target: Private parameter - set the branch to be
 
2123
            supplied as the target_branch to pull hooks.
 
2124
        """
 
2125
        result = PullResult()
 
2126
        result.source_branch = source
 
2127
        if _override_hook_target is None:
 
2128
            result.target_branch = self
 
2129
        else:
 
2130
            result.target_branch = _override_hook_target
 
2131
        source.lock_read()
 
2132
        try:
 
2133
            # We assume that during 'pull' the local repository is closer than
 
2134
            # the remote one.
 
2135
            graph = self.repository.get_graph(source.repository)
 
2136
            result.old_revno, result.old_revid = self.last_revision_info()
 
2137
            self.update_revisions(source, stop_revision, overwrite=overwrite,
 
2138
                                  graph=graph)
 
2139
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
 
2140
            result.new_revno, result.new_revid = self.last_revision_info()
 
2141
            if _hook_master:
 
2142
                result.master_branch = _hook_master
 
2143
                result.local_branch = result.target_branch
 
2144
            else:
 
2145
                result.master_branch = result.target_branch
 
2146
                result.local_branch = None
 
2147
            if run_hooks:
 
2148
                for hook in Branch.hooks['post_pull']:
 
2149
                    hook(result)
 
2150
        finally:
 
2151
            source.unlock()
 
2152
        return result
 
2153
 
2521
2154
    def _get_parent_location(self):
2522
2155
        _locs = ['parent', 'pull', 'x-pull']
2523
2156
        for l in _locs:
2527
2160
                pass
2528
2161
        return None
2529
2162
 
 
2163
    @needs_read_lock
 
2164
    def push(self, target, overwrite=False, stop_revision=None,
 
2165
             _override_hook_source_branch=None):
 
2166
        """See Branch.push.
 
2167
 
 
2168
        This is the basic concrete implementation of push()
 
2169
 
 
2170
        :param _override_hook_source_branch: If specified, run
 
2171
        the hooks passing this Branch as the source, rather than self.
 
2172
        This is for use of RemoteBranch, where push is delegated to the
 
2173
        underlying vfs-based Branch.
 
2174
        """
 
2175
        # TODO: Public option to disable running hooks - should be trivial but
 
2176
        # needs tests.
 
2177
        return _run_with_write_locked_target(
 
2178
            target, self._push_with_bound_branches, target, overwrite,
 
2179
            stop_revision,
 
2180
            _override_hook_source_branch=_override_hook_source_branch)
 
2181
 
 
2182
    def _push_with_bound_branches(self, target, overwrite,
 
2183
            stop_revision,
 
2184
            _override_hook_source_branch=None):
 
2185
        """Push from self into target, and into target's master if any.
 
2186
 
 
2187
        This is on the base BzrBranch class even though it doesn't support
 
2188
        bound branches because the *target* might be bound.
 
2189
        """
 
2190
        def _run_hooks():
 
2191
            if _override_hook_source_branch:
 
2192
                result.source_branch = _override_hook_source_branch
 
2193
            for hook in Branch.hooks['post_push']:
 
2194
                hook(result)
 
2195
 
 
2196
        bound_location = target.get_bound_location()
 
2197
        if bound_location and target.base != bound_location:
 
2198
            # there is a master branch.
 
2199
            #
 
2200
            # XXX: Why the second check?  Is it even supported for a branch to
 
2201
            # be bound to itself? -- mbp 20070507
 
2202
            master_branch = target.get_master_branch()
 
2203
            master_branch.lock_write()
 
2204
            try:
 
2205
                # push into the master from this branch.
 
2206
                self._basic_push(master_branch, overwrite, stop_revision)
 
2207
                # and push into the target branch from this. Note that we push from
 
2208
                # this branch again, because its considered the highest bandwidth
 
2209
                # repository.
 
2210
                result = self._basic_push(target, overwrite, stop_revision)
 
2211
                result.master_branch = master_branch
 
2212
                result.local_branch = target
 
2213
                _run_hooks()
 
2214
                return result
 
2215
            finally:
 
2216
                master_branch.unlock()
 
2217
        else:
 
2218
            # no master branch
 
2219
            result = self._basic_push(target, overwrite, stop_revision)
 
2220
            # TODO: Why set master_branch and local_branch if there's no
 
2221
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2222
            # 20070504
 
2223
            result.master_branch = target
 
2224
            result.local_branch = None
 
2225
            _run_hooks()
 
2226
            return result
 
2227
 
 
2228
    def _basic_push(self, target, overwrite, stop_revision):
 
2229
        """Basic implementation of push without bound branches or hooks.
 
2230
 
 
2231
        Must be called with self read locked and target write locked.
 
2232
        """
 
2233
        result = BranchPushResult()
 
2234
        result.source_branch = self
 
2235
        result.target_branch = target
 
2236
        result.old_revno, result.old_revid = target.last_revision_info()
 
2237
        if result.old_revid != self.last_revision():
 
2238
            # We assume that during 'push' this repository is closer than
 
2239
            # the target.
 
2240
            graph = self.repository.get_graph(target.repository)
 
2241
            target.update_revisions(self, stop_revision, overwrite=overwrite,
 
2242
                                    graph=graph)
 
2243
        if self._push_should_merge_tags():
 
2244
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
 
2245
        result.new_revno, result.new_revid = target.last_revision_info()
 
2246
        return result
 
2247
 
2530
2248
    def get_stacked_on_url(self):
2531
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2249
        raise errors.UnstackableBranchFormat(self._format, self.base)
2532
2250
 
2533
2251
    def set_push_location(self, location):
2534
2252
        """See Branch.set_push_location."""
2543
2261
            self._transport.put_bytes('parent', url + '\n',
2544
2262
                mode=self.bzrdir._get_file_mode())
2545
2263
 
2546
 
    @needs_write_lock
2547
 
    def unbind(self):
2548
 
        """If bound, unbind"""
2549
 
        return self.set_bound_location(None)
 
2264
 
 
2265
class BzrBranch5(BzrBranch):
 
2266
    """A format 5 branch. This supports new features over plain branches.
 
2267
 
 
2268
    It has support for a master_branch which is the data for bound branches.
 
2269
    """
 
2270
 
 
2271
    @needs_write_lock
 
2272
    def pull(self, source, overwrite=False, stop_revision=None,
 
2273
             run_hooks=True, possible_transports=None,
 
2274
             _override_hook_target=None):
 
2275
        """Pull from source into self, updating my master if any.
 
2276
 
 
2277
        :param run_hooks: Private parameter - if false, this branch
 
2278
            is being called because it's the master of the primary branch,
 
2279
            so it should not run its hooks.
 
2280
        """
 
2281
        bound_location = self.get_bound_location()
 
2282
        master_branch = None
 
2283
        if bound_location and source.base != bound_location:
 
2284
            # not pulling from master, so we need to update master.
 
2285
            master_branch = self.get_master_branch(possible_transports)
 
2286
            master_branch.lock_write()
 
2287
        try:
 
2288
            if master_branch:
 
2289
                # pull from source into master.
 
2290
                master_branch.pull(source, overwrite, stop_revision,
 
2291
                    run_hooks=False)
 
2292
            return super(BzrBranch5, self).pull(source, overwrite,
 
2293
                stop_revision, _hook_master=master_branch,
 
2294
                run_hooks=run_hooks,
 
2295
                _override_hook_target=_override_hook_target)
 
2296
        finally:
 
2297
            if master_branch:
 
2298
                master_branch.unlock()
 
2299
 
 
2300
    def get_bound_location(self):
 
2301
        try:
 
2302
            return self._transport.get_bytes('bound')[:-1]
 
2303
        except errors.NoSuchFile:
 
2304
            return None
 
2305
 
 
2306
    @needs_read_lock
 
2307
    def get_master_branch(self, possible_transports=None):
 
2308
        """Return the branch we are bound to.
 
2309
 
 
2310
        :return: Either a Branch, or None
 
2311
 
 
2312
        This could memoise the branch, but if thats done
 
2313
        it must be revalidated on each new lock.
 
2314
        So for now we just don't memoise it.
 
2315
        # RBC 20060304 review this decision.
 
2316
        """
 
2317
        bound_loc = self.get_bound_location()
 
2318
        if not bound_loc:
 
2319
            return None
 
2320
        try:
 
2321
            return Branch.open(bound_loc,
 
2322
                               possible_transports=possible_transports)
 
2323
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2324
            raise errors.BoundBranchConnectionFailure(
 
2325
                    self, bound_loc, e)
 
2326
 
 
2327
    @needs_write_lock
 
2328
    def set_bound_location(self, location):
 
2329
        """Set the target where this branch is bound to.
 
2330
 
 
2331
        :param location: URL to the target branch
 
2332
        """
 
2333
        if location:
 
2334
            self._transport.put_bytes('bound', location+'\n',
 
2335
                mode=self.bzrdir._get_file_mode())
 
2336
        else:
 
2337
            try:
 
2338
                self._transport.delete('bound')
 
2339
            except errors.NoSuchFile:
 
2340
                return False
 
2341
            return True
2550
2342
 
2551
2343
    @needs_write_lock
2552
2344
    def bind(self, other):
2574
2366
        # history around
2575
2367
        self.set_bound_location(other.base)
2576
2368
 
2577
 
    def get_bound_location(self):
2578
 
        try:
2579
 
            return self._transport.get_bytes('bound')[:-1]
2580
 
        except errors.NoSuchFile:
2581
 
            return None
2582
 
 
2583
 
    @needs_read_lock
2584
 
    def get_master_branch(self, possible_transports=None):
2585
 
        """Return the branch we are bound to.
2586
 
 
2587
 
        :return: Either a Branch, or None
2588
 
        """
2589
 
        if self._master_branch_cache is None:
2590
 
            self._master_branch_cache = self._get_master_branch(
2591
 
                possible_transports)
2592
 
        return self._master_branch_cache
2593
 
 
2594
 
    def _get_master_branch(self, possible_transports):
2595
 
        bound_loc = self.get_bound_location()
2596
 
        if not bound_loc:
2597
 
            return None
2598
 
        try:
2599
 
            return Branch.open(bound_loc,
2600
 
                               possible_transports=possible_transports)
2601
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2602
 
            raise errors.BoundBranchConnectionFailure(
2603
 
                    self, bound_loc, e)
2604
 
 
2605
2369
    @needs_write_lock
2606
 
    def set_bound_location(self, location):
2607
 
        """Set the target where this branch is bound to.
2608
 
 
2609
 
        :param location: URL to the target branch
2610
 
        """
2611
 
        self._master_branch_cache = None
2612
 
        if location:
2613
 
            self._transport.put_bytes('bound', location+'\n',
2614
 
                mode=self.bzrdir._get_file_mode())
2615
 
        else:
2616
 
            try:
2617
 
                self._transport.delete('bound')
2618
 
            except errors.NoSuchFile:
2619
 
                return False
2620
 
            return True
 
2370
    def unbind(self):
 
2371
        """If bound, unbind"""
 
2372
        return self.set_bound_location(None)
2621
2373
 
2622
2374
    @needs_write_lock
2623
2375
    def update(self, possible_transports=None):
2636
2388
            return old_tip
2637
2389
        return None
2638
2390
 
2639
 
    def _read_last_revision_info(self):
2640
 
        revision_string = self._transport.get_bytes('last-revision')
2641
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2642
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2643
 
        revno = int(revno)
2644
 
        return revno, revision_id
2645
 
 
2646
 
    def _write_last_revision_info(self, revno, revision_id):
2647
 
        """Simply write out the revision id, with no checks.
2648
 
 
2649
 
        Use set_last_revision_info to perform this safely.
2650
 
 
2651
 
        Does not update the revision_history cache.
2652
 
        """
2653
 
        revision_id = _mod_revision.ensure_null(revision_id)
2654
 
        out_string = '%d %s\n' % (revno, revision_id)
2655
 
        self._transport.put_bytes('last-revision', out_string,
2656
 
            mode=self.bzrdir._get_file_mode())
2657
 
 
2658
 
 
2659
 
class FullHistoryBzrBranch(BzrBranch):
2660
 
    """Bzr branch which contains the full revision history."""
2661
 
 
2662
 
    @needs_write_lock
2663
 
    def set_last_revision_info(self, revno, revision_id):
2664
 
        if not revision_id or not isinstance(revision_id, basestring):
2665
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2666
 
        revision_id = _mod_revision.ensure_null(revision_id)
2667
 
        # this old format stores the full history, but this api doesn't
2668
 
        # provide it, so we must generate, and might as well check it's
2669
 
        # correct
2670
 
        history = self._lefthand_history(revision_id)
2671
 
        if len(history) != revno:
2672
 
            raise AssertionError('%d != %d' % (len(history), revno))
2673
 
        self._set_revision_history(history)
2674
 
 
2675
 
    def _read_last_revision_info(self):
2676
 
        rh = self.revision_history()
2677
 
        revno = len(rh)
2678
 
        if revno:
2679
 
            return (revno, rh[-1])
2680
 
        else:
2681
 
            return (0, _mod_revision.NULL_REVISION)
2682
 
 
2683
 
    @deprecated_method(deprecated_in((2, 4, 0)))
2684
 
    @needs_write_lock
2685
 
    def set_revision_history(self, rev_history):
2686
 
        """See Branch.set_revision_history."""
2687
 
        self._set_revision_history(rev_history)
2688
 
 
2689
 
    def _set_revision_history(self, rev_history):
2690
 
        if 'evil' in debug.debug_flags:
2691
 
            mutter_callsite(3, "set_revision_history scales with history.")
2692
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
2693
 
        for rev_id in rev_history:
2694
 
            check_not_reserved_id(rev_id)
2695
 
        if Branch.hooks['post_change_branch_tip']:
2696
 
            # Don't calculate the last_revision_info() if there are no hooks
2697
 
            # that will use it.
2698
 
            old_revno, old_revid = self.last_revision_info()
2699
 
        if len(rev_history) == 0:
2700
 
            revid = _mod_revision.NULL_REVISION
2701
 
        else:
2702
 
            revid = rev_history[-1]
2703
 
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2704
 
        self._write_revision_history(rev_history)
2705
 
        self._clear_cached_state()
2706
 
        self._cache_revision_history(rev_history)
2707
 
        for hook in Branch.hooks['set_rh']:
2708
 
            hook(self, rev_history)
2709
 
        if Branch.hooks['post_change_branch_tip']:
2710
 
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2711
 
 
2712
 
    def _write_revision_history(self, history):
2713
 
        """Factored out of set_revision_history.
2714
 
 
2715
 
        This performs the actual writing to disk.
2716
 
        It is intended to be called by set_revision_history."""
2717
 
        self._transport.put_bytes(
2718
 
            'revision-history', '\n'.join(history),
2719
 
            mode=self.bzrdir._get_file_mode())
2720
 
 
2721
 
    def _gen_revision_history(self):
2722
 
        history = self._transport.get_bytes('revision-history').split('\n')
2723
 
        if history[-1:] == ['']:
2724
 
            # There shouldn't be a trailing newline, but just in case.
2725
 
            history.pop()
2726
 
        return history
2727
 
 
2728
 
    def _synchronize_history(self, destination, revision_id):
2729
 
        if not isinstance(destination, FullHistoryBzrBranch):
2730
 
            super(BzrBranch, self)._synchronize_history(
2731
 
                destination, revision_id)
2732
 
            return
2733
 
        if revision_id == _mod_revision.NULL_REVISION:
2734
 
            new_history = []
2735
 
        else:
2736
 
            new_history = self.revision_history()
2737
 
        if revision_id is not None and new_history != []:
2738
 
            try:
2739
 
                new_history = new_history[:new_history.index(revision_id) + 1]
2740
 
            except ValueError:
2741
 
                rev = self.repository.get_revision(revision_id)
2742
 
                new_history = rev.get_history(self.repository)[1:]
2743
 
        destination._set_revision_history(new_history)
2744
 
 
2745
 
    @needs_write_lock
2746
 
    def generate_revision_history(self, revision_id, last_rev=None,
2747
 
        other_branch=None):
2748
 
        """Create a new revision history that will finish with revision_id.
2749
 
 
2750
 
        :param revision_id: the new tip to use.
2751
 
        :param last_rev: The previous last_revision. If not None, then this
2752
 
            must be a ancestory of revision_id, or DivergedBranches is raised.
2753
 
        :param other_branch: The other branch that DivergedBranches should
2754
 
            raise with respect to.
2755
 
        """
2756
 
        self._set_revision_history(self._lefthand_history(revision_id,
2757
 
            last_rev, other_branch))
2758
 
 
2759
 
 
2760
 
class BzrBranch5(FullHistoryBzrBranch):
2761
 
    """A format 5 branch. This supports new features over plain branches.
2762
 
 
2763
 
    It has support for a master_branch which is the data for bound branches.
2764
 
    """
2765
 
 
2766
 
 
2767
 
class BzrBranch8(BzrBranch):
2768
 
    """A branch that stores tree-reference locations."""
 
2391
 
 
2392
class BzrBranch7(BzrBranch5):
 
2393
    """A branch with support for a fallback repository."""
2769
2394
 
2770
2395
    def _open_hook(self):
2771
2396
        if self._ignore_fallbacks:
2783
2408
                    raise AssertionError(
2784
2409
                        "'transform_fallback_location' hook %s returned "
2785
2410
                        "None, not a URL." % hook_name)
2786
 
            self._activate_fallback_location(url)
 
2411
            self._activate_fallback_location(url, None)
2787
2412
 
2788
2413
    def __init__(self, *args, **kwargs):
2789
2414
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2790
 
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
2415
        super(BzrBranch7, self).__init__(*args, **kwargs)
2791
2416
        self._last_revision_info_cache = None
2792
 
        self._reference_info = None
 
2417
        self._partial_revision_history_cache = []
2793
2418
 
2794
2419
    def _clear_cached_state(self):
2795
 
        super(BzrBranch8, self)._clear_cached_state()
 
2420
        super(BzrBranch7, self)._clear_cached_state()
2796
2421
        self._last_revision_info_cache = None
2797
 
        self._reference_info = None
 
2422
        self._partial_revision_history_cache = []
 
2423
 
 
2424
    def _last_revision_info(self):
 
2425
        revision_string = self._transport.get_bytes('last-revision')
 
2426
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2427
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2428
        revno = int(revno)
 
2429
        return revno, revision_id
 
2430
 
 
2431
    def _write_last_revision_info(self, revno, revision_id):
 
2432
        """Simply write out the revision id, with no checks.
 
2433
 
 
2434
        Use set_last_revision_info to perform this safely.
 
2435
 
 
2436
        Does not update the revision_history cache.
 
2437
        Intended to be called by set_last_revision_info and
 
2438
        _write_revision_history.
 
2439
        """
 
2440
        revision_id = _mod_revision.ensure_null(revision_id)
 
2441
        out_string = '%d %s\n' % (revno, revision_id)
 
2442
        self._transport.put_bytes('last-revision', out_string,
 
2443
            mode=self.bzrdir._get_file_mode())
 
2444
 
 
2445
    @needs_write_lock
 
2446
    def set_last_revision_info(self, revno, revision_id):
 
2447
        revision_id = _mod_revision.ensure_null(revision_id)
 
2448
        old_revno, old_revid = self.last_revision_info()
 
2449
        if self._get_append_revisions_only():
 
2450
            self._check_history_violation(revision_id)
 
2451
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2452
        self._write_last_revision_info(revno, revision_id)
 
2453
        self._clear_cached_state()
 
2454
        self._last_revision_info_cache = revno, revision_id
 
2455
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2456
 
 
2457
    def _synchronize_history(self, destination, revision_id):
 
2458
        """Synchronize last revision and revision history between branches.
 
2459
 
 
2460
        :see: Branch._synchronize_history
 
2461
        """
 
2462
        # XXX: The base Branch has a fast implementation of this method based
 
2463
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2464
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2465
        # but wants the fast implementation, so it calls
 
2466
        # Branch._synchronize_history directly.
 
2467
        Branch._synchronize_history(self, destination, revision_id)
2798
2468
 
2799
2469
    def _check_history_violation(self, revision_id):
2800
 
        current_revid = self.last_revision()
2801
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2470
        last_revision = _mod_revision.ensure_null(self.last_revision())
2802
2471
        if _mod_revision.is_null(last_revision):
2803
2472
            return
2804
 
        graph = self.repository.get_graph()
2805
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2806
 
            if lh_ancestor == current_revid:
2807
 
                return
2808
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2473
        if last_revision not in self._lefthand_history(revision_id):
 
2474
            raise errors.AppendRevisionsOnlyViolation(self.base)
2809
2475
 
2810
2476
    def _gen_revision_history(self):
2811
2477
        """Generate the revision history from last revision
2814
2480
        self._extend_partial_history(stop_index=last_revno-1)
2815
2481
        return list(reversed(self._partial_revision_history_cache))
2816
2482
 
 
2483
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2484
        """Extend the partial history to include a given index
 
2485
 
 
2486
        If a stop_index is supplied, stop when that index has been reached.
 
2487
        If a stop_revision is supplied, stop when that revision is
 
2488
        encountered.  Otherwise, stop when the beginning of history is
 
2489
        reached.
 
2490
 
 
2491
        :param stop_index: The index which should be present.  When it is
 
2492
            present, history extension will stop.
 
2493
        :param revision_id: The revision id which should be present.  When
 
2494
            it is encountered, history extension will stop.
 
2495
        """
 
2496
        repo = self.repository
 
2497
        if len(self._partial_revision_history_cache) == 0:
 
2498
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2499
        else:
 
2500
            start_revision = self._partial_revision_history_cache[-1]
 
2501
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2502
            #skip the last revision in the list
 
2503
            next_revision = iterator.next()
 
2504
        for revision_id in iterator:
 
2505
            self._partial_revision_history_cache.append(revision_id)
 
2506
            if (stop_index is not None and
 
2507
                len(self._partial_revision_history_cache) > stop_index):
 
2508
                break
 
2509
            if revision_id == stop_revision:
 
2510
                break
 
2511
 
 
2512
    def _write_revision_history(self, history):
 
2513
        """Factored out of set_revision_history.
 
2514
 
 
2515
        This performs the actual writing to disk, with format-specific checks.
 
2516
        It is intended to be called by BzrBranch5.set_revision_history.
 
2517
        """
 
2518
        if len(history) == 0:
 
2519
            last_revision = 'null:'
 
2520
        else:
 
2521
            if history != self._lefthand_history(history[-1]):
 
2522
                raise errors.NotLefthandHistory(history)
 
2523
            last_revision = history[-1]
 
2524
        if self._get_append_revisions_only():
 
2525
            self._check_history_violation(last_revision)
 
2526
        self._write_last_revision_info(len(history), last_revision)
 
2527
 
2817
2528
    @needs_write_lock
2818
2529
    def _set_parent_location(self, url):
2819
2530
        """Set the parent branch"""
2824
2535
        """Set the parent branch"""
2825
2536
        return self._get_config_location('parent_location')
2826
2537
 
2827
 
    @needs_write_lock
2828
 
    def _set_all_reference_info(self, info_dict):
2829
 
        """Replace all reference info stored in a branch.
2830
 
 
2831
 
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
2832
 
        """
2833
 
        s = StringIO()
2834
 
        writer = rio.RioWriter(s)
2835
 
        for key, (tree_path, branch_location) in info_dict.iteritems():
2836
 
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2837
 
                                branch_location=branch_location)
2838
 
            writer.write_stanza(stanza)
2839
 
        self._transport.put_bytes('references', s.getvalue())
2840
 
        self._reference_info = info_dict
2841
 
 
2842
 
    @needs_read_lock
2843
 
    def _get_all_reference_info(self):
2844
 
        """Return all the reference info stored in a branch.
2845
 
 
2846
 
        :return: A dict of {file_id: (tree_path, branch_location)}
2847
 
        """
2848
 
        if self._reference_info is not None:
2849
 
            return self._reference_info
2850
 
        rio_file = self._transport.get('references')
2851
 
        try:
2852
 
            stanzas = rio.read_stanzas(rio_file)
2853
 
            info_dict = dict((s['file_id'], (s['tree_path'],
2854
 
                             s['branch_location'])) for s in stanzas)
2855
 
        finally:
2856
 
            rio_file.close()
2857
 
        self._reference_info = info_dict
2858
 
        return info_dict
2859
 
 
2860
 
    def set_reference_info(self, file_id, tree_path, branch_location):
2861
 
        """Set the branch location to use for a tree reference.
2862
 
 
2863
 
        :param file_id: The file-id of the tree reference.
2864
 
        :param tree_path: The path of the tree reference in the tree.
2865
 
        :param branch_location: The location of the branch to retrieve tree
2866
 
            references from.
2867
 
        """
2868
 
        info_dict = self._get_all_reference_info()
2869
 
        info_dict[file_id] = (tree_path, branch_location)
2870
 
        if None in (tree_path, branch_location):
2871
 
            if tree_path is not None:
2872
 
                raise ValueError('tree_path must be None when branch_location'
2873
 
                                 ' is None.')
2874
 
            if branch_location is not None:
2875
 
                raise ValueError('branch_location must be None when tree_path'
2876
 
                                 ' is None.')
2877
 
            del info_dict[file_id]
2878
 
        self._set_all_reference_info(info_dict)
2879
 
 
2880
 
    def get_reference_info(self, file_id):
2881
 
        """Get the tree_path and branch_location for a tree reference.
2882
 
 
2883
 
        :return: a tuple of (tree_path, branch_location)
2884
 
        """
2885
 
        return self._get_all_reference_info().get(file_id, (None, None))
2886
 
 
2887
 
    def reference_parent(self, file_id, path, possible_transports=None):
2888
 
        """Return the parent branch for a tree-reference file_id.
2889
 
 
2890
 
        :param file_id: The file_id of the tree reference
2891
 
        :param path: The path of the file_id in the tree
2892
 
        :return: A branch associated with the file_id
2893
 
        """
2894
 
        branch_location = self.get_reference_info(file_id)[1]
2895
 
        if branch_location is None:
2896
 
            return Branch.reference_parent(self, file_id, path,
2897
 
                                           possible_transports)
2898
 
        branch_location = urlutils.join(self.user_url, branch_location)
2899
 
        return Branch.open(branch_location,
2900
 
                           possible_transports=possible_transports)
2901
 
 
2902
2538
    def set_push_location(self, location):
2903
2539
        """See Branch.set_push_location."""
2904
2540
        self._set_config_location('push_location', location)
2905
2541
 
2906
2542
    def set_bound_location(self, location):
2907
2543
        """See Branch.set_push_location."""
2908
 
        self._master_branch_cache = None
2909
2544
        result = None
2910
2545
        config = self.get_config()
2911
2546
        if location is None:
2942
2577
        # you can always ask for the URL; but you might not be able to use it
2943
2578
        # if the repo can't support stacking.
2944
2579
        ## self._check_stackable_repo()
2945
 
        # stacked_on_location is only ever defined in branch.conf, so don't
2946
 
        # waste effort reading the whole stack of config files.
2947
 
        config = self.get_config()._get_branch_data_config()
2948
 
        stacked_url = self._get_config_location('stacked_on_location',
2949
 
            config=config)
 
2580
        stacked_url = self._get_config_location('stacked_on_location')
2950
2581
        if stacked_url is None:
2951
2582
            raise errors.NotStacked(self)
2952
2583
        return stacked_url
2953
2584
 
 
2585
    def set_append_revisions_only(self, enabled):
 
2586
        if enabled:
 
2587
            value = 'True'
 
2588
        else:
 
2589
            value = 'False'
 
2590
        self.get_config().set_user_option('append_revisions_only', value,
 
2591
            warn_masked=True)
 
2592
 
2954
2593
    def _get_append_revisions_only(self):
2955
 
        return self.get_config(
2956
 
            ).get_user_option_as_bool('append_revisions_only')
 
2594
        value = self.get_config().get_user_option('append_revisions_only')
 
2595
        return value == 'True'
 
2596
 
 
2597
    @needs_write_lock
 
2598
    def generate_revision_history(self, revision_id, last_rev=None,
 
2599
                                  other_branch=None):
 
2600
        """See BzrBranch5.generate_revision_history"""
 
2601
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2602
        revno = len(history)
 
2603
        self.set_last_revision_info(revno, revision_id)
2957
2604
 
2958
2605
    @needs_read_lock
2959
2606
    def get_rev_id(self, revno, history=None):
2984
2631
        try:
2985
2632
            index = self._partial_revision_history_cache.index(revision_id)
2986
2633
        except ValueError:
2987
 
            try:
2988
 
                self._extend_partial_history(stop_revision=revision_id)
2989
 
            except errors.RevisionNotPresent, e:
2990
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2634
            self._extend_partial_history(stop_revision=revision_id)
2991
2635
            index = len(self._partial_revision_history_cache) - 1
2992
2636
            if self._partial_revision_history_cache[index] != revision_id:
2993
2637
                raise errors.NoSuchRevision(self, revision_id)
2994
2638
        return self.revno() - index
2995
2639
 
2996
2640
 
2997
 
class BzrBranch7(BzrBranch8):
2998
 
    """A branch with support for a fallback repository."""
2999
 
 
3000
 
    def set_reference_info(self, file_id, tree_path, branch_location):
3001
 
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
3002
 
 
3003
 
    def get_reference_info(self, file_id):
3004
 
        Branch.get_reference_info(self, file_id)
3005
 
 
3006
 
    def reference_parent(self, file_id, path, possible_transports=None):
3007
 
        return Branch.reference_parent(self, file_id, path,
3008
 
                                       possible_transports)
3009
 
 
3010
 
 
3011
2641
class BzrBranch6(BzrBranch7):
3012
2642
    """See BzrBranchFormat6 for the capabilities of this branch.
3013
2643
 
3016
2646
    """
3017
2647
 
3018
2648
    def get_stacked_on_url(self):
3019
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2649
        raise errors.UnstackableBranchFormat(self._format, self.base)
3020
2650
 
3021
2651
 
3022
2652
######################################################################
3048
2678
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3049
2679
    """
3050
2680
 
3051
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3052
2681
    def __int__(self):
3053
 
        """Return the relative change in revno.
3054
 
 
3055
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3056
 
        """
 
2682
        # DEPRECATED: pull used to return the change in revno
3057
2683
        return self.new_revno - self.old_revno
3058
2684
 
3059
2685
    def report(self, to_file):
3084
2710
        target, otherwise it will be None.
3085
2711
    """
3086
2712
 
3087
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3088
2713
    def __int__(self):
3089
 
        """Return the relative change in revno.
3090
 
 
3091
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3092
 
        """
 
2714
        # DEPRECATED: push used to return the change in revno
3093
2715
        return self.new_revno - self.old_revno
3094
2716
 
3095
2717
    def report(self, to_file):
3109
2731
 
3110
2732
    def __init__(self, branch):
3111
2733
        self.branch = branch
3112
 
        self.errors = []
3113
2734
 
3114
2735
    def report_results(self, verbose):
3115
2736
        """Report the check results via trace.note.
3117
2738
        :param verbose: Requests more detailed display of what was checked,
3118
2739
            if any.
3119
2740
        """
3120
 
        note('checked branch %s format %s', self.branch.user_url,
3121
 
            self.branch._format)
3122
 
        for error in self.errors:
3123
 
            note('found error:%s', error)
 
2741
        note('checked branch %s format %s',
 
2742
             self.branch.base,
 
2743
             self.branch._format)
3124
2744
 
3125
2745
 
3126
2746
class Converter5to6(object):
3164
2784
        branch._transport.put_bytes('format', format.get_format_string())
3165
2785
 
3166
2786
 
3167
 
class Converter7to8(object):
3168
 
    """Perform an in-place upgrade of format 6 to format 7"""
3169
 
 
3170
 
    def convert(self, branch):
3171
 
        format = BzrBranchFormat8()
3172
 
        branch._transport.put_bytes('references', '')
3173
 
        # update target format
3174
 
        branch._transport.put_bytes('format', format.get_format_string())
 
2787
 
 
2788
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
2789
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
2790
    duration.
 
2791
 
 
2792
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
2793
 
 
2794
    If an exception is raised by callable, then that exception *will* be
 
2795
    propagated, even if the unlock attempt raises its own error.  Thus
 
2796
    _run_with_write_locked_target should be preferred to simply doing::
 
2797
 
 
2798
        target.lock_write()
 
2799
        try:
 
2800
            return callable(*args, **kwargs)
 
2801
        finally:
 
2802
            target.unlock()
 
2803
 
 
2804
    """
 
2805
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
2806
    # should share code?
 
2807
    target.lock_write()
 
2808
    try:
 
2809
        result = callable(*args, **kwargs)
 
2810
    except:
 
2811
        exc_info = sys.exc_info()
 
2812
        try:
 
2813
            target.unlock()
 
2814
        finally:
 
2815
            raise exc_info[0], exc_info[1], exc_info[2]
 
2816
    else:
 
2817
        target.unlock()
 
2818
        return result
3175
2819
 
3176
2820
 
3177
2821
class InterBranch(InterObject):
3185
2829
    _optimisers = []
3186
2830
    """The available optimised InterBranch types."""
3187
2831
 
3188
 
    @classmethod
3189
 
    def _get_branch_formats_to_test(klass):
3190
 
        """Return an iterable of format tuples for testing.
3191
 
        
3192
 
        :return: An iterable of (from_format, to_format) to use when testing
3193
 
            this InterBranch class. Each InterBranch class should define this
3194
 
            method itself.
3195
 
        """
3196
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
3197
 
 
3198
 
    @needs_write_lock
3199
 
    def pull(self, overwrite=False, stop_revision=None,
3200
 
             possible_transports=None, local=False):
3201
 
        """Mirror source into target branch.
3202
 
 
3203
 
        The target branch is considered to be 'local', having low latency.
3204
 
 
3205
 
        :returns: PullResult instance
3206
 
        """
3207
 
        raise NotImplementedError(self.pull)
3208
 
 
3209
 
    @needs_write_lock
3210
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3211
 
             _override_hook_source_branch=None):
3212
 
        """Mirror the source branch into the target branch.
3213
 
 
3214
 
        The source branch is considered to be 'local', having low latency.
3215
 
        """
3216
 
        raise NotImplementedError(self.push)
3217
 
 
3218
 
    @needs_write_lock
3219
 
    def copy_content_into(self, revision_id=None):
3220
 
        """Copy the content of source into target
3221
 
 
3222
 
        revision_id: if not None, the revision history in the new branch will
3223
 
                     be truncated to end with revision_id.
3224
 
        """
3225
 
        raise NotImplementedError(self.copy_content_into)
3226
 
 
3227
 
    @needs_write_lock
3228
 
    def fetch(self, stop_revision=None, limit=None):
3229
 
        """Fetch revisions.
3230
 
 
3231
 
        :param stop_revision: Last revision to fetch
3232
 
        :param limit: Optional rough limit of revisions to fetch
3233
 
        """
3234
 
        raise NotImplementedError(self.fetch)
 
2832
    @staticmethod
 
2833
    def _get_branch_formats_to_test():
 
2834
        """Return a tuple with the Branch formats to use when testing."""
 
2835
        raise NotImplementedError(self._get_branch_formats_to_test)
 
2836
 
 
2837
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2838
                         graph=None):
 
2839
        """Pull in new perfect-fit revisions.
 
2840
 
 
2841
        :param stop_revision: Updated until the given revision
 
2842
        :param overwrite: Always set the branch pointer, rather than checking
 
2843
            to see if it is a proper descendant.
 
2844
        :param graph: A Graph object that can be used to query history
 
2845
            information. This can be None.
 
2846
        :return: None
 
2847
        """
 
2848
        raise NotImplementedError(self.update_revisions)
3235
2849
 
3236
2850
 
3237
2851
class GenericInterBranch(InterBranch):
3238
 
    """InterBranch implementation that uses public Branch functions."""
 
2852
    """InterBranch implementation that uses public Branch functions.
 
2853
    """
 
2854
 
 
2855
    @staticmethod
 
2856
    def _get_branch_formats_to_test():
 
2857
        return BranchFormat._default_format, BranchFormat._default_format
 
2858
 
 
2859
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2860
        graph=None):
 
2861
        """See InterBranch.update_revisions()."""
 
2862
        self.source.lock_read()
 
2863
        try:
 
2864
            other_revno, other_last_revision = self.source.last_revision_info()
 
2865
            stop_revno = None # unknown
 
2866
            if stop_revision is None:
 
2867
                stop_revision = other_last_revision
 
2868
                if _mod_revision.is_null(stop_revision):
 
2869
                    # if there are no commits, we're done.
 
2870
                    return
 
2871
                stop_revno = other_revno
 
2872
 
 
2873
            # what's the current last revision, before we fetch [and change it
 
2874
            # possibly]
 
2875
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2876
            # we fetch here so that we don't process data twice in the common
 
2877
            # case of having something to pull, and so that the check for
 
2878
            # already merged can operate on the just fetched graph, which will
 
2879
            # be cached in memory.
 
2880
            self.target.fetch(self.source, stop_revision)
 
2881
            # Check to see if one is an ancestor of the other
 
2882
            if not overwrite:
 
2883
                if graph is None:
 
2884
                    graph = self.target.repository.get_graph()
 
2885
                if self.target._check_if_descendant_or_diverged(
 
2886
                        stop_revision, last_rev, graph, self.source):
 
2887
                    # stop_revision is a descendant of last_rev, but we aren't
 
2888
                    # overwriting, so we're done.
 
2889
                    return
 
2890
            if stop_revno is None:
 
2891
                if graph is None:
 
2892
                    graph = self.target.repository.get_graph()
 
2893
                this_revno, this_last_revision = \
 
2894
                        self.target.last_revision_info()
 
2895
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2896
                                [(other_last_revision, other_revno),
 
2897
                                 (this_last_revision, this_revno)])
 
2898
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2899
        finally:
 
2900
            self.source.unlock()
3239
2901
 
3240
2902
    @classmethod
3241
 
    def is_compatible(klass, source, target):
 
2903
    def is_compatible(self, source, target):
3242
2904
        # GenericBranch uses the public API, so always compatible
3243
2905
        return True
3244
2906
 
3245
 
    @classmethod
3246
 
    def _get_branch_formats_to_test(klass):
3247
 
        return [(format_registry.get_default(), format_registry.get_default())]
3248
 
 
3249
 
    @classmethod
3250
 
    def unwrap_format(klass, format):
3251
 
        if isinstance(format, remote.RemoteBranchFormat):
3252
 
            format._ensure_real()
3253
 
            return format._custom_format
3254
 
        return format
3255
 
 
3256
 
    @needs_write_lock
3257
 
    def copy_content_into(self, revision_id=None):
3258
 
        """Copy the content of source into target
3259
 
 
3260
 
        revision_id: if not None, the revision history in the new branch will
3261
 
                     be truncated to end with revision_id.
3262
 
        """
3263
 
        self.source.update_references(self.target)
3264
 
        self.source._synchronize_history(self.target, revision_id)
3265
 
        try:
3266
 
            parent = self.source.get_parent()
3267
 
        except errors.InaccessibleParent, e:
3268
 
            mutter('parent was not accessible to copy: %s', e)
3269
 
        else:
3270
 
            if parent:
3271
 
                self.target.set_parent(parent)
3272
 
        if self.source._push_should_merge_tags():
3273
 
            self.source.tags.merge_to(self.target.tags)
3274
 
 
3275
 
    @needs_write_lock
3276
 
    def fetch(self, stop_revision=None, limit=None):
3277
 
        if self.target.base == self.source.base:
3278
 
            return (0, [])
3279
 
        self.source.lock_read()
3280
 
        try:
3281
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3282
 
            fetch_spec_factory.source_branch = self.source
3283
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3284
 
            fetch_spec_factory.source_repo = self.source.repository
3285
 
            fetch_spec_factory.target_repo = self.target.repository
3286
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3287
 
            fetch_spec_factory.limit = limit
3288
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3289
 
            return self.target.repository.fetch(self.source.repository,
3290
 
                fetch_spec=fetch_spec)
3291
 
        finally:
3292
 
            self.source.unlock()
3293
 
 
3294
 
    @needs_write_lock
3295
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3296
 
            graph=None):
3297
 
        other_revno, other_last_revision = self.source.last_revision_info()
3298
 
        stop_revno = None # unknown
3299
 
        if stop_revision is None:
3300
 
            stop_revision = other_last_revision
3301
 
            if _mod_revision.is_null(stop_revision):
3302
 
                # if there are no commits, we're done.
3303
 
                return
3304
 
            stop_revno = other_revno
3305
 
 
3306
 
        # what's the current last revision, before we fetch [and change it
3307
 
        # possibly]
3308
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3309
 
        # we fetch here so that we don't process data twice in the common
3310
 
        # case of having something to pull, and so that the check for
3311
 
        # already merged can operate on the just fetched graph, which will
3312
 
        # be cached in memory.
3313
 
        self.fetch(stop_revision=stop_revision)
3314
 
        # Check to see if one is an ancestor of the other
3315
 
        if not overwrite:
3316
 
            if graph is None:
3317
 
                graph = self.target.repository.get_graph()
3318
 
            if self.target._check_if_descendant_or_diverged(
3319
 
                    stop_revision, last_rev, graph, self.source):
3320
 
                # stop_revision is a descendant of last_rev, but we aren't
3321
 
                # overwriting, so we're done.
3322
 
                return
3323
 
        if stop_revno is None:
3324
 
            if graph is None:
3325
 
                graph = self.target.repository.get_graph()
3326
 
            this_revno, this_last_revision = \
3327
 
                    self.target.last_revision_info()
3328
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3329
 
                            [(other_last_revision, other_revno),
3330
 
                             (this_last_revision, this_revno)])
3331
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3332
 
 
3333
 
    @needs_write_lock
3334
 
    def pull(self, overwrite=False, stop_revision=None,
3335
 
             possible_transports=None, run_hooks=True,
3336
 
             _override_hook_target=None, local=False):
3337
 
        """Pull from source into self, updating my master if any.
3338
 
 
3339
 
        :param run_hooks: Private parameter - if false, this branch
3340
 
            is being called because it's the master of the primary branch,
3341
 
            so it should not run its hooks.
3342
 
        """
3343
 
        bound_location = self.target.get_bound_location()
3344
 
        if local and not bound_location:
3345
 
            raise errors.LocalRequiresBoundBranch()
3346
 
        master_branch = None
3347
 
        source_is_master = (self.source.user_url == bound_location)
3348
 
        if not local and bound_location and not source_is_master:
3349
 
            # not pulling from master, so we need to update master.
3350
 
            master_branch = self.target.get_master_branch(possible_transports)
3351
 
            master_branch.lock_write()
3352
 
        try:
3353
 
            if master_branch:
3354
 
                # pull from source into master.
3355
 
                master_branch.pull(self.source, overwrite, stop_revision,
3356
 
                    run_hooks=False)
3357
 
            return self._pull(overwrite,
3358
 
                stop_revision, _hook_master=master_branch,
3359
 
                run_hooks=run_hooks,
3360
 
                _override_hook_target=_override_hook_target,
3361
 
                merge_tags_to_master=not source_is_master)
3362
 
        finally:
3363
 
            if master_branch:
3364
 
                master_branch.unlock()
3365
 
 
3366
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3367
 
             _override_hook_source_branch=None):
3368
 
        """See InterBranch.push.
3369
 
 
3370
 
        This is the basic concrete implementation of push()
3371
 
 
3372
 
        :param _override_hook_source_branch: If specified, run the hooks
3373
 
            passing this Branch as the source, rather than self.  This is for
3374
 
            use of RemoteBranch, where push is delegated to the underlying
3375
 
            vfs-based Branch.
3376
 
        """
3377
 
        if lossy:
3378
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3379
 
        # TODO: Public option to disable running hooks - should be trivial but
3380
 
        # needs tests.
3381
 
 
3382
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3383
 
        op.add_cleanup(self.source.lock_read().unlock)
3384
 
        op.add_cleanup(self.target.lock_write().unlock)
3385
 
        return op.run(overwrite, stop_revision,
3386
 
            _override_hook_source_branch=_override_hook_source_branch)
3387
 
 
3388
 
    def _basic_push(self, overwrite, stop_revision):
3389
 
        """Basic implementation of push without bound branches or hooks.
3390
 
 
3391
 
        Must be called with source read locked and target write locked.
3392
 
        """
3393
 
        result = BranchPushResult()
3394
 
        result.source_branch = self.source
3395
 
        result.target_branch = self.target
3396
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3397
 
        self.source.update_references(self.target)
3398
 
        if result.old_revid != stop_revision:
3399
 
            # We assume that during 'push' this repository is closer than
3400
 
            # the target.
3401
 
            graph = self.source.repository.get_graph(self.target.repository)
3402
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3403
 
                    graph=graph)
3404
 
        if self.source._push_should_merge_tags():
3405
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3406
 
                overwrite)
3407
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3408
 
        return result
3409
 
 
3410
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3411
 
            _override_hook_source_branch=None):
3412
 
        """Push from source into target, and into target's master if any.
3413
 
        """
3414
 
        def _run_hooks():
3415
 
            if _override_hook_source_branch:
3416
 
                result.source_branch = _override_hook_source_branch
3417
 
            for hook in Branch.hooks['post_push']:
3418
 
                hook(result)
3419
 
 
3420
 
        bound_location = self.target.get_bound_location()
3421
 
        if bound_location and self.target.base != bound_location:
3422
 
            # there is a master branch.
3423
 
            #
3424
 
            # XXX: Why the second check?  Is it even supported for a branch to
3425
 
            # be bound to itself? -- mbp 20070507
3426
 
            master_branch = self.target.get_master_branch()
3427
 
            master_branch.lock_write()
3428
 
            operation.add_cleanup(master_branch.unlock)
3429
 
            # push into the master from the source branch.
3430
 
            master_inter = InterBranch.get(self.source, master_branch)
3431
 
            master_inter._basic_push(overwrite, stop_revision)
3432
 
            # and push into the target branch from the source. Note that
3433
 
            # we push from the source branch again, because it's considered
3434
 
            # the highest bandwidth repository.
3435
 
            result = self._basic_push(overwrite, stop_revision)
3436
 
            result.master_branch = master_branch
3437
 
            result.local_branch = self.target
3438
 
        else:
3439
 
            master_branch = None
3440
 
            # no master branch
3441
 
            result = self._basic_push(overwrite, stop_revision)
3442
 
            # TODO: Why set master_branch and local_branch if there's no
3443
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3444
 
            # 20070504
3445
 
            result.master_branch = self.target
3446
 
            result.local_branch = None
3447
 
        _run_hooks()
3448
 
        return result
3449
 
 
3450
 
    def _pull(self, overwrite=False, stop_revision=None,
3451
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3452
 
             _override_hook_target=None, local=False,
3453
 
             merge_tags_to_master=True):
3454
 
        """See Branch.pull.
3455
 
 
3456
 
        This function is the core worker, used by GenericInterBranch.pull to
3457
 
        avoid duplication when pulling source->master and source->local.
3458
 
 
3459
 
        :param _hook_master: Private parameter - set the branch to
3460
 
            be supplied as the master to pull hooks.
3461
 
        :param run_hooks: Private parameter - if false, this branch
3462
 
            is being called because it's the master of the primary branch,
3463
 
            so it should not run its hooks.
3464
 
            is being called because it's the master of the primary branch,
3465
 
            so it should not run its hooks.
3466
 
        :param _override_hook_target: Private parameter - set the branch to be
3467
 
            supplied as the target_branch to pull hooks.
3468
 
        :param local: Only update the local branch, and not the bound branch.
3469
 
        """
3470
 
        # This type of branch can't be bound.
3471
 
        if local:
3472
 
            raise errors.LocalRequiresBoundBranch()
3473
 
        result = PullResult()
3474
 
        result.source_branch = self.source
3475
 
        if _override_hook_target is None:
3476
 
            result.target_branch = self.target
3477
 
        else:
3478
 
            result.target_branch = _override_hook_target
3479
 
        self.source.lock_read()
3480
 
        try:
3481
 
            # We assume that during 'pull' the target repository is closer than
3482
 
            # the source one.
3483
 
            self.source.update_references(self.target)
3484
 
            graph = self.target.repository.get_graph(self.source.repository)
3485
 
            # TODO: Branch formats should have a flag that indicates 
3486
 
            # that revno's are expensive, and pull() should honor that flag.
3487
 
            # -- JRV20090506
3488
 
            result.old_revno, result.old_revid = \
3489
 
                self.target.last_revision_info()
3490
 
            self._update_revisions(stop_revision, overwrite=overwrite,
3491
 
                graph=graph)
3492
 
            # TODO: The old revid should be specified when merging tags, 
3493
 
            # so a tags implementation that versions tags can only 
3494
 
            # pull in the most recent changes. -- JRV20090506
3495
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3496
 
                overwrite, ignore_master=not merge_tags_to_master)
3497
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3498
 
            if _hook_master:
3499
 
                result.master_branch = _hook_master
3500
 
                result.local_branch = result.target_branch
3501
 
            else:
3502
 
                result.master_branch = result.target_branch
3503
 
                result.local_branch = None
3504
 
            if run_hooks:
3505
 
                for hook in Branch.hooks['post_pull']:
3506
 
                    hook(result)
3507
 
        finally:
3508
 
            self.source.unlock()
3509
 
        return result
3510
 
 
3511
2907
 
3512
2908
InterBranch.register_optimiser(GenericInterBranch)