~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Canonical.com Patch Queue Manager
  • Date: 2009-03-17 07:05:37 UTC
  • mfrom: (4152.1.2 branch.stacked.streams)
  • Revision ID: pqm@pqm.ubuntu.com-20090317070537-zaud24vjs2szna87
(robertc) Add client-side streaming from stacked branches (over
        bzr:// protocols) when the sort order is compatible with doing
        that. (Robert Collins, Andrew Bennetts)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005-2010 Canonical Ltd
 
1
# Copyright (C) 2005, 2006, 2007, 2008, 2009 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
 
 
17
 
 
18
 
from cStringIO import StringIO
 
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
 
 
17
 
19
18
import sys
20
19
 
21
20
from bzrlib.lazy_import import lazy_import
25
24
        bzrdir,
26
25
        cache_utf8,
27
26
        config as _mod_config,
28
 
        controldir,
29
27
        debug,
30
28
        errors,
31
29
        lockdir,
32
30
        lockable_files,
33
 
        remote,
34
31
        repository,
35
32
        revision as _mod_revision,
36
 
        rio,
37
33
        symbol_versioning,
38
34
        transport,
39
35
        tsort,
40
36
        ui,
41
37
        urlutils,
42
38
        )
43
 
from bzrlib.config import BranchConfig, TransportConfig
 
39
from bzrlib.config import BranchConfig
44
40
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
45
41
from bzrlib.tag import (
46
42
    BasicTags,
48
44
    )
49
45
""")
50
46
 
51
 
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
47
from bzrlib.decorators import needs_read_lock, needs_write_lock
52
48
from bzrlib.hooks import HookPoint, Hooks
53
49
from bzrlib.inter import InterObject
54
 
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
55
50
from bzrlib import registry
56
51
from bzrlib.symbol_versioning import (
57
52
    deprecated_in,
65
60
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
66
61
 
67
62
 
68
 
class Branch(controldir.ControlComponent):
 
63
# TODO: Maybe include checks for common corruption of newlines, etc?
 
64
 
 
65
# TODO: Some operations like log might retrieve the same revisions
 
66
# repeatedly to calculate deltas.  We could perhaps have a weakref
 
67
# cache in memory to make this faster.  In general anything can be
 
68
# cached in memory between lock and unlock operations. .. nb thats
 
69
# what the transaction identity map provides
 
70
 
 
71
 
 
72
######################################################################
 
73
# branch objects
 
74
 
 
75
class Branch(object):
69
76
    """Branch holding a history of revisions.
70
77
 
71
 
    :ivar base:
72
 
        Base directory/url of the branch; using control_url and
73
 
        control_transport is more standardized.
 
78
    base
 
79
        Base directory/url of the branch.
74
80
 
75
81
    hooks: An instance of BranchHooks.
76
82
    """
78
84
    # - RBC 20060112
79
85
    base = None
80
86
 
81
 
    @property
82
 
    def control_transport(self):
83
 
        return self._transport
84
 
 
85
 
    @property
86
 
    def user_transport(self):
87
 
        return self.bzrdir.user_transport
88
 
 
89
87
    def __init__(self, *ignored, **ignored_too):
90
88
        self.tags = self._format.make_tags(self)
91
89
        self._revision_history_cache = None
92
90
        self._revision_id_to_revno_cache = None
93
91
        self._partial_revision_id_to_revno_cache = {}
94
 
        self._partial_revision_history_cache = []
95
92
        self._last_revision_info_cache = None
96
93
        self._merge_sorted_revisions_cache = None
97
94
        self._open_hook()
102
99
    def _open_hook(self):
103
100
        """Called by init to allow simpler extension of the base class."""
104
101
 
105
 
    def _activate_fallback_location(self, url):
106
 
        """Activate the branch/repository from url as a fallback repository."""
107
 
        repo = self._get_fallback_repository(url)
108
 
        if repo.has_same_location(self.repository):
109
 
            raise errors.UnstackableLocationError(self.user_url, url)
110
 
        self.repository.add_fallback_repository(repo)
111
 
 
112
102
    def break_lock(self):
113
103
        """Break a lock if one is present from another instance.
114
104
 
123
113
        if master is not None:
124
114
            master.break_lock()
125
115
 
126
 
    def _check_stackable_repo(self):
127
 
        if not self.repository._format.supports_external_lookups:
128
 
            raise errors.UnstackableRepositoryFormat(self.repository._format,
129
 
                self.repository.base)
130
 
 
131
 
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
132
 
        """Extend the partial history to include a given index
133
 
 
134
 
        If a stop_index is supplied, stop when that index has been reached.
135
 
        If a stop_revision is supplied, stop when that revision is
136
 
        encountered.  Otherwise, stop when the beginning of history is
137
 
        reached.
138
 
 
139
 
        :param stop_index: The index which should be present.  When it is
140
 
            present, history extension will stop.
141
 
        :param stop_revision: The revision id which should be present.  When
142
 
            it is encountered, history extension will stop.
143
 
        """
144
 
        if len(self._partial_revision_history_cache) == 0:
145
 
            self._partial_revision_history_cache = [self.last_revision()]
146
 
        repository._iter_for_revno(
147
 
            self.repository, self._partial_revision_history_cache,
148
 
            stop_index=stop_index, stop_revision=stop_revision)
149
 
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
150
 
            self._partial_revision_history_cache.pop()
151
 
 
152
 
    def _get_check_refs(self):
153
 
        """Get the references needed for check().
154
 
 
155
 
        See bzrlib.check.
156
 
        """
157
 
        revid = self.last_revision()
158
 
        return [('revision-existence', revid), ('lefthand-distance', revid)]
159
 
 
160
116
    @staticmethod
161
117
    def open(base, _unsupported=False, possible_transports=None):
162
118
        """Open the branch rooted at base.
166
122
        """
167
123
        control = bzrdir.BzrDir.open(base, _unsupported,
168
124
                                     possible_transports=possible_transports)
169
 
        return control.open_branch(unsupported=_unsupported)
 
125
        return control.open_branch(_unsupported)
170
126
 
171
127
    @staticmethod
172
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
128
    def open_from_transport(transport, _unsupported=False):
173
129
        """Open the branch rooted at transport"""
174
130
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
175
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
131
        return control.open_branch(_unsupported)
176
132
 
177
133
    @staticmethod
178
134
    def open_containing(url, possible_transports=None):
199
155
        return self.supports_tags() and self.tags.get_tag_dict()
200
156
 
201
157
    def get_config(self):
202
 
        """Get a bzrlib.config.BranchConfig for this Branch.
203
 
 
204
 
        This can then be used to get and set configuration options for the
205
 
        branch.
206
 
 
207
 
        :return: A bzrlib.config.BranchConfig.
208
 
        """
209
158
        return BranchConfig(self)
210
159
 
211
 
    def _get_config(self):
212
 
        """Get the concrete config for just the config in this branch.
213
 
 
214
 
        This is not intended for client use; see Branch.get_config for the
215
 
        public API.
216
 
 
217
 
        Added in 1.14.
218
 
 
219
 
        :return: An object supporting get_option and set_option.
220
 
        """
221
 
        raise NotImplementedError(self._get_config)
222
 
 
223
 
    def _get_fallback_repository(self, url):
224
 
        """Get the repository we fallback to at url."""
225
 
        url = urlutils.join(self.base, url)
226
 
        a_branch = Branch.open(url,
227
 
            possible_transports=[self.bzrdir.root_transport])
228
 
        return a_branch.repository
229
 
 
230
160
    def _get_tags_bytes(self):
231
161
        """Get the bytes of a serialised tags dict.
232
162
 
247
177
        if not local and not config.has_explicit_nickname():
248
178
            try:
249
179
                master = self.get_master_branch(possible_transports)
250
 
                if master and self.user_url == master.user_url:
251
 
                    raise errors.RecursiveBind(self.user_url)
252
180
                if master is not None:
253
181
                    # return the master branch value
254
182
                    return master.nick
255
 
            except errors.RecursiveBind, e:
256
 
                raise e
257
183
            except errors.BzrError, e:
258
184
                # Silently fall back to local implicit nick if the master is
259
185
                # unavailable
296
222
        new_history.reverse()
297
223
        return new_history
298
224
 
299
 
    def lock_write(self, token=None):
300
 
        """Lock the branch for write operations.
301
 
 
302
 
        :param token: A token to permit reacquiring a previously held and
303
 
            preserved lock.
304
 
        :return: A BranchWriteLockResult.
305
 
        """
 
225
    def lock_write(self):
306
226
        raise NotImplementedError(self.lock_write)
307
227
 
308
228
    def lock_read(self):
309
 
        """Lock the branch for read operations.
310
 
 
311
 
        :return: A bzrlib.lock.LogicalLockResult.
312
 
        """
313
229
        raise NotImplementedError(self.lock_read)
314
230
 
315
231
    def unlock(self):
440
356
            * 'include' - the stop revision is the last item in the result
441
357
            * 'with-merges' - include the stop revision and all of its
442
358
              merged revisions in the result
443
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
444
 
              that are in both ancestries
445
359
        :param direction: either 'reverse' or 'forward':
446
360
            * reverse means return the start_revision_id first, i.e.
447
361
              start at the most recent revision and go backwards in history
469
383
        # start_revision_id.
470
384
        if self._merge_sorted_revisions_cache is None:
471
385
            last_revision = self.last_revision()
472
 
            known_graph = self.repository.get_known_graph_ancestry(
473
 
                [last_revision])
474
 
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
475
 
                last_revision)
 
386
            graph = self.repository.get_graph()
 
387
            parent_map = dict(((key, value) for key, value in
 
388
                     graph.iter_ancestry([last_revision]) if value is not None))
 
389
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
390
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
391
                generate_revno=True)
 
392
            # Drop the sequence # before caching
 
393
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
394
 
476
395
        filtered = self._filter_merge_sorted_revisions(
477
396
            self._merge_sorted_revisions_cache, start_revision_id,
478
397
            stop_revision_id, stop_rule)
479
 
        # Make sure we don't return revisions that are not part of the
480
 
        # start_revision_id ancestry.
481
 
        filtered = self._filter_start_non_ancestors(filtered)
482
398
        if direction == 'reverse':
483
399
            return filtered
484
400
        if direction == 'forward':
491
407
        """Iterate over an inclusive range of sorted revisions."""
492
408
        rev_iter = iter(merge_sorted_revisions)
493
409
        if start_revision_id is not None:
494
 
            for node in rev_iter:
495
 
                rev_id = node.key[-1]
 
410
            for rev_id, depth, revno, end_of_merge in rev_iter:
496
411
                if rev_id != start_revision_id:
497
412
                    continue
498
413
                else:
499
414
                    # The decision to include the start or not
500
415
                    # depends on the stop_rule if a stop is provided
501
 
                    # so pop this node back into the iterator
502
 
                    rev_iter = chain(iter([node]), rev_iter)
 
416
                    rev_iter = chain(
 
417
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
418
                        rev_iter)
503
419
                    break
504
420
        if stop_revision_id is None:
505
 
            # Yield everything
506
 
            for node in rev_iter:
507
 
                rev_id = node.key[-1]
508
 
                yield (rev_id, node.merge_depth, node.revno,
509
 
                       node.end_of_merge)
 
421
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
422
                yield rev_id, depth, revno, end_of_merge
510
423
        elif stop_rule == 'exclude':
511
 
            for node in rev_iter:
512
 
                rev_id = node.key[-1]
 
424
            for rev_id, depth, revno, end_of_merge in rev_iter:
513
425
                if rev_id == stop_revision_id:
514
426
                    return
515
 
                yield (rev_id, node.merge_depth, node.revno,
516
 
                       node.end_of_merge)
 
427
                yield rev_id, depth, revno, end_of_merge
517
428
        elif stop_rule == 'include':
518
 
            for node in rev_iter:
519
 
                rev_id = node.key[-1]
520
 
                yield (rev_id, node.merge_depth, node.revno,
521
 
                       node.end_of_merge)
 
429
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
430
                yield rev_id, depth, revno, end_of_merge
522
431
                if rev_id == stop_revision_id:
523
432
                    return
524
 
        elif stop_rule == 'with-merges-without-common-ancestry':
525
 
            # We want to exclude all revisions that are already part of the
526
 
            # stop_revision_id ancestry.
527
 
            graph = self.repository.get_graph()
528
 
            ancestors = graph.find_unique_ancestors(start_revision_id,
529
 
                                                    [stop_revision_id])
530
 
            for node in rev_iter:
531
 
                rev_id = node.key[-1]
532
 
                if rev_id not in ancestors:
533
 
                    continue
534
 
                yield (rev_id, node.merge_depth, node.revno,
535
 
                       node.end_of_merge)
536
433
        elif stop_rule == 'with-merges':
537
434
            stop_rev = self.repository.get_revision(stop_revision_id)
538
435
            if stop_rev.parent_ids:
539
436
                left_parent = stop_rev.parent_ids[0]
540
437
            else:
541
438
                left_parent = _mod_revision.NULL_REVISION
542
 
            # left_parent is the actual revision we want to stop logging at,
543
 
            # since we want to show the merged revisions after the stop_rev too
544
 
            reached_stop_revision_id = False
545
 
            revision_id_whitelist = []
546
 
            for node in rev_iter:
547
 
                rev_id = node.key[-1]
 
439
            for rev_id, depth, revno, end_of_merge in rev_iter:
548
440
                if rev_id == left_parent:
549
 
                    # reached the left parent after the stop_revision
550
441
                    return
551
 
                if (not reached_stop_revision_id or
552
 
                        rev_id in revision_id_whitelist):
553
 
                    yield (rev_id, node.merge_depth, node.revno,
554
 
                       node.end_of_merge)
555
 
                    if reached_stop_revision_id or rev_id == stop_revision_id:
556
 
                        # only do the merged revs of rev_id from now on
557
 
                        rev = self.repository.get_revision(rev_id)
558
 
                        if rev.parent_ids:
559
 
                            reached_stop_revision_id = True
560
 
                            revision_id_whitelist.extend(rev.parent_ids)
 
442
                yield rev_id, depth, revno, end_of_merge
561
443
        else:
562
444
            raise ValueError('invalid stop_rule %r' % stop_rule)
563
445
 
564
 
    def _filter_start_non_ancestors(self, rev_iter):
565
 
        # If we started from a dotted revno, we want to consider it as a tip
566
 
        # and don't want to yield revisions that are not part of its
567
 
        # ancestry. Given the order guaranteed by the merge sort, we will see
568
 
        # uninteresting descendants of the first parent of our tip before the
569
 
        # tip itself.
570
 
        first = rev_iter.next()
571
 
        (rev_id, merge_depth, revno, end_of_merge) = first
572
 
        yield first
573
 
        if not merge_depth:
574
 
            # We start at a mainline revision so by definition, all others
575
 
            # revisions in rev_iter are ancestors
576
 
            for node in rev_iter:
577
 
                yield node
578
 
 
579
 
        clean = False
580
 
        whitelist = set()
581
 
        pmap = self.repository.get_parent_map([rev_id])
582
 
        parents = pmap.get(rev_id, [])
583
 
        if parents:
584
 
            whitelist.update(parents)
585
 
        else:
586
 
            # If there is no parents, there is nothing of interest left
587
 
 
588
 
            # FIXME: It's hard to test this scenario here as this code is never
589
 
            # called in that case. -- vila 20100322
590
 
            return
591
 
 
592
 
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
593
 
            if not clean:
594
 
                if rev_id in whitelist:
595
 
                    pmap = self.repository.get_parent_map([rev_id])
596
 
                    parents = pmap.get(rev_id, [])
597
 
                    whitelist.remove(rev_id)
598
 
                    whitelist.update(parents)
599
 
                    if merge_depth == 0:
600
 
                        # We've reached the mainline, there is nothing left to
601
 
                        # filter
602
 
                        clean = True
603
 
                else:
604
 
                    # A revision that is not part of the ancestry of our
605
 
                    # starting revision.
606
 
                    continue
607
 
            yield (rev_id, merge_depth, revno, end_of_merge)
608
 
 
609
446
    def leave_lock_in_place(self):
610
447
        """Tell this branch object not to release the physical lock when this
