~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Ian Clatworthy
  • Date: 2009-12-03 23:21:16 UTC
  • mfrom: (4852.4.1 RCStoVCS)
  • mto: This revision was merged to the branch mainline in revision 4860.
  • Revision ID: ian.clatworthy@canonical.com-20091203232116-f8igfvc6muqrn4yx
Revision Control -> Version Control in docs

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2012 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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
from __future__ import absolute_import
18
 
 
19
 
import bzrlib.bzrdir
20
17
 
21
18
from cStringIO import StringIO
 
19
import sys
22
20
 
23
21
from bzrlib.lazy_import import lazy_import
24
22
lazy_import(globals(), """
25
 
import itertools
 
23
from itertools import chain
26
24
from bzrlib import (
27
 
    bzrdir,
28
 
    controldir,
29
 
    cache_utf8,
30
 
    cleanup,
31
 
    config as _mod_config,
32
 
    debug,
33
 
    errors,
34
 
    fetch,
35
 
    graph as _mod_graph,
36
 
    lockdir,
37
 
    lockable_files,
38
 
    remote,
39
 
    repository,
40
 
    revision as _mod_revision,
41
 
    rio,
42
 
    tag as _mod_tag,
43
 
    transport,
44
 
    ui,
45
 
    urlutils,
46
 
    vf_search,
 
25
        bzrdir,
 
26
        cache_utf8,
 
27
        config as _mod_config,
 
28
        debug,
 
29
        errors,
 
30
        lockdir,
 
31
        lockable_files,
 
32
        repository,
 
33
        revision as _mod_revision,
 
34
        rio,
 
35
        symbol_versioning,
 
36
        transport,
 
37
        tsort,
 
38
        ui,
 
39
        urlutils,
 
40
        )
 
41
from bzrlib.config import BranchConfig, TransportConfig
 
42
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
 
43
from bzrlib.tag import (
 
44
    BasicTags,
 
45
    DisabledTags,
47
46
    )
48
 
from bzrlib.i18n import gettext, ngettext
49
47
""")
50
48
 
51
 
# Explicitly import bzrlib.bzrdir so that the BzrProber
52
 
# is guaranteed to be registered.
53
 
import bzrlib.bzrdir
54
 
 
55
 
from bzrlib import (
56
 
    bzrdir,
57
 
    controldir,
58
 
    )
59
 
from bzrlib.decorators import (
60
 
    needs_read_lock,
61
 
    needs_write_lock,
62
 
    only_raises,
63
 
    )
64
 
from bzrlib.hooks import Hooks
 
49
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
50
from bzrlib.hooks import HookPoint, Hooks
65
51
from bzrlib.inter import InterObject
66
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
52
from bzrlib.lock import _RelockDebugMixin
67
53
from bzrlib import registry
68
54
from bzrlib.symbol_versioning import (
69
55
    deprecated_in,
72
58
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
73
59
 
74
60
 
75
 
class Branch(controldir.ControlComponent):
 
61
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
 
62
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
 
63
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
 
64
 
 
65
 
 
66
# TODO: Maybe include checks for common corruption of newlines, etc?
 
67
 
 
68
# TODO: Some operations like log might retrieve the same revisions
 
69
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
70
# cache in memory to make this faster.  In general anything can be
 
71
# cached in memory between lock and unlock operations. .. nb thats
 
72
# what the transaction identity map provides
 
73
 
 
74
 
 
75
######################################################################
 
76
# branch objects
 
77
 
 
78
class Branch(object):
76
79
    """Branch holding a history of revisions.
77
80
 
78
 
    :ivar base:
79
 
        Base directory/url of the branch; using control_url and
80
 
        control_transport is more standardized.
81
 
    :ivar hooks: An instance of BranchHooks.
82
 
    :ivar _master_branch_cache: cached result of get_master_branch, see
83
 
        _clear_cached_state.
 
81
    base
 
82
        Base directory/url of the branch.
 
83
 
 
84
    hooks: An instance of BranchHooks.
84
85
    """
85
86
    # this is really an instance variable - FIXME move it there
86
87
    # - RBC 20060112
87
88
    base = None
88
89
 
89
 
    @property
90
 
    def control_transport(self):
91
 
        return self._transport
92
 
 
93
 
    @property
94
 
    def user_transport(self):
95
 
        return self.bzrdir.user_transport
96
 
 
97
 
    def __init__(self, possible_transports=None):
 
90
    def __init__(self, *ignored, **ignored_too):
98
91
        self.tags = self._format.make_tags(self)
99
92
        self._revision_history_cache = None
100
93
        self._revision_id_to_revno_cache = None
101
94
        self._partial_revision_id_to_revno_cache = {}
102
95
        self._partial_revision_history_cache = []
103
 
        self._tags_bytes = None
104
96
        self._last_revision_info_cache = None
105
 
        self._master_branch_cache = None
106
97
        self._merge_sorted_revisions_cache = None
107
 
        self._open_hook(possible_transports)
 
98
        self._open_hook()
108
99
        hooks = Branch.hooks['open']
109
100
        for hook in hooks:
110
101
            hook(self)
111
102
 
112
 
    def _open_hook(self, possible_transports):
 
103
    def _open_hook(self):
113
104
        """Called by init to allow simpler extension of the base class."""
114
105
 
115
 
    def _activate_fallback_location(self, url, possible_transports):
 
106
    def _activate_fallback_location(self, url):
116
107
        """Activate the branch/repository from url as a fallback repository."""
117
 
        for existing_fallback_repo in self.repository._fallback_repositories:
118
 
            if existing_fallback_repo.user_url == url:
119
 
                # This fallback is already configured.  This probably only
120
 
                # happens because ControlDir.sprout is a horrible mess.  To avoid
121
 
                # confusing _unstack we don't add this a second time.
122
 
                mutter('duplicate activation of fallback %r on %r', url, self)
123
 
                return
124
 
        repo = self._get_fallback_repository(url, possible_transports)
 
108
        repo = self._get_fallback_repository(url)
125
109
        if repo.has_same_location(self.repository):
126
 
            raise errors.UnstackableLocationError(self.user_url, url)
 
110
            raise errors.UnstackableLocationError(self.base, url)
127
111
        self.repository.add_fallback_repository(repo)
128
112
 
129
113
    def break_lock(self):
181
165
        For instance, if the branch is at URL/.bzr/branch,
182
166
        Branch.open(URL) -> a Branch instance.
183
167
        """
184
 
        control = controldir.ControlDir.open(base,
185
 
            possible_transports=possible_transports, _unsupported=_unsupported)
186
 
        return control.open_branch(unsupported=_unsupported,
187
 
            possible_transports=possible_transports)
 
168
        control = bzrdir.BzrDir.open(base, _unsupported,
 
169
                                     possible_transports=possible_transports)
 
170
        return control.open_branch(_unsupported)
188
171
 
189
172
    @staticmethod
190
 
    def open_from_transport(transport, name=None, _unsupported=False,
191
 
            possible_transports=None):
 
173
    def open_from_transport(transport, _unsupported=False):
192
174
        """Open the branch rooted at transport"""
193
 
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
194
 
        return control.open_branch(name=name, unsupported=_unsupported,
195
 
            possible_transports=possible_transports)
 
175
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
 
176
        return control.open_branch(_unsupported)
196
177
 
197
178
    @staticmethod
198
179
    def open_containing(url, possible_transports=None):
206
187
        format, UnknownFormatError or UnsupportedFormatError are raised.
207
188
        If there is one, it is returned, along with the unused portion of url.
208
189
        """
209
 
        control, relpath = controldir.ControlDir.open_containing(url,
 
190
        control, relpath = bzrdir.BzrDir.open_containing(url,
210
191
                                                         possible_transports)
211
 
        branch = control.open_branch(possible_transports=possible_transports)
212
 
        return (branch, relpath)
 
192
        return control.open_branch(), relpath
213
193
 
214
194
    def _push_should_merge_tags(self):
215
195
        """Should _basic_push merge this branch's tags into the target?
220
200
        return self.supports_tags() and self.tags.get_tag_dict()
221
201
 
222
202
    def get_config(self):
223
 
        """Get a bzrlib.config.BranchConfig for this Branch.
224
 
 
225
 
        This can then be used to get and set configuration options for the
226
 
        branch.
227
 
 
228
 
        :return: A bzrlib.config.BranchConfig.
229
 
        """
230
 
        return _mod_config.BranchConfig(self)
231
 
 
232
 
    def get_config_stack(self):
233
 
        """Get a bzrlib.config.BranchStack for this Branch.
234
 
 
235
 
        This can then be used to get and set configuration options for the
236
 
        branch.
237
 
 
238
 
        :return: A bzrlib.config.BranchStack.
239
 
        """
240
 
        return _mod_config.BranchStack(self)
 
203
        return BranchConfig(self)
241
204
 
242
205
    def _get_config(self):
243
206
        """Get the concrete config for just the config in this branch.
251
214
        """
252
215
        raise NotImplementedError(self._get_config)
253
216
 
254
 
    def _get_fallback_repository(self, url, possible_transports):
 
217
    def _get_fallback_repository(self, url):
255
218
        """Get the repository we fallback to at url."""
256
219
        url = urlutils.join(self.base, url)
257
 
        a_branch = Branch.open(url, possible_transports=possible_transports)
258
 
        return a_branch.repository
 
220
        a_bzrdir = bzrdir.BzrDir.open(url,
 
221
            possible_transports=[self.bzrdir.root_transport])
 
222
        return a_bzrdir.open_branch().repository
259
223
 
260
 
    @needs_read_lock
261
224
    def _get_tags_bytes(self):
262
225
        """Get the bytes of a serialised tags dict.
263
226
 
270
233
        :return: The bytes of the tags file.
271
234
        :seealso: Branch._set_tags_bytes.
272
235
        """
273
 
        if self._tags_bytes is None:
274
 
            self._tags_bytes = self._transport.get_bytes('tags')
275
 
        return self._tags_bytes
 
236
        return self._transport.get_bytes('tags')
276
237
 
277
238
    def _get_nick(self, local=False, possible_transports=None):
278
239
        config = self.get_config()
280
241
        if not local and not config.has_explicit_nickname():
281
242
            try:
282
243
                master = self.get_master_branch(possible_transports)
283
 
                if master and self.user_url == master.user_url:
284
 
                    raise errors.RecursiveBind(self.user_url)
285
244
                if master is not None:
286
245
                    # return the master branch value
287
246
                    return master.nick
288
 
            except errors.RecursiveBind, e:
289
 
                raise e
290
247
            except errors.BzrError, e:
291
248
                # Silently fall back to local implicit nick if the master is
292
249
                # unavailable
329
286
        new_history.reverse()
330
287
        return new_history
331
288
 
332
 
    def lock_write(self, token=None):
333
 
        """Lock the branch for write operations.
334
 
 
335
 
        :param token: A token to permit reacquiring a previously held and
336
 
            preserved lock.
337
 
        :return: A BranchWriteLockResult.
338
 
        """
 
289
    def lock_write(self):
339
290
        raise NotImplementedError(self.lock_write)
340
291
 
341
292
    def lock_read(self):
342
 
        """Lock the branch for read operations.
343
 
 
344
 
        :return: A bzrlib.lock.LogicalLockResult.
345
 
        """
346
293
        raise NotImplementedError(self.lock_read)
347
294
 
348
295
    def unlock(self):
469
416
            after. If None, the rest of history is included.
470
417
        :param stop_rule: if stop_revision_id is not None, the precise rule
471
418
            to use for termination:
472
 
 
473
419
            * 'exclude' - leave the stop revision out of the result (default)
474
420
            * 'include' - the stop revision is the last item in the result
475
421
            * 'with-merges' - include the stop revision and all of its
476
422
              merged revisions in the result
477
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
478
 
              that are in both ancestries
479
423
        :param direction: either 'reverse' or 'forward':
480
 
 
481
424
            * reverse means return the start_revision_id first, i.e.
482
425
              start at the most recent revision and go backwards in history
483
426
            * forward returns tuples in the opposite order to reverse.
504
447
        # start_revision_id.
505
448
        if self._merge_sorted_revisions_cache is None:
506
449
            last_revision = self.last_revision()
507
 
            known_graph = self.repository.get_known_graph_ancestry(
508
 
                [last_revision])
 
450
            last_key = (last_revision,)
 
451
            known_graph = self.repository.revisions.get_known_graph_ancestry(
 
452
                [last_key])
509
453
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
510
 
                last_revision)
 
454
                last_key)
511
455
        filtered = self._filter_merge_sorted_revisions(
512
456
            self._merge_sorted_revisions_cache, start_revision_id,
513
457
            stop_revision_id, stop_rule)
514
 
        # Make sure we don't return revisions that are not part of the
515
 
        # start_revision_id ancestry.
516
 
        filtered = self._filter_start_non_ancestors(filtered)
517
458
        if direction == 'reverse':
518
459
            return filtered
519
460
        if direction == 'forward':
527
468
        rev_iter = iter(merge_sorted_revisions)
528
469
        if start_revision_id is not None:
529
470
            for node in rev_iter:
530
 
                rev_id = node.key
 
471
                rev_id = node.key[-1]
531
472
                if rev_id != start_revision_id:
532
473
                    continue
533
474
                else:
534
475
                    # The decision to include the start or not
535
476
                    # depends on the stop_rule if a stop is provided
536
477
                    # so pop this node back into the iterator
537
 
                    rev_iter = itertools.chain(iter([node]), rev_iter)
 
478
                    rev_iter = chain(iter([node]), rev_iter)
538
479
                    break
539
480
        if stop_revision_id is None:
540
481
            # Yield everything
541
482
            for node in rev_iter:
542
 
                rev_id = node.key
 
483
                rev_id = node.key[-1]
543
484
                yield (rev_id, node.merge_depth, node.revno,
544
485
                       node.end_of_merge)
545
486
        elif stop_rule == 'exclude':
546
487
            for node in rev_iter:
547
 
                rev_id = node.key
 
488
                rev_id = node.key[-1]
548
489
                if rev_id == stop_revision_id:
549
490
                    return
550
491
                yield (rev_id, node.merge_depth, node.revno,
551
492
                       node.end_of_merge)
552
493
        elif stop_rule == 'include':
553
494
            for node in rev_iter:
554
 
                rev_id = node.key
 
495
                rev_id = node.key[-1]
555
496
                yield (rev_id, node.merge_depth, node.revno,
556
497
                       node.end_of_merge)
557
498
                if rev_id == stop_revision_id:
558
499
                    return
559
 
        elif stop_rule == 'with-merges-without-common-ancestry':
560
 
            # We want to exclude all revisions that are already part of the
561
 
            # stop_revision_id ancestry.
562
 
            graph = self.repository.get_graph()
563
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
564
 
                                                    [stop_revision_id])
565
 
            for node in rev_iter:
566
 
                rev_id = node.key
567
 
                if rev_id not in ancestors:
568
 
                    continue
569
 
                yield (rev_id, node.merge_depth, node.revno,
570
 
                       node.end_of_merge)
571
500
        elif stop_rule == 'with-merges':
572
501
            stop_rev = self.repository.get_revision(stop_revision_id)
573
502
            if stop_rev.parent_ids:
574
503
                left_parent = stop_rev.parent_ids[0]
575
504
            else:
576
505
                left_parent = _mod_revision.NULL_REVISION
577
 
            # left_parent is the actual revision we want to stop logging at,
578
 
            # since we want to show the merged revisions after the stop_rev too
579
 
            reached_stop_revision_id = False
580
 
            revision_id_whitelist = []
581
506
            for node in rev_iter:
582
 
                rev_id = node.key
 
507
                rev_id = node.key[-1]
583
508
                if rev_id == left_parent:
584
 
                    # reached the left parent after the stop_revision
585
509
                    return
586
 
                if (not reached_stop_revision_id or
587
 
                        rev_id in revision_id_whitelist):
588
 
                    yield (rev_id, node.merge_depth, node.revno,
 
510
                yield (rev_id, node.merge_depth, node.revno,
589
511
                       node.end_of_merge)
590
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
591
 
                        # only do the merged revs of rev_id from now on
592
 
                        rev = self.repository.get_revision(rev_id)
593
 
                        if rev.parent_ids:
594
 
                            reached_stop_revision_id = True
595
 
                            revision_id_whitelist.extend(rev.parent_ids)
596
512
        else:
597
513
            raise ValueError('invalid stop_rule %r' % stop_rule)
598
514
 
599
 
    def _filter_start_non_ancestors(self, rev_iter):
600
 
        # If we started from a dotted revno, we want to consider it as a tip
601
 
        # and don't want to yield revisions that are not part of its
602
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
603
 
        # uninteresting descendants of the first parent of our tip before the
604
 
        # tip itself.
605
 
        first = rev_iter.next()
606
 
        (rev_id, merge_depth, revno, end_of_merge) = first
607
 
        yield first
608
 
        if not merge_depth:
609
 
            # We start at a mainline revision so by definition, all others
610
 
            # revisions in rev_iter are ancestors
611
 
            for node in rev_iter:
612
 
                yield node
613
 
 
614
 
        clean = False
615
 
        whitelist = set()
616
 
        pmap = self.repository.get_parent_map([rev_id])
617
 
        parents = pmap.get(rev_id, [])
618
 
        if parents:
619
 
            whitelist.update(parents)
620
 
        else:
621
 
            # If there is no parents, there is nothing of interest left
622
 
 
623
 
            # FIXME: It's hard to test this scenario here as this code is never
624
 
            # called in that case. -- vila 20100322
625
 
            return
626
 
 
627
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
628
 
            if not clean:
629
 
                if rev_id in whitelist:
630
 
                    pmap = self.repository.get_parent_map([rev_id])
631
 
                    parents = pmap.get(rev_id, [])
632
 
                    whitelist.remove(rev_id)
633
 
                    whitelist.update(parents)
634
 
                    if merge_depth == 0:
635
 
                        # We've reached the mainline, there is nothing left to
636
 
                        # filter
637
 
                        clean = True
638
 
                else:
639
 
                    # A revision that is not part of the ancestry of our
640
 
                    # starting revision.
641
 
                    continue
642
 
            yield (rev_id, merge_depth, revno, end_of_merge)
643
 
 
644
515
    def leave_lock_in_place(self):
645
516
        """Tell this branch object not to release the physical lock when this
646
517
        object is unlocked.
663
534
        :param other: The branch to bind to
664
535
        :type other: Branch
665
536
        """
666
 
        raise errors.UpgradeRequired(self.user_url)
667
 
 
668
 
    def get_append_revisions_only(self):
669
 
        """Whether it is only possible to append revisions to the history.
670
 
        """
671
 
        if not self._format.supports_set_append_revisions_only():
672
 
            return False
673
 
        return self.get_config_stack().get('append_revisions_only')
 
537
        raise errors.UpgradeRequired(self.base)
674
538
 
675
539
    def set_append_revisions_only(self, enabled):
676
540
        if not self._format.supports_set_append_revisions_only():
677
 
            raise errors.UpgradeRequired(self.user_url)
678
 
        self.get_config_stack().set('append_revisions_only', enabled)
 
541
            raise errors.UpgradeRequired(self.base)
 
542
        if enabled:
 
543
            value = 'True'
 
544
        else:
 
545
            value = 'False'
 
546
        self.get_config().set_user_option('append_revisions_only', value,
 
547
            warn_masked=True)
679
548
 
680
549
    def set_reference_info(self, file_id, tree_path, branch_location):
681
550
        """Set the branch location to use for a tree reference."""
686
555
        raise errors.UnsupportedOperation(self.get_reference_info, self)
687
556
 
688
557
    @needs_write_lock
689
 
    def fetch(self, from_branch, last_revision=None, limit=None):
 
558
    def fetch(self, from_branch, last_revision=None, pb=None):
690
559
        """Copy revisions from from_branch into this branch.
691
560
 
692
561
        :param from_branch: Where to copy from.
693
562
        :param last_revision: What revision to stop at (None for at the end
694
563
                              of the branch.
695
 
        :param limit: Optional rough limit of revisions to fetch
 
564
        :param pb: An optional progress bar to use.
696
565
        :return: None
697
566
        """
698
 
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
567
        if self.base == from_branch.base:
 
568
            return (0, [])
 
569
        if pb is not None:
 
570
            symbol_versioning.warn(
 
571
                symbol_versioning.deprecated_in((1, 14, 0))
 
572
                % "pb parameter to fetch()")
 
573
        from_branch.lock_read()
 
574
        try:
 
575
            if last_revision is None:
 
576
                last_revision = from_branch.last_revision()
 
577
                last_revision = _mod_revision.ensure_null(last_revision)
 
578
            return self.repository.fetch(from_branch.repository,
 
579
                                         revision_id=last_revision,
 
580
                                         pb=pb)
 
581
        finally:
 
582
            from_branch.unlock()
699
583
 
700
584
    def get_bound_location(self):
701
585
        """Return the URL of the branch we are bound to.
708
592
    def get_old_bound_location(self):
709
593
        """Return the URL of the branch we used to be bound to
710
594
        """
711
 
        raise errors.UpgradeRequired(self.user_url)
 
595
        raise errors.UpgradeRequired(self.base)
712
596
 
713
 
    def get_commit_builder(self, parents, config_stack=None, timestamp=None,
 
597
    def get_commit_builder(self, parents, config=None, timestamp=None,
714
598
                           timezone=None, committer=None, revprops=None,
715
 
                           revision_id=None, lossy=False):
 
599
                           revision_id=None):
716
600
        """Obtain a CommitBuilder for this branch.
717
601
 
718
602
        :param parents: Revision ids of the parents of the new revision.
722
606
        :param committer: Optional committer to set for commit.
723
607
        :param revprops: Optional dictionary of revision properties.
724
608
        :param revision_id: Optional revision id.
725
 
        :param lossy: Whether to discard data that can not be natively
726
 
            represented, when pushing to a foreign VCS 
727
609
        """
728
610
 
729
 
        if config_stack is None:
730
 
            config_stack = self.get_config_stack()
 
611
        if config is None:
 
612
            config = self.get_config()
731
613
 
732
 
        return self.repository.get_commit_builder(self, parents, config_stack,
733
 
            timestamp, timezone, committer, revprops, revision_id,
734
 
            lossy)
 
614
        return self.repository.get_commit_builder(self, parents, config,
 
615
            timestamp, timezone, committer, revprops, revision_id)
735
616
 
736
617
    def get_master_branch(self, possible_transports=None):
737
618
        """Return the branch we are bound to.
740
621
        """
741
622
        return None
742
623
 
743
 
    @deprecated_method(deprecated_in((2, 5, 0)))
744
624
    def get_revision_delta(self, revno):
745
625
        """Return the delta for one revision.
746
626
 
747
627
        The delta is relative to its mainline predecessor, or the
748
628
        empty tree for revision 1.
749
629
        """
750
 
        try:
751
 
            revid = self.get_rev_id(revno)
752
 
        except errors.NoSuchRevision:
 
630
        rh = self.revision_history()
 
631
        if not (1 <= revno <= len(rh)):
753
632
            raise errors.InvalidRevisionNumber(revno)
754
 
        return self.repository.get_revision_delta(revid)
 
633
        return self.repository.get_revision_delta(rh[revno-1])
755
634
 
756
635
    def get_stacked_on_url(self):
757
636
        """Get the URL this branch is stacked against.
766
645
        """Print `file` to stdout."""
767
646
        raise NotImplementedError(self.print_file)
768
647
 
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
 
        (last_revno, last_revid) = self.last_revision_info()
789
 
        known_revision_ids = [
790
 
            (last_revid, last_revno),
791
 
            (_mod_revision.NULL_REVISION, 0),
792
 
            ]
793
 
        if last_rev is not None:
794
 
            if not graph.is_ancestor(last_rev, revision_id):
795
 
                # our previous tip is not merged into stop_revision
796
 
                raise errors.DivergedBranches(self, other_branch)
797
 
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
798
 
        self.set_last_revision_info(revno, revision_id)
 
648
    def set_revision_history(self, rev_history):
 
649
        raise NotImplementedError(self.set_revision_history)
799
650
 
800
651
    @needs_write_lock
801
652
    def set_parent(self, url):
825
676
            stacking.
826
677
        """
827
678
        if not self._format.supports_stacking():
828
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
679
            raise errors.UnstackableBranchFormat(self._format, self.base)
829
680
        # XXX: Changing from one fallback repository to another does not check
830
681
        # that all the data you need is present in the new fallback.
831
682
        # Possibly it should.
838
689
                return
839
690
            self._unstack()
840
691
        else:
841
 
            self._activate_fallback_location(url,
842
 
                possible_transports=[self.bzrdir.root_transport])
 
692
            self._activate_fallback_location(url)
843
693
        # write this out after the repository is stacked to avoid setting a
844
694
        # stacked config that doesn't work.
845
695
        self._set_config_location('stacked_on_location', url)
846
696
 
847
697
    def _unstack(self):
848
698
        """Change a branch to be unstacked, copying data as needed.
849
 
 
 
699
        
850
700
        Don't call this directly, use set_stacked_on_url(None).
851
701
        """
852
702
        pb = ui.ui_factory.nested_progress_bar()
853
703
        try:
854
 
            pb.update(gettext("Unstacking"))
 
704
            pb.update("Unstacking")
855
705
            # The basic approach here is to fetch the tip of the branch,
856
706
            # including all available ghosts, from the existing stacked
857
707
            # repository into a new repository object without the fallbacks. 
861
711
            old_repository = self.repository
862
712
            if len(old_repository._fallback_repositories) != 1:
863
713
                raise AssertionError("can't cope with fallback repositories "
864
 
                    "of %r (fallbacks: %r)" % (old_repository,
865
 
                        old_repository._fallback_repositories))
866
 
            # Open the new repository object.
867
 
            # Repositories don't offer an interface to remove fallback
868
 
            # repositories today; take the conceptually simpler option and just
869
 
            # reopen it.  We reopen it starting from the URL so that we
870
 
            # get a separate connection for RemoteRepositories and can
871
 
            # stream from one of them to the other.  This does mean doing
872
 
            # separate SSH connection setup, but unstacking is not a
873
 
            # common operation so it's tolerable.
874
 
            new_bzrdir = controldir.ControlDir.open(
875
 
                self.bzrdir.root_transport.base)
876
 
            new_repository = new_bzrdir.find_repository()
877
 
            if new_repository._fallback_repositories:
878
 
                raise AssertionError("didn't expect %r to have "
879
 
                    "fallback_repositories"
880
 
                    % (self.repository,))
881
 
            # Replace self.repository with the new repository.
882
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
883
 
            # lock count) of self.repository to the new repository.
884
 
            lock_token = old_repository.lock_write().repository_token
885
 
            self.repository = new_repository
886
 
            if isinstance(self, remote.RemoteBranch):
887
 
                # Remote branches can have a second reference to the old
888
 
                # repository that need to be replaced.
889
 
                if self._real_branch is not None:
890
 
                    self._real_branch.repository = new_repository
891
 
            self.repository.lock_write(token=lock_token)
892
 
            if lock_token is not None:
893
 
                old_repository.leave_lock_in_place()
 
714
                    "of %r" % (self.repository,))
 
715
            # unlock it, including unlocking the fallback
894
716
            old_repository.unlock()
895
 
            if lock_token is not None:
896
 
                # XXX: self.repository.leave_lock_in_place() before this
897
 
                # function will not be preserved.  Fortunately that doesn't
898
 
                # affect the current default format (2a), and would be a
899
 
                # corner-case anyway.
900
 
                #  - Andrew Bennetts, 2010/06/30
901
 
                self.repository.dont_leave_lock_in_place()
902
 
            old_lock_count = 0
903
 
            while True:
904
 
                try:
905
 
                    old_repository.unlock()
906
 
                except errors.LockNotHeld:
907
 
                    break
908
 
                old_lock_count += 1
909
 
            if old_lock_count == 0:
910
 
                raise AssertionError(
911
 
                    'old_repository should have been locked at least once.')
912
 
            for i in range(old_lock_count-1):
 
717
            old_repository.lock_read()
 
718
            try:
 
719
                # Repositories don't offer an interface to remove fallback
 
720
                # repositories today; take the conceptually simpler option and just
 
721
                # reopen it.  We reopen it starting from the URL so that we
 
722
                # get a separate connection for RemoteRepositories and can
 
723
                # stream from one of them to the other.  This does mean doing
 
724
                # separate SSH connection setup, but unstacking is not a
 
725
                # common operation so it's tolerable.
 
726
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
727
                new_repository = new_bzrdir.find_repository()
 
728
                self.repository = new_repository
 
729
                if self.repository._fallback_repositories:
 
730
                    raise AssertionError("didn't expect %r to have "
 
731
                        "fallback_repositories"
 
732
                        % (self.repository,))
 
733
                # this is not paired with an unlock because it's just restoring
 
734
                # the previous state; the lock's released when set_stacked_on_url
 
735
                # returns
913
736
                self.repository.lock_write()
914
 
            # Fetch from the old repository into the new.
915
 
            old_repository.lock_read()
916
 
            try:
917
737
                # XXX: If you unstack a branch while it has a working tree
918
738
                # with a pending merge, the pending-merged revisions will no
919
739
                # longer be present.  You can (probably) revert and remerge.
920
 
                try:
921
 
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
922
 
                except errors.TagsNotSupported:
923
 
                    tags_to_fetch = set()
924
 
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
925
 
                    old_repository, required_ids=[self.last_revision()],
926
 
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
927
 
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
740
                #
 
741
                # XXX: This only fetches up to the tip of the repository; it
 
742
                # doesn't bring across any tags.  That's fairly consistent
 
743
                # with how branch works, but perhaps not ideal.
 
744
                self.repository.fetch(old_repository,
 
745
                    revision_id=self.last_revision(),
 
746
                    find_ghosts=True)
928
747
            finally:
929
748
                old_repository.unlock()
930
749
        finally:
935
754
 
936
755
        :seealso: Branch._get_tags_bytes.
937
756
        """
938
 
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
939
 
        op.add_cleanup(self.lock_write().unlock)
940
 
        return op.run_simple(bytes)
941
 
 
942
 
    def _set_tags_bytes_locked(self, bytes):
943
 
        self._tags_bytes = bytes
944
 
        return self._transport.put_bytes('tags', bytes)
 
757
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
758
            'tags', bytes)
945
759
 
946
760
    def _cache_revision_history(self, rev_history):
947
761
        """Set the cached revision history to rev_history.
968
782
        This means the next call to revision_history will need to call
969
783
        _gen_revision_history.
970
784
 
971
 
        This API is semi-public; it is only for use by subclasses, all other
972
 
        code should consider it to be private.
 
785
        This API is semi-public; it only for use by subclasses, all other code
 
786
        should consider it to be private.
973
787
        """
974
788
        self._revision_history_cache = None
975
789
        self._revision_id_to_revno_cache = None
976
790
        self._last_revision_info_cache = None
977
 
        self._master_branch_cache = None
978
791
        self._merge_sorted_revisions_cache = None
979
792
        self._partial_revision_history_cache = []
980
793
        self._partial_revision_id_to_revno_cache = {}
981
 
        self._tags_bytes = None
982
794
 
983
795
    def _gen_revision_history(self):
984
796
        """Return sequence of revision hashes on to this branch.
995
807
        """
996
808
        raise NotImplementedError(self._gen_revision_history)
997
809
 
998
 
    def _revision_history(self):
 
810
    @needs_read_lock
 
811
    def revision_history(self):
 
812
        """Return sequence of revision ids on this branch.
 
813
 
 
814
        This method will cache the revision history for as long as it is safe to
 
815
        do so.
 
816
        """
999
817
        if 'evil' in debug.debug_flags:
1000
818
            mutter_callsite(3, "revision_history scales with history.")
1001
819
        if self._revision_history_cache is not None:
1015
833
 
1016
834
    def unbind(self):
1017
835
        """Older format branches cannot bind or unbind."""
1018
 
        raise errors.UpgradeRequired(self.user_url)
 
836
        raise errors.UpgradeRequired(self.base)
1019
837
 
1020
838
    def last_revision(self):
1021
839
        """Return last revision id, or NULL_REVISION."""
1028
846
        :return: A tuple (revno, revision_id).
1029
847
        """
1030
848
        if self._last_revision_info_cache is None:
1031
 
            self._last_revision_info_cache = self._read_last_revision_info()
 
849
            self._last_revision_info_cache = self._last_revision_info()
1032
850
        return self._last_revision_info_cache
1033
851
 
1034
 
    def _read_last_revision_info(self):
1035
 
        raise NotImplementedError(self._read_last_revision_info)
1036
 
 
1037
 
    def import_last_revision_info_and_tags(self, source, revno, revid,
1038
 
                                           lossy=False):
 
852
    def _last_revision_info(self):
 
853
        rh = self.revision_history()
 
854
        revno = len(rh)
 
855
        if revno:
 
856
            return (revno, rh[-1])
 
857
        else:
 
858
            return (0, _mod_revision.NULL_REVISION)
 
859
 
 
860
    @deprecated_method(deprecated_in((1, 6, 0)))
 
861
    def missing_revisions(self, other, stop_revision=None):
 
862
        """Return a list of new revisions that would perfectly fit.
 
863
 
 
864
        If self and other have not diverged, return a list of the revisions
 
865
        present in other, but missing from self.
 
866
        """
 
867
        self_history = self.revision_history()
 
868
        self_len = len(self_history)
 
869
        other_history = other.revision_history()
 
870
        other_len = len(other_history)
 
871
        common_index = min(self_len, other_len) -1
 
872
        if common_index >= 0 and \
 
873
            self_history[common_index] != other_history[common_index]:
 
874
            raise errors.DivergedBranches(self, other)
 
875
 
 
876
        if stop_revision is None:
 
877
            stop_revision = other_len
 
878
        else:
 
879
            if stop_revision > other_len:
 
880
                raise errors.NoSuchRevision(self, stop_revision)
 
881
        return other_history[self_len:stop_revision]
 
882
 
 
883
    @needs_write_lock
 
884
    def update_revisions(self, other, stop_revision=None, overwrite=False,
 
885
                         graph=None):
 
886
        """Pull in new perfect-fit revisions.
 
887
 
 
888
        :param other: Another Branch to pull from
 
889
        :param stop_revision: Updated until the given revision
 
890
        :param overwrite: Always set the branch pointer, rather than checking
 
891
            to see if it is a proper descendant.
 
892
        :param graph: A Graph object that can be used to query history
 
893
            information. This can be None.
 
894
        :return: None
 
895
        """
 
896
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
897
            overwrite, graph)
 
898
 
 
899
    def import_last_revision_info(self, source_repo, revno, revid):
1039
900
        """Set the last revision info, importing from another repo if necessary.
1040
901
 
1041
902
        This is used by the bound branch code to upload a revision to
1042
903
        the master branch first before updating the tip of the local branch.
1043
 
        Revisions referenced by source's tags are also transferred.
1044
904
 
1045
 
        :param source: Source branch to optionally fetch from
 
905
        :param source_repo: Source repository to optionally fetch from
1046
906
        :param revno: Revision number of the new tip
1047
907
        :param revid: Revision id of the new tip
1048
 
        :param lossy: Whether to discard metadata that can not be
1049
 
            natively represented
1050
 
        :return: Tuple with the new revision number and revision id
1051
 
            (should only be different from the arguments when lossy=True)
1052
908
        """
1053
 
        if not self.repository.has_same_location(source.repository):
1054
 
            self.fetch(source, revid)
 
909
        if not self.repository.has_same_location(source_repo):
 
910
            self.repository.fetch(source_repo, revision_id=revid)
1055
911
        self.set_last_revision_info(revno, revid)
1056
 
        return (revno, revid)
1057
912
 
1058
913
    def revision_id_to_revno(self, revision_id):
1059
914
        """Given a revision id, return its revno"""
1060
915
        if _mod_revision.is_null(revision_id):
1061
916
            return 0
1062
 
        history = self._revision_history()
 
917
        history = self.revision_history()
1063
918
        try:
1064
919
            return history.index(revision_id) + 1
1065
920
        except ValueError:
1080
935
            self._extend_partial_history(distance_from_last)
1081
936
        return self._partial_revision_history_cache[distance_from_last]
1082
937
 
 
938
    @needs_write_lock
1083
939
    def pull(self, source, overwrite=False, stop_revision=None,
1084
940
             possible_transports=None, *args, **kwargs):
1085
941
        """Mirror source into this branch.
1092
948
            stop_revision=stop_revision,
1093
949
            possible_transports=possible_transports, *args, **kwargs)
1094
950
 
1095
 
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1096
 
            *args, **kwargs):
 
951
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
952
        **kwargs):
1097
953
        """Mirror this branch into target.
1098
954
 
1099
955
        This branch is considered to be 'local', having low latency.
1100
956
        """
1101
957
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1102
 
            lossy, *args, **kwargs)
 
958
            *args, **kwargs)
 
959
 
 
960
    def lossy_push(self, target, stop_revision=None):
 
961
        """Push deltas into another branch.
 
962
 
 
963
        :note: This does not, like push, retain the revision ids from 
 
964
            the source branch and will, rather than adding bzr-specific 
 
965
            metadata, push only those semantics of the revision that can be 
 
966
            natively represented by this branch' VCS.
 
967
 
 
968
        :param target: Target branch
 
969
        :param stop_revision: Revision to push, defaults to last revision.
 
970
        :return: BranchPushResult with an extra member revidmap: 
 
971
            A dictionary mapping revision ids from the target branch 
 
972
            to new revision ids in the target branch, for each 
 
973
            revision that was pushed.
 
974
        """
 
975
        inter = InterBranch.get(self, target)
 
976
        lossy_push = getattr(inter, "lossy_push", None)
 
977
        if lossy_push is None:
 
978
            raise errors.LossyPushToSameVCS(self, target)
 
979
        return lossy_push(stop_revision)
1103
980
 
1104
981
    def basis_tree(self):
1105
982
        """Return `Tree` object for last revision."""
1122
999
        try:
1123
1000
            return urlutils.join(self.base[:-1], parent)
1124
1001
        except errors.InvalidURLJoin, e:
1125
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
1002
            raise errors.InaccessibleParent(parent, self.base)
1126
1003
 
1127
1004
    def _get_parent_location(self):
1128
1005
        raise NotImplementedError(self._get_parent_location)
1130
1007
    def _set_config_location(self, name, url, config=None,
1131
1008
                             make_relative=False):
1132
1009
        if config is None:
1133
 
            config = self.get_config_stack()
 
1010
            config = self.get_config()
1134
1011
        if url is None:
1135
1012
            url = ''
1136
1013
        elif make_relative:
1137
1014
            url = urlutils.relative_url(self.base, url)
1138
 
        config.set(name, url)
 
1015
        config.set_user_option(name, url, warn_masked=True)
1139
1016
 
1140
1017
    def _get_config_location(self, name, config=None):
1141
1018
        if config is None:
1142
 
            config = self.get_config_stack()
1143
 
        location = config.get(name)
 
1019
            config = self.get_config()
 
1020
        location = config.get_user_option(name)
1144
1021
        if location == '':
1145
1022
            location = None
1146
1023
        return location
1147
1024
 
1148
1025
    def get_child_submit_format(self):
1149
1026
        """Return the preferred format of submissions to this branch."""
1150
 
        return self.get_config_stack().get('child_submit_format')
 
1027
        return self.get_config().get_user_option("child_submit_format")
1151
1028
 
1152
1029
    def get_submit_branch(self):
1153
1030
        """Return the submit location of the branch.
1156
1033
        pattern is that the user can override it by specifying a
1157
1034
        location.
1158
1035
        """
1159
 
        return self.get_config_stack().get('submit_branch')
 
1036
        return self.get_config().get_user_option('submit_branch')
1160
1037
 
1161
1038
    def set_submit_branch(self, location):
1162
1039
        """Return the submit location of the branch.
1165
1042
        pattern is that the user can override it by specifying a
1166
1043
        location.
1167
1044
        """
1168
 
        self.get_config_stack().set('submit_branch', location)
 
1045
        self.get_config().set_user_option('submit_branch', location,
 
1046
            warn_masked=True)
1169
1047
 
1170
1048
    def get_public_branch(self):
1171
1049
        """Return the public location of the branch.
1184
1062
        self._set_config_location('public_branch', location)
1185
1063
 
1186
1064
    def get_push_location(self):
1187
 
        """Return None or the location to push this branch to."""
1188
 
        return self.get_config_stack().get('push_location')
 
1065
        """Return the None or the location to push this branch to."""
 
1066
        push_loc = self.get_config().get_user_option('push_location')
 
1067
        return push_loc
1189
1068
 
1190
1069
    def set_push_location(self, location):
1191
1070
        """Set a new push location for this branch."""
1211
1090
        params = ChangeBranchTipParams(
1212
1091
            self, old_revno, new_revno, old_revid, new_revid)
1213
1092
        for hook in hooks:
1214
 
            hook(params)
 
1093
            try:
 
1094
                hook(params)
 
1095
            except errors.TipChangeRejected:
 
1096
                raise
 
1097
            except Exception:
 
1098
                exc_info = sys.exc_info()
 
1099
                hook_name = Branch.hooks.get_hook_name(hook)
 
1100
                raise errors.HookFailed(
 
1101
                    'pre_change_branch_tip', hook_name, exc_info)
1215
1102
 
1216
1103
    @needs_write_lock
1217
1104
    def update(self):
1258
1145
        return result
1259
1146
 
1260
1147
    @needs_read_lock
1261
 
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1262
 
            repository=None):
 