611
448
        object is unlocked.
628
465
        :param other: The branch to bind to
629
466
        :type other: Branch
630
467
        """
631
 
        raise errors.UpgradeRequired(self.user_url)
632
 
 
633
 
    def set_append_revisions_only(self, enabled):
634
 
        if not self._format.supports_set_append_revisions_only():
635
 
            raise errors.UpgradeRequired(self.user_url)
636
 
        if enabled:
637
 
            value = 'True'
638
 
        else:
639
 
            value = 'False'
640
 
        self.get_config().set_user_option('append_revisions_only', value,
641
 
            warn_masked=True)
642
 
 
643
 
    def set_reference_info(self, file_id, tree_path, branch_location):
644
 
        """Set the branch location to use for a tree reference."""
645
 
        raise errors.UnsupportedOperation(self.set_reference_info, self)
646
 
 
647
 
    def get_reference_info(self, file_id):
648
 
        """Get the tree_path and branch_location for a tree reference."""
649
 
        raise errors.UnsupportedOperation(self.get_reference_info, self)
 
468
        raise errors.UpgradeRequired(self.base)
650
469
 
651
470
    @needs_write_lock
652
471
    def fetch(self, from_branch, last_revision=None, pb=None):
686
505
    def get_old_bound_location(self):
687
506
        """Return the URL of the branch we used to be bound to
688
507
        """
689
 
        raise errors.UpgradeRequired(self.user_url)
 
508
        raise errors.UpgradeRequired(self.base)
690
509
 
691
510
    def get_commit_builder(self, parents, config=None, timestamp=None,
692
511
                           timezone=None, committer=None, revprops=None,
742
561
    def set_revision_history(self, rev_history):
743
562
        raise NotImplementedError(self.set_revision_history)
744
563
 
745
 
    @needs_write_lock
746
 
    def set_parent(self, url):
747
 
        """See Branch.set_parent."""
748
 
        # TODO: Maybe delete old location files?
749
 
        # URLs should never be unicode, even on the local fs,
750
 
        # FIXUP this and get_parent in a future branch format bump:
751
 
        # read and rewrite the file. RBC 20060125
752
 
        if url is not None:
753
 
            if isinstance(url, unicode):
754
 
                try:
755
 
                    url = url.encode('ascii')
756
 
                except UnicodeEncodeError:
757
 
                    raise errors.InvalidURL(url,
758
 
                        "Urls must be 7-bit ascii, "
759
 
                        "use bzrlib.urlutils.escape")
760
 
            url = urlutils.relative_url(self.base, url)
761
 
        self._set_parent_location(url)
762
 
 
763
 
    @needs_write_lock
764
564
    def set_stacked_on_url(self, url):
765
565
        """Set the URL this branch is stacked against.
766
566
 
769
569
        :raises UnstackableRepositoryFormat: If the repository does not support
770
570
            stacking.
771
571
        """
772
 
        if not self._format.supports_stacking():
773
 
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
774
 
        # XXX: Changing from one fallback repository to another does not check
775
 
        # that all the data you need is present in the new fallback.
776
 
        # Possibly it should.
777
 
        self._check_stackable_repo()
778
 
        if not url:
779
 
            try:
780
 
                old_url = self.get_stacked_on_url()
781
 
            except (errors.NotStacked, errors.UnstackableBranchFormat,
782
 
                errors.UnstackableRepositoryFormat):
783
 
                return
784
 
            self._unstack()
785
 
        else:
786
 
            self._activate_fallback_location(url)
787
 
        # write this out after the repository is stacked to avoid setting a
788
 
        # stacked config that doesn't work.
789
 
        self._set_config_location('stacked_on_location', url)
790
 
 
791
 
    def _unstack(self):
792
 
        """Change a branch to be unstacked, copying data as needed.
793
 
        
794
 
        Don't call this directly, use set_stacked_on_url(None).
795
 
        """
796
 
        pb = ui.ui_factory.nested_progress_bar()
797
 
        try:
798
 
            pb.update("Unstacking")
799
 
            # The basic approach here is to fetch the tip of the branch,
800
 
            # including all available ghosts, from the existing stacked
801
 
            # repository into a new repository object without the fallbacks. 
802
 
            #
803
 
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
804
 
            # correct for CHKMap repostiories
805
 
            old_repository = self.repository
806
 
            if len(old_repository._fallback_repositories) != 1:
807
 
                raise AssertionError("can't cope with fallback repositories "
808
 
                    "of %r" % (self.repository,))
809
 
            # Open the new repository object.
810
 
            # Repositories don't offer an interface to remove fallback
811
 
            # repositories today; take the conceptually simpler option and just
812
 
            # reopen it.  We reopen it starting from the URL so that we
813
 
            # get a separate connection for RemoteRepositories and can
814
 
            # stream from one of them to the other.  This does mean doing
815
 
            # separate SSH connection setup, but unstacking is not a
816
 
            # common operation so it's tolerable.
817
 
            new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
818
 
            new_repository = new_bzrdir.find_repository()
819
 
            if new_repository._fallback_repositories:
820
 
                raise AssertionError("didn't expect %r to have "
821
 
                    "fallback_repositories"
822
 
                    % (self.repository,))
823
 
            # Replace self.repository with the new repository.
824
 
            # Do our best to transfer the lock state (i.e. lock-tokens and
825
 
            # lock count) of self.repository to the new repository.
826
 
            lock_token = old_repository.lock_write().repository_token
827
 
            self.repository = new_repository
828
 
            if isinstance(self, remote.RemoteBranch):
829
 
                # Remote branches can have a second reference to the old
830
 
                # repository that need to be replaced.
831
 
                if self._real_branch is not None:
832
 
                    self._real_branch.repository = new_repository
833
 
            self.repository.lock_write(token=lock_token)
834
 
            if lock_token is not None:
835
 
                old_repository.leave_lock_in_place()
836
 
            old_repository.unlock()
837
 
            if lock_token is not None:
838
 
                # XXX: self.repository.leave_lock_in_place() before this
839
 
                # function will not be preserved.  Fortunately that doesn't
840
 
                # affect the current default format (2a), and would be a
841
 
                # corner-case anyway.
842
 
                #  - Andrew Bennetts, 2010/06/30
843
 
                self.repository.dont_leave_lock_in_place()
844
 
            old_lock_count = 0
845
 
            while True:
846
 
                try:
847
 
                    old_repository.unlock()
848
 
                except errors.LockNotHeld:
849
 
                    break
850
 
                old_lock_count += 1
851
 
            if old_lock_count == 0:
852
 
                raise AssertionError(
853
 
                    'old_repository should have been locked at least once.')
854
 
            for i in range(old_lock_count-1):
855
 
                self.repository.lock_write()
856
 
            # Fetch from the old repository into the new.
857
 
            old_repository.lock_read()
858
 
            try:
859
 
                # XXX: If you unstack a branch while it has a working tree
860
 
                # with a pending merge, the pending-merged revisions will no
861
 
                # longer be present.  You can (probably) revert and remerge.
862
 
                #
863
 
                # XXX: This only fetches up to the tip of the repository; it
864
 
                # doesn't bring across any tags.  That's fairly consistent
865
 
                # with how branch works, but perhaps not ideal.
866
 
                self.repository.fetch(old_repository,
867
 
                    revision_id=self.last_revision(),
868
 
                    find_ghosts=True)
869
 
            finally:
870
 
                old_repository.unlock()
871
 
        finally:
872
 
            pb.finished()
 
572
        raise NotImplementedError(self.set_stacked_on_url)
873
573
 
874
574
    def _set_tags_bytes(self, bytes):
875
575
        """Mirror method for _get_tags_bytes.
911
611
        self._revision_id_to_revno_cache = None
912
612
        self._last_revision_info_cache = None
913
613
        self._merge_sorted_revisions_cache = None
914
 
        self._partial_revision_history_cache = []
915
 
        self._partial_revision_id_to_revno_cache = {}
916
614
 
917
615
    def _gen_revision_history(self):
918
616
        """Return sequence of revision hashes on to this branch.
955
653
 
956
654
    def unbind(self):
957
655
        """Older format branches cannot bind or unbind."""
958
 
        raise errors.UpgradeRequired(self.user_url)
 
656
        raise errors.UpgradeRequired(self.base)
 
657
 
 
658
    def set_append_revisions_only(self, enabled):
 
659
        """Older format branches are never restricted to append-only"""
 
660
        raise errors.UpgradeRequired(self.base)
959
661
 
960
662
    def last_revision(self):
961
663
        """Return last revision id, or NULL_REVISION."""
1002
704
                raise errors.NoSuchRevision(self, stop_revision)
1003
705
        return other_history[self_len:stop_revision]
1004
706
 
 
707
    @needs_write_lock
1005
708
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1006
709
                         graph=None):
1007
710
        """Pull in new perfect-fit revisions.
1041
744
        except ValueError:
1042
745
            raise errors.NoSuchRevision(self, revision_id)
1043
746
 
1044
 
    @needs_read_lock
1045
747
    def get_rev_id(self, revno, history=None):
1046
748
        """Find the revision id of the specified revno."""
1047
749
        if revno == 0:
1048
750
            return _mod_revision.NULL_REVISION
1049
 
        last_revno, last_revid = self.last_revision_info()
1050
 
        if revno == last_revno:
1051
 
            return last_revid
1052
 
        if revno <= 0 or revno > last_revno:
 
751
        if history is None:
 
752
            history = self.revision_history()
 
753
        if revno <= 0 or revno > len(history):
1053
754
            raise errors.NoSuchRevision(self, revno)
1054
 
        distance_from_last = last_revno - revno
1055
 
        if len(self._partial_revision_history_cache) <= distance_from_last:
1056
 
            self._extend_partial_history(distance_from_last)
1057
 
        return self._partial_revision_history_cache[distance_from_last]
 
755
        return history[revno - 1]
1058
756
 
1059
757
    def pull(self, source, overwrite=False, stop_revision=None,
1060
 
             possible_transports=None, *args, **kwargs):
 
758
             possible_transports=None, _override_hook_target=None):
1061
759
        """Mirror source into this branch.
1062
760
 
1063
761
        This branch is considered to be 'local', having low latency.
1064
762
 
1065
763
        :returns: PullResult instance
1066
764
        """
1067
 
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1068
 
            stop_revision=stop_revision,
1069
 
            possible_transports=possible_transports, *args, **kwargs)
 
765
        raise NotImplementedError(self.pull)
1070
766
 
1071
 
    def push(self, target, overwrite=False, stop_revision=None, *args,
1072
 
        **kwargs):
 
767
    def push(self, target, overwrite=False, stop_revision=None):
1073
768
        """Mirror this branch into target.
1074
769
 
1075
770
        This branch is considered to be 'local', having low latency.
1076
771
        """
1077
 
        return InterBranch.get(self, target).push(overwrite, stop_revision,
1078
 
            *args, **kwargs)
1079
 
 
1080
 
    def lossy_push(self, target, stop_revision=None):
1081
 
        """Push deltas into another branch.
1082
 
 
1083
 
        :note: This does not, like push, retain the revision ids from 
1084
 
            the source branch and will, rather than adding bzr-specific 
1085
 
            metadata, push only those semantics of the revision that can be 
1086
 
            natively represented by this branch' VCS.
1087
 
 
1088
 
        :param target: Target branch
1089
 
        :param stop_revision: Revision to push, defaults to last revision.
1090
 
        :return: BranchPushResult with an extra member revidmap: 
1091
 
            A dictionary mapping revision ids from the target branch 
1092
 
            to new revision ids in the target branch, for each 
1093
 
            revision that was pushed.
1094
 
        """