1148
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1263
1149
        """Create a new line of development from the branch, into to_bzrdir.
1264
1150
 
1265
1151
        to_bzrdir controls the branch format.
1270
1156
        if (repository_policy is not None and
1271
1157
            repository_policy.requires_stacking()):
1272
1158
            to_bzrdir._format.require_stacking(_skip_repo=True)
1273
 
        result = to_bzrdir.create_branch(repository=repository)
 
1159
        result = to_bzrdir.create_branch()
1274
1160
        result.lock_write()
1275
1161
        try:
1276
1162
            if repository_policy is not None:
1277
1163
                repository_policy.configure_branch(result)
1278
1164
            self.copy_content_into(result, revision_id=revision_id)
1279
 
            master_url = self.get_bound_location()
1280
 
            if master_url is None:
1281
 
                result.set_parent(self.bzrdir.root_transport.base)
1282
 
            else:
1283
 
                result.set_parent(master_url)
 
1165
            result.set_parent(self.bzrdir.root_transport.base)
1284
1166
        finally:
1285
1167
            result.unlock()
1286
1168
        return result
1310
1192
                revno = 1
1311
1193
        destination.set_last_revision_info(revno, revision_id)
1312
1194
 
 
1195
    @needs_read_lock
1313
1196
    def copy_content_into(self, destination, revision_id=None):
1314
1197
        """Copy the content of self into destination.
1315
1198
 
1316
1199
        revision_id: if not None, the revision history in the new branch will
1317
1200
                     be truncated to end with revision_id.
1318
1201
        """
1319
 
        return InterBranch.get(self, destination).copy_content_into(
1320
 
            revision_id=revision_id)
 
1202
        self.update_references(destination)
 
1203
        self._synchronize_history(destination, revision_id)
 
1204
        try:
 
1205
            parent = self.get_parent()
 
1206
        except errors.InaccessibleParent, e:
 
1207
            mutter('parent was not accessible to copy: %s', e)
 
1208
        else:
 
1209
            if parent:
 
1210
                destination.set_parent(parent)
 
1211
        if self._push_should_merge_tags():
 
1212
            self.tags.merge_to(destination.tags)
1321
1213
 
1322
1214
    def update_references(self, target):
1323
1215
        if not getattr(self._format, 'supports_reference_locations', False):
1360
1252
        # TODO: We should probably also check that self.revision_history
1361
1253
        # matches the repository for older branch formats.
1362
1254
        # If looking for the code that cross-checks repository parents against
1363
 
        # the Graph.iter_lefthand_ancestry output, that is now a repository
 
1255
        # the iter_reverse_revision_history output, that is now a repository
1364
1256
        # specific check.
1365
1257
        return result
1366
1258
 
1367
 
    def _get_checkout_format(self, lightweight=False):
 
1259
    def _get_checkout_format(self):
1368
1260
        """Return the most suitable metadir for a checkout of this branch.
1369
1261
        Weaves are used if this branch's repository uses weaves.
1370
1262
        """
1371
 
        format = self.repository.bzrdir.checkout_metadir()
1372
 
        format.set_branch_format(self._format)
 
1263
        if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
 
1264
            from bzrlib.repofmt import weaverepo
 
1265
            format = bzrdir.BzrDirMetaFormat1()
 
1266
            format.repository_format = weaverepo.RepositoryFormat7()
 
1267
        else:
 
1268
            format = self.repository.bzrdir.checkout_metadir()
 
1269
            format.set_branch_format(self._format)
1373
1270
        return format
1374
1271
 
1375
1272
    def create_clone_on_transport(self, to_transport, revision_id=None,
1376
 
        stacked_on=None, create_prefix=False, use_existing_dir=False,
1377
 
        no_tree=None):
 
1273
        stacked_on=None, create_prefix=False, use_existing_dir=False):
1378
1274
        """Create a clone of this branch and its bzrdir.
1379
1275
 
1380
1276
        :param to_transport: The transport to clone onto.
1387
1283
        """
1388
1284
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1389
1285
        # clone call. Or something. 20090224 RBC/spiv.
1390
 
        # XXX: Should this perhaps clone colocated branches as well, 
1391
 
        # rather than just the default branch? 20100319 JRV
1392
1286
        if revision_id is None:
1393
1287
            revision_id = self.last_revision()
1394
1288
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1395
1289
            revision_id=revision_id, stacked_on=stacked_on,
1396
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1397
 
            no_tree=no_tree)
 
1290
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
1398
1291
        return dir_to.open_branch()
1399
1292
 
1400
1293
    def create_checkout(self, to_location, revision_id=None,
1405
1298
        :param to_location: The url to produce the checkout at
1406
1299
        :param revision_id: The revision to check out
1407
1300
        :param lightweight: If True, produce a lightweight checkout, otherwise,
1408
 
            produce a bound branch (heavyweight checkout)
 
1301
        produce a bound branch (heavyweight checkout)
1409
1302
        :param accelerator_tree: A tree which can be used for retrieving file
1410
1303
            contents more quickly than the revision tree, i.e. a workingtree.
1411
1304
            The revision tree will be used for cases where accelerator_tree's
1416
1309
        """
1417
1310
        t = transport.get_transport(to_location)
1418
1311
        t.ensure_base()
1419
 
        format = self._get_checkout_format(lightweight=lightweight)
1420
 
        try:
 
1312
        if lightweight:
 
1313
            format = self._get_checkout_format()
1421
1314
            checkout = format.initialize_on_transport(t)
1422
 
        except errors.AlreadyControlDirError:
1423
 
            # It's fine if the control directory already exists,
1424
 
            # as long as there is no existing branch and working tree.
1425
 
            checkout = controldir.ControlDir.open_from_transport(t)
1426
 
            try:
1427
 
                checkout.open_branch()
1428
 
            except errors.NotBranchError:
1429
 
                pass
1430
 
            else:
1431
 
                raise errors.AlreadyControlDirError(t.base)
1432
 
            if checkout.control_transport.base == self.bzrdir.control_transport.base:
1433
 
                # When checking out to the same control directory,
1434
 
                # always create a lightweight checkout
1435
 
                lightweight = True
1436
 
 
1437
 
        if lightweight:
1438
 
            from_branch = checkout.set_branch_reference(target_branch=self)
 
1315
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1439
1316
        else:
1440
 
            policy = checkout.determine_repository_policy()
1441
 
            repo = policy.acquire_repository()[0]
1442
 
            checkout_branch = checkout.create_branch()
 
1317
            format = self._get_checkout_format()
 
1318
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
 
1319
                to_location, force_new_tree=False, format=format)
 
1320
            checkout = checkout_branch.bzrdir
1443
1321
            checkout_branch.bind(self)
1444
1322
            # pull up to the specified revision_id to set the initial
1445
1323
            # branch tip correctly, and seed it with history.
1446
1324
            checkout_branch.pull(self, stop_revision=revision_id)
1447
 
            from_branch = None
 
1325
            from_branch=None
1448
1326
        tree = checkout.create_workingtree(revision_id,
1449
1327
                                           from_branch=from_branch,
1450
1328
                                           accelerator_tree=accelerator_tree,
1471
1349
 
1472
1350
    def reference_parent(self, file_id, path, possible_transports=None):
1473
1351
        """Return the parent branch for a tree-reference file_id
1474
 
 
1475
1352
        :param file_id: The file_id of the tree reference
1476
1353
        :param path: The path of the file_id in the tree
1477
1354
        :return: A branch associated with the file_id
1483
1360
    def supports_tags(self):
1484
1361
        return self._format.supports_tags()
1485
1362
 
1486
 
    def automatic_tag_name(self, revision_id):
1487
 
        """Try to automatically find the tag name for a revision.
1488
 
 
1489
 
        :param revision_id: Revision id of the revision.
1490
 
        :return: A tag name or None if no tag name could be determined.
1491
 
        """
1492
 
        for hook in Branch.hooks['automatic_tag_name']:
1493
 
            ret = hook(self, revision_id)
1494
 
            if ret is not None:
1495
 
                return ret
1496
 
        return None
1497
 
 
1498
1363
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1499
1364
                                         other_branch):
1500
1365
        """Ensure that revision_b is a descendant of revision_a.
1530
1395
        else:
1531
1396
            raise AssertionError("invalid heads: %r" % (heads,))
1532
1397
 
1533
 
    def heads_to_fetch(self):
1534
 
        """Return the heads that must and that should be fetched to copy this
1535
 
        branch into another repo.
1536
 
 
1537
 
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
1538
 
            set of heads that must be fetched.  if_present_fetch is a set of
1539
 
            heads that must be fetched if present, but no error is necessary if
1540
 
            they are not present.
1541
 
        """
1542
 
        # For bzr native formats must_fetch is just the tip, and
1543
 
        # if_present_fetch are the tags.
1544
 
        must_fetch = set([self.last_revision()])
1545
 
        if_present_fetch = set()
1546
 
        if self.get_config_stack().get('branch.fetch_tags'):
1547
 
            try:
1548
 
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
1549
 
            except errors.TagsNotSupported:
1550
 
                pass
1551
 
        must_fetch.discard(_mod_revision.NULL_REVISION)
1552
 
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1553
 
        return must_fetch, if_present_fetch
1554
 
 
1555
 
 
1556
 
class BranchFormat(controldir.ControlComponentFormat):
 
1398
 
 
1399
class BranchFormat(object):
1557
1400
    """An encapsulation of the initialization and open routines for a format.
1558
1401
 
1559
1402
    Formats provide three things:
1560
1403
     * An initialization routine,
1561
 
     * a format description
 
1404
     * a format string,
1562
1405
     * an open routine.
1563
1406
 
1564
1407
    Formats are placed in an dict by their format string for reference
1565
 
    during branch opening. It's not required that these be instances, they
 
1408
    during branch opening. Its not required that these be instances, they
1566
1409
    can be classes themselves with class methods - it simply depends on
1567
1410
    whether state is needed for a given format or not.
1568
1411
 
1571
1414
    object will be created every time regardless.
1572
1415
    """
1573
1416
 
 
1417
    _default_format = None
 
1418
    """The default format used for new branches."""
 
1419
 
 
1420
    _formats = {}
 
1421
    """The known formats."""
 
1422
 
 
1423
    can_set_append_revisions_only = True
 
1424
 
1574
1425
    def __eq__(self, other):
1575
1426
        return self.__class__ is other.__class__
1576
1427
 
1577
1428
    def __ne__(self, other):
1578
1429
        return not (self == other)
1579
1430
 
1580
 
    def get_reference(self, controldir, name=None):
1581
 
        """Get the target reference of the branch in controldir.
 
1431
    @classmethod
 
1432
    def find_format(klass, a_bzrdir):
 
1433
        """Return the format for the branch object in a_bzrdir."""
 
1434
        try:
 
1435
            transport = a_bzrdir.get_branch_transport(None)
 
1436
            format_string = transport.get_bytes("format")
 
1437
            return klass._formats[format_string]
 
1438
        except errors.NoSuchFile:
 
1439
            raise errors.NotBranchError(path=transport.base)
 
1440
        except KeyError:
 
1441
            raise errors.UnknownFormatError(format=format_string, kind='branch')
 
1442
 
 
1443
    @classmethod
 
1444
    def get_default_format(klass):
 
1445
        """Return the current default format."""
 
1446
        return klass._default_format
 
1447
 
 
1448
    def get_reference(self, a_bzrdir):
 
1449
        """Get the target reference of the branch in a_bzrdir.
1582
1450
 
1583
1451
        format probing must have been completed before calling
1584
1452
        this method - it is assumed that the format of the branch
1585
 
        in controldir is correct.
 
1453
        in a_bzrdir is correct.
1586
1454
 
1587
 
        :param controldir: The controldir to get the branch data from.
1588
 
        :param name: Name of the colocated branch to fetch
 
1455
        :param a_bzrdir: The bzrdir to get the branch data from.
1589
1456
        :return: None if the branch is not a reference branch.
1590
1457
        """
1591
1458
        return None
1592
1459
 
1593
1460
    @classmethod
1594
 
    def set_reference(self, controldir, name, to_branch):
1595
 
        """Set the target reference of the branch in controldir.
 
1461
    def set_reference(self, a_bzrdir, to_branch):
 
1462
        """Set the target reference of the branch in a_bzrdir.
1596
1463
 
1597
1464
        format probing must have been completed before calling
1598
1465
        this method - it is assumed that the format of the branch
1599
 
        in controldir is correct.
 
1466
        in a_bzrdir is correct.
1600
1467
 
1601
 
        :param controldir: The controldir to set the branch reference for.
1602
 
        :param name: Name of colocated branch to set, None for default
 
1468
        :param a_bzrdir: The bzrdir to set the branch reference for.
1603
1469
        :param to_branch: branch that the checkout is to reference
1604
1470
        """
1605
1471
        raise NotImplementedError(self.set_reference)
1606
1472
 
 
1473
    def get_format_string(self):
 
1474
        """Return the ASCII format string that identifies this format."""
 
1475
        raise NotImplementedError(self.get_format_string)
 
1476
 
1607
1477
    def get_format_description(self):
1608
1478
        """Return the short format description for this format."""
1609
1479
        raise NotImplementedError(self.get_format_description)
1610
1480
 
1611
 
    def _run_post_branch_init_hooks(self, controldir, name, branch):
1612
 
        hooks = Branch.hooks['post_branch_init']
1613
 
        if not hooks:
1614
 
            return
1615
 
        params = BranchInitHookParams(self, controldir, name, branch)
1616
 
        for hook in hooks:
1617
 
            hook(params)
1618
 
 
1619
 
    def initialize(self, controldir, name=None, repository=None,
1620
 
                   append_revisions_only=None):
1621
 
        """Create a branch of this format in controldir.
1622
 
 
1623
 
        :param name: Name of the colocated branch to create.
 
1481
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1482
                           set_format=True):
 
1483
        """Initialize a branch in a bzrdir, with specified files
 
1484
 
 
1485
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1486
        :param utf8_files: The files to create as a list of
 
1487
            (filename, content) tuples
 
1488
        :param set_format: If True, set the format with
 
1489
            self.get_format_string.  (BzrBranch4 has its format set
 
1490
            elsewhere)
 
1491
        :return: a branch in this format
1624
1492
        """
 
1493
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1494
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1495
        lock_map = {
 
1496
            'metadir': ('lock', lockdir.LockDir),
 
1497
            'branch4': ('branch-lock', lockable_files.TransportLock),
 
1498
        }
 
1499
        lock_name, lock_class = lock_map[lock_type]
 
1500
        control_files = lockable_files.LockableFiles(branch_transport,
 
1501
            lock_name, lock_class)
 
1502
        control_files.create_lock()
 
1503
        try:
 
1504
            control_files.lock_write()
 
1505
        except errors.LockContention:
 
1506
            if lock_type != 'branch4':
 
1507
                raise
 
1508
            lock_taken = False
 
1509
        else:
 
1510
            lock_taken = True
 
1511
        if set_format:
 
1512
            utf8_files += [('format', self.get_format_string())]
 
1513
        try:
 
1514
            for (filename, content) in utf8_files:
 
1515
                branch_transport.put_bytes(
 
1516
                    filename, content,
 
1517
                    mode=a_bzrdir._get_file_mode())
 
1518
        finally:
 
1519
            if lock_taken:
 
1520
                control_files.unlock()
 
1521
        return self.open(a_bzrdir, _found=True)
 
1522
 
 
1523
    def initialize(self, a_bzrdir):
 
1524
        """Create a branch of this format in a_bzrdir."""
1625
1525
        raise NotImplementedError(self.initialize)
1626
1526
 
1627
1527
    def is_supported(self):
1645
1545
        Note that it is normal for branch to be a RemoteBranch when using tags
1646
1546
        on a RemoteBranch.
1647
1547
        """
1648
 
        return _mod_tag.DisabledTags(branch)
 
1548
        return DisabledTags(branch)
1649
1549
 
1650
1550
    def network_name(self):
1651
1551
        """A simple byte string uniquely identifying this format for RPC calls.
1657
1557
        """
1658
1558
        raise NotImplementedError(self.network_name)
1659
1559
 
1660
 
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1661
 
            found_repository=None, possible_transports=None):