1095
 
        inter = InterBranch.get(self, target)
1096
 
        lossy_push = getattr(inter, "lossy_push", None)
1097
 
        if lossy_push is None:
1098
 
            raise errors.LossyPushToSameVCS(self, target)
1099
 
        return lossy_push(stop_revision)
 
772
        raise NotImplementedError(self.push)
1100
773
 
1101
774
    def basis_tree(self):
1102
775
        """Return `Tree` object for last revision."""
1119
792
        try:
1120
793
            return urlutils.join(self.base[:-1], parent)
1121
794
        except errors.InvalidURLJoin, e:
1122
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
795
            raise errors.InaccessibleParent(parent, self.base)
1123
796
 
1124
797
    def _get_parent_location(self):
1125
798
        raise NotImplementedError(self._get_parent_location)
1142
815
            location = None
1143
816
        return location
1144
817
 
1145
 
    def get_child_submit_format(self):
1146
 
        """Return the preferred format of submissions to this branch."""
1147
 
        return self.get_config().get_user_option("child_submit_format")
1148
 
 
1149
818
    def get_submit_branch(self):
1150
819
        """Return the submit location of the branch.
1151
820
 
1168
837
    def get_public_branch(self):
1169
838
        """Return the public location of the branch.
1170
839
 
1171
 
        This is used by merge directives.
 
840
        This is is used by merge directives.
1172
841
        """
1173
842
        return self._get_config_location('public_branch')
1174
843
 
1210
879
        params = ChangeBranchTipParams(
1211
880
            self, old_revno, new_revno, old_revid, new_revid)
1212
881
        for hook in hooks:
1213
 
            hook(params)
 
882
            try:
 
883
                hook(params)
 
884
            except errors.TipChangeRejected:
 
885
                raise
 
886
            except Exception:
 
887
                exc_info = sys.exc_info()
 
888
                hook_name = Branch.hooks.get_hook_name(hook)
 
889
                raise errors.HookFailed(
 
890
                    'pre_change_branch_tip', hook_name, exc_info)
 
891
 
 
892
    def set_parent(self, url):
 
893
        raise NotImplementedError(self.set_parent)
1214
894
 
1215
895
    @needs_write_lock
1216
896
    def update(self):
1247
927
                     be truncated to end with revision_id.
1248
928
        """
1249
929
        result = to_bzrdir.create_branch()
1250
 
        result.lock_write()
1251
 
        try:
1252
 
            if repository_policy is not None:
1253
 
                repository_policy.configure_branch(result)
1254
 
            self.copy_content_into(result, revision_id=revision_id)
1255
 
        finally:
1256
 
            result.unlock()
1257
 
        return result
 
930
        if repository_policy is not None:
 
931
            repository_policy.configure_branch(result)
 
932
        self.copy_content_into(result, revision_id=revision_id)
 
933
        return  result
1258
934
 
1259
935
    @needs_read_lock
1260
936
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1265
941
        revision_id: if not None, the revision history in the new branch will
1266
942
                     be truncated to end with revision_id.
1267
943
        """
1268
 
        if (repository_policy is not None and
1269
 
            repository_policy.requires_stacking()):
1270
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1271
944
        result = to_bzrdir.create_branch()
1272
 
        result.lock_write()
1273
 
        try:
1274
 
            if repository_policy is not None:
1275
 
                repository_policy.configure_branch(result)
1276
 
            self.copy_content_into(result, revision_id=revision_id)
1277
 
            result.set_parent(self.bzrdir.root_transport.base)
1278
 
        finally:
1279
 
            result.unlock()
 
945
        if repository_policy is not None:
 
946
            repository_policy.configure_branch(result)
 
947
        self.copy_content_into(result, revision_id=revision_id)
 
948
        result.set_parent(self.bzrdir.root_transport.base)
1280
949
        return result
1281
950
 
1282
951
    def _synchronize_history(self, destination, revision_id):
1294
963
        source_revno, source_revision_id = self.last_revision_info()
1295
964
        if revision_id is None:
1296
965
            revno, revision_id = source_revno, source_revision_id
 
966
        elif source_revision_id == revision_id:
 
967
            # we know the revno without needing to walk all of history
 
968
            revno = source_revno
1297
969
        else:
1298
 
            graph = self.repository.get_graph()
1299
 
            try:
1300
 
                revno = graph.find_distance_to_null(revision_id, 
1301
 
                    [(source_revision_id, source_revno)])
1302
 
            except errors.GhostRevisionsHaveNoRevno:
1303
 
                # Default to 1, if we can't find anything else
1304
 
                revno = 1
 
970
            # To figure out the revno for a random revision, we need to build
 
971
            # the revision history, and count its length.
 
972
            # We don't care about the order, just how long it is.
 
973
            # Alternatively, we could start at the current location, and count
 
974
            # backwards. But there is no guarantee that we will find it since
 
975
            # it may be a merged revision.
 
976
            revno = len(list(self.repository.iter_reverse_revision_history(
 
977
                                                                revision_id)))
1305
978
        destination.set_last_revision_info(revno, revision_id)
1306
979
 
 
980
    @needs_read_lock
1307
981
    def copy_content_into(self, destination, revision_id=None):
1308
982
        """Copy the content of self into destination.
1309
983
 
1310
984
        revision_id: if not None, the revision history in the new branch will
1311
985
                     be truncated to end with revision_id.
1312
986
        """
1313
 
        return InterBranch.get(self, destination).copy_content_into(
1314
 
            revision_id=revision_id)
1315
 
 
1316
 
    def update_references(self, target):
1317
 
        if not getattr(self._format, 'supports_reference_locations', False):
1318
 
            return
1319
 
        reference_dict = self._get_all_reference_info()
1320
 
        if len(reference_dict) == 0:
1321
 
            return
1322
 
        old_base = self.base
1323
 
        new_base = target.base
1324
 
        target_reference_dict = target._get_all_reference_info()
1325
 
        for file_id, (tree_path, branch_location) in (
1326
 
            reference_dict.items()):
1327
 
            branch_location = urlutils.rebase_url(branch_location,
1328
 
                                                  old_base, new_base)
1329
 
            target_reference_dict.setdefault(
1330
 
                file_id, (tree_path, branch_location))
1331
 
        target._set_all_reference_info(target_reference_dict)
 
987
        self._synchronize_history(destination, revision_id)
 
988
        try:
 
989
            parent = self.get_parent()
 
990
        except errors.InaccessibleParent, e:
 
991
            mutter('parent was not accessible to copy: %s', e)
 
992
        else:
 
993
            if parent:
 
994
                destination.set_parent(parent)
 
995
        if self._push_should_merge_tags():
 
996
            self.tags.merge_to(destination.tags)
1332
997
 
1333
998
    @needs_read_lock
1334
 
    def check(self, refs):
 
999
    def check(self):
1335
1000
        """Check consistency of the branch.
1336
1001
 
1337
1002
        In particular this checks that revisions given in the revision-history
1340
1005
 
1341
1006
        Callers will typically also want to check the repository.
1342
1007
 
1343
 
        :param refs: Calculated refs for this branch as specified by
1344
 
            branch._get_check_refs()
1345
1008
        :return: A BranchCheckResult.
1346
1009
        """
1347
 
        result = BranchCheckResult(self)
 
1010
        mainline_parent_id = None
1348
1011
        last_revno, last_revision_id = self.last_revision_info()
1349
 
        actual_revno = refs[('lefthand-distance', last_revision_id)]
1350
 
        if actual_revno != last_revno:
1351
 
            result.errors.append(errors.BzrCheckError(
1352
 
                'revno does not match len(mainline) %s != %s' % (
1353
 
                last_revno, actual_revno)))
1354
 
        # TODO: We should probably also check that self.revision_history
1355
 
        # matches the repository for older branch formats.
1356
 
        # If looking for the code that cross-checks repository parents against
1357
 
        # the iter_reverse_revision_history output, that is now a repository
1358
 
        # specific check.
1359
 
        return result
 
1012
        real_rev_history = list(self.repository.iter_reverse_revision_history(
 
1013
                                last_revision_id))
 
1014
        real_rev_history.reverse()
 
1015
        if len(real_rev_history) != last_revno:
 
1016
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
1017
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
1018
        # TODO: We should probably also check that real_rev_history actually
 
1019
        #       matches self.revision_history()
 
1020
        for revision_id in real_rev_history:
 
1021
            try:
 
1022
                revision = self.repository.get_revision(revision_id)
 
1023
            except errors.NoSuchRevision, e:
 
1024
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1025
                            % revision_id)
 
1026
            # In general the first entry on the revision history has no parents.
 
1027
            # But it's not illegal for it to have parents listed; this can happen
 
1028
            # in imports from Arch when the parents weren't reachable.
 
1029
            if mainline_parent_id is not None:
 
1030
                if mainline_parent_id not in revision.parent_ids:
 
1031
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1032
                                        "parents of {%s}"
 
1033
                                        % (mainline_parent_id, revision_id))
 
1034
            mainline_parent_id = revision_id
 
1035
        return BranchCheckResult(self)
1360
1036
 
1361
1037
    def _get_checkout_format(self):
1362
1038
        """Return the most suitable metadir for a checkout of this branch.
1372
1048
        return format
1373
1049
 
1374
1050
    def create_clone_on_transport(self, to_transport, revision_id=None,
1375
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1051
        stacked_on=None):
1376
1052
        """Create a clone of this branch and its bzrdir.
1377
1053
 
1378
1054
        :param to_transport: The transport to clone onto.
1379
1055
        :param revision_id: The revision id to use as tip in the new branch.
1380
1056
            If None the tip is obtained from this branch.
1381
1057
        :param stacked_on: An optional URL to stack the clone on.
1382
 
        :param create_prefix: Create any missing directories leading up to
1383
 
            to_transport.
1384
 
        :param use_existing_dir: Use an existing directory if one exists.
1385
1058
        """
1386
1059
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1387
1060
        # clone call. Or something. 20090224 RBC/spiv.
1388
 
        # XXX: Should this perhaps clone colocated branches as well, 
1389
 
        # rather than just the default branch? 20100319 JRV
1390
 
        if revision_id is None:
1391
 
            revision_id = self.last_revision()
1392
1061
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1393
 
            revision_id=revision_id, stacked_on=stacked_on,
1394
 
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1062
            revision_id=revision_id, stacked_on=stacked_on)
1395
1063
        return dir_to.open_branch()
1396
1064
 
1397
1065
    def create_checkout(self, to_location, revision_id=None,
1416
1084
        if lightweight:
1417
1085
            format = self._get_checkout_format()
1418
1086
            checkout = format.initialize_on_transport(t)
1419
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1420
 
                target_branch=self)
 
1087
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1421
1088
        else:
1422
1089
            format = self._get_checkout_format()
1423
1090
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1452
1119
        reconciler.reconcile()
1453
1120
        return reconciler
1454
1121
 
1455
 
    def reference_parent(self, file_id, path, possible_transports=None):
 
1122
    def reference_parent(self, file_id, path):
1456
1123
        """Return the parent branch for a tree-reference file_id
1457
1124
        :param file_id: The file_id of the tree reference
1458
1125
        :param path: The path of the file_id in the tree
1459
1126
        :return: A branch associated with the file_id
1460
1127
        """
1461
1128
        # FIXME should provide multiple branches, based on config
1462
 
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
1463
 
                           possible_transports=possible_transports)
 
1129
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
1464
1130
 
1465
1131
    def supports_tags(self):
1466
1132
        return self._format.supports_tags()
1467
1133
 
1468
 
    def automatic_tag_name(self, revision_id):
1469
 
        """Try to automatically find the tag name for a revision.
1470
 
 
1471
 
        :param revision_id: Revision id of the revision.
1472
 
        :return: A tag name or None if no tag name could be determined.
1473
 
        """
1474
 
        for hook in Branch.hooks['automatic_tag_name']:
1475
 
            ret = hook(self, revision_id)
1476
 
            if ret is not None:
1477
 
                return ret
1478
 
        return None
1479
 
 
1480
1134
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1481
1135
                                         other_branch):
1482
1136
        """Ensure that revision_b is a descendant of revision_a.
1537
1191
    _formats = {}
1538
1192
    """The known formats."""
1539
1193
 
1540
 
    can_set_append_revisions_only = True
1541
 
 
1542
1194
    def __eq__(self, other):
1543
1195
        return self.__class__ is other.__class__
1544
1196
 
1546
1198
        return not (self == other)
1547
1199
 
1548
1200
    @classmethod
1549
 
    def find_format(klass, a_bzrdir, name=None):
 
1201
    def find_format(klass, a_bzrdir):
1550
1202
        """Return the format for the branch object in a_bzrdir."""
1551
1203
        try:
1552
 
            transport = a_bzrdir.get_branch_transport(None, name=name)
1553
 
            format_string = transport.get_bytes("format")
1554
 
            format = klass._formats[format_string]
1555
 
            if isinstance(format, MetaDirBranchFormatFactory):
1556
 
                return format()
1557
 
            return format
 
1204
            transport = a_bzrdir.get_branch_transport(None)
 
1205
            format_string = transport.get("format").read()
 
1206
            return klass._formats[format_string]
1558
1207
        except errors.NoSuchFile:
1559
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1208
            raise errors.NotBranchError(path=transport.base)
1560
1209
        except KeyError:
1561
1210
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1562
1211
 
1565
1214
        """Return the current default format."""
1566
1215
        return klass._default_format
1567
1216
 
1568
 
    @classmethod
1569
 
    def get_formats(klass):
1570
 
        """Get all the known formats.