1662
 
        """Return the branch object for controldir.
 
1560
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1561
        """Return the branch object for a_bzrdir
1663
1562
 
1664
 
        :param controldir: A ControlDir that contains a branch.
1665
 
        :param name: Name of colocated branch to open
 
1563
        :param a_bzrdir: A BzrDir that contains a branch.
1666
1564
        :param _found: a private parameter, do not use it. It is used to
1667
1565
            indicate if format probing has already be done.
1668
1566
        :param ignore_fallbacks: when set, no fallback branches will be opened
1670
1568
        """
1671
1569
        raise NotImplementedError(self.open)
1672
1570
 
 
1571
    @classmethod
 
1572
    def register_format(klass, format):
 
1573
        """Register a metadir format."""
 
1574
        klass._formats[format.get_format_string()] = format
 
1575
        # Metadir formats have a network name of their format string, and get
 
1576
        # registered as class factories.
 
1577
        network_format_registry.register(format.get_format_string(), format.__class__)
 
1578
 
 
1579
    @classmethod
 
1580
    def set_default_format(klass, format):
 
1581
        klass._default_format = format
 
1582
 
1673
1583
    def supports_set_append_revisions_only(self):
1674
1584
        """True if this format supports set_append_revisions_only."""
1675
1585
        return False
1678
1588
        """True if this format records a stacked-on branch."""
1679
1589
        return False
1680
1590
 
1681
 
    def supports_leaving_lock(self):
1682
 
        """True if this format supports leaving locks in place."""
1683
 
        return False # by default
 
1591
    @classmethod
 
1592
    def unregister_format(klass, format):
 
1593
        del klass._formats[format.get_format_string()]
1684
1594
 
1685
1595
    def __str__(self):
1686
1596
        return self.get_format_description().rstrip()
1689
1599
        """True if this format supports tags stored in the branch"""
1690
1600
        return False  # by default
1691
1601
 
1692
 
    def tags_are_versioned(self):
1693
 
        """Whether the tag container for this branch versions tags."""
1694
 
        return False
1695
 
 
1696
 
    def supports_tags_referencing_ghosts(self):
1697
 
        """True if tags can reference ghost revisions."""
1698
 
        return True
1699
 
 
1700
 
 
1701
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1702
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1703
 
    
1704
 
    While none of the built in BranchFormats are lazy registered yet,
1705
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1706
 
    use it, and the bzr-loom plugin uses it as well (see
1707
 
    bzrlib.plugins.loom.formats).
1708
 
    """
1709
 
 
1710
 
    def __init__(self, format_string, module_name, member_name):
1711
 
        """Create a MetaDirBranchFormatFactory.
1712
 
 
1713
 
        :param format_string: The format string the format has.
1714
 
        :param module_name: Module to load the format class from.
1715
 
        :param member_name: Attribute name within the module for the format class.
1716
 
        """
1717
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1718
 
        self._format_string = format_string
1719
 
 
1720
 
    def get_format_string(self):
1721
 
        """See BranchFormat.get_format_string."""
1722
 
        return self._format_string
1723
 
 
1724
 
    def __call__(self):
1725
 
        """Used for network_format_registry support."""
1726
 
        return self.get_obj()()
1727
 
 
1728
1602
 
1729
1603
class BranchHooks(Hooks):
1730
1604
    """A dictionary mapping hook name to a list of callables for branch hooks.
1731
1605
 
1732
 
    e.g. ['post_push'] Is the list of items to be called when the
1733
 
    push function is invoked.
 
1606
    e.g. ['set_rh'] Is the list of items to be called when the
 
1607
    set_revision_history function is invoked.
1734
1608
    """
1735
1609
 
1736
1610
    def __init__(self):
1739
1613
        These are all empty initially, because by default nothing should get
1740
1614
        notified.
1741
1615
        """
1742
 
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1743
 
        self.add_hook('open',
 
1616
        Hooks.__init__(self)
 
1617
        self.create_hook(HookPoint('set_rh',
 
1618
            "Invoked whenever the revision history has been set via "
 
1619
            "set_revision_history. The api signature is (branch, "
 
1620
            "revision_history), and the branch will be write-locked. "
 
1621
            "The set_rh hook can be expensive for bzr to trigger, a better "
 
1622
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1623
        self.create_hook(HookPoint('open',
1744
1624
            "Called with the Branch object that has been opened after a "
1745
 
            "branch is opened.", (1, 8))
1746
 
        self.add_hook('post_push',
 
1625
            "branch is opened.", (1, 8), None))
 
1626
        self.create_hook(HookPoint('post_push',
1747
1627
            "Called after a push operation completes. post_push is called "
1748
1628
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1749
 
            "bzr client.", (0, 15))
1750
 
        self.add_hook('post_pull',
 
1629
            "bzr client.", (0, 15), None))
 
1630
        self.create_hook(HookPoint('post_pull',
1751
1631
            "Called after a pull operation completes. post_pull is called "
1752
1632
            "with a bzrlib.branch.PullResult object and only runs in the "
1753
 
            "bzr client.", (0, 15))
1754
 
        self.add_hook('pre_commit',
1755
 
            "Called after a commit is calculated but before it is "
 
1633
            "bzr client.", (0, 15), None))
 
1634
        self.create_hook(HookPoint('pre_commit',
 
1635
            "Called after a commit is calculated but before it is is "
1756
1636
            "completed. pre_commit is called with (local, master, old_revno, "
1757
1637
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1758
1638
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1760
1640
            "basis revision. hooks MUST NOT modify this delta. "
1761
1641
            " future_tree is an in-memory tree obtained from "
1762
1642
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1763
 
            "tree.", (0,91))
1764
 
        self.add_hook('post_commit',
 
1643
            "tree.", (0,91), None))
 
1644
        self.create_hook(HookPoint('post_commit',
1765
1645
            "Called in the bzr client after a commit has completed. "
1766
1646
            "post_commit is called with (local, master, old_revno, old_revid, "
1767
1647
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
1768
 
            "commit to a branch.", (0, 15))
1769
 
        self.add_hook('post_uncommit',
 
1648
            "commit to a branch.", (0, 15), None))
 
1649
        self.create_hook(HookPoint('post_uncommit',
1770
1650
            "Called in the bzr client after an uncommit completes. "
1771
1651
            "post_uncommit is called with (local, master, old_revno, "
1772
1652
            "old_revid, new_revno, new_revid) where local is the local branch "
1773
1653
            "or None, master is the target branch, and an empty branch "
1774
 
            "receives new_revno of 0, new_revid of None.", (0, 15))
1775
 
        self.add_hook('pre_change_branch_tip',
 
1654
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1655
        self.create_hook(HookPoint('pre_change_branch_tip',
1776
1656
            "Called in bzr client and server before a change to the tip of a "
1777
1657
            "branch is made. pre_change_branch_tip is called with a "
1778
1658
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1779
 
            "commit, uncommit will all trigger this hook.", (1, 6))
1780
 
        self.add_hook('post_change_branch_tip',
 
1659
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1660
        self.create_hook(HookPoint('post_change_branch_tip',
1781
1661
            "Called in bzr client and server after a change to the tip of a "
1782
1662
            "branch is made. post_change_branch_tip is called with a "
1783
1663
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1784
 
            "commit, uncommit will all trigger this hook.", (1, 4))
1785
 
        self.add_hook('transform_fallback_location',
 
1664
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1665
        self.create_hook(HookPoint('transform_fallback_location',
1786
1666
            "Called when a stacked branch is activating its fallback "
1787
1667
            "locations. transform_fallback_location is called with (branch, "
1788
1668
            "url), and should return a new url. Returning the same url "
1793
1673
            "fallback locations have not been activated. When there are "
1794
1674
            "multiple hooks installed for transform_fallback_location, "
1795
1675
            "all are called with the url returned from the previous hook."
1796
 
            "The order is however undefined.", (1, 9))
1797
 
        self.add_hook('automatic_tag_name',
1798
 
            "Called to determine an automatic tag name for a revision. "
1799
 
            "automatic_tag_name is called with (branch, revision_id) and "
1800
 
            "should return a tag name or None if no tag name could be "
1801
 
            "determined. The first non-None tag name returned will be used.",
1802
 
            (2, 2))
1803
 
        self.add_hook('post_branch_init',
1804
 
            "Called after new branch initialization completes. "
1805
 
            "post_branch_init is called with a "
1806
 
            "bzrlib.branch.BranchInitHookParams. "
1807
 
            "Note that init, branch and checkout (both heavyweight and "
1808
 
            "lightweight) will all trigger this hook.", (2, 2))
1809
 
        self.add_hook('post_switch',
1810
 
            "Called after a checkout switches branch. "
1811
 
            "post_switch is called with a "
1812
 
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1813
 
 
 
1676
            "The order is however undefined.", (1, 9), None))
1814
1677
 
1815
1678
 
1816
1679
# install the default hooks into the Branch class.
1818
1681
 
1819
1682
 
1820
1683
class ChangeBranchTipParams(object):
1821
 
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1684
    """Object holding parameters passed to *_change_branch_tip hooks.
1822
1685
 
1823
1686
    There are 5 fields that hooks may wish to access:
1824
1687
 
1855
1718
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1856
1719
 
1857
1720
 
1858
 
class BranchInitHookParams(object):
1859
 
    """Object holding parameters passed to `*_branch_init` hooks.
1860
 
 
1861
 
    There are 4 fields that hooks may wish to access:
1862
 
 
1863
 
    :ivar format: the branch format
1864
 
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
1865
 
    :ivar name: name of colocated branch, if any (or None)
1866
 
    :ivar branch: the branch created
1867
 
 
1868
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1869
 
    the checkout, hence they are different from the corresponding fields in
1870
 
    branch, which refer to the original branch.
1871
 
    """
1872
 
 
1873
 
    def __init__(self, format, controldir, name, branch):
1874
 
        """Create a group of BranchInitHook parameters.
1875
 
 
1876
 
        :param format: the branch format
1877
 
        :param controldir: the ControlDir where the branch will be/has been
1878
 
            initialized
1879
 
        :param name: name of colocated branch, if any (or None)
1880
 
        :param branch: the branch created
1881
 
 
1882
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1883
 
        to the checkout, hence they are different from the corresponding fields
1884
 
        in branch, which refer to the original branch.
1885
 
        """
1886
 
        self.format = format
1887
 
        self.bzrdir = controldir
1888
 
        self.name = name
1889
 
        self.branch = branch
1890
 
 
1891
 
    def __eq__(self, other):
1892
 
        return self.__dict__ == other.__dict__
1893
 
 
1894
 
    def __repr__(self):
1895
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1896
 
 
1897
 
 
1898
 
class SwitchHookParams(object):
1899
 
    """Object holding parameters passed to `*_switch` hooks.
1900
 
 
1901
 
    There are 4 fields that hooks may wish to access:
1902
 
 
1903
 
    :ivar control_dir: ControlDir of the checkout to change
1904
 
    :ivar to_branch: branch that the checkout is to reference
1905
 
    :ivar force: skip the check for local commits in a heavy checkout
1906
 
    :ivar revision_id: revision ID to switch to (or None)
1907
 
    """
1908
 
 
1909
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1910
 
        """Create a group of SwitchHook parameters.
1911
 
 
1912
 
        :param control_dir: ControlDir of the checkout to change
1913
 
        :param to_branch: branch that the checkout is to reference
1914
 
        :param force: skip the check for local commits in a heavy checkout
1915
 
        :param revision_id: revision ID to switch to (or None)
1916
 
        """
1917
 
        self.control_dir = control_dir
1918
 
        self.to_branch = to_branch
1919
 
        self.force = force
1920
 
        self.revision_id = revision_id
1921
 
 
1922
 
    def __eq__(self, other):
1923
 
        return self.__dict__ == other.__dict__
1924
 
 
1925
 
    def __repr__(self):
1926
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1927
 
            self.control_dir, self.to_branch,
1928
 
            self.revision_id)
1929
 
 
1930
 
 
1931
 
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
1932
 
    """Base class for branch formats that live in meta directories.
1933
 
    """
 
1721
class BzrBranchFormat4(BranchFormat):
 
1722
    """Bzr branch format 4.
 
1723
 
 
1724
    This format has:
 
1725
     - a revision-history file.
 
1726
     - a branch-lock lock file [ to be shared with the bzrdir ]
 
1727
    """
 
1728
 
 
1729
    def get_format_description(self):
 
1730
        """See BranchFormat.get_format_description()."""
 
1731
        return "Branch format 4"
 
1732
 
 
1733
    def initialize(self, a_bzrdir):
 
1734
        """Create a branch of this format in a_bzrdir."""
 
1735
        utf8_files = [('revision-history', ''),
 
1736
                      ('branch-name', ''),
 
1737
                      ]
 
1738
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1739
                                       lock_type='branch4', set_format=False)
1934
1740
 
1935
1741
    def __init__(self):
1936
 
        BranchFormat.__init__(self)
1937
 
        bzrdir.BzrFormat.__init__(self)
1938
 
 
1939
 
    @classmethod
1940
 
    def find_format(klass, controldir, name=None):
1941
 
        """Return the format for the branch object in controldir."""
1942
 
        try:
1943
 
            transport = controldir.get_branch_transport(None, name=name)
1944
 
        except errors.NoSuchFile:
1945
 
            raise errors.NotBranchError(path=name, bzrdir=controldir)
1946
 
        try:
1947
 
            format_string = transport.get_bytes("format")
1948
 
        except errors.NoSuchFile:
1949
 
            raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
1950
 
        return klass._find_format(format_registry, 'branch', format_string)
 
1742
        super(BzrBranchFormat4, self).__init__()
 
1743
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
 
1744
 
 
1745
    def network_name(self):
 
1746
        """The network name for this format is the control dirs disk label."""
 
1747
        return self._matchingbzrdir.get_format_string()
 
1748
 
 
1749
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
 
1750
        """See BranchFormat.open()."""
 
1751
        if not _found:
 
1752
            # we are being called directly and must probe.
 
1753
            raise NotImplementedError
 
1754
        return BzrBranch(_format=self,
 
1755
                         _control_files=a_bzrdir._control_files,
 
1756
                         a_bzrdir=a_bzrdir,
 
1757
                         _repository=a_bzrdir.open_repository())
 
1758
 
 
1759
    def __str__(self):
 
1760
        return "Bazaar-NG branch format 4"
 
1761
 
 
1762
 
 
1763
class BranchFormatMetadir(BranchFormat):
 
1764
    """Common logic for meta-dir based branch formats."""
1951
1765
 
1952
1766
    def _branch_class(self):
1953
1767
        """What class to instantiate on open calls."""
1954
1768
        raise NotImplementedError(self._branch_class)
1955
1769
 
1956
 
    def _get_initial_config(self, append_revisions_only=None):
1957
 
        if append_revisions_only:
1958
 
            return "append_revisions_only = True\n"
1959
 
        else:
1960
 
            # Avoid writing anything if append_revisions_only is disabled,
1961
 
            # as that is the default.
1962
 
            return ""
1963
 
 
1964
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1965
 
                           repository=None):
1966
 
        """Initialize a branch in a control dir, with specified files
1967
 
 
1968
 
        :param a_bzrdir: The bzrdir to initialize the branch in
1969
 
        :param utf8_files: The files to create as a list of
1970
 
            (filename, content) tuples
1971
 
        :param name: Name of colocated branch to create, if any
1972
 
        :return: a branch in this format
 
1770
    def network_name(self):
 
1771
        """A simple byte string uniquely identifying this format for RPC calls.
 
1772
 
 
1773
        Metadir branch formats use their format string.