1571
 
 
1572
 
        Warning: This triggers a load of all lazy registered formats: do not
1573
 
        use except when that is desireed.
1574
 
        """
1575
 
        result = []
1576
 
        for fmt in klass._formats.values():
1577
 
            if isinstance(fmt, MetaDirBranchFormatFactory):
1578
 
                fmt = fmt()
1579
 
            result.append(fmt)
1580
 
        return result
1581
 
 
1582
 
    def get_reference(self, a_bzrdir, name=None):
 
1217
    def get_reference(self, a_bzrdir):
1583
1218
        """Get the target reference of the branch in a_bzrdir.
1584
1219
 
1585
1220
        format probing must have been completed before calling
1587
1222
        in a_bzrdir is correct.
1588
1223
 
1589
1224
        :param a_bzrdir: The bzrdir to get the branch data from.
1590
 
        :param name: Name of the colocated branch to fetch
1591
1225
        :return: None if the branch is not a reference branch.
1592
1226
        """
1593
1227
        return None
1594
1228
 
1595
1229
    @classmethod
1596
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1230
    def set_reference(self, a_bzrdir, to_branch):
1597
1231
        """Set the target reference of the branch in a_bzrdir.
1598
1232
 
1599
1233
        format probing must have been completed before calling
1601
1235
        in a_bzrdir is correct.
1602
1236
 
1603
1237
        :param a_bzrdir: The bzrdir to set the branch reference for.
1604
 
        :param name: Name of colocated branch to set, None for default
1605
1238
        :param to_branch: branch that the checkout is to reference
1606
1239
        """
1607
1240
        raise NotImplementedError(self.set_reference)
1614
1247
        """Return the short format description for this format."""
1615
1248
        raise NotImplementedError(self.get_format_description)
1616
1249
 
1617
 
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1618
 
        hooks = Branch.hooks['post_branch_init']
1619
 
        if not hooks:
1620
 
            return
1621
 
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
1622
 
        for hook in hooks:
1623
 
            hook(params)
1624
 
 
1625
 
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1626
 
                           lock_type='metadir', set_format=True):
 
1250
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1251
                           set_format=True):
1627
1252
        """Initialize a branch in a bzrdir, with specified files
1628
1253
 
1629
1254
        :param a_bzrdir: The bzrdir to initialize the branch in
1630
1255
        :param utf8_files: The files to create as a list of
1631
1256
            (filename, content) tuples
1632
 
        :param name: Name of colocated branch to create, if any
1633
1257
        :param set_format: If True, set the format with
1634
1258
            self.get_format_string.  (BzrBranch4 has its format set
1635
1259
            elsewhere)
1636
1260
        :return: a branch in this format
1637
1261
        """
1638
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1639
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1262
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1263
        branch_transport = a_bzrdir.get_branch_transport(self)
1640
1264
        lock_map = {
1641
1265
            'metadir': ('lock', lockdir.LockDir),
1642
1266
            'branch4': ('branch-lock', lockable_files.TransportLock),
1645
1269
        control_files = lockable_files.LockableFiles(branch_transport,
1646
1270
            lock_name, lock_class)
1647
1271
        control_files.create_lock()
1648
 
        try:
1649
 
            control_files.lock_write()
1650
 
        except errors.LockContention:
1651
 
            if lock_type != 'branch4':
1652
 
                raise
1653
 
            lock_taken = False
1654
 
        else:
1655
 
            lock_taken = True
 
1272
        control_files.lock_write()
1656
1273
        if set_format:
1657
1274
            utf8_files += [('format', self.get_format_string())]
1658
1275
        try:
1661
1278
                    filename, content,
1662
1279
                    mode=a_bzrdir._get_file_mode())
1663
1280
        finally:
1664
 
            if lock_taken:
1665
 
                control_files.unlock()
1666
 
        branch = self.open(a_bzrdir, name, _found=True)
1667
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1668
 
        return branch
 
1281
            control_files.unlock()
 
1282
        return self.open(a_bzrdir, _found=True)
1669
1283
 
1670
 
    def initialize(self, a_bzrdir, name=None):
1671
 
        """Create a branch of this format in a_bzrdir.
1672
 
        
1673
 
        :param name: Name of the colocated branch to create.
1674
 
        """
 
1284
    def initialize(self, a_bzrdir):
 
1285
        """Create a branch of this format in a_bzrdir."""
1675
1286
        raise NotImplementedError(self.initialize)
1676
1287
 
1677
1288
    def is_supported(self):
1707
1318
        """
1708
1319
        raise NotImplementedError(self.network_name)
1709
1320
 
1710
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1321
    def open(self, a_bzrdir, _found=False):
1711
1322
        """Return the branch object for a_bzrdir
1712
1323
 
1713
 
        :param a_bzrdir: A BzrDir that contains a branch.
1714
 
        :param name: Name of colocated branch to open
1715
 
        :param _found: a private parameter, do not use it. It is used to
1716
 
            indicate if format probing has already be done.
1717
 
        :param ignore_fallbacks: when set, no fallback branches will be opened
1718
 
            (if there are any).  Default is to open fallbacks.
 
1324
        _found is a private parameter, do not use it. It is used to indicate
 
1325
               if format probing has already be done.
1719
1326
        """
1720
1327
        raise NotImplementedError(self.open)
1721
1328
 
1722
1329
    @classmethod
1723
1330
    def register_format(klass, format):
1724
 
        """Register a metadir format.
1725
 
        
1726
 
        See MetaDirBranchFormatFactory for the ability to register a format
1727
 
        without loading the code the format needs until it is actually used.
1728
 
        """
 
1331
        """Register a metadir format."""
1729
1332
        klass._formats[format.get_format_string()] = format
1730
1333
        # Metadir formats have a network name of their format string, and get
1731
 
        # registered as factories.
1732
 
        if isinstance(format, MetaDirBranchFormatFactory):
1733
 
            network_format_registry.register(format.get_format_string(), format)
1734
 
        else:
1735
 
            network_format_registry.register(format.get_format_string(),
1736
 
                format.__class__)
 
1334
        # registered as class factories.
 
1335
        network_format_registry.register(format.get_format_string(), format.__class__)
1737
1336
 
1738
1337
    @classmethod
1739
1338
    def set_default_format(klass, format):
1740
1339
        klass._default_format = format
1741
1340
 
1742
 
    def supports_set_append_revisions_only(self):
1743
 
        """True if this format supports set_append_revisions_only."""
1744
 
        return False
1745
 
 
1746
1341
    def supports_stacking(self):
1747
1342
        """True if this format records a stacked-on branch."""
1748
1343
        return False
1759
1354
        return False  # by default
1760
1355
 
1761
1356
 
1762
 
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1763
 
    """A factory for a BranchFormat object, permitting simple lazy registration.
1764
 
    
1765
 
    While none of the built in BranchFormats are lazy registered yet,
1766
 
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1767
 
    use it, and the bzr-loom plugin uses it as well (see
1768
 
    bzrlib.plugins.loom.formats).
1769
 
    """
1770
 
 
1771
 
    def __init__(self, format_string, module_name, member_name):
1772
 
        """Create a MetaDirBranchFormatFactory.
1773
 
 
1774
 
        :param format_string: The format string the format has.
1775
 
        :param module_name: Module to load the format class from.
1776
 
        :param member_name: Attribute name within the module for the format class.
1777
 
        """
1778
 
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
1779
 
        self._format_string = format_string
1780
 
        
1781
 
    def get_format_string(self):
1782
 
        """See BranchFormat.get_format_string."""
1783
 
        return self._format_string
1784
 
 
1785
 
    def __call__(self):
1786
 
        """Used for network_format_registry support."""
1787
 
        return self.get_obj()()
1788
 
 
1789
 
 
1790
1357
class BranchHooks(Hooks):
1791
1358
    """A dictionary mapping hook name to a list of callables for branch hooks.
1792
1359
 
1838
1405
            "post_uncommit is called with (local, master, old_revno, "
1839
1406
            "old_revid, new_revno, new_revid) where local is the local branch "
1840
1407
            "or None, master is the target branch, and an empty branch "
1841
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1408
            "recieves new_revno of 0, new_revid of None.", (0, 15), None))
1842
1409
        self.create_hook(HookPoint('pre_change_branch_tip',
1843
1410
            "Called in bzr client and server before a change to the tip of a "
1844
1411
            "branch is made. pre_change_branch_tip is called with a "
1861
1428
            "multiple hooks installed for transform_fallback_location, "
1862
1429
            "all are called with the url returned from the previous hook."
1863
1430
            "The order is however undefined.", (1, 9), None))
1864
 
        self.create_hook(HookPoint('automatic_tag_name',
1865
 
            "Called to determine an automatic tag name for a revision. "
1866
 
            "automatic_tag_name is called with (branch, revision_id) and "
1867
 
            "should return a tag name or None if no tag name could be "
1868
 
            "determined. The first non-None tag name returned will be used.",
1869
 
            (2, 2), None))
1870
 
        self.create_hook(HookPoint('post_branch_init',
1871
 
            "Called after new branch initialization completes. "
1872
 
            "post_branch_init is called with a "
1873
 
            "bzrlib.branch.BranchInitHookParams. "
1874
 
            "Note that init, branch and checkout (both heavyweight and "
1875
 
            "lightweight) will all trigger this hook.", (2, 2), None))
1876
 
        self.create_hook(HookPoint('post_switch',
1877
 
            "Called after a checkout switches branch. "
1878
 
            "post_switch is called with a "
1879
 
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
1880
 
 
1881
1431
 
1882
1432
 
1883
1433
# install the default hooks into the Branch class.
1922
1472
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1923
1473
 
1924
1474
 
1925
 
class BranchInitHookParams(object):
1926
 
    """Object holding parameters passed to *_branch_init hooks.
1927
 
 
1928
 
    There are 4 fields that hooks may wish to access:
1929
 
 
1930
 
    :ivar format: the branch format
1931
 
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
1932
 
    :ivar name: name of colocated branch, if any (or None)
1933
 
    :ivar branch: the branch created
1934
 
 
1935
 
    Note that for lightweight checkouts, the bzrdir and format fields refer to
1936
 
    the checkout, hence they are different from the corresponding fields in
1937
 
    branch, which refer to the original branch.
1938
 
    """
1939
 
 
1940
 
    def __init__(self, format, a_bzrdir, name, branch):
1941
 
        """Create a group of BranchInitHook parameters.
1942
 
 
1943
 
        :param format: the branch format
1944
 
        :param a_bzrdir: the BzrDir where the branch will be/has been
1945
 
            initialized
1946
 
        :param name: name of colocated branch, if any (or None)
1947
 
        :param branch: the branch created
1948
 
 
1949
 
        Note that for lightweight checkouts, the bzrdir and format fields refer
1950
 
        to the checkout, hence they are different from the corresponding fields
1951
 
        in branch, which refer to the original branch.
1952
 
        """
1953
 
        self.format = format
1954
 
        self.bzrdir = a_bzrdir
1955
 
        self.name = name
1956
 
        self.branch = branch
1957
 
 
1958
 
    def __eq__(self, other):
1959
 
        return self.__dict__ == other.__dict__
1960
 
 
1961
 
    def __repr__(self):
1962
 
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
1963
 
 
1964
 
 
1965
 
class SwitchHookParams(object):
1966
 
    """Object holding parameters passed to *_switch hooks.
1967
 
 
1968
 
    There are 4 fields that hooks may wish to access:
1969
 
 
1970
 
    :ivar control_dir: BzrDir of the checkout to change
1971
 
    :ivar to_branch: branch that the checkout is to reference
1972
 
    :ivar force: skip the check for local commits in a heavy checkout
1973
 
    :ivar revision_id: revision ID to switch to (or None)
1974
 
    """
1975
 
 
1976
 
    def __init__(self, control_dir, to_branch, force, revision_id):
1977
 
        """Create a group of SwitchHook parameters.
1978
 
 
1979
 
        :param control_dir: BzrDir of the checkout to change
1980
 
        :param to_branch: branch that the checkout is to reference
1981
 
        :param force: skip the check for local commits in a heavy checkout
1982
 
        :param revision_id: revision ID to switch to (or None)
1983
 
        """
1984
 
        self.control_dir = control_dir
1985
 
        self.to_branch = to_branch
1986
 
        self.force = force
1987
 
        self.revision_id = revision_id
1988
 
 
1989
 
    def __eq__(self, other):
1990
 
        return self.__dict__ == other.__dict__
1991
 
 
1992
 
    def __repr__(self):
1993
 
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1994
 
            self.control_dir, self.to_branch,
1995
 
            self.revision_id)
1996
 
 
1997
 
 
1998
1475
class BzrBranchFormat4(BranchFormat):
1999
1476
    """Bzr branch format 4.
2000
1477
 
2007
1484
        """See BranchFormat.get_format_description()."""
2008
1485
        return "Branch format 4"
2009
1486
 
2010
 
    def initialize(self, a_bzrdir, name=None):
 
1487
    def initialize(self, a_bzrdir):
2011
1488
        """Create a branch of this format in a_bzrdir."""
2012
1489
        utf8_files = [('revision-history', ''),
2013
1490
                      ('branch-name', ''),
2014
1491
                      ]
2015
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1492
        return self._initialize_helper(a_bzrdir, utf8_files,
2016
1493
                                       lock_type='branch4', set_format=False)
2017
1494
 
2018
1495
    def __init__(self):
2023
1500
        """The network name for this format is the control dirs disk label."""
2024
1501
        return self._matchingbzrdir.get_format_string()
2025
1502
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2027
 
        """See BranchFormat.open()."""
 
1503
    def open(self, a_bzrdir, _found=False):
 
1504
        """Return the branch object for a_bzrdir
 
1505
 
 
1506
        _found is a private parameter, do not use it. It is used to indicate
 
1507
               if format probing has already be done.
 
1508
        """
2028
1509
        if not _found:
2029
1510
            # we are being called directly and must probe.
2030
1511
            raise NotImplementedError
2031
1512
        return BzrBranch(_format=self,
2032
1513
                         _control_files=a_bzrdir._control_files,
2033
1514
                         a_bzrdir=a_bzrdir,
2034
 
                         name=name,
2035
1515
                         _repository=a_bzrdir.open_repository())
2036
1516
 
2037
1517
    def __str__(self):
2052
1532
        """
2053
1533
        return self.get_format_string()
2054
1534
 
2055
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2056
 
        """See BranchFormat.open()."""
 
1535
    def open(self, a_bzrdir, _found=False):
 
1536
        """Return the branch object for a_bzrdir.
 
1537
 
 
1538
        _found is a private parameter, do not use it. It is used to indicate
 
1539
               if format probing has already be done.
 
1540
        """
2057
1541
        if not _found:
2058
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1542
            format = BranchFormat.find_format(a_bzrdir)
2059
1543
            if format.__class__ != self.__class__:
2060
1544
                raise AssertionError("wrong format %r found for %r" %
2061
1545
                    (format, self))
2062
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2063
1546
        try:
 
1547
            transport = a_bzrdir.get_branch_transport(None)
2064
1548
            control_files = lockable_files.LockableFiles(transport, 'lock',
2065
1549
                                                         lockdir.LockDir)
2066
1550
            return self._branch_class()(_format=self,
2067
1551
                              _control_files=control_files,
2068
 
                              name=name,
2069
1552
                              a_bzrdir=a_bzrdir,
2070
 
                              _repository=a_bzrdir.find_repository(),
2071
 
                              ignore_fallbacks=ignore_fallbacks)
 
1553
                              _repository=a_bzrdir.find_repository())
2072
1554
        except errors.NoSuchFile:
2073
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1555
            raise errors.NotBranchError(path=transport.base)
2074
1556
 
2075
1557
    def __init__(self):
2076
1558
        super(BranchFormatMetadir, self).__init__()
2105
1587
        """See BranchFormat.get_format_description()."""
2106
1588
        return "Branch format 5"
2107
1589
 
2108
 
    def initialize(self, a_bzrdir, name=None):
 
1590
    def initialize(self, a_bzrdir):
2109
1591
        """Create a branch of this format in a_bzrdir."""
2110
1592
        utf8_files = [('revision-history', ''),
2111
1593
                      ('branch-name', ''),
2112
1594
                      ]
2113
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1595
        return self._initialize_helper(a_bzrdir, utf8_files)
2114
1596
 
2115
1597
    def supports_tags(self):
2116
1598
        return False
2138
1620
        """See BranchFormat.get_format_description()."""
2139
1621
        return "Branch format 6"
2140
1622
 
2141
 
    def initialize(self, a_bzrdir, name=None):
2142
 
        """Create a branch of this format in a_bzrdir."""
2143
 
        utf8_files = [('last-revision', '0 null:\n'),
2144
 
                      ('branch.conf', ''),
2145
 
                      ('tags', ''),
2146
 
                      ]
2147
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2148
 
 
2149
 
    def make_tags(self, branch):
2150
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2151
 
        return BasicTags(branch)
2152
 
 
2153
 
    def supports_set_append_revisions_only(self):
2154
 
        return True
2155
 
 
2156
 
 
2157
 
class BzrBranchFormat8(BranchFormatMetadir):
2158
 
    """Metadir format supporting storing locations of subtree branches."""
2159
 
 
2160
 
    def _branch_class(self):
2161
 
        return BzrBranch8
2162
 
 
2163
 
    def get_format_string(self):
2164
 
        """See BranchFormat.get_format_string()."""
2165
 
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2166
 
 
2167
 
    def get_format_description(self):
2168
 
        """See BranchFormat.get_format_description()."""
2169
 
        return "Branch format 8"
2170
 
 
2171
 
    def initialize(self, a_bzrdir, name=None):
2172
 
        """Create a branch of this format in a_bzrdir."""
2173
 
        utf8_files = [('last-revision', '0 null:\n'),
2174
 
                      ('branch.conf', ''),
2175
 
                      ('tags', ''),
2176
 
                      ('references', '')
2177
 
                      ]
2178
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2179
 
 
2180
 
    def __init__(self):
2181
 
        super(BzrBranchFormat8, self).__init__()
2182
 
        self._matchingbzrdir.repository_format = \
2183
 
            RepositoryFormatKnitPack5RichRoot()
2184
 
 
2185
 
    def make_tags(self, branch):
2186
 
        """See bzrlib.branch.BranchFormat.make_tags()."""
2187
 
        return BasicTags(branch)
2188
 
 
2189
 
    def supports_set_append_revisions_only(self):
2190
 
        return True
2191
 
 
2192
 
    def supports_stacking(self):
2193
 
        return True
2194
 
 
2195
 
    supports_reference_locations = True
2196
 
 
2197
 
 
2198
 
class BzrBranchFormat7(BzrBranchFormat8):
 
1623
    def initialize(self, a_bzrdir):
 
1624
        """Create a branch of this format in a_bzrdir."""
 
1625
        utf8_files = [('last-revision', '0 null:\n'),
 
1626
                      ('branch.conf', ''),
 
1627
                      ('tags', ''),
 
1628
                      ]
 
1629
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1630
 
 
1631
    def make_tags(self, branch):
 
1632
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1633
        return BasicTags(branch)
 
1634
 
 
1635
 
 
1636
 
 
1637
class BzrBranchFormat7(BranchFormatMetadir):
2199
1638
    """Branch format with last-revision, tags, and a stacked location pointer.
2200
1639
 
2201
1640
    The stacked location pointer is passed down to the repository and requires
2204
1643
    This format was introduced in bzr 1.6.
2205
1644
    """
2206
1645
 
2207
 
    def initialize(self, a_bzrdir, name=None):
2208
 
        """Create a branch of this format in a_bzrdir."""
2209
 
        utf8_files = [('last-revision', '0 null:\n'),
2210
 
                      ('branch.conf', ''),
2211
 
                      ('tags', ''),
2212
 
                      ]
2213
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
2214
 
 
2215
1646
    def _branch_class(self):
2216
1647
        return BzrBranch7
2217
1648
 
2223
1654
        """See BranchFormat.get_format_description()."""
2224
1655
        return "Branch format 7"
2225
1656
 
2226
 
    def supports_set_append_revisions_only(self):
 
1657
    def initialize(self, a_bzrdir):
 
1658
        """Create a branch of this format in a_bzrdir."""
 
1659
        utf8_files = [('last-revision', '0 null:\n'),
 
1660
                      ('branch.conf', ''),
 
1661
                      ('tags', ''),
 
1662
                      ]
 
1663
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1664
 
 
1665
    def __init__(self):
 
1666
        super(BzrBranchFormat7, self).__init__()
 
1667
        self._matchingbzrdir.repository_format = \
 
1668
            RepositoryFormatKnitPack5RichRoot()
 
1669
 
 
1670
    def make_tags(self, branch):
 
1671
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1672
        return BasicTags(branch)
 
1673
 
 
1674
    def supports_stacking(self):
2227
1675
        return True
2228
1676
 
2229
 
    supports_reference_locations = False
2230
 
 
2231
1677
 
2232
1678
class BranchReferenceFormat(BranchFormat):
2233
1679
    """Bzr branch reference format.
2248
1694
        """See BranchFormat.get_format_description()."""
2249
1695
        return "Checkout reference format 1"
2250
1696
 
2251
 
    def get_reference(self, a_bzrdir, name=None):
 
1697
    def get_reference(self, a_bzrdir):
2252
1698
        """See BranchFormat.get_reference()."""
2253
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2254
 
        return transport.get_bytes('location')
 
1699
        transport = a_bzrdir.get_branch_transport(None)
 
1700
        return transport.get('location').read()
2255
1701
 
2256
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1702
    def set_reference(self, a_bzrdir, to_branch):
2257
1703
        """See BranchFormat.set_reference()."""
2258
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1704
        transport = a_bzrdir.get_branch_transport(None)
2259
1705
        location = transport.put_bytes('location', to_branch.base)
2260
1706
 
2261
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1707
    def initialize(self, a_bzrdir, target_branch=None):
2262
1708
        """Create a branch of this format in a_bzrdir."""
2263
1709
        if target_branch is None:
2264
1710
            # this format does not implement branch itself, thus the implicit
2265
1711
            # creation contract must see it as uninitializable
2266
1712
            raise errors.UninitializableFormat(self)
2267
 
        mutter('creating branch reference in %s', a_bzrdir.user_url)
2268
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1713
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1714
        branch_transport = a_bzrdir.get_branch_transport(self)
2269
1715
        branch_transport.put_bytes('location',
2270
 
            target_branch.bzrdir.user_url)
 
1716
            target_branch.bzrdir.root_transport.base)
2271
1717
        branch_transport.put_bytes('format', self.get_format_string())
2272
 
        branch = self.open(
2273
 
            a_bzrdir, name, _found=True,
 
1718
        return self.open(
 
1719
            a_bzrdir, _found=True,
2274
1720
            possible_transports=[target_branch.bzrdir.root_transport])
2275
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2276
 
        return branch
2277
1721
 
2278
1722
    def __init__(self):
2279
1723
        super(BranchReferenceFormat, self).__init__()
2285
1729
        def clone(to_bzrdir, revision_id=None,
2286
1730
            repository_policy=None):
2287
1731
            """See Branch.clone()."""
2288
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
1732
            return format.initialize(to_bzrdir, a_branch)
2289
1733
            # cannot obey revision_id limits when cloning a reference ...
2290
1734
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2291
1735
            # emit some sort of warning/error to the caller ?!
2292
1736
        return clone
2293
1737
 
2294
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
2295
 
             possible_transports=None, ignore_fallbacks=False):
 
1738
    def open(self, a_bzrdir, _found=False, location=None,
 
1739
             possible_transports=None):
2296
1740
        """Return the branch that the branch reference in a_bzrdir points at.
2297
1741
 
2298
 
        :param a_bzrdir: A BzrDir that contains a branch.
2299
 
        :param name: Name of colocated branch to open, if any
2300
 
        :param _found: a private parameter, do not use it. It is used to
2301
 
            indicate if format probing has already be done.
2302
 
        :param ignore_fallbacks: when set, no fallback branches will be opened
2303
 
            (if there are any).  Default is to open fallbacks.
2304
 
        :param location: The location of the referenced branch.  If
2305
 
            unspecified, this will be determined from the branch reference in
2306
 
            a_bzrdir.
2307
 
        :param possible_transports: An optional reusable transports list.
 
1742
        _found is a private parameter, do not use it. It is used to indicate
 
1743
               if format probing has already be done.
2308
1744
        """
2309
1745
        if not _found:
2310
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1746
            format = BranchFormat.find_format(a_bzrdir)
2311
1747
            if format.__class__ != self.__class__:
2312
1748
                raise AssertionError("wrong format %r found for %r" %
2313
1749
                    (format, self))
2314
1750
        if location is None:
2315
 
            location = self.get_reference(a_bzrdir, name)
 
1751
            location = self.get_reference(a_bzrdir)
2316
1752
        real_bzrdir = bzrdir.BzrDir.open(
2317
1753
            location, possible_transports=possible_transports)
2318
 
        result = real_bzrdir.open_branch(name=name, 
2319
 
            ignore_fallbacks=ignore_fallbacks)
 
1754
        result = real_bzrdir.open_branch()
2320
1755
        # this changes the behaviour of result.clone to create a new reference
2321
1756
        # rather than a copy of the content of the branch.
2322
1757
        # I did not use a proxy object because that needs much more extensive
2343
1778
__format5 = BzrBranchFormat5()
2344
1779
__format6 = BzrBranchFormat6()
2345
1780
__format7 = BzrBranchFormat7()
2346
 
__format8 = BzrBranchFormat8()
2347
1781
BranchFormat.register_format(__format5)
2348
1782
BranchFormat.register_format(BranchReferenceFormat())
2349
1783
BranchFormat.register_format(__format6)
2350
1784
BranchFormat.register_format(__format7)
2351
 
BranchFormat.register_format(__format8)
2352
 
BranchFormat.set_default_format(__format7)
 
1785
BranchFormat.set_default_format(__format6)
2353
1786
_legacy_formats = [BzrBranchFormat4(),
2354
1787
    ]
2355
1788
network_format_registry.register(
2356
1789
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2357
1790
 
2358
1791
 
2359
 
class BranchWriteLockResult(LogicalLockResult):
2360
 
    """The result of write locking a branch.
2361
 
 
2362
 
    :ivar branch_token: The token obtained from the underlying branch lock, or
2363
 
        None.
2364
 
    :ivar unlock: A callable which will unlock the lock.
2365
 
    """
2366
 
 
2367
 
    def __init__(self, unlock, branch_token):
2368
 
        LogicalLockResult.__init__(self, unlock)
2369
 
        self.branch_token = branch_token
2370
 
 
2371
 
    def __repr__(self):
2372
 
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2373
 
            self.unlock)
2374
 
 
2375
 
 
2376
 
class BzrBranch(Branch, _RelockDebugMixin):
 
1792
class BzrBranch(Branch):
2377
1793
    """A branch stored in the actual filesystem.
2378
1794
 
2379
1795
    Note that it's "local" in the context of the filesystem; it doesn't
2385
1801
    :ivar repository: Repository for this branch.
2386
1802
    :ivar base: The url of the base directory for this branch; the one
2387
1803
        containing the .bzr directory.
2388
 
    :ivar name: Optional colocated branch name as it exists in the control
2389
 
        directory.
2390
1804
    """