1973
1774
        """
1974
 
        if name is None:
1975
 
            name = a_bzrdir._get_selected_branch()
1976
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1977
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1978
 
        control_files = lockable_files.LockableFiles(branch_transport,
1979
 
            'lock', lockdir.LockDir)
1980
 
        control_files.create_lock()
1981
 
        control_files.lock_write()
1982
 
        try:
1983
 
            utf8_files += [('format', self.as_string())]
1984
 
            for (filename, content) in utf8_files:
1985
 
                branch_transport.put_bytes(
1986
 
                    filename, content,
1987
 
                    mode=a_bzrdir._get_file_mode())
1988
 
        finally:
1989
 
            control_files.unlock()
1990
 
        branch = self.open(a_bzrdir, name, _found=True,
1991
 
                found_repository=repository)
1992
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1993
 
        return branch
 
1775
        return self.get_format_string()
1994
1776
 
1995
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1996
 
            found_repository=None, possible_transports=None):
 
1777
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1997
1778
        """See BranchFormat.open()."""
1998
 
        if name is None:
1999
 
            name = a_bzrdir._get_selected_branch()
2000
1779
        if not _found:
2001
 
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
1780
            format = BranchFormat.find_format(a_bzrdir)
2002
1781
            if format.__class__ != self.__class__:
2003
1782
                raise AssertionError("wrong format %r found for %r" %
2004
1783
                    (format, self))
2005
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2006
1784
        try:
 
1785
            transport = a_bzrdir.get_branch_transport(None)
2007
1786
            control_files = lockable_files.LockableFiles(transport, 'lock',
2008
1787
                                                         lockdir.LockDir)
2009
 
            if found_repository is None:
2010
 
                found_repository = a_bzrdir.find_repository()
2011
1788
            return self._branch_class()(_format=self,
2012
1789
                              _control_files=control_files,
2013
 
                              name=name,
2014
1790
                              a_bzrdir=a_bzrdir,
2015
 
                              _repository=found_repository,
2016
 
                              ignore_fallbacks=ignore_fallbacks,
2017
 
                              possible_transports=possible_transports)
 
1791
                              _repository=a_bzrdir.find_repository(),
 
1792
                              ignore_fallbacks=ignore_fallbacks)
2018
1793
        except errors.NoSuchFile:
2019
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2020
 
 
2021
 
    @property
2022
 
    def _matchingbzrdir(self):
2023
 
        ret = bzrdir.BzrDirMetaFormat1()
2024
 
        ret.set_branch_format(self)
2025
 
        return ret
2026
 
 
2027
 
    def supports_tags(self):
2028
 
        return True
2029
 
 
2030
 
    def supports_leaving_lock(self):
2031
 
        return True
2032
 
 
2033
 
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
2034
 
            basedir=None):
2035
 
        BranchFormat.check_support_status(self,
2036
 
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
2037
 
            basedir=basedir)
2038
 
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
2039
 
            recommend_upgrade=recommend_upgrade, basedir=basedir)
 
1794
            raise errors.NotBranchError(path=transport.base)
 
1795
 
 
1796
    def __init__(self):
 
1797
        super(BranchFormatMetadir, self).__init__()
 
1798
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
1799
        self._matchingbzrdir.set_branch_format(self)
 
1800
 
 
1801
    def supports_tags(self):
 
1802
        return True
 
1803
 
 
1804
 
 
1805
class BzrBranchFormat5(BranchFormatMetadir):
 
1806
    """Bzr branch format 5.
 
1807
 
 
1808
    This format has:
 
1809
     - a revision-history file.
 
1810
     - a format string
 
1811
     - a lock dir guarding the branch itself
 
1812
     - all of this stored in a branch/ subdirectory
 
1813
     - works with shared repositories.
 
1814
 
 
1815
    This format is new in bzr 0.8.
 
1816
    """
 
1817
 
 
1818
    def _branch_class(self):
 
1819
        return BzrBranch5
 
1820
 
 
1821
    def get_format_string(self):
 
1822
        """See BranchFormat.get_format_string()."""
 
1823
        return "Bazaar-NG branch format 5\n"
 
1824
 
 
1825
    def get_format_description(self):
 
1826
        """See BranchFormat.get_format_description()."""
 
1827
        return "Branch format 5"
 
1828
 
 
1829
    def initialize(self, a_bzrdir):
 
1830
        """Create a branch of this format in a_bzrdir."""
 
1831
        utf8_files = [('revision-history', ''),
 
1832
                      ('branch-name', ''),
 
1833
                      ]
 
1834
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1835
 
 
1836
    def supports_tags(self):
 
1837
        return False
2040
1838
 
2041
1839
 
2042
1840
class BzrBranchFormat6(BranchFormatMetadir):
2053
1851
    def _branch_class(self):
2054
1852
        return BzrBranch6
2055
1853
 
2056
 
    @classmethod
2057
 
    def get_format_string(cls):
 
1854
    def get_format_string(self):
2058
1855
        """See BranchFormat.get_format_string()."""
2059
1856
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
2060
1857
 
2062
1859
        """See BranchFormat.get_format_description()."""
2063
1860
        return "Branch format 6"
2064
1861
 
2065
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2066
 
                   append_revisions_only=None):
 
1862
    def initialize(self, a_bzrdir):
2067
1863
        """Create a branch of this format in a_bzrdir."""
2068
1864
        utf8_files = [('last-revision', '0 null:\n'),
2069
 
                      ('branch.conf',
2070
 
                          self._get_initial_config(append_revisions_only)),
 
1865
                      ('branch.conf', ''),
2071
1866
                      ('tags', ''),
2072
1867
                      ]
2073
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1868
        return self._initialize_helper(a_bzrdir, utf8_files)
2074
1869
 
2075
1870
    def make_tags(self, branch):
2076
1871
        """See bzrlib.branch.BranchFormat.make_tags()."""
2077
 
        return _mod_tag.BasicTags(branch)
 
1872
        return BasicTags(branch)
2078
1873
 
2079
1874
    def supports_set_append_revisions_only(self):
2080
1875
        return True
2086
1881
    def _branch_class(self):
2087
1882
        return BzrBranch8
2088
1883
 
2089
 
    @classmethod
2090
 
    def get_format_string(cls):
 
1884
    def get_format_string(self):
2091
1885
        """See BranchFormat.get_format_string()."""
2092
1886
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2093
1887
 
2095
1889
        """See BranchFormat.get_format_description()."""
2096
1890
        return "Branch format 8"
2097
1891
 
2098
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2099
 
                   append_revisions_only=None):
 
1892
    def initialize(self, a_bzrdir):
2100
1893
        """Create a branch of this format in a_bzrdir."""
2101
1894
        utf8_files = [('last-revision', '0 null:\n'),
2102
 
                      ('branch.conf',
2103
 
                          self._get_initial_config(append_revisions_only)),
 
1895
                      ('branch.conf', ''),
2104
1896
                      ('tags', ''),
2105
1897
                      ('references', '')
2106
1898
                      ]
2107
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1899
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1900
 
 
1901
    def __init__(self):
 
1902
        super(BzrBranchFormat8, self).__init__()
 
1903
        self._matchingbzrdir.repository_format = \
 
1904
            RepositoryFormatKnitPack5RichRoot()
2108
1905
 
2109
1906
    def make_tags(self, branch):
2110
1907
        """See bzrlib.branch.BranchFormat.make_tags()."""
2111
 
        return _mod_tag.BasicTags(branch)
 
1908
        return BasicTags(branch)
2112
1909
 
2113
1910
    def supports_set_append_revisions_only(self):
2114
1911
        return True
2119
1916
    supports_reference_locations = True
2120
1917
 
2121
1918
 
2122
 
class BzrBranchFormat7(BranchFormatMetadir):
 
1919
class BzrBranchFormat7(BzrBranchFormat8):
2123
1920
    """Branch format with last-revision, tags, and a stacked location pointer.
2124
1921
 
2125
1922
    The stacked location pointer is passed down to the repository and requires
2128
1925
    This format was introduced in bzr 1.6.
2129
1926
    """
2130
1927
 
2131
 
    def initialize(self, a_bzrdir, name=None, repository=None,
2132
 
                   append_revisions_only=None):
 
1928
    def initialize(self, a_bzrdir):
2133
1929
        """Create a branch of this format in a_bzrdir."""
2134
1930
        utf8_files = [('last-revision', '0 null:\n'),
2135
 
                      ('branch.conf',
2136
 
                          self._get_initial_config(append_revisions_only)),
 
1931
                      ('branch.conf', ''),
2137
1932
                      ('tags', ''),
2138
1933
                      ]
2139
 
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
1934
        return self._initialize_helper(a_bzrdir, utf8_files)
2140
1935
 
2141
1936
    def _branch_class(self):
2142
1937
        return BzrBranch7
2143
1938
 
2144
 
    @classmethod
2145
 
    def get_format_string(cls):
 
1939
    def get_format_string(self):
2146
1940
        """See BranchFormat.get_format_string()."""
2147
1941
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2148
1942
 
2153
1947
    def supports_set_append_revisions_only(self):
2154
1948
        return True
2155
1949
 
2156
 
    def supports_stacking(self):
2157
 
        return True
2158
 
 
2159
 
    def make_tags(self, branch):
2160
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2161
 
        return _mod_tag.BasicTags(branch)
2162
 
 
2163
1950
    supports_reference_locations = False
2164
1951
 
2165
1952
 
2166
 
class BranchReferenceFormat(BranchFormatMetadir):
 
1953
class BranchReferenceFormat(BranchFormat):
2167
1954
    """Bzr branch reference format.
2168
1955
 
2169
1956
    Branch references are used in implementing checkouts, they
2174
1961
     - a format string
2175
1962
    """
2176
1963
 
2177
 
    @classmethod
2178
 
    def get_format_string(cls):
 
1964
    def get_format_string(self):
2179
1965
        """See BranchFormat.get_format_string()."""
2180
1966
        return "Bazaar-NG Branch Reference Format 1\n"
2181
1967
 
2183
1969
        """See BranchFormat.get_format_description()."""
2184
1970
        return "Checkout reference format 1"
2185
1971
 
2186
 
    def get_reference(self, a_bzrdir, name=None):
 
1972
    def get_reference(self, a_bzrdir):
2187
1973
        """See BranchFormat.get_reference()."""
2188
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1974
        transport = a_bzrdir.get_branch_transport(None)
2189
1975
        return transport.get_bytes('location')
2190
1976
 
2191
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1977
    def set_reference(self, a_bzrdir, to_branch):
2192
1978
        """See BranchFormat.set_reference()."""
2193
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1979
        transport = a_bzrdir.get_branch_transport(None)
2194
1980
        location = transport.put_bytes('location', to_branch.base)
2195
1981
 
2196
 
    def initialize(self, a_bzrdir, name=None, target_branch=None,
2197
 
            repository=None, append_revisions_only=None):
 
1982
    def initialize(self, a_bzrdir, target_branch=None):
2198
1983
        """Create a branch of this format in a_bzrdir."""
2199
1984
        if target_branch is None:
2200
1985
            # this format does not implement branch itself, thus the implicit
2201
1986
            # creation contract must see it as uninitializable
2202
1987
            raise errors.UninitializableFormat(self)
2203
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2204
 
        if a_bzrdir._format.fixed_components:
2205
 
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
2206
 
        if name is None:
2207
 
            name = a_bzrdir._get_selected_branch()
2208
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1988
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1989
        branch_transport = a_bzrdir.get_branch_transport(self)
2209
1990
        branch_transport.put_bytes('location',
2210
 
            target_branch.user_url)
2211
 
        branch_transport.put_bytes('format', self.as_string())
2212
 
        branch = self.open(a_bzrdir, name, _found=True,
 
1991
            target_branch.bzrdir.root_transport.base)
 
1992
        branch_transport.put_bytes('format', self.get_format_string())
 
1993
        return self.open(
 
1994
            a_bzrdir, _found=True,
2213
1995
            possible_transports=[target_branch.bzrdir.root_transport])
2214
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2215
 
        return branch
 
1996
 
 
1997
    def __init__(self):
 
1998
        super(BranchReferenceFormat, self).__init__()
 
1999
        self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
 
2000
        self._matchingbzrdir.set_branch_format(self)
2216
2001
 
2217
2002
    def _make_reference_clone_function(format, a_branch):
2218
2003
        """Create a clone() routine for a branch dynamically."""
2219
2004
        def clone(to_bzrdir, revision_id=None,
2220
2005
            repository_policy=None):
2221
2006
            """See Branch.clone()."""
2222
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2007
            return format.initialize(to_bzrdir, a_branch)
2223
2008
            # cannot obey revision_id limits when cloning a reference ...
2224
2009
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2225
2010
            # emit some sort of warning/error to the caller ?!
2226
2011
        return clone
2227
2012
 
2228
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2229
 
             possible_transports=None, ignore_fallbacks=False,
2230
 
             found_repository=None):
 
2013
    def open(self, a_bzrdir, _found=False, location=None,
 
2014
             possible_transports=None, ignore_fallbacks=False):
2231
2015
        """Return the branch that the branch reference in a_bzrdir points at.
2232
2016
 
2233
2017
        :param a_bzrdir: A BzrDir that contains a branch.
2234
 
        :param name: Name of colocated branch to open, if any
2235
2018
        :param _found: a private parameter, do not use it. It is used to
2236
2019
            indicate if format probing has already be done.
2237
2020
        :param ignore_fallbacks: when set, no fallback branches will be opened
2241
2024
            a_bzrdir.
2242
2025
        :param possible_transports: An optional reusable transports list.
2243
2026
        """
2244
 
        if name is None:
2245
 
            name = a_bzrdir._get_selected_branch()
2246
2027
        if not _found:
2247
 
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2028
            format = BranchFormat.find_format(a_bzrdir)
2248
2029
            if format.__class__ != self.__class__:
2249
2030
                raise AssertionError("wrong format %r found for %r" %
2250
2031
                    (format, self))
2251
2032
        if location is None:
2252
 
            location = self.get_reference(a_bzrdir, name)
2253
 
        real_bzrdir = controldir.ControlDir.open(
 
2033
            location = self.get_reference(a_bzrdir)
 
2034
        real_bzrdir = bzrdir.BzrDir.open(
2254
2035
            location, possible_transports=possible_transports)
2255
 
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
2256
 
            possible_transports=possible_transports)
 
2036
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2257
2037
        # this changes the behaviour of result.clone to create a new reference
2258
2038
        # rather than a copy of the content of the branch.
2259
2039
        # I did not use a proxy object because that needs much more extensive
2266
2046
        return result
2267
2047
 
2268
2048
 
2269
 
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2270
 
    """Branch format registry."""
2271
 
 
2272
 
    def __init__(self, other_registry=None):
2273
 
        super(BranchFormatRegistry, self).__init__(other_registry)
2274
 
        self._default_format = None
2275
 
 
2276
 
    def set_default(self, format):
2277
 
        self._default_format = format
2278
 
 
2279
 
    def get_default(self):
2280
 
        return self._default_format
2281
 
 
2282
 
 
2283
2049
network_format_registry = registry.FormatRegistry()
2284
2050
"""Registry of formats indexed by their network name.
2285
2051
 
2288
2054
BranchFormat.network_name() for more detail.
2289
2055
"""
2290
2056
 
2291
 
format_registry = BranchFormatRegistry(network_format_registry)
2292
 
 
2293
2057
 
2294
2058
# formats which have no format string are not discoverable
2295
2059
# and not independently creatable, so are not registered.
 
2060
__format5 = BzrBranchFormat5()
2296
2061
__format6 = BzrBranchFormat6()
2297
2062
__format7 = BzrBranchFormat7()
2298
2063
__format8 = BzrBranchFormat8()
2299
 
format_registry.register_lazy(
2300
 
    "Bazaar-NG branch format 5\n", "bzrlib.branchfmt.fullhistory", "BzrBranchFormat5")
2301
 
format_registry.register(BranchReferenceFormat())
2302
 
format_registry.register(__format6)
2303
 
format_registry.register(__format7)
2304
 
format_registry.register(__format8)
2305
 
format_registry.set_default(__format7)
2306
 
 
2307
 
 
2308
 
class BranchWriteLockResult(LogicalLockResult):
2309
 
    """The result of write locking a branch.
2310
 
 
2311
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2312
 
        None.
2313
 
    :ivar unlock: A callable which will unlock the lock.
2314
 
    """
2315
 
 
2316
 
    def __init__(self, unlock, branch_token):
2317
 
        LogicalLockResult.__init__(self, unlock)
2318
 
        self.branch_token = branch_token
2319
 
 
2320
 
    def __repr__(self):
2321
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2322
 
            self.unlock)
 
2064
BranchFormat.register_format(__format5)
 
2065
BranchFormat.register_format(BranchReferenceFormat())
 
2066
BranchFormat.register_format(__format6)
 
2067
BranchFormat.register_format(__format7)
 
2068
BranchFormat.register_format(__format8)
 
2069
BranchFormat.set_default_format(__format7)
 
2070
_legacy_formats = [BzrBranchFormat4(),
 
2071
    ]
 
2072
network_format_registry.register(
 
2073
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2323
2074
 
2324
2075
 
2325
2076
class BzrBranch(Branch, _RelockDebugMixin):
2334
2085
    :ivar repository: Repository for this branch.
2335
2086
    :ivar base: The url of the base directory for this branch; the one
2336
2087
        containing the .bzr directory.
2337
 
    :ivar name: Optional colocated branch name as it exists in the control
2338
 
        directory.
2339
2088
    """
2340
2089
 
2341
2090
    def __init__(self, _format=None,
2342
 
                 _control_files=None, a_bzrdir=None, name=None,
2343
 
                 _repository=None, ignore_fallbacks=False,
2344
 
                 possible_transports=None):
 
2091
                 _control_files=None, a_bzrdir=None, _repository=None,
 
2092
                 ignore_fallbacks=False):
2345
2093
        """Create new branch object at a particular location."""
2346
2094
        if a_bzrdir is None:
2347
2095
            raise ValueError('a_bzrdir must be supplied')
2348
 
        if name is None:
2349
 
            raise ValueError('name must be supplied')
2350
 
        self.bzrdir = a_bzrdir
2351
 
        self._user_transport = self.bzrdir.transport.clone('..')
2352
 
        if name != "":
2353
 
            self._user_transport.set_segment_parameter(
2354
 
                "branch", urlutils.escape(name))
2355
 
        self._base = self._user_transport.base
2356
 
        self.name = name
 
2096
        else:
 
2097
            self.bzrdir = a_bzrdir
 
2098
        self._base = self.bzrdir.transport.clone('..').base
 
2099
        # XXX: We should be able to just do
 
2100
        #   self.base = self.bzrdir.root_transport.base
 