2391
1805
 
2392
1806
    def __init__(self, _format=None,
2393
 
                 _control_files=None, a_bzrdir=None, name=None,
2394
 
                 _repository=None, ignore_fallbacks=False):
 
1807
                 _control_files=None, a_bzrdir=None, _repository=None):
2395
1808
        """Create new branch object at a particular location."""
2396
1809
        if a_bzrdir is None:
2397
1810
            raise ValueError('a_bzrdir must be supplied')
2398
1811
        else:
2399
1812
            self.bzrdir = a_bzrdir
2400
1813
        self._base = self.bzrdir.transport.clone('..').base
2401
 
        self.name = name
2402
1814
        # XXX: We should be able to just do
2403
1815
        #   self.base = self.bzrdir.root_transport.base
2404
1816
        # but this does not quite work yet -- mbp 20080522
2411
1823
        Branch.__init__(self)
2412
1824
 
2413
1825
    def __str__(self):
2414
 
        if self.name is None:
2415
 
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
2416
 
        else:
2417
 
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
2418
 
                self.name)
 
1826
        return '%s(%r)' % (self.__class__.__name__, self.base)
2419
1827
 
2420
1828
    __repr__ = __str__
2421
1829
 
2425
1833
 
2426
1834
    base = property(_get_base, doc="The URL for the root of this branch.")
2427
1835
 
2428
 
    def _get_config(self):
2429
 
        return TransportConfig(self._transport, 'branch.conf')
2430
 
 
2431
1836
    def is_locked(self):
2432
1837
        return self.control_files.is_locked()
2433
1838
 
2434
1839
    def lock_write(self, token=None):
2435
 
        """Lock the branch for write operations.
2436
 
 
2437
 
        :param token: A token to permit reacquiring a previously held and
2438
 
            preserved lock.
2439
 
        :return: A BranchWriteLockResult.
2440
 
        """
2441
 
        if not self.is_locked():
2442
 
            self._note_lock('w')
2443
 
        # All-in-one needs to always unlock/lock.
2444
 
        repo_control = getattr(self.repository, 'control_files', None)
2445
 
        if self.control_files == repo_control or not self.is_locked():
2446
 
            self.repository._warn_if_deprecated(self)
2447
 
            self.repository.lock_write()
2448
 
            took_lock = True
2449
 
        else:
2450
 
            took_lock = False
 
1840
        repo_token = self.repository.lock_write()
2451
1841
        try:
2452
 
            return BranchWriteLockResult(self.unlock,
2453
 
                self.control_files.lock_write(token=token))
 
1842
            token = self.control_files.lock_write(token=token)
2454
1843
        except:
2455
 
            if took_lock:
2456
 
                self.repository.unlock()
 
1844
            self.repository.unlock()
2457
1845
            raise
 
1846
        return token
2458
1847
 
2459
1848
    def lock_read(self):
2460
 
        """Lock the branch for read operations.
2461
 
 
2462
 
        :return: A bzrlib.lock.LogicalLockResult.
2463
 
        """
2464
 
        if not self.is_locked():
2465
 
            self._note_lock('r')
2466
 
        # All-in-one needs to always unlock/lock.
2467
 
        repo_control = getattr(self.repository, 'control_files', None)
2468
 
        if self.control_files == repo_control or not self.is_locked():
2469
 
            self.repository._warn_if_deprecated(self)
2470
 
            self.repository.lock_read()
2471
 
            took_lock = True
2472
 
        else:
2473
 
            took_lock = False
 
1849
        self.repository.lock_read()
2474
1850
        try:
2475
1851
            self.control_files.lock_read()
2476
 
            return LogicalLockResult(self.unlock)
2477
1852
        except:
2478
 
            if took_lock:
2479
 
                self.repository.unlock()
 
1853
            self.repository.unlock()
2480
1854
            raise
2481
1855
 
2482
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2483
1856
    def unlock(self):
 
1857
        # TODO: test for failed two phase locks. This is known broken.
2484
1858
        try:
2485
1859
            self.control_files.unlock()
2486
1860
        finally:
2487
 
            # All-in-one needs to always unlock/lock.
2488
 
            repo_control = getattr(self.repository, 'control_files', None)
2489
 
            if (self.control_files == repo_control or
2490
 
                not self.control_files.is_locked()):
2491
 
                self.repository.unlock()
2492
 
            if not self.control_files.is_locked():
2493
 
                # we just released the lock
2494
 
                self._clear_cached_state()
 
1861
            self.repository.unlock()
 
1862
        if not self.control_files.is_locked():
 
1863
            # we just released the lock
 
1864
            self._clear_cached_state()
2495
1865
 
2496
1866
    def peek_lock_mode(self):
2497
1867
        if self.control_files._lock_count == 0:
2616
1986
        """See Branch.basis_tree."""
2617
1987
        return self.repository.revision_tree(self.last_revision())
2618
1988
 
 
1989
    @needs_write_lock
 
1990
    def pull(self, source, overwrite=False, stop_revision=None,
 
1991
             _hook_master=None, run_hooks=True, possible_transports=None,
 
1992
             _override_hook_target=None):
 
1993
        """See Branch.pull.
 
1994
 
 
1995
        :param _hook_master: Private parameter - set the branch to
 
1996
            be supplied as the master to pull hooks.
 
1997
        :param run_hooks: Private parameter - if false, this branch
 
1998
            is being called because it's the master of the primary branch,
 
1999
            so it should not run its hooks.
 
2000
        :param _override_hook_target: Private parameter - set the branch to be
 
2001
            supplied as the target_branch to pull hooks.
 
2002
        """
 
2003
        result = PullResult()
 
2004
        result.source_branch = source
 
2005
        if _override_hook_target is None:
 
2006
            result.target_branch = self
 
2007
        else:
 
2008
            result.target_branch = _override_hook_target
 
2009
        source.lock_read()
 
2010
        try:
 
2011
            # We assume that during 'pull' the local repository is closer than
 
2012
            # the remote one.
 
2013
            graph = self.repository.get_graph(source.repository)
 
2014
            result.old_revno, result.old_revid = self.last_revision_info()
 
2015
            self.update_revisions(source, stop_revision, overwrite=overwrite,
 
2016
                                  graph=graph)
 
2017
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
 
2018
            result.new_revno, result.new_revid = self.last_revision_info()
 
2019
            if _hook_master:
 
2020
                result.master_branch = _hook_master
 
2021
                result.local_branch = result.target_branch
 
2022
            else:
 
2023
                result.master_branch = result.target_branch
 
2024
                result.local_branch = None
 
2025
            if run_hooks:
 
2026
                for hook in Branch.hooks['post_pull']:
 
2027
                    hook(result)
 
2028
        finally:
 
2029
            source.unlock()
 
2030
        return result
 
2031
 
2619
2032
    def _get_parent_location(self):
2620
2033
        _locs = ['parent', 'pull', 'x-pull']
2621
2034
        for l in _locs:
2625
2038
                pass
2626
2039
        return None
2627
2040
 
 
2041
    @needs_read_lock
 
2042
    def push(self, target, overwrite=False, stop_revision=None,
 
2043
             _override_hook_source_branch=None):
 
2044
        """See Branch.push.
 
2045
 
 
2046
        This is the basic concrete implementation of push()
 
2047
 
 
2048
        :param _override_hook_source_branch: If specified, run
 
2049
        the hooks passing this Branch as the source, rather than self.
 
2050
        This is for use of RemoteBranch, where push is delegated to the
 
2051
        underlying vfs-based Branch.
 
2052
        """
 
2053
        # TODO: Public option to disable running hooks - should be trivial but
 
2054
        # needs tests.
 
2055
        return _run_with_write_locked_target(
 
2056
            target, self._push_with_bound_branches, target, overwrite,
 
2057
            stop_revision,
 
2058
            _override_hook_source_branch=_override_hook_source_branch)
 
2059
 
 
2060
    def _push_with_bound_branches(self, target, overwrite,
 
2061
            stop_revision,
 
2062
            _override_hook_source_branch=None):
 
2063
        """Push from self into target, and into target's master if any.
 
2064
 
 
2065
        This is on the base BzrBranch class even though it doesn't support
 
2066
        bound branches because the *target* might be bound.
 
2067
        """
 
2068
        def _run_hooks():
 
2069
            if _override_hook_source_branch:
 
2070
                result.source_branch = _override_hook_source_branch
 
2071
            for hook in Branch.hooks['post_push']:
 
2072
                hook(result)
 
2073
 
 
2074
        bound_location = target.get_bound_location()
 
2075
        if bound_location and target.base != bound_location:
 
2076
            # there is a master branch.
 
2077
            #
 
2078
            # XXX: Why the second check?  Is it even supported for a branch to
 
2079
            # be bound to itself? -- mbp 20070507
 
2080
            master_branch = target.get_master_branch()
 
2081
            master_branch.lock_write()
 
2082
            try:
 
2083
                # push into the master from this branch.
 
2084
                self._basic_push(master_branch, overwrite, stop_revision)
 
2085
                # and push into the target branch from this. Note that we push from
 
2086
                # this branch again, because its considered the highest bandwidth
 
2087
                # repository.
 
2088
                result = self._basic_push(target, overwrite, stop_revision)
 
2089
                result.master_branch = master_branch
 
2090
                result.local_branch = target
 
2091
                _run_hooks()
 
2092
                return result
 
2093
            finally:
 
2094
                master_branch.unlock()
 
2095
        else:
 
2096
            # no master branch
 
2097
            result = self._basic_push(target, overwrite, stop_revision)
 
2098
            # TODO: Why set master_branch and local_branch if there's no
 
2099
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2100
            # 20070504
 
2101
            result.master_branch = target
 
2102
            result.local_branch = None
 
2103
            _run_hooks()
 
2104
            return result
 
2105
 
2628
2106
    def _basic_push(self, target, overwrite, stop_revision):
2629
2107
        """Basic implementation of push without bound branches or hooks.
2630
2108
 
2631
 
        Must be called with source read locked and target write locked.
 
2109
        Must be called with self read locked and target write locked.
2632
2110
        """
2633
2111
        result = BranchPushResult()
2634
2112
        result.source_branch = self
2635
2113
        result.target_branch = target
2636
2114
        result.old_revno, result.old_revid = target.last_revision_info()
2637
 
        self.update_references(target)
2638
2115
        if result.old_revid != self.last_revision():
2639
2116
            # We assume that during 'push' this repository is closer than
2640
2117
            # the target.
2641
2118
            graph = self.repository.get_graph(target.repository)
2642
 
            target.update_revisions(self, stop_revision,
2643
 
                overwrite=overwrite, graph=graph)
 
2119
            target.update_revisions(self, stop_revision, overwrite=overwrite,
 
2120
                                    graph=graph)
2644
2121
        if self._push_should_merge_tags():
2645
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2646
 
                overwrite)
 
2122
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2647
2123
        result.new_revno, result.new_revid = target.last_revision_info()
2648
2124
        return result
2649
2125
 
2650
2126
    def get_stacked_on_url(self):
2651
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2127
        raise errors.UnstackableBranchFormat(self._format, self.base)
2652
2128
 
2653
2129
    def set_push_location(self, location):
2654
2130
        """See Branch.set_push_location."""
2656
2132
            'push_location', location,
2657
2133
            store=_mod_config.STORE_LOCATION_NORECURSE)
2658
2134
 
 
2135
    @needs_write_lock
 
2136
    def set_parent(self, url):
 
2137
        """See Branch.set_parent."""
 
2138
        # TODO: Maybe delete old location files?
 
2139
        # URLs should never be unicode, even on the local fs,
 
2140
        # FIXUP this and get_parent in a future branch format bump:
 
2141
        # read and rewrite the file. RBC 20060125
 
2142
        if url is not None:
 
2143
            if isinstance(url, unicode):
 
2144
                try:
 
2145
                    url = url.encode('ascii')
 
2146
                except UnicodeEncodeError:
 
2147
                    raise errors.InvalidURL(url,
 
2148
                        "Urls must be 7-bit ascii, "
 
2149
                        "use bzrlib.urlutils.escape")
 
2150
            url = urlutils.relative_url(self.base, url)
 
2151
        self._set_parent_location(url)
 
2152
 
2659
2153
    def _set_parent_location(self, url):
2660
2154
        if url is None:
2661
2155
            self._transport.delete('parent')
2663
2157
            self._transport.put_bytes('parent', url + '\n',
2664
2158
                mode=self.bzrdir._get_file_mode())
2665
2159
 
 
2160
    def set_stacked_on_url(self, url):
 
2161
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2162
 
2666
2163
 
2667
2164
class BzrBranch5(BzrBranch):
2668
2165
    """A format 5 branch. This supports new features over plain branches.
2670
2167
    It has support for a master_branch which is the data for bound branches.
2671
2168
    """
2672
2169
 
 
2170
    @needs_write_lock
 
2171
    def pull(self, source, overwrite=False, stop_revision=None,
 
2172
             run_hooks=True, possible_transports=None,
 
2173
             _override_hook_target=None):
 
2174
        """Pull from source into self, updating my master if any.
 
2175
 
 
2176
        :param run_hooks: Private parameter - if false, this branch
 
2177
            is being called because it's the master of the primary branch,
 
2178
            so it should not run its hooks.
 
2179
        """
 
2180
        bound_location = self.get_bound_location()
 
2181
        master_branch = None
 
2182
        if bound_location and source.base != bound_location:
 
2183
            # not pulling from master, so we need to update master.
 
2184
            master_branch = self.get_master_branch(possible_transports)
 
2185
            master_branch.lock_write()
 
2186
        try:
 
2187
            if master_branch:
 
2188
                # pull from source into master.
 
2189
                master_branch.pull(source, overwrite, stop_revision,
 
2190
                    run_hooks=False)
 
2191
            return super(BzrBranch5, self).pull(source, overwrite,
 
2192
                stop_revision, _hook_master=master_branch,
 
2193
                run_hooks=run_hooks,
 
2194
                _override_hook_target=_override_hook_target)
 
2195
        finally:
 
2196
            if master_branch:
 
2197
                master_branch.unlock()
 
2198
 
2673
2199
    def get_bound_location(self):
2674
2200
        try:
2675
2201
            return self._transport.get_bytes('bound')[:-1]
2762
2288
        return None
2763
2289
 
2764
2290
 
2765
 
class BzrBranch8(BzrBranch5):
2766
 
    """A branch that stores tree-reference locations."""
 
2291
class BzrBranch7(BzrBranch5):
 
2292
    """A branch with support for a fallback repository."""
 
2293
 
 
2294
    def _get_fallback_repository(self, url):
 
2295
        """Get the repository we fallback to at url."""
 
2296
        url = urlutils.join(self.base, url)
 
2297
        a_bzrdir = bzrdir.BzrDir.open(url,
 
2298
                                      possible_transports=[self._transport])
 
2299
        return a_bzrdir.open_branch().repository
 
2300
 
 
2301
    def _activate_fallback_location(self, url):
 
2302
        """Activate the branch/repository from url as a fallback repository."""
 
2303
        self.repository.add_fallback_repository(
 
2304
            self._get_fallback_repository(url))
2767
2305
 
2768
2306
    def _open_hook(self):
2769
 
        if self._ignore_fallbacks:
2770
 
            return
2771
2307
        try:
2772
2308
            url = self.get_stacked_on_url()
2773
2309
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2783
2319
                        "None, not a URL." % hook_name)
2784
2320
            self._activate_fallback_location(url)
2785
2321
 
 
2322
    def _check_stackable_repo(self):
 
2323
        if not self.repository._format.supports_external_lookups:
 
2324
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
2325
                self.repository.base)
 
2326
 
2786
2327
    def __init__(self, *args, **kwargs):
2787
 
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2788
 
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
2328
        super(BzrBranch7, self).__init__(*args, **kwargs)
2789
2329
        self._last_revision_info_cache = None
2790
 
        self._reference_info = None
 
2330
        self._partial_revision_history_cache = []
2791
2331
 
2792
2332
    def _clear_cached_state(self):
2793
 
        super(BzrBranch8, self)._clear_cached_state()
 
2333
        super(BzrBranch7, self)._clear_cached_state()
2794
2334
        self._last_revision_info_cache = None
2795
 
        self._reference_info = None
 
2335
        self._partial_revision_history_cache = []
2796
2336
 
2797
2337
    def _last_revision_info(self):
2798
2338
        revision_string = self._transport.get_bytes('last-revision')
2844
2384
        if _mod_revision.is_null(last_revision):
2845
2385
            return
2846
2386
        if last_revision not in self._lefthand_history(revision_id):
2847
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2387
            raise errors.AppendRevisionsOnlyViolation(self.base)
2848
2388
 
2849
2389
    def _gen_revision_history(self):
2850
2390
        """Generate the revision history from last revision
2853
2393
        self._extend_partial_history(stop_index=last_revno-1)
2854
2394
        return list(reversed(self._partial_revision_history_cache))
2855
2395
 
 
2396
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2397
        """Extend the partial history to include a given index
 
2398
 
 
2399
        If a stop_index is supplied, stop when that index has been reached.
 
2400
        If a stop_revision is supplied, stop when that revision is
 
2401
        encountered.  Otherwise, stop when the beginning of history is
 
2402
        reached.
 
2403
 
 
2404
        :param stop_index: The index which should be present.  When it is
 
2405
            present, history extension will stop.
 
2406
        :param revision_id: The revision id which should be present.  When
 
2407
            it is encountered, history extension will stop.
 
2408
        """
 
2409
        repo = self.repository
 
2410
        if len(self._partial_revision_history_cache) == 0:
 
2411
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2412
        else:
 
2413
            start_revision = self._partial_revision_history_cache[-1]
 
2414
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2415
            #skip the last revision in the list
 
2416
            next_revision = iterator.next()
 
2417
        for revision_id in iterator:
 
2418
            self._partial_revision_history_cache.append(revision_id)
 
2419
            if (stop_index is not None and
 
2420
                len(self._partial_revision_history_cache) > stop_index):
 
2421
                break
 
2422
            if revision_id == stop_revision:
 
2423
                break
 
2424
 
2856
2425
    def _write_revision_history(self, history):
2857
2426
        """Factored out of set_revision_history.
2858
2427
 
2879
2448
        """Set the parent branch"""
2880
2449
        return self._get_config_location('parent_location')
2881
2450
 
2882
 
    @needs_write_lock
2883
 
    def _set_all_reference_info(self, info_dict):
2884
 
        """Replace all reference info stored in a branch.
2885
 
 
2886
 
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
2887
 
        """
2888
 
        s = StringIO()
2889
 
        writer = rio.RioWriter(s)
2890
 
        for key, (tree_path, branch_location) in info_dict.iteritems():
2891
 
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2892
 
                                branch_location=branch_location)
2893
 
            writer.write_stanza(stanza)
2894
 
        self._transport.put_bytes('references', s.getvalue())
2895
 
        self._reference_info = info_dict
2896
 
 
2897
 
    @needs_read_lock
2898
 
    def _get_all_reference_info(self):
2899
 
        """Return all the reference info stored in a branch.
2900
 
 
2901
 
        :return: A dict of {file_id: (tree_path, branch_location)}
2902
 
        """
2903
 
        if self._reference_info is not None:
2904
 
            return self._reference_info
2905
 
        rio_file = self._transport.get('references')
2906
 
        try:
2907
 
            stanzas = rio.read_stanzas(rio_file)
2908
 
            info_dict = dict((s['file_id'], (s['tree_path'],
2909
 
                             s['branch_location'])) for s in stanzas)
2910
 
        finally:
2911
 
            rio_file.close()
2912
 
        self._reference_info = info_dict
2913
 
        return info_dict
2914
 
 
2915
 
    def set_reference_info(self, file_id, tree_path, branch_location):
2916
 
        """Set the branch location to use for a tree reference.
2917
 
 
2918
 
        :param file_id: The file-id of the tree reference.
2919
 
        :param tree_path: The path of the tree reference in the tree.
2920
 
        :param branch_location: The location of the branch to retrieve tree
2921
 
            references from.
2922
 
        """
2923
 
        info_dict = self._get_all_reference_info()
2924
 
        info_dict[file_id] = (tree_path, branch_location)
2925
 
        if None in (tree_path, branch_location):
2926
 
            if tree_path is not None:
2927
 
                raise ValueError('tree_path must be None when branch_location'
2928
 
                                 ' is None.')
2929
 
            if branch_location is not None:
2930
 
                raise ValueError('branch_location must be None when tree_path'
2931
 
                                 ' is None.')
2932
 
            del info_dict[file_id]
2933
 
        self._set_all_reference_info(info_dict)
2934
 
 
2935
 
    def get_reference_info(self, file_id):
2936
 
        """Get the tree_path and branch_location for a tree reference.
2937
 
 
2938
 
        :return: a tuple of (tree_path, branch_location)
2939
 
        """
2940
 
        return self._get_all_reference_info().get(file_id, (None, None))
2941
 
 
2942
 
    def reference_parent(self, file_id, path, possible_transports=None):
2943
 
        """Return the parent branch for a tree-reference file_id.
2944
 
 
2945
 
        :param file_id: The file_id of the tree reference
2946
 
        :param path: The path of the file_id in the tree
2947
 
        :return: A branch associated with the file_id
2948
 
        """
2949
 
        branch_location = self.get_reference_info(file_id)[1]
2950
 
        if branch_location is None:
2951
 
            return Branch.reference_parent(self, file_id, path,
2952
 
                                           possible_transports)
2953
 
        branch_location = urlutils.join(self.user_url, branch_location)
2954
 
        return Branch.open(branch_location,
2955
 
                           possible_transports=possible_transports)
2956
 
 
2957
2451
    def set_push_location(self, location):
2958
2452
        """See Branch.set_push_location."""
2959
2453
        self._set_config_location('push_location', location)
3001
2495
            raise errors.NotStacked(self)
3002
2496
        return stacked_url
3003
2497
 
 
2498
    def set_append_revisions_only(self, enabled):
 
2499
        if enabled:
 
2500
            value = 'True'
 
2501
        else:
 
2502
            value = 'False'
 
2503
        self.get_config().set_user_option('append_revisions_only', value,
 
2504
            warn_masked=True)
 
2505
 
 
2506
    def set_stacked_on_url(self, url):
 
2507
        self._check_stackable_repo()
 
2508
        if not url:
 
2509
            try:
 
2510
                old_url = self.get_stacked_on_url()
 
2511
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
2512
                errors.UnstackableRepositoryFormat):
 
2513
                return
 
2514
            url = ''
 
2515
            # repositories don't offer an interface to remove fallback
 
2516
            # repositories today; take the conceptually simpler option and just
 
2517
            # reopen it.
 
2518
            self.repository = self.bzrdir.find_repository()
 
2519
            # for every revision reference the branch has, ensure it is pulled
 
2520
            # in.
 
2521
            source_repository = self._get_fallback_repository(old_url)
 
2522
            for revision_id in chain([self.last_revision()],
 
2523
                self.tags.get_reverse_tag_dict()):
 
2524
                self.repository.fetch(source_repository, revision_id,
 
2525
                    find_ghosts=True)
 
2526
        else:
 
2527
            self._activate_fallback_location(url)
 
2528
        # write this out after the repository is stacked to avoid setting a
 
2529
        # stacked config that doesn't work.
 
2530
        self._set_config_location('stacked_on_location', url)
 
2531
 
3004
2532
    def _get_append_revisions_only(self):
3005
 
        return self.get_config(
3006
 
            ).get_user_option_as_bool('append_revisions_only')
 
2533
        value = self.get_config().get_user_option('append_revisions_only')
 
2534
        return value == 'True'
3007
2535
 
3008
2536
    @needs_write_lock