2101
        # but this does not quite work yet -- mbp 20080522
2357
2102
        self._format = _format
2358
2103
        if _control_files is None:
2359
2104
            raise ValueError('BzrBranch _control_files is None')
2360
2105
        self.control_files = _control_files
2361
2106
        self._transport = _control_files._transport
2362
2107
        self.repository = _repository
2363
 
        self.conf_store = None
2364
 
        Branch.__init__(self, possible_transports)
 
2108
        Branch.__init__(self)
2365
2109
 
2366
2110
    def __str__(self):
2367
 
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2111
        return '%s(%r)' % (self.__class__.__name__, self.base)
2368
2112
 
2369
2113
    __repr__ = __str__
2370
2114
 
2374
2118
 
2375
2119
    base = property(_get_base, doc="The URL for the root of this branch.")
2376
2120
 
2377
 
    @property
2378
 
    def user_transport(self):
2379
 
        return self._user_transport
2380
 
 
2381
2121
    def _get_config(self):
2382
 
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
2383
 
 
2384
 
    def _get_config_store(self):
2385
 
        if self.conf_store is None:
2386
 
            self.conf_store =  _mod_config.BranchStore(self)
2387
 
        return self.conf_store
 
2122
        return TransportConfig(self._transport, 'branch.conf')
2388
2123
 
2389
2124
    def is_locked(self):
2390
2125
        return self.control_files.is_locked()
2391
2126
 
2392
2127
    def lock_write(self, token=None):
2393
 
        """Lock the branch for write operations.
2394
 
 
2395
 
        :param token: A token to permit reacquiring a previously held and
2396
 
            preserved lock.
2397
 
        :return: A BranchWriteLockResult.
2398
 
        """
2399
2128
        if not self.is_locked():
2400
2129
            self._note_lock('w')
2401
 
            self.repository._warn_if_deprecated(self)
 
2130
        # All-in-one needs to always unlock/lock.
 
2131
        repo_control = getattr(self.repository, 'control_files', None)
 
2132
        if self.control_files == repo_control or not self.is_locked():
2402
2133
            self.repository.lock_write()
2403
2134
            took_lock = True
2404
2135
        else:
2405
2136
            took_lock = False
2406
2137
        try:
2407
 
            return BranchWriteLockResult(self.unlock,
2408
 
                self.control_files.lock_write(token=token))
 
2138
            return self.control_files.lock_write(token=token)
2409
2139
        except:
2410
2140
            if took_lock:
2411
2141
                self.repository.unlock()
2412
2142
            raise
2413
2143
 
2414
2144
    def lock_read(self):
2415
 
        """Lock the branch for read operations.
2416
 
 
2417
 
        :return: A bzrlib.lock.LogicalLockResult.
2418
 
        """
2419
2145
        if not self.is_locked():
2420
2146
            self._note_lock('r')
2421
 
            self.repository._warn_if_deprecated(self)
 
2147
        # All-in-one needs to always unlock/lock.
 
2148
        repo_control = getattr(self.repository, 'control_files', None)
 
2149
        if self.control_files == repo_control or not self.is_locked():
2422
2150
            self.repository.lock_read()
2423
2151
            took_lock = True
2424
2152
        else:
2425
2153
            took_lock = False
2426
2154
        try:
2427
2155
            self.control_files.lock_read()
2428
 
            return LogicalLockResult(self.unlock)
2429
2156
        except:
2430
2157
            if took_lock:
2431
2158
                self.repository.unlock()
2433
2160
 
2434
2161
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2435
2162
    def unlock(self):
2436
 
        if self.control_files._lock_count == 1 and self.conf_store is not None:
2437
 
            self.conf_store.save_changes()
2438
2163
        try:
2439
2164
            self.control_files.unlock()
2440
2165
        finally:
 
2166
            # All-in-one needs to always unlock/lock.
 
2167
            repo_control = getattr(self.repository, 'control_files', None)
 
2168
            if (self.control_files == repo_control or
 
2169
                not self.control_files.is_locked()):
 
2170
                self.repository.unlock()
2441
2171
            if not self.control_files.is_locked():
2442
 
                self.repository.unlock()
2443
2172
                # we just released the lock
2444
2173
                self._clear_cached_state()
2445
2174
 
2457
2186
        """See Branch.print_file."""
2458
2187
        return self.repository.print_file(file, revision_id)
2459
2188
 
 
2189
    def _write_revision_history(self, history):
 
2190
        """Factored out of set_revision_history.
 
2191
 
 
2192
        This performs the actual writing to disk.
 
2193
        It is intended to be called by BzrBranch5.set_revision_history."""
 
2194
        self._transport.put_bytes(
 
2195
            'revision-history', '\n'.join(history),
 
2196
            mode=self.bzrdir._get_file_mode())
 
2197
 
 
2198
    @needs_write_lock
 
2199
    def set_revision_history(self, rev_history):
 
2200
        """See Branch.set_revision_history."""
 
2201
        if 'evil' in debug.debug_flags:
 
2202
            mutter_callsite(3, "set_revision_history scales with history.")
 
2203
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
2204
        for rev_id in rev_history:
 
2205
            check_not_reserved_id(rev_id)
 
2206
        if Branch.hooks['post_change_branch_tip']:
 
2207
            # Don't calculate the last_revision_info() if there are no hooks
 
2208
            # that will use it.
 
2209
            old_revno, old_revid = self.last_revision_info()
 
2210
        if len(rev_history) == 0:
 
2211
            revid = _mod_revision.NULL_REVISION
 
2212
        else:
 
2213
            revid = rev_history[-1]
 
2214
        self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
 
2215
        self._write_revision_history(rev_history)
 
2216
        self._clear_cached_state()
 
2217
        self._cache_revision_history(rev_history)
 
2218
        for hook in Branch.hooks['set_rh']:
 
2219
            hook(self, rev_history)
 
2220
        if Branch.hooks['post_change_branch_tip']:
 
2221
            self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2222
 
 
2223
    def _synchronize_history(self, destination, revision_id):
 
2224
        """Synchronize last revision and revision history between branches.
 
2225
 
 
2226
        This version is most efficient when the destination is also a
 
2227
        BzrBranch5, but works for BzrBranch6 as long as the revision
 
2228
        history is the true lefthand parent history, and all of the revisions
 
2229
        are in the destination's repository.  If not, set_revision_history
 
2230
        will fail.
 
2231
 
 
2232
        :param destination: The branch to copy the history into
 
2233
        :param revision_id: The revision-id to truncate history at.  May
 
2234
          be None to copy complete history.
 
2235
        """
 
2236
        if not isinstance(destination._format, BzrBranchFormat5):
 
2237
            super(BzrBranch, self)._synchronize_history(
 
2238
                destination, revision_id)
 
2239
            return
 
2240
        if revision_id == _mod_revision.NULL_REVISION:
 
2241
            new_history = []
 
2242
        else:
 
2243
            new_history = self.revision_history()
 
2244
        if revision_id is not None and new_history != []:
 
2245
            try:
 
2246
                new_history = new_history[:new_history.index(revision_id) + 1]
 
2247
            except ValueError:
 
2248
                rev = self.repository.get_revision(revision_id)
 
2249
                new_history = rev.get_history(self.repository)[1:]
 
2250
        destination.set_revision_history(new_history)
 
2251
 
2460
2252
    @needs_write_lock
2461
2253
    def set_last_revision_info(self, revno, revision_id):
2462
 
        if not revision_id or not isinstance(revision_id, basestring):
2463
 
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2254
        """Set the last revision of this branch.
 
2255
 
 
2256
        The caller is responsible for checking that the revno is correct
 
2257
        for this revision id.
 
2258
 
 
2259
        It may be possible to set the branch last revision to an id not
 
2260
        present in the repository.  However, branches can also be
 
2261
        configured to check constraints on history, in which case this may not
 
2262
        be permitted.
 
2263
        """
2464
2264
        revision_id = _mod_revision.ensure_null(revision_id)
2465
 
        old_revno, old_revid = self.last_revision_info()
2466
 
        if self.get_append_revisions_only():
2467
 
            self._check_history_violation(revision_id)
2468
 
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
2469
 
        self._write_last_revision_info(revno, revision_id)
2470
 
        self._clear_cached_state()
2471
 
        self._last_revision_info_cache = revno, revision_id
2472
 
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2265
        # this old format stores the full history, but this api doesn't
 
2266
        # provide it, so we must generate, and might as well check it's
 
2267
        # correct
 
2268
        history = self._lefthand_history(revision_id)
 
2269
        if len(history) != revno:
 
2270
            raise AssertionError('%d != %d' % (len(history), revno))
 
2271
        self.set_revision_history(history)
 
2272
 
 
2273
    def _gen_revision_history(self):
 
2274
        history = self._transport.get_bytes('revision-history').split('\n')
 
2275
        if history[-1:] == ['']:
 
2276
            # There shouldn't be a trailing newline, but just in case.
 
2277
            history.pop()
 
2278
        return history
 
2279
 
 
2280
    @needs_write_lock
 
2281
    def generate_revision_history(self, revision_id, last_rev=None,
 
2282
        other_branch=None):
 
2283
        """Create a new revision history that will finish with revision_id.
 
2284
 
 
2285
        :param revision_id: the new tip to use.
 
2286
        :param last_rev: The previous last_revision. If not None, then this
 
2287
            must be a ancestory of revision_id, or DivergedBranches is raised.
 
2288
        :param other_branch: The other branch that DivergedBranches should
 
2289
            raise with respect to.
 
2290
        """
 
2291
        self.set_revision_history(self._lefthand_history(revision_id,
 
2292
            last_rev, other_branch))
2473
2293
 
2474
2294
    def basis_tree(self):
2475
2295
        """See Branch.basis_tree."""
2484
2304
                pass
2485
2305
        return None
2486
2306
 
 
2307
    def _basic_push(self, target, overwrite, stop_revision):
 
2308
        """Basic implementation of push without bound branches or hooks.
 
2309
 
 
2310
        Must be called with source read locked and target write locked.
 
2311
        """
 
2312
        result = BranchPushResult()
 
2313
        result.source_branch = self
 
2314
        result.target_branch = target
 
2315
        result.old_revno, result.old_revid = target.last_revision_info()
 
2316
        self.update_references(target)
 
2317
        if result.old_revid != self.last_revision():
 
2318
            # We assume that during 'push' this repository is closer than
 
2319
            # the target.
 
2320
            graph = self.repository.get_graph(target.repository)
 
2321
            target.update_revisions(self, stop_revision,
 
2322
                overwrite=overwrite, graph=graph)
 
2323
        if self._push_should_merge_tags():
 
2324
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2325
                overwrite)
 
2326
        result.new_revno, result.new_revid = target.last_revision_info()
 
2327
        return result
 
2328
 
2487
2329
    def get_stacked_on_url(self):
2488
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2330
        raise errors.UnstackableBranchFormat(self._format, self.base)
2489
2331
 
2490
2332
    def set_push_location(self, location):
2491
2333
        """See Branch.set_push_location."""
2500
2342
            self._transport.put_bytes('parent', url + '\n',
2501
2343
                mode=self.bzrdir._get_file_mode())
2502
2344
 
 
2345
 
 
2346
class BzrBranch5(BzrBranch):
 
2347
    """A format 5 branch. This supports new features over plain branches.
 
2348
 
 
2349
    It has support for a master_branch which is the data for bound branches.
 
2350
    """
 
2351
 
 
2352
    def get_bound_location(self):
 
2353
        try:
 
2354
            return self._transport.get_bytes('bound')[:-1]
 
2355
        except errors.NoSuchFile:
 
2356
            return None
 
2357
 
 
2358
    @needs_read_lock
 
2359
    def get_master_branch(self, possible_transports=None):
 
2360
        """Return the branch we are bound to.
 
2361
 
 
2362
        :return: Either a Branch, or None
 
2363
 
 
2364
        This could memoise the branch, but if thats done
 
2365
        it must be revalidated on each new lock.
 
2366
        So for now we just don't memoise it.
 
2367
        # RBC 20060304 review this decision.
 
2368
        """
 
2369
        bound_loc = self.get_bound_location()
 
2370
        if not bound_loc:
 
2371
            return None
 
2372
        try:
 
2373
            return Branch.open(bound_loc,
 
2374
                               possible_transports=possible_transports)
 
2375
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2376
            raise errors.BoundBranchConnectionFailure(
 
2377
                    self, bound_loc, e)
 
2378
 
2503
2379
    @needs_write_lock
2504
 
    def unbind(self):
2505
 
        """If bound, unbind"""
2506
 
        return self.set_bound_location(None)
 
2380
    def set_bound_location(self, location):
 
2381
        """Set the target where this branch is bound to.
 
2382
 
 
2383
        :param location: URL to the target branch
 
2384
        """
 
2385
        if location:
 
2386
            self._transport.put_bytes('bound', location+'\n',
 
2387
                mode=self.bzrdir._get_file_mode())
 
2388
        else:
 
2389
            try:
 
2390
                self._transport.delete('bound')
 
2391
            except errors.NoSuchFile:
 
2392
                return False
 
2393
            return True
2507
2394
 
2508
2395
    @needs_write_lock
2509
2396
    def bind(self, other):
2531
2418
        # history around
2532
2419
        self.set_bound_location(other.base)
2533
2420
 
2534
 
    def get_bound_location(self):
2535
 
        try:
2536
 
            return self._transport.get_bytes('bound')[:-1]
2537
 
        except errors.NoSuchFile:
2538
 
            return None
2539
 
 
2540
 
    @needs_read_lock
2541
 
    def get_master_branch(self, possible_transports=None):
2542
 
        """Return the branch we are bound to.
2543
 
 
2544
 
        :return: Either a Branch, or None
2545
 
        """
2546
 
        if self._master_branch_cache is None:
2547
 
            self._master_branch_cache = self._get_master_branch(
2548
 
                possible_transports)
2549
 
        return self._master_branch_cache
2550
 
 
2551
 
    def _get_master_branch(self, possible_transports):
2552
 
        bound_loc = self.get_bound_location()
2553
 
        if not bound_loc:
2554
 
            return None
2555
 
        try:
2556
 
            return Branch.open(bound_loc,
2557
 
                               possible_transports=possible_transports)
2558
 
        except (errors.NotBranchError, errors.ConnectionError), e:
2559
 
            raise errors.BoundBranchConnectionFailure(
2560
 
                    self, bound_loc, e)
2561
 
 
2562
2421
    @needs_write_lock
2563
 
    def set_bound_location(self, location):
2564
 
        """Set the target where this branch is bound to.
2565
 
 
2566
 
        :param location: URL to the target branch
2567
 
        """
2568
 
        self._master_branch_cache = None
2569
 
        if location:
2570
 
            self._transport.put_bytes('bound', location+'\n',
2571
 
                mode=self.bzrdir._get_file_mode())
2572
 
        else:
2573
 
            try:
2574
 
                self._transport.delete('bound')
2575
 
            except errors.NoSuchFile:
2576
 
                return False
2577
 
            return True
 
2422
    def unbind(self):
 
2423
        """If bound, unbind"""
 
2424
        return self.set_bound_location(None)
2578
2425
 
2579
2426
    @needs_write_lock
2580
2427
    def update(self, possible_transports=None):
2593
2440
            return old_tip
2594
2441
        return None
2595
2442
 
2596
 
    def _read_last_revision_info(self):
2597
 
        revision_string = self._transport.get_bytes('last-revision')
2598
 
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2599
 
        revision_id = cache_utf8.get_cached_utf8(revision_id)
2600
 
        revno = int(revno)
2601
 
        return revno, revision_id
2602
 
 
2603
 
    def _write_last_revision_info(self, revno, revision_id):
2604
 
        """Simply write out the revision id, with no checks.
2605
 
 
2606
 
        Use set_last_revision_info to perform this safely.
2607
 
 
2608
 
        Does not update the revision_history cache.
2609
 
        """
2610
 
        revision_id = _mod_revision.ensure_null(revision_id)
2611
 
        out_string = '%d %s\n' % (revno, revision_id)
2612
 
        self._transport.put_bytes('last-revision', out_string,
2613
 
            mode=self.bzrdir._get_file_mode())
2614
 
 
2615
 
    @needs_write_lock
2616
 
    def update_feature_flags(self, updated_flags):
2617
 
        """Update the feature flags for this branch.
2618
 
 
2619
 
        :param updated_flags: Dictionary mapping feature names to necessities
2620
 
            A necessity can be None to indicate the feature should be removed
2621
 
        """
2622
 
        self._format._update_feature_flags(updated_flags)
2623
 
        self.control_transport.put_bytes('format', self._format.as_string())
2624
 
 
2625
 
 
2626
 
class BzrBranch8(BzrBranch):
 
2443
 
 
2444
class BzrBranch8(BzrBranch5):
2627
2445
    """A branch that stores tree-reference locations."""
2628
2446
 
2629
 
    def _open_hook(self, possible_transports=None):
 
2447
    def _open_hook(self):
2630
2448
        if self._ignore_fallbacks:
2631
2449
            return
2632
 
        if possible_transports is None:
2633
 
            possible_transports = [self.bzrdir.root_transport]
2634
2450
        try:
2635
2451
            url = self.get_stacked_on_url()
2636
2452
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2644
2460
                    raise AssertionError(
2645
2461
                        "'transform_fallback_location' hook %s returned "
2646
2462
                        "None, not a URL." % hook_name)
2647
 
            self._activate_fallback_location(url,
2648
 
                possible_transports=possible_transports)
 
2463
            self._activate_fallback_location(url)
2649
2464
 
2650
2465
    def __init__(self, *args, **kwargs):
2651
2466
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2658
2473
        self._last_revision_info_cache = None
2659
2474
        self._reference_info = None
2660
2475
 
 
2476
    def _last_revision_info(self):
 
2477
        revision_string = self._transport.get_bytes('last-revision')
 
2478
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2479
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2480
        revno = int(revno)
 
2481
        return revno, revision_id
 
2482
 
 
2483
    def _write_last_revision_info(self, revno, revision_id):
 
2484
        """Simply write out the revision id, with no checks.
 
2485
 
 
2486
        Use set_last_revision_info to perform this safely.
 
2487
 
 
2488
        Does not update the revision_history cache.
 
2489
        Intended to be called by set_last_revision_info and
 
2490
        _write_revision_history.
 
2491
        """
 
2492
        revision_id = _mod_revision.ensure_null(revision_id)
 