3009
2537
    def generate_revision_history(self, revision_id, last_rev=None,
3049
2577
        return self.revno() - index
3050
2578
 
3051
2579
 
3052
 
class BzrBranch7(BzrBranch8):
3053
 
    """A branch with support for a fallback repository."""
3054
 
 
3055
 
    def set_reference_info(self, file_id, tree_path, branch_location):
3056
 
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
3057
 
 
3058
 
    def get_reference_info(self, file_id):
3059
 
        Branch.get_reference_info(self, file_id)
3060
 
 
3061
 
    def reference_parent(self, file_id, path, possible_transports=None):
3062
 
        return Branch.reference_parent(self, file_id, path,
3063
 
                                       possible_transports)
3064
 
 
3065
 
 
3066
2580
class BzrBranch6(BzrBranch7):
3067
2581
    """See BzrBranchFormat6 for the capabilities of this branch.
3068
2582
 
3071
2585
    """
3072
2586
 
3073
2587
    def get_stacked_on_url(self):
3074
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2588
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2589
 
 
2590
    def set_stacked_on_url(self, url):
 
2591
        raise errors.UnstackableBranchFormat(self._format, self.base)
3075
2592
 
3076
2593
 
3077
2594
######################################################################
3156
2673
 
3157
2674
    def __init__(self, branch):
3158
2675
        self.branch = branch
3159
 
        self.errors = []
3160
2676
 
3161
2677
    def report_results(self, verbose):
3162
2678
        """Report the check results via trace.note.
3164
2680
        :param verbose: Requests more detailed display of what was checked,
3165
2681
            if any.
3166
2682
        """
3167
 
        note('checked branch %s format %s', self.branch.user_url,
3168
 
            self.branch._format)
3169
 
        for error in self.errors:
3170
 
            note('found error:%s', error)
 
2683
        note('checked branch %s format %s',
 
2684
             self.branch.base,
 
2685
             self.branch._format)
3171
2686
 
3172
2687
 
3173
2688
class Converter5to6(object):
3211
2726
        branch._transport.put_bytes('format', format.get_format_string())
3212
2727
 
3213
2728
 
3214
 
class Converter7to8(object):
3215
 
    """Perform an in-place upgrade of format 6 to format 7"""
3216
 
 
3217
 
    def convert(self, branch):
3218
 
        format = BzrBranchFormat8()
3219
 
        branch._transport.put_bytes('references', '')
3220
 
        # update target format
3221
 
        branch._transport.put_bytes('format', format.get_format_string())
3222
 
 
3223
2729
 
3224
2730
def _run_with_write_locked_target(target, callable, *args, **kwargs):
3225
2731
    """Run ``callable(*args, **kwargs)``, write-locking target for the
3265
2771
    _optimisers = []
3266
2772
    """The available optimised InterBranch types."""
3267
2773
 
3268
 
    @classmethod
3269
 
    def _get_branch_formats_to_test(klass):
3270
 
        """Return an iterable of format tuples for testing.
3271
 
        
3272
 
        :return: An iterable of (from_format, to_format) to use when testing
3273
 
            this InterBranch class. Each InterBranch class should define this
3274
 
            method itself.
3275
 
        """
3276
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
3277
 
 
3278
 
    @needs_write_lock
3279
 
    def pull(self, overwrite=False, stop_revision=None,
3280
 
             possible_transports=None, local=False):
3281
 
        """Mirror source into target branch.
3282
 
 
3283
 
        The target branch is considered to be 'local', having low latency.
3284
 
 
3285
 
        :returns: PullResult instance
3286
 
        """
3287
 
        raise NotImplementedError(self.pull)
3288
 
 
3289
 
    @needs_write_lock
 
2774
    @staticmethod
 
2775
    def _get_branch_formats_to_test():
 
2776
        """Return a tuple with the Branch formats to use when testing."""
 
2777
        raise NotImplementedError(self._get_branch_formats_to_test)
 
2778
 
3290
2779
    def update_revisions(self, stop_revision=None, overwrite=False,
3291
2780
                         graph=None):
3292
2781
        """Pull in new perfect-fit revisions.
3300
2789
        """
3301
2790
        raise NotImplementedError(self.update_revisions)
3302
2791
 
3303
 
    @needs_write_lock
3304
 
    def push(self, overwrite=False, stop_revision=None,
3305
 
             _override_hook_source_branch=None):
3306
 
        """Mirror the source branch into the target branch.
3307
 
 
3308
 
        The source branch is considered to be 'local', having low latency.
3309
 
        """
3310
 
        raise NotImplementedError(self.push)
3311
 
 
3312
 
    @needs_write_lock
3313
 
    def copy_content_into(self, revision_id=None):
3314
 
        """Copy the content of source into target
3315
 
 
3316
 
        revision_id: if not None, the revision history in the new branch will
3317
 
                     be truncated to end with revision_id.
3318
 
        """
3319
 
        raise NotImplementedError(self.copy_content_into)
3320
 
 
3321
2792
 
3322
2793
class GenericInterBranch(InterBranch):
3323
 
    """InterBranch implementation that uses public Branch functions."""
3324
 
 
3325
 
    @classmethod
3326
 
    def is_compatible(klass, source, target):
3327
 
        # GenericBranch uses the public API, so always compatible
3328
 
        return True
3329
 
 
3330
 
    @classmethod
3331
 
    def _get_branch_formats_to_test(klass):
3332
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3333
 
 
3334
 
    @classmethod
3335
 
    def unwrap_format(klass, format):
3336
 
        if isinstance(format, remote.RemoteBranchFormat):
3337
 
            format._ensure_real()
3338
 
            return format._custom_format
3339
 
        return format                                                                                                  
3340
 
 
3341
 
    @needs_write_lock
3342
 
    def copy_content_into(self, revision_id=None):
3343
 
        """Copy the content of source into target
3344
 
 
3345
 
        revision_id: if not None, the revision history in the new branch will
3346
 
                     be truncated to end with revision_id.
3347
 
        """
3348
 
        self.source.update_references(self.target)
3349
 
        self.source._synchronize_history(self.target, revision_id)
3350
 
        try:
3351
 
            parent = self.source.get_parent()
3352
 
        except errors.InaccessibleParent, e:
3353
 
            mutter('parent was not accessible to copy: %s', e)
3354
 
        else:
3355
 
            if parent:
3356
 
                self.target.set_parent(parent)
3357
 
        if self.source._push_should_merge_tags():
3358
 
            self.source.tags.merge_to(self.target.tags)
3359
 
 
3360
 
    @needs_write_lock
 
2794
    """InterBranch implementation that uses public Branch functions.
 
2795
    """
 
2796
 
 
2797
    @staticmethod
 
2798
    def _get_branch_formats_to_test():
 
2799
        return BranchFormat._default_format, BranchFormat._default_format
 
2800
 
3361
2801
    def update_revisions(self, stop_revision=None, overwrite=False,
3362
2802
        graph=None):
3363
2803
        """See InterBranch.update_revisions()."""
3364
 
        other_revno, other_last_revision = self.source.last_revision_info()
3365
 
        stop_revno = None # unknown
3366
 
        if stop_revision is None:
3367
 
            stop_revision = other_last_revision
3368
 
            if _mod_revision.is_null(stop_revision):
3369
 
                # if there are no commits, we're done.
3370
 
                return
3371
 
            stop_revno = other_revno
3372
 
 
3373
 
        # what's the current last revision, before we fetch [and change it
3374
 
        # possibly]
3375
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3376
 
        # we fetch here so that we don't process data twice in the common
3377
 
        # case of having something to pull, and so that the check for
3378
 
        # already merged can operate on the just fetched graph, which will
3379
 
        # be cached in memory.
3380
 
        self.target.fetch(self.source, stop_revision)
3381
 
        # Check to see if one is an ancestor of the other
3382
 
        if not overwrite:
3383
 
            if graph is None:
3384
 
                graph = self.target.repository.get_graph()
3385
 
            if self.target._check_if_descendant_or_diverged(
3386
 
                    stop_revision, last_rev, graph, self.source):
3387
 
                # stop_revision is a descendant of last_rev, but we aren't
3388
 
                # overwriting, so we're done.
3389
 
                return
3390
 
        if stop_revno is None:
3391
 
            if graph is None:
3392
 
                graph = self.target.repository.get_graph()
3393
 
            this_revno, this_last_revision = \
3394
 
                    self.target.last_revision_info()
3395
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3396
 
                            [(other_last_revision, other_revno),
3397
 
                             (this_last_revision, this_revno)])
3398
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3399
 
 
3400
 
    @needs_write_lock
3401
 
    def pull(self, overwrite=False, stop_revision=None,
3402
 
             possible_transports=None, run_hooks=True,
3403
 
             _override_hook_target=None, local=False):
3404
 
        """Pull from source into self, updating my master if any.
3405
 
 
3406
 
        :param run_hooks: Private parameter - if false, this branch
3407
 
            is being called because it's the master of the primary branch,
3408
 
            so it should not run its hooks.
3409
 
        """
3410
 
        bound_location = self.target.get_bound_location()
3411
 
        if local and not bound_location:
3412
 
            raise errors.LocalRequiresBoundBranch()
3413
 
        master_branch = None
3414
 
        if not local and bound_location and self.source.user_url != bound_location:
3415
 
            # not pulling from master, so we need to update master.
3416
 
            master_branch = self.target.get_master_branch(possible_transports)
3417
 
            master_branch.lock_write()
3418
 
        try:
3419
 
            if master_branch:
3420
 
                # pull from source into master.
3421
 
                master_branch.pull(self.source, overwrite, stop_revision,
3422
 
                    run_hooks=False)
3423
 
            return self._pull(overwrite,
3424
 
                stop_revision, _hook_master=master_branch,
3425
 
                run_hooks=run_hooks,
3426
 
                _override_hook_target=_override_hook_target)
3427
 
        finally:
3428
 
            if master_branch:
3429
 
                master_branch.unlock()
3430
 
 
3431
 
    def push(self, overwrite=False, stop_revision=None,
3432
 
             _override_hook_source_branch=None):
3433
 
        """See InterBranch.push.
3434
 
 
3435
 
        This is the basic concrete implementation of push()
3436
 
 
3437
 
        :param _override_hook_source_branch: If specified, run
3438
 
        the hooks passing this Branch as the source, rather than self.
3439
 
        This is for use of RemoteBranch, where push is delegated to the
3440
 
        underlying vfs-based Branch.
3441
 
        """
3442
 
        # TODO: Public option to disable running hooks - should be trivial but
3443
 
        # needs tests.
3444
 
        self.source.lock_read()
3445
 
        try:
3446
 
            return _run_with_write_locked_target(
3447
 
                self.target, self._push_with_bound_branches, overwrite,
3448
 
                stop_revision,
3449
 
                _override_hook_source_branch=_override_hook_source_branch)
3450
 
        finally:
3451
 
            self.source.unlock()
3452
 
 
3453
 
    def _push_with_bound_branches(self, overwrite, stop_revision,
3454
 
            _override_hook_source_branch=None):
3455
 
        """Push from source into target, and into target's master if any.
3456
 
        """
3457
 
        def _run_hooks():
3458
 
            if _override_hook_source_branch:
3459
 
                result.source_branch = _override_hook_source_branch
3460
 
            for hook in Branch.hooks['post_push']:
3461
 
                hook(result)
3462
 
 
3463
 
        bound_location = self.target.get_bound_location()
3464
 
        if bound_location and self.target.base != bound_location:
3465
 
            # there is a master branch.
3466
 
            #
3467
 
            # XXX: Why the second check?  Is it even supported for a branch to
3468
 
            # be bound to itself? -- mbp 20070507
3469
 
            master_branch = self.target.get_master_branch()
3470
 
            master_branch.lock_write()
3471
 
            try:
3472
 
                # push into the master from the source branch.
3473
 
                self.source._basic_push(master_branch, overwrite, stop_revision)
3474
 
                # and push into the target branch from the source. Note that we
3475
 
                # push from the source branch again, because its considered the
3476
 
                # highest bandwidth repository.
3477
 
                result = self.source._basic_push(self.target, overwrite,
3478
 
                    stop_revision)
3479
 
                result.master_branch = master_branch
3480
 
                result.local_branch = self.target
3481
 
                _run_hooks()
3482
 
                return result
3483
 
            finally:
3484
 
                master_branch.unlock()
3485
 
        else:
3486
 
            # no master branch
3487
 
            result = self.source._basic_push(self.target, overwrite,
3488
 
                stop_revision)
3489
 
            # TODO: Why set master_branch and local_branch if there's no
3490
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3491
 
            # 20070504
3492
 
            result.master_branch = self.target
3493
 
            result.local_branch = None
3494
 
            _run_hooks()
3495
 
            return result
3496
 
 
3497
 
    def _pull(self, overwrite=False, stop_revision=None,
3498
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3499
 
             _override_hook_target=None, local=False):
3500
 
        """See Branch.pull.
3501
 
 
3502
 
        This function is the core worker, used by GenericInterBranch.pull to
3503
 
        avoid duplication when pulling source->master and source->local.
3504
 
 
3505
 
        :param _hook_master: Private parameter - set the branch to
3506
 
            be supplied as the master to pull hooks.
3507
 
        :param run_hooks: Private parameter - if false, this branch
3508
 
            is being called because it's the master of the primary branch,
3509
 
            so it should not run its hooks.
3510
 
        :param _override_hook_target: Private parameter - set the branch to be
3511
 
            supplied as the target_branch to pull hooks.
3512
 
        :param local: Only update the local branch, and not the bound branch.
3513
 
        """
3514
 
        # This type of branch can't be bound.
3515
 
        if local:
3516
 
            raise errors.LocalRequiresBoundBranch()
3517
 
        result = PullResult()
3518
 
        result.source_branch = self.source
3519
 
        if _override_hook_target is None:
3520
 
            result.target_branch = self.target
3521
 
        else:
3522
 
            result.target_branch = _override_hook_target
3523
 
        self.source.lock_read()
3524
 
        try:
3525
 
            # We assume that during 'pull' the target repository is closer than
3526
 
            # the source one.
3527
 
            self.source.update_references(self.target)
3528
 
            graph = self.target.repository.get_graph(self.source.repository)
3529
 
            # TODO: Branch formats should have a flag that indicates 
3530
 
            # that revno's are expensive, and pull() should honor that flag.
3531
 
            # -- JRV20090506
3532
 
            result.old_revno, result.old_revid = \
3533
 
                self.target.last_revision_info()
3534
 
            self.target.update_revisions(self.source, stop_revision,
3535
 
                overwrite=overwrite, graph=graph)
3536
 
            # TODO: The old revid should be specified when merging tags, 
3537
 
            # so a tags implementation that versions tags can only 
3538
 
            # pull in the most recent changes. -- JRV20090506
3539
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3540
 
                overwrite)
3541
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3542
 
            if _hook_master:
3543
 
                result.master_branch = _hook_master
3544
 
                result.local_branch = result.target_branch
3545
 
            else:
3546
 
                result.master_branch = result.target_branch
3547
 
                result.local_branch = None
3548
 
            if run_hooks:
3549
 
                for hook in Branch.hooks['post_pull']:
3550
 
                    hook(result)
3551
 
        finally:
3552
 
            self.source.unlock()
3553
 
        return result
 
2804
        self.source.lock_read()
 
2805
        try:
 
2806
            other_revno, other_last_revision = self.source.last_revision_info()
 
2807
            stop_revno = None # unknown
 
2808
            if stop_revision is None:
 
2809
                stop_revision = other_last_revision
 
2810
                if _mod_revision.is_null(stop_revision):
 
2811
                    # if there are no commits, we're done.
 
2812
                    return
 
2813
                stop_revno = other_revno
 
2814
 
 
2815
            # what's the current last revision, before we fetch [and change it
 
2816
            # possibly]
 
2817
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2818
            # we fetch here so that we don't process data twice in the common
 
2819
            # case of having something to pull, and so that the check for
 
2820
            # already merged can operate on the just fetched graph, which will
 
2821
            # be cached in memory.
 
2822
            self.target.fetch(self.source, stop_revision)
 
2823
            # Check to see if one is an ancestor of the other
 
2824
            if not overwrite:
 
2825
                if graph is None:
 
2826
                    graph = self.target.repository.get_graph()
 
2827
                if self.target._check_if_descendant_or_diverged(
 
2828
                        stop_revision, last_rev, graph, self.source):
 
2829
                    # stop_revision is a descendant of last_rev, but we aren't
 
2830
                    # overwriting, so we're done.
 
2831
                    return
 
2832
            if stop_revno is None:
 
2833
                if graph is None:
 
2834
                    graph = self.target.repository.get_graph()
 
2835
                this_revno, this_last_revision = \
 
2836
                        self.target.last_revision_info()
 
2837
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2838
                                [(other_last_revision, other_revno),
 
2839
                                 (this_last_revision, this_revno)])
 
2840
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2841
        finally:
 
2842
            self.source.unlock()
 
2843
 
 
2844
    @classmethod
 
2845
    def is_compatible(self, source, target):
 
2846
        # GenericBranch uses the public API, so always compatible
 
2847
        return True
3554
2848
 
3555
2849
 
3556
2850
InterBranch.register_optimiser(GenericInterBranch)