2493
        out_string = '%d %s\n' % (revno, revision_id)
 
2494
        self._transport.put_bytes('last-revision', out_string,
 
2495
            mode=self.bzrdir._get_file_mode())
 
2496
 
 
2497
    @needs_write_lock
 
2498
    def set_last_revision_info(self, revno, revision_id):
 
2499
        revision_id = _mod_revision.ensure_null(revision_id)
 
2500
        old_revno, old_revid = self.last_revision_info()
 
2501
        if self._get_append_revisions_only():
 
2502
            self._check_history_violation(revision_id)
 
2503
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2504
        self._write_last_revision_info(revno, revision_id)
 
2505
        self._clear_cached_state()
 
2506
        self._last_revision_info_cache = revno, revision_id
 
2507
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2508
 
 
2509
    def _synchronize_history(self, destination, revision_id):
 
2510
        """Synchronize last revision and revision history between branches.
 
2511
 
 
2512
        :see: Branch._synchronize_history
 
2513
        """
 
2514
        # XXX: The base Branch has a fast implementation of this method based
 
2515
        # on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
 
2516
        # that uses set_revision_history.  This class inherits from BzrBranch5,
 
2517
        # but wants the fast implementation, so it calls
 
2518
        # Branch._synchronize_history directly.
 
2519
        Branch._synchronize_history(self, destination, revision_id)
 
2520
 
2661
2521
    def _check_history_violation(self, revision_id):
2662
 
        current_revid = self.last_revision()
2663
 
        last_revision = _mod_revision.ensure_null(current_revid)
 
2522
        last_revision = _mod_revision.ensure_null(self.last_revision())
2664
2523
        if _mod_revision.is_null(last_revision):
2665
2524
            return
2666
 
        graph = self.repository.get_graph()
2667
 
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2668
 
            if lh_ancestor == current_revid:
2669
 
                return
2670
 
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2525
        if last_revision not in self._lefthand_history(revision_id):
 
2526
            raise errors.AppendRevisionsOnlyViolation(self.base)
2671
2527
 
2672
2528
    def _gen_revision_history(self):
2673
2529
        """Generate the revision history from last revision
2676
2532
        self._extend_partial_history(stop_index=last_revno-1)
2677
2533
        return list(reversed(self._partial_revision_history_cache))
2678
2534
 
 
2535
    def _write_revision_history(self, history):
 
2536
        """Factored out of set_revision_history.
 
2537
 
 
2538
        This performs the actual writing to disk, with format-specific checks.
 
2539
        It is intended to be called by BzrBranch5.set_revision_history.
 
2540
        """
 
2541
        if len(history) == 0:
 
2542
            last_revision = 'null:'
 
2543
        else:
 
2544
            if history != self._lefthand_history(history[-1]):
 
2545
                raise errors.NotLefthandHistory(history)
 
2546
            last_revision = history[-1]
 
2547
        if self._get_append_revisions_only():
 
2548
            self._check_history_violation(last_revision)
 
2549
        self._write_last_revision_info(len(history), last_revision)
 
2550
 
2679
2551
    @needs_write_lock
2680
2552
    def _set_parent_location(self, url):
2681
2553
        """Set the parent branch"""
2757
2629
        if branch_location is None:
2758
2630
            return Branch.reference_parent(self, file_id, path,
2759
2631
                                           possible_transports)
2760
 
        branch_location = urlutils.join(self.user_url, branch_location)
 
2632
        branch_location = urlutils.join(self.base, branch_location)
2761
2633
        return Branch.open(branch_location,
2762
2634
                           possible_transports=possible_transports)
2763
2635
 
2767
2639
 
2768
2640
    def set_bound_location(self, location):
2769
2641
        """See Branch.set_push_location."""
2770
 
        self._master_branch_cache = None
2771
2642
        result = None
2772
 
        conf = self.get_config_stack()
 
2643
        config = self.get_config()
2773
2644
        if location is None:
2774
 
            if not conf.get('bound'):
 
2645
            if config.get_user_option('bound') != 'True':
2775
2646
                return False
2776
2647
            else:
2777
 
                conf.set('bound', 'False')
 
2648
                config.set_user_option('bound', 'False', warn_masked=True)
2778
2649
                return True
2779
2650
        else:
2780
2651
            self._set_config_location('bound_location', location,
2781
 
                                      config=conf)
2782
 
            conf.set('bound', 'True')
 
2652
                                      config=config)
 
2653
            config.set_user_option('bound', 'True', warn_masked=True)
2783
2654
        return True
2784
2655
 
2785
2656
    def _get_bound_location(self, bound):
2786
2657
        """Return the bound location in the config file.
2787
2658
 
2788
2659
        Return None if the bound parameter does not match"""
2789
 
        conf = self.get_config_stack()
2790
 
        if conf.get('bound') != bound:
 
2660
        config = self.get_config()
 
2661
        config_bound = (config.get_user_option('bound') == 'True')
 
2662
        if config_bound != bound:
2791
2663
            return None
2792
 
        return self._get_config_location('bound_location', config=conf)
 
2664
        return self._get_config_location('bound_location', config=config)
2793
2665
 
2794
2666
    def get_bound_location(self):
2795
 
        """See Branch.get_bound_location."""
 
2667
        """See Branch.set_push_location."""
2796
2668
        return self._get_bound_location(True)
2797
2669
 
2798
2670
    def get_old_bound_location(self):
2803
2675
        # you can always ask for the URL; but you might not be able to use it
2804
2676
        # if the repo can't support stacking.
2805
2677
        ## self._check_stackable_repo()
2806
 
        # stacked_on_location is only ever defined in branch.conf, so don't
2807
 
        # waste effort reading the whole stack of config files.
2808
 
        conf = _mod_config.BranchOnlyStack(self)
2809
 
        stacked_url = self._get_config_location('stacked_on_location',
2810
 
                                                config=conf)
 
2678
        stacked_url = self._get_config_location('stacked_on_location')
2811
2679
        if stacked_url is None:
2812
2680
            raise errors.NotStacked(self)
2813
 
        return stacked_url.encode('utf-8')
 
2681
        return stacked_url
 
2682
 
 
2683
    def _get_append_revisions_only(self):
 
2684
        value = self.get_config().get_user_option('append_revisions_only')
 
2685
        return value == 'True'
 
2686
 
 
2687
    @needs_write_lock
 
2688
    def generate_revision_history(self, revision_id, last_rev=None,
 
2689
                                  other_branch=None):
 
2690
        """See BzrBranch5.generate_revision_history"""
 
2691
        history = self._lefthand_history(revision_id, last_rev, other_branch)
 
2692
        revno = len(history)
 
2693
        self.set_last_revision_info(revno, revision_id)
2814
2694
 
2815
2695
    @needs_read_lock
2816
2696
    def get_rev_id(self, revno, history=None):
2841
2721
        try:
2842
2722
            index = self._partial_revision_history_cache.index(revision_id)
2843
2723
        except ValueError:
2844
 
            try:
2845
 
                self._extend_partial_history(stop_revision=revision_id)
2846
 
            except errors.RevisionNotPresent, e:
2847
 
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2724
            self._extend_partial_history(stop_revision=revision_id)
2848
2725
            index = len(self._partial_revision_history_cache) - 1
2849
 
            if index < 0:
2850
 
                raise errors.NoSuchRevision(self, revision_id)
2851
2726
            if self._partial_revision_history_cache[index] != revision_id:
2852
2727
                raise errors.NoSuchRevision(self, revision_id)
2853
2728
        return self.revno() - index
2875
2750
    """
2876
2751
 
2877
2752
    def get_stacked_on_url(self):
2878
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2753
        raise errors.UnstackableBranchFormat(self._format, self.base)
2879
2754
 
2880
2755
 
2881
2756
######################################################################
2905
2780
    :ivar local_branch: target branch if there is a Master, else None
2906
2781
    :ivar target_branch: Target/destination branch object. (write locked)
2907
2782
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2908
 
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
2909
2783
    """
2910
2784
 
 
2785
    def __int__(self):
 
2786
        # DEPRECATED: pull used to return the change in revno
 
2787
        return self.new_revno - self.old_revno
 
2788
 
2911
2789
    def report(self, to_file):
2912
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
2913
 
        tag_updates = getattr(self, "tag_updates", None)
2914
2790
        if not is_quiet():
2915
 
            if self.old_revid != self.new_revid:
 
2791
            if self.old_revid == self.new_revid:
 
2792
                to_file.write('No revisions to pull.\n')
 
2793
            else:
2916
2794
                to_file.write('Now on revision %d.\n' % self.new_revno)
2917
 
            if tag_updates:
2918
 
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
2919
 
            if self.old_revid == self.new_revid and not tag_updates:
2920
 
                if not tag_conflicts:
2921
 
                    to_file.write('No revisions or tags to pull.\n')
2922
 
                else:
2923
 
                    to_file.write('No revisions to pull.\n')
2924
2795
        self._show_tag_conficts(to_file)
2925
2796
 
2926
2797
 
2943
2814
        target, otherwise it will be None.
2944
2815
    """
2945
2816
 
 
2817
    def __int__(self):
 
2818
        # DEPRECATED: push used to return the change in revno
 
2819
        return self.new_revno - self.old_revno
 
2820
 
2946
2821
    def report(self, to_file):
2947
 
        # TODO: This function gets passed a to_file, but then
2948
 
        # ignores it and calls note() instead. This is also
2949
 
        # inconsistent with PullResult(), which writes to stdout.
2950
 
        # -- JRV20110901, bug #838853
2951
 
        tag_conflicts = getattr(self, "tag_conflicts", None)
2952
 
        tag_updates = getattr(self, "tag_updates", None)
2953
 
        if not is_quiet():
2954
 
            if self.old_revid != self.new_revid:
2955
 
                note(gettext('Pushed up to revision %d.') % self.new_revno)
2956
 
            if tag_updates:
2957
 
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
2958
 
            if self.old_revid == self.new_revid and not tag_updates:
2959
 
                if not tag_conflicts:
2960
 
                    note(gettext('No new revisions or tags to push.'))
2961
 
                else:
2962
 
                    note(gettext('No new revisions to push.'))
 
2822
        """Write a human-readable description of the result."""
 
2823
        if self.old_revid == self.new_revid:
 
2824
            note('No new revisions to push.')
 
2825
        else:
 
2826
            note('Pushed up to revision %d.' % self.new_revno)
2963
2827
        self._show_tag_conficts(to_file)
2964
2828
 
2965
2829
 
2979
2843
        :param verbose: Requests more detailed display of what was checked,
2980
2844
            if any.
2981
2845
        """
2982
 
        note(gettext('checked branch {0} format {1}').format(
2983
 
                                self.branch.user_url, self.branch._format))
 
2846
        note('checked branch %s format %s', self.branch.base,
 
2847
            self.branch._format)
2984
2848
        for error in self.errors:
2985
 
            note(gettext('found error:%s'), error)
 
2849
            note('found error:%s', error)
2986
2850
 
2987
2851
 
2988
2852
class Converter5to6(object):
2995
2859
 
2996
2860
        # Copy source data into target
2997
2861
        new_branch._write_last_revision_info(*branch.last_revision_info())
2998
 
        new_branch.lock_write()
2999
 
        try:
3000
 
            new_branch.set_parent(branch.get_parent())
3001
 
            new_branch.set_bound_location(branch.get_bound_location())
3002
 
            new_branch.set_push_location(branch.get_push_location())
3003
 
        finally:
3004
 
            new_branch.unlock()
 
2862
        new_branch.set_parent(branch.get_parent())
 
2863
        new_branch.set_bound_location(branch.get_bound_location())
 
2864
        new_branch.set_push_location(branch.get_push_location())
3005
2865
 
3006
2866
        # New branch has no tags by default
3007
2867
        new_branch.tags._set_tag_dict({})
3008
2868
 
3009
2869
        # Copying done; now update target format
3010
2870
        new_branch._transport.put_bytes('format',
3011
 
            format.as_string(),
 
2871
            format.get_format_string(),
3012
2872
            mode=new_branch.bzrdir._get_file_mode())
3013
2873
 
3014
2874
        # Clean up old files
3015
2875
        new_branch._transport.delete('revision-history')
3016
 
        branch.lock_write()
3017
2876
        try:
3018
 
            try:
3019
 
                branch.set_parent(None)
3020
 
            except errors.NoSuchFile:
3021
 
                pass
3022
 
            branch.set_bound_location(None)
3023
 
        finally:
3024
 
            branch.unlock()
 
2877
            branch.set_parent(None)
 
2878
        except errors.NoSuchFile:
 
2879
            pass
 
2880
        branch.set_bound_location(None)
3025
2881
 
3026
2882
 
3027
2883
class Converter6to7(object):
3031
2887
        format = BzrBranchFormat7()
3032
2888
        branch._set_config_location('stacked_on_location', '')
3033
2889
        # update target format
3034
 
        branch._transport.put_bytes('format', format.as_string())
 
2890
        branch._transport.put_bytes('format', format.get_format_string())
3035
2891
 
3036
2892
 
3037
2893
class Converter7to8(object):
3038
 
    """Perform an in-place upgrade of format 7 to format 8"""
 
2894
    """Perform an in-place upgrade of format 6 to format 7"""
3039
2895
 
3040
2896
    def convert(self, branch):
3041
2897
        format = BzrBranchFormat8()
3042
2898
        branch._transport.put_bytes('references', '')
3043
2899
        # update target format
3044
 
        branch._transport.put_bytes('format', format.as_string())
 
2900
        branch._transport.put_bytes('format', format.get_format_string())
 
2901
 
 
2902
 
 
2903
def _run_with_write_locked_target(target, callable, *args, **kwargs):
 
2904
    """Run ``callable(*args, **kwargs)``, write-locking target for the
 
2905
    duration.
 
2906
 
 
2907
    _run_with_write_locked_target will attempt to release the lock it acquires.
 
2908
 
 
2909
    If an exception is raised by callable, then that exception *will* be
 
2910
    propagated, even if the unlock attempt raises its own error.  Thus
 
2911
    _run_with_write_locked_target should be preferred to simply doing::
 
2912
 
 
2913
        target.lock_write()
 
2914
        try:
 
2915
            return callable(*args, **kwargs)
 
2916
        finally:
 
2917
            target.unlock()
 
2918
 
 
2919
    """
 
2920
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
 
2921
    # should share code?
 
2922
    target.lock_write()
 
2923
    try:
 
2924
        result = callable(*args, **kwargs)
 
2925
    except:
 
2926
        exc_info = sys.exc_info()
 
2927
        try:
 
2928
            target.unlock()
 
2929
        finally:
 
2930
            raise exc_info[0], exc_info[1], exc_info[2]
 
2931
    else:
 
2932
        target.unlock()
 
2933
        return result
3045
2934
 
3046
2935
 
3047
2936
class InterBranch(InterObject):
3055
2944
    _optimisers = []
3056
2945
    """The available optimised InterBranch types."""
3057
2946
 
3058
 
    @classmethod
3059
 
    def _get_branch_formats_to_test(klass):
3060
 
        """Return an iterable of format tuples for testing.
3061
 
        
3062
 
        :return: An iterable of (from_format, to_format) to use when testing
3063
 
            this InterBranch class. Each InterBranch class should define this
3064
 
            method itself.
3065
 
        """
3066
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2947
    @staticmethod
 
2948
    def _get_branch_formats_to_test():
 
2949
        """Return a tuple with the Branch formats to use when testing."""
 
2950
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3067
2951
 
3068
 
    @needs_write_lock
3069
2952
    def pull(self, overwrite=False, stop_revision=None,
3070
2953
             possible_transports=None, local=False):
3071
2954
        """Mirror source into target branch.
3076
2959
        """
3077
2960
        raise NotImplementedError(self.pull)
3078
2961
 
3079
 
    @needs_write_lock
3080
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2962
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2963
                         graph=None):
 
2964
        """Pull in new perfect-fit revisions.
 
2965
 
 
2966
        :param stop_revision: Updated until the given revision
 
2967
        :param overwrite: Always set the branch pointer, rather than checking
 
2968
            to see if it is a proper descendant.
 
2969
        :param graph: A Graph object that can be used to query history
 
2970
            information. This can be None.
 
2971
        :return: None
 
2972
        """
 
2973
        raise NotImplementedError(self.update_revisions)
 
2974
 
 
2975
    def push(self, overwrite=False, stop_revision=None,
3081
2976
             _override_hook_source_branch=None):
3082
2977
        """Mirror the source branch into the target branch.
3083
2978
 
3085
2980
        """
3086
2981
        raise NotImplementedError(self.push)
3087
2982
 
3088
 
    @needs_write_lock
3089
 
    def copy_content_into(self, revision_id=None):
3090
 
        """Copy the content of source into target
3091
 
 
3092
 
        revision_id: if not None, the revision history in the new branch will
3093
 
                     be truncated to end with revision_id.
3094
 
        """
3095
 
        raise NotImplementedError(self.copy_content_into)
3096
 
 
3097
 
    @needs_write_lock
3098
 
    def fetch(self, stop_revision=None, limit=None):
3099
 
        """Fetch revisions.
3100
 
 
3101
 
        :param stop_revision: Last revision to fetch
3102
 
        :param limit: Optional rough limit of revisions to fetch
3103
 
        """
3104
 
        raise NotImplementedError(self.fetch)
3105
 
 
3106
 
 
3107
 
def _fix_overwrite_type(overwrite):
3108
 
    if isinstance(overwrite, bool):
3109
 
        if overwrite:
3110
 
            return ["history", "tags"]
3111
 
        else:
3112
 
            return []
3113
 
    return overwrite
3114
 
 
3115
2983
 
3116
2984
class GenericInterBranch(InterBranch):
3117
 
    """InterBranch implementation that uses public Branch functions."""
3118
 
 
3119
 
    @classmethod
3120
 
    def is_compatible(klass, source, target):
3121
 
        # GenericBranch uses the public API, so always compatible
3122
 
        return True
3123
 
 
3124
 
    @classmethod
3125
 
    def _get_branch_formats_to_test(klass):
3126
 
        return [(format_registry.get_default(), format_registry.get_default())]
3127
 
 
3128
 
    @classmethod
3129
 
    def unwrap_format(klass, format):
3130
 
        if isinstance(format, remote.RemoteBranchFormat):
3131
 
            format._ensure_real()
3132
 
            return format._custom_format
3133
 
        return format
3134
 
 
3135
 
    @needs_write_lock
3136
 
    def copy_content_into(self, revision_id=None):
3137
 
        """Copy the content of source into target
3138
 
 
3139
 
        revision_id: if not None, the revision history in the new branch will
3140
 
                     be truncated to end with revision_id.
3141
 
        """
3142
 
        self.source.update_references(self.target)
3143
 
        self.source._synchronize_history(self.target, revision_id)
3144
 
        try:
3145
 
            parent = self.source.get_parent()
3146
 
        except errors.InaccessibleParent, e:
3147
 
            mutter('parent was not accessible to copy: %s', e)
3148
 
        else:
3149
 
            if parent:
3150
 
                self.target.set_parent(parent)
3151
 
        if self.source._push_should_merge_tags():
3152
 
            self.source.tags.merge_to(self.target.tags)
3153
 
 
3154
 
    @needs_write_lock
3155
 
    def fetch(self, stop_revision=None, limit=None):
3156
 
        if self.target.base == self.source.base:
3157
 
            return (0, [])
 
2985
    """InterBranch implementation that uses public Branch functions.
 
2986
    """
 
2987
 
 
2988
    @staticmethod
 
2989
    def _get_branch_formats_to_test():
 
2990
        return BranchFormat._default_format, BranchFormat._default_format
 
2991
 
 
2992
    def update_revisions(self, stop_revision=None, overwrite=False,
 
2993
        graph=None):
 
2994
        """See InterBranch.update_revisions()."""
3158
2995
        self.source.lock_read()
3159
2996
        try:
3160
 
            fetch_spec_factory = fetch.FetchSpecFactory()
3161
 
            fetch_spec_factory.source_branch = self.source
3162
 
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3163
 
            fetch_spec_factory.source_repo = self.source.repository
3164
 
            fetch_spec_factory.target_repo = self.target.repository
3165
 
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3166
 
            fetch_spec_factory.limit = limit
3167
 
            fetch_spec = fetch_spec_factory.make_fetch_spec()
3168
 
            return self.target.repository.fetch(self.source.repository,
3169
 
                fetch_spec=fetch_spec)
 
2997
            other_revno, other_last_revision = self.source.last_revision_info()
 
2998
            stop_revno = None # unknown
 
2999
            if stop_revision is None:
 
3000
                stop_revision = other_last_revision
 
3001
                if _mod_revision.is_null(stop_revision):
 
3002
                    # if there are no commits, we're done.
 
3003
                    return
 
3004
                stop_revno = other_revno
 
3005
 
 
3006
            # what's the current last revision, before we fetch [and change it
 
3007
            # possibly]
 
3008
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3009
            # we fetch here so that we don't process data twice in the common
 
3010
            # case of having something to pull, and so that the check for
 
3011
            # already merged can operate on the just fetched graph, which will
 
3012
            # be cached in memory.
 
3013
            self.target.fetch(self.source, stop_revision)
 
3014
            # Check to see if one is an ancestor of the other
 
3015
            if not overwrite:
 
3016
                if graph is None:
 
3017
                    graph = self.target.repository.get_graph()
 
3018
                if self.target._check_if_descendant_or_diverged(
 
3019
                        stop_revision, last_rev, graph, self.source):
 
3020
                    # stop_revision is a descendant of last_rev, but we aren't
 
3021
                    # overwriting, so we're done.
 
3022
                    return
 
3023
            if stop_revno is None:
 
3024
                if graph is None:
 
3025
                    graph = self.target.repository.get_graph()
 
3026
                this_revno, this_last_revision = \
 
3027
                        self.target.last_revision_info()
 
3028
                stop_revno = graph.find_distance_to_null(stop_revision,
 
3029
                                [(other_last_revision, other_revno),
 
3030
                                 (this_last_revision, this_revno)])
 
3031
            self.target.set_last_revision_info(stop_revno, stop_revision)
3170
3032
        finally:
3171
3033
            self.source.unlock()
3172
3034
 
3173
 
    @needs_write_lock
3174
 
    def _update_revisions(self, stop_revision=None, overwrite=False,
3175
 
            graph=None):
3176
 
        other_revno, other_last_revision = self.source.last_revision_info()
3177
 
        stop_revno = None # unknown
3178
 
        if stop_revision is None:
3179
 
            stop_revision = other_last_revision
3180
 
            if _mod_revision.is_null(stop_revision):
3181
 
                # if there are no commits, we're done.
3182
 
                return
3183
 
            stop_revno = other_revno
3184
 
 
3185
 
        # what's the current last revision, before we fetch [and change it
3186
 
        # possibly]
3187
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3188
 
        # we fetch here so that we don't process data twice in the common
3189
 
        # case of having something to pull, and so that the check for
3190
 
        # already merged can operate on the just fetched graph, which will
3191
 
        # be cached in memory.
3192
 
        self.fetch(stop_revision=stop_revision)
3193
 
        # Check to see if one is an ancestor of the other
3194
 
        if not overwrite:
3195
 
            if graph is None:
3196
 
                graph = self.target.repository.get_graph()
3197
 
            if self.target._check_if_descendant_or_diverged(
3198
 
                    stop_revision, last_rev, graph, self.source):
3199
 
                # stop_revision is a descendant of last_rev, but we aren't
3200
 
                # overwriting, so we're done.
3201
 
                return
3202
 
        if stop_revno is None:
3203
 
            if graph is None:
3204
 
                graph = self.target.repository.get_graph()
3205
 
            this_revno, this_last_revision = \
3206
 
                    self.target.last_revision_info()
3207
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3208
 
                            [(other_last_revision, other_revno),
3209
 
                             (this_last_revision, this_revno)])
3210
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3211
 
 
3212
 
    @needs_write_lock
3213
3035
    def pull(self, overwrite=False, stop_revision=None,
3214
 
             possible_transports=None, run_hooks=True,
3215
 
             _override_hook_target=None, local=False):
3216
 
        """Pull from source into self, updating my master if any.
3217
 
 
3218
 
        :param run_hooks: Private parameter - if false, this branch
3219
 
            is being called because it's the master of the primary branch,
3220
 
            so it should not run its hooks.
3221
 
        """
3222
 
        bound_location = self.target.get_bound_location()
3223
 
        if local and not bound_location:
3224
 
            raise errors.LocalRequiresBoundBranch()
3225
 
        master_branch = None
3226
 
        source_is_master = False
3227
 
        if bound_location:
3228
 
            # bound_location comes from a config file, some care has to be
3229
 
            # taken to relate it to source.user_url
3230
 
            normalized = urlutils.normalize_url(bound_location)
3231
 
            try:
3232
 
                relpath = self.source.user_transport.relpath(normalized)
3233
 
                source_is_master = (relpath == '')
3234
 
            except (errors.PathNotChild, errors.InvalidURL):
3235
 
                source_is_master = False
3236
 
        if not local and bound_location and not source_is_master:
3237
 
            # not pulling from master, so we need to update master.
3238
 
            master_branch = self.target.get_master_branch(possible_transports)
3239
 
            master_branch.lock_write()
3240
 
        try:
3241
 
            if master_branch:
3242
 
                # pull from source into master.
3243
 
                master_branch.pull(self.source, overwrite, stop_revision,
3244
 
                    run_hooks=False)
3245
 
            return self._pull(overwrite,
3246
 
                stop_revision, _hook_master=master_branch,
3247
 
                run_hooks=run_hooks,
3248
 
                _override_hook_target=_override_hook_target,
3249
 
                merge_tags_to_master=not source_is_master)
3250
 
        finally:
3251
 
            if master_branch:
3252
 
                master_branch.unlock()
3253
 
 
3254
 
    def push(self, overwrite=False, stop_revision=None, lossy=False,
3255
 
             _override_hook_source_branch=None):
3256
 
        """See InterBranch.push.
3257
 
 
3258
 
        This is the basic concrete implementation of push()
3259
 
 
3260
 
        :param _override_hook_source_branch: If specified, run the hooks
3261
 
            passing this Branch as the source, rather than self.  This is for
3262
 
            use of RemoteBranch, where push is delegated to the underlying
3263
 
            vfs-based Branch.
3264
 
        """
3265
 
        if lossy:
3266
 
            raise errors.LossyPushToSameVCS(self.source, self.target)
3267
 
        # TODO: Public option to disable running hooks - should be trivial but
3268
 
        # needs tests.
3269
 
 
3270
 
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3271
 
        op.add_cleanup(self.source.lock_read().unlock)
3272
 
        op.add_cleanup(self.target.lock_write().unlock)
3273
 
        return op.run(overwrite, stop_revision,
3274
 
            _override_hook_source_branch=_override_hook_source_branch)
3275
 
 
3276
 
    def _basic_push(self, overwrite, stop_revision):
3277
 
        """Basic implementation of push without bound branches or hooks.
3278
 
 
3279
 
        Must be called with source read locked and target write locked.
3280
 
        """
3281
 
        result = BranchPushResult()
3282
 
        result.source_branch = self.source
3283
 
        result.target_branch = self.target
3284
 
        result.old_revno, result.old_revid = self.target.last_revision_info()
3285
 
        self.source.update_references(self.target)
3286
 
        overwrite = _fix_overwrite_type(overwrite)
3287
 
        if result.old_revid != stop_revision:
3288
 
            # We assume that during 'push' this repository is closer than
3289
 
            # the target.
3290
 
            graph = self.source.repository.get_graph(self.target.repository)
3291
 
            self._update_revisions(stop_revision,
3292
 
                overwrite=("history" in overwrite),
3293
 
                graph=graph)
3294
 
        if self.source._push_should_merge_tags():
3295
 
            result.tag_updates, result.tag_conflicts = (
3296
 
                self.source.tags.merge_to(
3297
 
                self.target.tags, "tags" in overwrite))
3298
 
        result.new_revno, result.new_revid = self.target.last_revision_info()
3299
 
        return result
3300
 
 
3301
 
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3302
 
            _override_hook_source_branch=None):
3303
 
        """Push from source into target, and into target's master if any.
3304
 
        """
3305
 
        def _run_hooks():
3306
 
            if _override_hook_source_branch:
3307
 
                result.source_branch = _override_hook_source_branch
3308
 
            for hook in Branch.hooks['post_push']:
3309
 
                hook(result)
3310
 
 
3311
 
        bound_location = self.target.get_bound_location()
3312
 
        if bound_location and self.target.base != bound_location:
3313
 
            # there is a master branch.
3314
 
            #
3315
 
            # XXX: Why the second check?  Is it even supported for a branch to
3316
 
            # be bound to itself? -- mbp 20070507
3317
 
            master_branch = self.target.get_master_branch()
3318
 
            master_branch.lock_write()
3319
 
            operation.add_cleanup(master_branch.unlock)
3320
 
            # push into the master from the source branch.
3321
 
            master_inter = InterBranch.get(self.source, master_branch)
3322
 
            master_inter._basic_push(overwrite, stop_revision)
3323
 
            # and push into the target branch from the source. Note that
3324
 
            # we push from the source branch again, because it's considered
3325
 
            # the highest bandwidth repository.
3326
 
            result = self._basic_push(overwrite, stop_revision)
3327
 
            result.master_branch = master_branch
3328
 
            result.local_branch = self.target
3329
 
        else:
3330
 
            master_branch = None
3331
 
            # no master branch
3332
 
            result = self._basic_push(overwrite, stop_revision)
3333
 
            # TODO: Why set master_branch and local_branch if there's no
3334
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3335
 
            # 20070504
3336
 
            result.master_branch = self.target
3337
 
            result.local_branch = None
3338
 
        _run_hooks()
3339
 
        return result
3340
 
 
3341
 
    def _pull(self, overwrite=False, stop_revision=None,
3342
3036
             possible_transports=None, _hook_master=None, run_hooks=True,
3343
 
             _override_hook_target=None, local=False,
3344
 
             merge_tags_to_master=True):
 
3037
             _override_hook_target=None, local=False):
3345
3038
        """See Branch.pull.
3346
3039
 
3347
 
        This function is the core worker, used by GenericInterBranch.pull to
3348
 
        avoid duplication when pulling source->master and source->local.
3349
 
 
3350
3040
        :param _hook_master: Private parameter - set the branch to
3351
3041
            be supplied as the master to pull hooks.
3352
3042
        :param run_hooks: Private parameter - if false, this branch
3353
3043
            is being called because it's the master of the primary branch,
3354
3044
            so it should not run its hooks.
3355
 
            is being called because it's the master of the primary branch,
3356
 
            so it should not run its hooks.
3357
3045
        :param _override_hook_target: Private parameter - set the branch to be
3358
3046
            supplied as the target_branch to pull hooks.
3359
3047
        :param local: Only update the local branch, and not the bound branch.
3378
3066
            # -- JRV20090506
3379
3067
            result.old_revno, result.old_revid = \
3380
3068
                self.target.last_revision_info()
3381
 
            overwrite = _fix_overwrite_type(overwrite)
3382
 
            self._update_revisions(stop_revision,
3383
 
                overwrite=("history" in overwrite),
3384
 
                graph=graph)
 
3069
            self.target.update_revisions(self.source, stop_revision,
 
3070
                overwrite=overwrite, graph=graph)
3385
3071
            # TODO: The old revid should be specified when merging tags, 
3386
3072
            # so a tags implementation that versions tags can only 
3387
3073
            # pull in the most recent changes. -- JRV20090506
3388
 
            result.tag_updates, result.tag_conflicts = (
3389
 
                self.source.tags.merge_to(self.target.tags,
3390
 
                    "tags" in overwrite,
3391
 
                    ignore_master=not merge_tags_to_master))
 
3074
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3075
                overwrite)
3392
3076
            result.new_revno, result.new_revid = self.target.last_revision_info()
3393
3077
            if _hook_master:
3394
3078
                result.master_branch = _hook_master
3403
3087
            self.source.unlock()
3404
3088
        return result
3405
3089
 
 
3090
    def push(self, overwrite=False, stop_revision=None,
 
3091
             _override_hook_source_branch=None):
 
3092
        """See InterBranch.push.
 
3093
 
 
3094
        This is the basic concrete implementation of push()
 
3095
 
 
3096
        :param _override_hook_source_branch: If specified, run
 
3097
        the hooks passing this Branch as the source, rather than self.
 
3098
        This is for use of RemoteBranch, where push is delegated to the
 
3099
        underlying vfs-based Branch.
 
3100
        """
 
3101
        # TODO: Public option to disable running hooks - should be trivial but
 
3102
        # needs tests.
 
3103
        self.source.lock_read()
 
3104
        try:
 
3105
            return _run_with_write_locked_target(
 
3106
                self.target, self._push_with_bound_branches, overwrite,
 
3107
                stop_revision,
 
3108
                _override_hook_source_branch=_override_hook_source_branch)
 
3109
        finally:
 
3110
            self.source.unlock()
 
3111
 
 
3112
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3113
            _override_hook_source_branch=None):
 
3114
        """Push from source into target, and into target's master if any.
 
3115
        """
 
3116
        def _run_hooks():
 
3117
            if _override_hook_source_branch:
 
3118
                result.source_branch = _override_hook_source_branch
 
3119
            for hook in Branch.hooks['post_push']:
 
3120
                hook(result)
 
3121
 
 
3122
        bound_location = self.target.get_bound_location()
 
3123
        if bound_location and self.target.base != bound_location:
 
3124
            # there is a master branch.
 
3125
            #
 
3126
            # XXX: Why the second check?  Is it even supported for a branch to
 
3127
            # be bound to itself? -- mbp 20070507
 
3128
            master_branch = self.target.get_master_branch()
 
3129
            master_branch.lock_write()
 
3130
            try:
 
3131
                # push into the master from the source branch.
 
3132
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3133
                # and push into the target branch from the source. Note that we
 
3134
                # push from the source branch again, because its considered the
 
3135
                # highest bandwidth repository.
 
3136
                result = self.source._basic_push(self.target, overwrite,
 
3137
                    stop_revision)
 
3138
                result.master_branch = master_branch
 
3139
                result.local_branch = self.target
 
3140
                _run_hooks()
 
3141
                return result
 
3142
            finally:
 
3143
                master_branch.unlock()
 
3144
        else:
 
3145
            # no master branch
 
3146
            result = self.source._basic_push(self.target, overwrite,
 
3147
                stop_revision)
 
3148
            # TODO: Why set master_branch and local_branch if there's no
 
3149
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3150
            # 20070504
 
3151
            result.master_branch = self.target
 
3152
            result.local_branch = None
 
3153
            _run_hooks()
 
3154
            return result
 
3155
 
 
3156
    @classmethod
 
3157
    def is_compatible(self, source, target):
 
3158
        # GenericBranch uses the public API, so always compatible
 
3159
        return True
 
3160
 
 
3161
 
 
3162
class InterToBranch5(GenericInterBranch):
 
3163
 
 
3164
    @staticmethod
 
3165
    def _get_branch_formats_to_test():
 
3166
        return BranchFormat._default_format, BzrBranchFormat5()
 
3167
 
 
3168
    def pull(self, overwrite=False, stop_revision=None,
 
3169
             possible_transports=None, run_hooks=True,
 
3170
             _override_hook_target=None, local=False):
 
3171
        """Pull from source into self, updating my master if any.
 
3172
 
 
3173
        :param run_hooks: Private parameter - if false, this branch
 
3174
            is being called because it's the master of the primary branch,
 
3175
            so it should not run its hooks.
 
3176
        """
 
3177
        bound_location = self.target.get_bound_location()
 
3178
        if local and not bound_location:
 
3179
            raise errors.LocalRequiresBoundBranch()
 
3180
        master_branch = None
 
3181
        if not local and bound_location and self.source.base != bound_location:
 
3182
            # not pulling from master, so we need to update master.
 
3183
            master_branch = self.target.get_master_branch(possible_transports)
 
3184
            master_branch.lock_write()
 
3185
        try:
 
3186
            if master_branch:
 
3187
                # pull from source into master.
 
3188
                master_branch.pull(self.source, overwrite, stop_revision,
 
3189
                    run_hooks=False)
 
3190
            return super(InterToBranch5, self).pull(overwrite,
 
3191
                stop_revision, _hook_master=master_branch,
 
3192
                run_hooks=run_hooks,
 
3193
                _override_hook_target=_override_hook_target)
 
3194
        finally:
 
3195
            if master_branch:
 
3196
                master_branch.unlock()
 
3197
 
3406
3198
 
3407
3199
InterBranch.register_optimiser(GenericInterBranch)
 
3200
InterBranch.register_optimiser(InterToBranch5)