~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Vincent Ladeuil
  • Date: 2009-04-06 14:01:16 UTC
  • mto: (4241.10.1 bzr.1.14)
  • mto: This revision was merged to the branch mainline in revision 4267.
  • Revision ID: v.ladeuil+lp@free.fr-20090406140116-zkbvjtaxfhbql4l4
Fix unicode related OSX failures.

* bzrlib/tests/test_export.py: 
Fix imports.

* bzrlib/tests/blackbox/test_export.py:
(TestExport.test_tar_export_unicode,
TestExport.test_zip_export_unicode): Use a less problematic
unicode char for OSX.

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
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
 
18
 
from cStringIO import StringIO
19
18
import sys
20
19
 
21
20
from bzrlib.lazy_import import lazy_import
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,
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()
104
101
 
105
102
    def _activate_fallback_location(self, url):
106
103
        """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)
 
104
        self.repository.add_fallback_repository(
 
105
            self._get_fallback_repository(url))
111
106
 
112
107
    def break_lock(self):
113
108
        """Break a lock if one is present from another instance.
128
123
            raise errors.UnstackableRepositoryFormat(self.repository._format,
129
124
                self.repository.base)
130
125
 
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
126
    @staticmethod
161
127
    def open(base, _unsupported=False, possible_transports=None):
162
128
        """Open the branch rooted at base.
166
132
        """
167
133
        control = bzrdir.BzrDir.open(base, _unsupported,
168
134
                                     possible_transports=possible_transports)
169
 
        return control.open_branch(unsupported=_unsupported)
 
135
        return control.open_branch(_unsupported)
170
136
 
171
137
    @staticmethod
172
 
    def open_from_transport(transport, name=None, _unsupported=False):
 
138
    def open_from_transport(transport, _unsupported=False):
173
139
        """Open the branch rooted at transport"""
174
140
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
175
 
        return control.open_branch(name=name, unsupported=_unsupported)
 
141
        return control.open_branch(_unsupported)
176
142
 
177
143
    @staticmethod
178
144
    def open_containing(url, possible_transports=None):
199
165
        return self.supports_tags() and self.tags.get_tag_dict()
200
166
 
201
167
    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
168
        return BranchConfig(self)
210
169
 
211
170
    def _get_config(self):
223
182
    def _get_fallback_repository(self, url):
224
183
        """Get the repository we fallback to at url."""
225
184
        url = urlutils.join(self.base, url)
226
 
        a_branch = Branch.open(url,
 
185
        a_bzrdir = bzrdir.BzrDir.open(url,
227
186
            possible_transports=[self.bzrdir.root_transport])
228
 
        return a_branch.repository
 
187
        return a_bzrdir.open_branch().repository
229
188
 
230
189
    def _get_tags_bytes(self):
231
190
        """Get the bytes of a serialised tags dict.
247
206
        if not local and not config.has_explicit_nickname():
248
207
            try:
249
208
                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
209
                if master is not None:
253
210
                    # return the master branch value
254
211
                    return master.nick
255
 
            except errors.RecursiveBind, e:
256
 
                raise e
257
212
            except errors.BzrError, e:
258
213
                # Silently fall back to local implicit nick if the master is
259
214
                # unavailable
296
251
        new_history.reverse()
297
252
        return new_history
298
253
 
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
 
        """
 
254
    def lock_write(self):
306
255
        raise NotImplementedError(self.lock_write)
307
256
 
308
257
    def lock_read(self):
309
 
        """Lock the branch for read operations.
310
 
 
311
 
        :return: A bzrlib.lock.LogicalLockResult.
312
 
        """
313
258
        raise NotImplementedError(self.lock_read)
314
259
 
315
260
    def unlock(self):
440
385
            * 'include' - the stop revision is the last item in the result
441
386
            * 'with-merges' - include the stop revision and all of its
442
387
              merged revisions in the result
443
 
            * 'with-merges-without-common-ancestry' - filter out revisions 
444
 
              that are in both ancestries
445
388
        :param direction: either 'reverse' or 'forward':
446
389
            * reverse means return the start_revision_id first, i.e.
447
390
              start at the most recent revision and go backwards in history
469
412
        # start_revision_id.
470
413
        if self._merge_sorted_revisions_cache is None:
471
414
            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)
 
415
            graph = self.repository.get_graph()
 
416
            parent_map = dict(((key, value) for key, value in
 
417
                     graph.iter_ancestry([last_revision]) if value is not None))
 
418
            revision_graph = repository._strip_NULL_ghosts(parent_map)
 
419
            revs = tsort.merge_sort(revision_graph, last_revision, None,
 
420
                generate_revno=True)
 
421
            # Drop the sequence # before caching
 
422
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
 
423
 
476
424
        filtered = self._filter_merge_sorted_revisions(
477
425
            self._merge_sorted_revisions_cache, start_revision_id,
478
426
            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
427
        if direction == 'reverse':
483
428
            return filtered
484
429
        if direction == 'forward':
491
436
        """Iterate over an inclusive range of sorted revisions."""
492
437
        rev_iter = iter(merge_sorted_revisions)
493
438
        if start_revision_id is not None:
494
 
            for node in rev_iter:
495
 
                rev_id = node.key[-1]
 
439
            for rev_id, depth, revno, end_of_merge in rev_iter:
496
440
                if rev_id != start_revision_id:
497
441
                    continue
498
442
                else:
499
443
                    # The decision to include the start or not
500
444
                    # 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)
 
445
                    rev_iter = chain(
 
446
                        iter([(rev_id, depth, revno, end_of_merge)]),
 
447
                        rev_iter)
503
448
                    break
504
449
        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)
 
450
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
451
                yield rev_id, depth, revno, end_of_merge
510
452
        elif stop_rule == 'exclude':
511
 
            for node in rev_iter:
512
 
                rev_id = node.key[-1]
 
453
            for rev_id, depth, revno, end_of_merge in rev_iter:
513
454
                if rev_id == stop_revision_id:
514
455
                    return
515
 
                yield (rev_id, node.merge_depth, node.revno,
516
 
                       node.end_of_merge)
 
456
                yield rev_id, depth, revno, end_of_merge
517
457
        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)
 
458
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
459
                yield rev_id, depth, revno, end_of_merge
522
460
                if rev_id == stop_revision_id:
523
461
                    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
462
        elif stop_rule == 'with-merges':
537
463
            stop_rev = self.repository.get_revision(stop_revision_id)
538
464
            if stop_rev.parent_ids:
539
465
                left_parent = stop_rev.parent_ids[0]
540
466
            else:
541
467
                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]
 
468
            for rev_id, depth, revno, end_of_merge in rev_iter:
548
469
                if rev_id == left_parent:
549
 
                    # reached the left parent after the stop_revision
550
470
                    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)
 
471
                yield rev_id, depth, revno, end_of_merge
561
472
        else:
562
473
            raise ValueError('invalid stop_rule %r' % stop_rule)
563
474
 
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
475
    def leave_lock_in_place(self):
610
476
        """Tell this branch object not to release the physical lock when this
611
477
        object is unlocked.
628
494
        :param other: The branch to bind to
629
495
        :type other: Branch
630
496
        """
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)
 
497
        raise errors.UpgradeRequired(self.base)
650
498
 
651
499
    @needs_write_lock
652
500
    def fetch(self, from_branch, last_revision=None, pb=None):
686
534
    def get_old_bound_location(self):
687
535
        """Return the URL of the branch we used to be bound to
688
536
        """
689
 
        raise errors.UpgradeRequired(self.user_url)
 
537
        raise errors.UpgradeRequired(self.base)
690
538
 
691
539
    def get_commit_builder(self, parents, config=None, timestamp=None,
692
540
                           timezone=None, committer=None, revprops=None,
742
590
    def set_revision_history(self, rev_history):
743
591
        raise NotImplementedError(self.set_revision_history)
744
592
 
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
593
    def set_stacked_on_url(self, url):
765
594
        """Set the URL this branch is stacked against.
766
595
 
770
599
            stacking.
771
600
        """
772
601
        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.
 
602
            raise errors.UnstackableBranchFormat(self._format, self.base)
777
603
        self._check_stackable_repo()
778
604
        if not url:
779
605
            try:
781
607
            except (errors.NotStacked, errors.UnstackableBranchFormat,
782
608
                errors.UnstackableRepositoryFormat):
783
609
                return
784
 
            self._unstack()
 
610
            url = ''
 
611
            # repositories don't offer an interface to remove fallback
 
612
            # repositories today; take the conceptually simpler option and just
 
613
            # reopen it.
 
614
            self.repository = self.bzrdir.find_repository()
 
615
            # for every revision reference the branch has, ensure it is pulled
 
616
            # in.
 
617
            source_repository = self._get_fallback_repository(old_url)
 
618
            for revision_id in chain([self.last_revision()],
 
619
                self.tags.get_reverse_tag_dict()):
 
620
                self.repository.fetch(source_repository, revision_id,
 
621
                    find_ghosts=True)
785
622
        else:
786
623
            self._activate_fallback_location(url)
787
624
        # write this out after the repository is stacked to avoid setting a
788
625
        # stacked config that doesn't work.
789
626
        self._set_config_location('stacked_on_location', url)
790
627
 
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()
873
628
 
874
629
    def _set_tags_bytes(self, bytes):
875
630
        """Mirror method for _get_tags_bytes.
911
666
        self._revision_id_to_revno_cache = None
912
667
        self._last_revision_info_cache = None
913
668
        self._merge_sorted_revisions_cache = None
914
 
        self._partial_revision_history_cache = []
915
 
        self._partial_revision_id_to_revno_cache = {}
916
669
 
917
670
    def _gen_revision_history(self):
918
671
        """Return sequence of revision hashes on to this branch.
955
708
 
956
709
    def unbind(self):
957
710
        """Older format branches cannot bind or unbind."""
958
 
        raise errors.UpgradeRequired(self.user_url)
 
711
        raise errors.UpgradeRequired(self.base)
 
712
 
 
713
    def set_append_revisions_only(self, enabled):
 
714
        """Older format branches are never restricted to append-only"""
 
715
        raise errors.UpgradeRequired(self.base)
959
716
 
960
717
    def last_revision(self):
961
718
        """Return last revision id, or NULL_REVISION."""
1002
759
                raise errors.NoSuchRevision(self, stop_revision)
1003
760
        return other_history[self_len:stop_revision]
1004
761
 
 
762
    @needs_write_lock
1005
763
    def update_revisions(self, other, stop_revision=None, overwrite=False,
1006
764
                         graph=None):
1007
765
        """Pull in new perfect-fit revisions.
1041
799
        except ValueError:
1042
800
            raise errors.NoSuchRevision(self, revision_id)
1043
801
 
1044
 
    @needs_read_lock
1045
802
    def get_rev_id(self, revno, history=None):
1046
803
        """Find the revision id of the specified revno."""
1047
804
        if revno == 0:
1048
805
            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:
 
806
        if history is None:
 
807
            history = self.revision_history()
 
808
        if revno <= 0 or revno > len(history):
1053
809
            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]
 
810
        return history[revno - 1]
1058
811
 
1059
812
    def pull(self, source, overwrite=False, stop_revision=None,
1060
 
             possible_transports=None, *args, **kwargs):
 
813
             possible_transports=None, _override_hook_target=None):
1061
814
        """Mirror source into this branch.
1062
815
 
1063
816
        This branch is considered to be 'local', having low latency.
1064
817
 
1065
818
        :returns: PullResult instance
1066
819
        """
1067
 
        return InterBranch.get(source, self).pull(overwrite=overwrite,
1068
 
            stop_revision=stop_revision,
1069
 
            possible_transports=possible_transports, *args, **kwargs)
 
820
        raise NotImplementedError(self.pull)
1070
821
 
1071
 
    def push(self, target, overwrite=False, stop_revision=None, *args,
1072
 
        **kwargs):
 
822
    def push(self, target, overwrite=False, stop_revision=None):
1073
823
        """Mirror this branch into target.
1074
824
 
1075
825
        This branch is considered to be 'local', having low latency.
1076
826
        """
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)
 
827
        raise NotImplementedError(self.push)
1100
828
 
1101
829
    def basis_tree(self):
1102
830
        """Return `Tree` object for last revision."""
1119
847
        try:
1120
848
            return urlutils.join(self.base[:-1], parent)
1121
849
        except errors.InvalidURLJoin, e:
1122
 
            raise errors.InaccessibleParent(parent, self.user_url)
 
850
            raise errors.InaccessibleParent(parent, self.base)
1123
851
 
1124
852
    def _get_parent_location(self):
1125
853
        raise NotImplementedError(self._get_parent_location)
1142
870
            location = None
1143
871
        return location
1144
872
 
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
873
    def get_submit_branch(self):
1150
874
        """Return the submit location of the branch.
1151
875
 
1168
892
    def get_public_branch(self):
1169
893
        """Return the public location of the branch.
1170
894
 
1171
 
        This is used by merge directives.
 
895
        This is is used by merge directives.
1172
896
        """
1173
897
        return self._get_config_location('public_branch')
1174
898
 
1210
934
        params = ChangeBranchTipParams(
1211
935
            self, old_revno, new_revno, old_revid, new_revid)
1212
936
        for hook in hooks:
1213
 
            hook(params)
 
937
            try:
 
938
                hook(params)
 
939
            except errors.TipChangeRejected:
 
940
                raise
 
941
            except Exception:
 
942
                exc_info = sys.exc_info()
 
943
                hook_name = Branch.hooks.get_hook_name(hook)
 
944
                raise errors.HookFailed(
 
945
                    'pre_change_branch_tip', hook_name, exc_info)
 
946
 
 
947
    def set_parent(self, url):
 
948
        raise NotImplementedError(self.set_parent)
1214
949
 
1215
950
    @needs_write_lock
1216
951
    def update(self):
1247
982
                     be truncated to end with revision_id.
1248
983
        """
1249
984
        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
 
985
        if repository_policy is not None:
 
986
            repository_policy.configure_branch(result)
 
987
        self.copy_content_into(result, revision_id=revision_id)
 
988
        return  result
1258
989
 
1259
990
    @needs_read_lock
1260
991
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
1265
996
        revision_id: if not None, the revision history in the new branch will
1266
997
                     be truncated to end with revision_id.
1267
998
        """
1268
 
        if (repository_policy is not None and
1269
 
            repository_policy.requires_stacking()):
1270
 
            to_bzrdir._format.require_stacking(_skip_repo=True)
1271
999
        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()
 
1000
        if repository_policy is not None:
 
1001
            repository_policy.configure_branch(result)
 
1002
        self.copy_content_into(result, revision_id=revision_id)
 
1003
        result.set_parent(self.bzrdir.root_transport.base)
1280
1004
        return result
1281
1005
 
1282
1006
    def _synchronize_history(self, destination, revision_id):
1294
1018
        source_revno, source_revision_id = self.last_revision_info()
1295
1019
        if revision_id is None:
1296
1020
            revno, revision_id = source_revno, source_revision_id
 
1021
        elif source_revision_id == revision_id:
 
1022
            # we know the revno without needing to walk all of history
 
1023
            revno = source_revno
1297
1024
        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
 
1025
            # To figure out the revno for a random revision, we need to build
 
1026
            # the revision history, and count its length.
 
1027
            # We don't care about the order, just how long it is.
 
1028
            # Alternatively, we could start at the current location, and count
 
1029
            # backwards. But there is no guarantee that we will find it since
 
1030
            # it may be a merged revision.
 
1031
            revno = len(list(self.repository.iter_reverse_revision_history(
 
1032
                                                                revision_id)))
1305
1033
        destination.set_last_revision_info(revno, revision_id)
1306
1034
 
 
1035
    @needs_read_lock
1307
1036
    def copy_content_into(self, destination, revision_id=None):
1308
1037
        """Copy the content of self into destination.
1309
1038
 
1310
1039
        revision_id: if not None, the revision history in the new branch will
1311
1040
                     be truncated to end with revision_id.
1312
1041
        """
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)
 
1042
        self._synchronize_history(destination, revision_id)
 
1043
        try:
 
1044
            parent = self.get_parent()
 
1045
        except errors.InaccessibleParent, e:
 
1046
            mutter('parent was not accessible to copy: %s', e)
 
1047
        else:
 
1048
            if parent:
 
1049
                destination.set_parent(parent)
 
1050
        if self._push_should_merge_tags():
 
1051
            self.tags.merge_to(destination.tags)
1332
1052
 
1333
1053
    @needs_read_lock
1334
 
    def check(self, refs):
 
1054
    def check(self):
1335
1055
        """Check consistency of the branch.
1336
1056
 
1337
1057
        In particular this checks that revisions given in the revision-history
1340
1060
 
1341
1061
        Callers will typically also want to check the repository.
1342
1062
 
1343
 
        :param refs: Calculated refs for this branch as specified by
1344
 
            branch._get_check_refs()
1345
1063
        :return: A BranchCheckResult.
1346
1064
        """
1347
 
        result = BranchCheckResult(self)
 
1065
        mainline_parent_id = None
1348
1066
        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
 
1067
        real_rev_history = list(self.repository.iter_reverse_revision_history(
 
1068
                                last_revision_id))
 
1069
        real_rev_history.reverse()
 
1070
        if len(real_rev_history) != last_revno:
 
1071
            raise errors.BzrCheckError('revno does not match len(mainline)'
 
1072
                ' %s != %s' % (last_revno, len(real_rev_history)))
 
1073
        # TODO: We should probably also check that real_rev_history actually
 
1074
        #       matches self.revision_history()
 
1075
        for revision_id in real_rev_history:
 
1076
            try:
 
1077
                revision = self.repository.get_revision(revision_id)
 
1078
            except errors.NoSuchRevision, e:
 
1079
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
 
1080
                            % revision_id)
 
1081
            # In general the first entry on the revision history has no parents.
 
1082
            # But it's not illegal for it to have parents listed; this can happen
 
1083
            # in imports from Arch when the parents weren't reachable.
 
1084
            if mainline_parent_id is not None:
 
1085
                if mainline_parent_id not in revision.parent_ids:
 
1086
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
 
1087
                                        "parents of {%s}"
 
1088
                                        % (mainline_parent_id, revision_id))
 
1089
            mainline_parent_id = revision_id
 
1090
        return BranchCheckResult(self)
1360
1091
 
1361
1092
    def _get_checkout_format(self):
1362
1093
        """Return the most suitable metadir for a checkout of this branch.
1372
1103
        return format
1373
1104
 
1374
1105
    def create_clone_on_transport(self, to_transport, revision_id=None,
1375
 
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1106
        stacked_on=None):
1376
1107
        """Create a clone of this branch and its bzrdir.
1377
1108
 
1378
1109
        :param to_transport: The transport to clone onto.
1379
1110
        :param revision_id: The revision id to use as tip in the new branch.
1380
1111
            If None the tip is obtained from this branch.
1381
1112
        :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
1113
        """
1386
1114
        # XXX: Fix the bzrdir API to allow getting the branch back from the
1387
1115
        # 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
1116
        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)
 
1117
            revision_id=revision_id, stacked_on=stacked_on)
1395
1118
        return dir_to.open_branch()
1396
1119
 
1397
1120
    def create_checkout(self, to_location, revision_id=None,
1416
1139
        if lightweight:
1417
1140
            format = self._get_checkout_format()
1418
1141
            checkout = format.initialize_on_transport(t)
1419
 
            from_branch = BranchReferenceFormat().initialize(checkout, 
1420
 
                target_branch=self)
 
1142
            from_branch = BranchReferenceFormat().initialize(checkout, self)
1421
1143
        else:
1422
1144
            format = self._get_checkout_format()
1423
1145
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1452
1174
        reconciler.reconcile()
1453
1175
        return reconciler
1454
1176
 
1455
 
    def reference_parent(self, file_id, path, possible_transports=None):
 
1177
    def reference_parent(self, file_id, path):
1456
1178
        """Return the parent branch for a tree-reference file_id
1457
1179
        :param file_id: The file_id of the tree reference
1458
1180
        :param path: The path of the file_id in the tree
1459
1181
        :return: A branch associated with the file_id
1460
1182
        """
1461
1183
        # FIXME should provide multiple branches, based on config
1462
 
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
1463
 
                           possible_transports=possible_transports)
 
1184
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
1464
1185
 
1465
1186
    def supports_tags(self):
1466
1187
        return self._format.supports_tags()
1467
1188
 
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
1189
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1481
1190
                                         other_branch):
1482
1191
        """Ensure that revision_b is a descendant of revision_a.
1522
1231
     * an open routine.
1523
1232
 
1524
1233
    Formats are placed in an dict by their format string for reference
1525
 
    during branch opening. It's not required that these be instances, they
 
1234
    during branch opening. Its not required that these be instances, they
1526
1235
    can be classes themselves with class methods - it simply depends on
1527
1236
    whether state is needed for a given format or not.
1528
1237
 
1537
1246
    _formats = {}
1538
1247
    """The known formats."""
1539
1248
 
1540
 
    can_set_append_revisions_only = True
1541
 
 
1542
1249
    def __eq__(self, other):
1543
1250
        return self.__class__ is other.__class__
1544
1251
 
1546
1253
        return not (self == other)
1547
1254
 
1548
1255
    @classmethod
1549
 
    def find_format(klass, a_bzrdir, name=None):
 
1256
    def find_format(klass, a_bzrdir):
1550
1257
        """Return the format for the branch object in a_bzrdir."""
1551
1258
        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
 
1259
            transport = a_bzrdir.get_branch_transport(None)
 
1260
            format_string = transport.get("format").read()
 
1261
            return klass._formats[format_string]
1558
1262
        except errors.NoSuchFile:
1559
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1263
            raise errors.NotBranchError(path=transport.base)
1560
1264
        except KeyError:
1561
1265
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1562
1266
 
1565
1269
        """Return the current default format."""
1566
1270
        return klass._default_format
1567
1271
 
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):
 
1272
    def get_reference(self, a_bzrdir):
1583
1273
        """Get the target reference of the branch in a_bzrdir.
1584
1274
 
1585
1275
        format probing must have been completed before calling
1587
1277
        in a_bzrdir is correct.
1588
1278
 
1589
1279
        :param a_bzrdir: The bzrdir to get the branch data from.
1590
 
        :param name: Name of the colocated branch to fetch
1591
1280
        :return: None if the branch is not a reference branch.
1592
1281
        """
1593
1282
        return None
1594
1283
 
1595
1284
    @classmethod
1596
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1285
    def set_reference(self, a_bzrdir, to_branch):
1597
1286
        """Set the target reference of the branch in a_bzrdir.
1598
1287
 
1599
1288
        format probing must have been completed before calling
1601
1290
        in a_bzrdir is correct.
1602
1291
 
1603
1292
        :param a_bzrdir: The bzrdir to set the branch reference for.
1604
 
        :param name: Name of colocated branch to set, None for default
1605
1293
        :param to_branch: branch that the checkout is to reference
1606
1294
        """
1607
1295
        raise NotImplementedError(self.set_reference)
1614
1302
        """Return the short format description for this format."""
1615
1303
        raise NotImplementedError(self.get_format_description)
1616
1304
 
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):
 
1305
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
 
1306
                           set_format=True):
1627
1307
        """Initialize a branch in a bzrdir, with specified files
1628
1308
 
1629
1309
        :param a_bzrdir: The bzrdir to initialize the branch in
1630
1310
        :param utf8_files: The files to create as a list of
1631
1311
            (filename, content) tuples
1632
 
        :param name: Name of colocated branch to create, if any
1633
1312
        :param set_format: If True, set the format with
1634
1313
            self.get_format_string.  (BzrBranch4 has its format set
1635
1314
            elsewhere)
1636
1315
        :return: a branch in this format
1637
1316
        """
1638
 
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1639
 
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1317
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
 
1318
        branch_transport = a_bzrdir.get_branch_transport(self)
1640
1319
        lock_map = {
1641
1320
            'metadir': ('lock', lockdir.LockDir),
1642
1321
            'branch4': ('branch-lock', lockable_files.TransportLock),
1645
1324
        control_files = lockable_files.LockableFiles(branch_transport,
1646
1325
            lock_name, lock_class)
1647
1326
        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
 
1327
        control_files.lock_write()
1656
1328
        if set_format:
1657
1329
            utf8_files += [('format', self.get_format_string())]
1658
1330
        try:
1661
1333
                    filename, content,
1662
1334
                    mode=a_bzrdir._get_file_mode())
1663
1335
        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
 
1336
            control_files.unlock()
 
1337
        return self.open(a_bzrdir, _found=True)
1669
1338
 
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
 
        """
 
1339
    def initialize(self, a_bzrdir):
 
1340
        """Create a branch of this format in a_bzrdir."""
1675
1341
        raise NotImplementedError(self.initialize)
1676
1342
 
1677
1343
    def is_supported(self):
1707
1373
        """
1708
1374
        raise NotImplementedError(self.network_name)
1709
1375
 
1710
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1376
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
1711
1377
        """Return the branch object for a_bzrdir
1712
1378
 
1713
1379
        :param a_bzrdir: A BzrDir that contains a branch.
1714
 
        :param name: Name of colocated branch to open
1715
1380
        :param _found: a private parameter, do not use it. It is used to
1716
1381
            indicate if format probing has already be done.
1717
1382
        :param ignore_fallbacks: when set, no fallback branches will be opened
1721
1386
 
1722
1387
    @classmethod
1723
1388
    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
 
        """
 
1389
        """Register a metadir format."""
1729
1390
        klass._formats[format.get_format_string()] = format
1730
1391
        # 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__)
 
1392
        # registered as class factories.
 
1393
        network_format_registry.register(format.get_format_string(), format.__class__)
1737
1394
 
1738
1395
    @classmethod
1739
1396
    def set_default_format(klass, format):
1740
1397
        klass._default_format = format
1741
1398
 
1742
 
    def supports_set_append_revisions_only(self):
1743
 
        """True if this format supports set_append_revisions_only."""
1744
 
        return False
1745
 
 
1746
1399
    def supports_stacking(self):
1747
1400
        """True if this format records a stacked-on branch."""
1748
1401
        return False
1759
1412
        return False  # by default
1760
1413
 
1761
1414
 
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
1415
class BranchHooks(Hooks):
1791
1416
    """A dictionary mapping hook name to a list of callables for branch hooks.
1792
1417
 
1819
1444
            "with a bzrlib.branch.PullResult object and only runs in the "
1820
1445
            "bzr client.", (0, 15), None))
1821
1446
        self.create_hook(HookPoint('pre_commit',
1822
 
            "Called after a commit is calculated but before it is "
 
1447
            "Called after a commit is calculated but before it is is "
1823
1448
            "completed. pre_commit is called with (local, master, old_revno, "
1824
1449
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
1825
1450
            "). old_revid is NULL_REVISION for the first commit to a branch, "
1838
1463
            "post_uncommit is called with (local, master, old_revno, "
1839
1464
            "old_revid, new_revno, new_revid) where local is the local branch "
1840
1465
            "or None, master is the target branch, and an empty branch "
1841
 
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1466
            "recieves new_revno of 0, new_revid of None.", (0, 15), None))
1842
1467
        self.create_hook(HookPoint('pre_change_branch_tip',
1843
1468
            "Called in bzr client and server before a change to the tip of a "
1844
1469
            "branch is made. pre_change_branch_tip is called with a "
1861
1486
            "multiple hooks installed for transform_fallback_location, "
1862
1487
            "all are called with the url returned from the previous hook."
1863
1488
            "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
1489
 
1882
1490
 
1883
1491
# install the default hooks into the Branch class.
1922
1530
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1923
1531
 
1924
1532
 
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
1533
class BzrBranchFormat4(BranchFormat):
1999
1534
    """Bzr branch format 4.
2000
1535
 
2007
1542
        """See BranchFormat.get_format_description()."""
2008
1543
        return "Branch format 4"
2009
1544
 
2010
 
    def initialize(self, a_bzrdir, name=None):
 
1545
    def initialize(self, a_bzrdir):
2011
1546
        """Create a branch of this format in a_bzrdir."""
2012
1547
        utf8_files = [('revision-history', ''),
2013
1548
                      ('branch-name', ''),
2014
1549
                      ]
2015
 
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
 
1550
        return self._initialize_helper(a_bzrdir, utf8_files,
2016
1551
                                       lock_type='branch4', set_format=False)
2017
1552
 
2018
1553
    def __init__(self):
2023
1558
        """The network name for this format is the control dirs disk label."""
2024
1559
        return self._matchingbzrdir.get_format_string()
2025
1560
 
2026
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1561
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2027
1562
        """See BranchFormat.open()."""
2028
1563
        if not _found:
2029
1564
            # we are being called directly and must probe.
2031
1566
        return BzrBranch(_format=self,
2032
1567
                         _control_files=a_bzrdir._control_files,
2033
1568
                         a_bzrdir=a_bzrdir,
2034
 
                         name=name,
2035
1569
                         _repository=a_bzrdir.open_repository())
2036
1570
 
2037
1571
    def __str__(self):
2052
1586
        """
2053
1587
        return self.get_format_string()
2054
1588
 
2055
 
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1589
    def open(self, a_bzrdir, _found=False, ignore_fallbacks=False):
2056
1590
        """See BranchFormat.open()."""
2057
1591
        if not _found:
2058
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1592
            format = BranchFormat.find_format(a_bzrdir)
2059
1593
            if format.__class__ != self.__class__:
2060
1594
                raise AssertionError("wrong format %r found for %r" %
2061
1595
                    (format, self))
2062
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2063
1596
        try:
 
1597
            transport = a_bzrdir.get_branch_transport(None)
2064
1598
            control_files = lockable_files.LockableFiles(transport, 'lock',
2065
1599
                                                         lockdir.LockDir)
2066
1600
            return self._branch_class()(_format=self,
2067
1601
                              _control_files=control_files,
2068
 
                              name=name,
2069
1602
                              a_bzrdir=a_bzrdir,
2070
1603
                              _repository=a_bzrdir.find_repository(),
2071
1604
                              ignore_fallbacks=ignore_fallbacks)
2072
1605
        except errors.NoSuchFile:
2073
 
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
1606
            raise errors.NotBranchError(path=transport.base)
2074
1607
 
2075
1608
    def __init__(self):
2076
1609
        super(BranchFormatMetadir, self).__init__()
2105
1638
        """See BranchFormat.get_format_description()."""
2106
1639
        return "Branch format 5"
2107
1640
 
2108
 
    def initialize(self, a_bzrdir, name=None):
 
1641
    def initialize(self, a_bzrdir):
2109
1642
        """Create a branch of this format in a_bzrdir."""
2110
1643
        utf8_files = [('revision-history', ''),
2111
1644
                      ('branch-name', ''),
2112
1645
                      ]
2113
 
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
1646
        return self._initialize_helper(a_bzrdir, utf8_files)
2114
1647
 
2115
1648
    def supports_tags(self):
2116
1649
        return False
2138
1671
        """See BranchFormat.get_format_description()."""
2139
1672
        return "Branch format 6"
2140
1673
 
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):
 
1674
    def initialize(self, a_bzrdir):
 
1675
        """Create a branch of this format in a_bzrdir."""
 
1676
        utf8_files = [('last-revision', '0 null:\n'),
 
1677
                      ('branch.conf', ''),
 
1678
                      ('tags', ''),
 
1679
                      ]
 
1680
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1681
 
 
1682
    def make_tags(self, branch):
 
1683
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1684
        return BasicTags(branch)
 
1685
 
 
1686
 
 
1687
 
 
1688
class BzrBranchFormat7(BranchFormatMetadir):
2199
1689
    """Branch format with last-revision, tags, and a stacked location pointer.
2200
1690
 
2201
1691
    The stacked location pointer is passed down to the repository and requires
2204
1694
    This format was introduced in bzr 1.6.
2205
1695
    """
2206
1696
 
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
1697
    def _branch_class(self):
2216
1698
        return BzrBranch7
2217
1699
 
2223
1705
        """See BranchFormat.get_format_description()."""
2224
1706
        return "Branch format 7"
2225
1707
 
2226
 
    def supports_set_append_revisions_only(self):
 
1708
    def initialize(self, a_bzrdir):
 
1709
        """Create a branch of this format in a_bzrdir."""
 
1710
        utf8_files = [('last-revision', '0 null:\n'),
 
1711
                      ('branch.conf', ''),
 
1712
                      ('tags', ''),
 
1713
                      ]
 
1714
        return self._initialize_helper(a_bzrdir, utf8_files)
 
1715
 
 
1716
    def __init__(self):
 
1717
        super(BzrBranchFormat7, self).__init__()
 
1718
        self._matchingbzrdir.repository_format = \
 
1719
            RepositoryFormatKnitPack5RichRoot()
 
1720
 
 
1721
    def make_tags(self, branch):
 
1722
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
1723
        return BasicTags(branch)
 
1724
 
 
1725
    def supports_stacking(self):
2227
1726
        return True
2228
1727
 
2229
 
    supports_reference_locations = False
2230
 
 
2231
1728
 
2232
1729
class BranchReferenceFormat(BranchFormat):
2233
1730
    """Bzr branch reference format.
2248
1745
        """See BranchFormat.get_format_description()."""
2249
1746
        return "Checkout reference format 1"
2250
1747
 
2251
 
    def get_reference(self, a_bzrdir, name=None):
 
1748
    def get_reference(self, a_bzrdir):
2252
1749
        """See BranchFormat.get_reference()."""
2253
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
2254
 
        return transport.get_bytes('location')
 
1750
        transport = a_bzrdir.get_branch_transport(None)
 
1751
        return transport.get('location').read()
2255
1752
 
2256
 
    def set_reference(self, a_bzrdir, name, to_branch):
 
1753
    def set_reference(self, a_bzrdir, to_branch):
2257
1754
        """See BranchFormat.set_reference()."""
2258
 
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
1755
        transport = a_bzrdir.get_branch_transport(None)
2259
1756
        location = transport.put_bytes('location', to_branch.base)
2260
1757
 
2261
 
    def initialize(self, a_bzrdir, name=None, target_branch=None):
 
1758
    def initialize(self, a_bzrdir, target_branch=None):
2262
1759
        """Create a branch of this format in a_bzrdir."""
2263
1760
        if target_branch is None:
2264
1761
            # this format does not implement branch itself, thus the implicit
2265
1762
            # creation contract must see it as uninitializable
2266
1763
            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)
 
1764
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
 
1765
        branch_transport = a_bzrdir.get_branch_transport(self)
2269
1766
        branch_transport.put_bytes('location',
2270
 
            target_branch.bzrdir.user_url)
 
1767
            target_branch.bzrdir.root_transport.base)
2271
1768
        branch_transport.put_bytes('format', self.get_format_string())
2272
 
        branch = self.open(
2273
 
            a_bzrdir, name, _found=True,
 
1769
        return self.open(
 
1770
            a_bzrdir, _found=True,
2274
1771
            possible_transports=[target_branch.bzrdir.root_transport])
2275
 
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2276
 
        return branch
2277
1772
 
2278
1773
    def __init__(self):
2279
1774
        super(BranchReferenceFormat, self).__init__()
2285
1780
        def clone(to_bzrdir, revision_id=None,
2286
1781
            repository_policy=None):
2287
1782
            """See Branch.clone()."""
2288
 
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
1783
            return format.initialize(to_bzrdir, a_branch)
2289
1784
            # cannot obey revision_id limits when cloning a reference ...
2290
1785
            # FIXME RBC 20060210 either nuke revision_id for clone, or
2291
1786
            # emit some sort of warning/error to the caller ?!
2292
1787
        return clone
2293
1788
 
2294
 
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
1789
    def open(self, a_bzrdir, _found=False, location=None,
2295
1790
             possible_transports=None, ignore_fallbacks=False):
2296
1791
        """Return the branch that the branch reference in a_bzrdir points at.
2297
1792
 
2298
1793
        :param a_bzrdir: A BzrDir that contains a branch.
2299
 
        :param name: Name of colocated branch to open, if any
2300
1794
        :param _found: a private parameter, do not use it. It is used to
2301
1795
            indicate if format probing has already be done.
2302
1796
        :param ignore_fallbacks: when set, no fallback branches will be opened
2307
1801
        :param possible_transports: An optional reusable transports list.
2308
1802
        """
2309
1803
        if not _found:
2310
 
            format = BranchFormat.find_format(a_bzrdir, name=name)
 
1804
            format = BranchFormat.find_format(a_bzrdir)
2311
1805
            if format.__class__ != self.__class__:
2312
1806
                raise AssertionError("wrong format %r found for %r" %
2313
1807
                    (format, self))
2314
1808
        if location is None:
2315
 
            location = self.get_reference(a_bzrdir, name)
 
1809
            location = self.get_reference(a_bzrdir)
2316
1810
        real_bzrdir = bzrdir.BzrDir.open(
2317
1811
            location, possible_transports=possible_transports)
2318
 
        result = real_bzrdir.open_branch(name=name, 
2319
 
            ignore_fallbacks=ignore_fallbacks)
 
1812
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks)
2320
1813
        # this changes the behaviour of result.clone to create a new reference
2321
1814
        # rather than a copy of the content of the branch.
2322
1815
        # I did not use a proxy object because that needs much more extensive
2343
1836
__format5 = BzrBranchFormat5()
2344
1837
__format6 = BzrBranchFormat6()
2345
1838
__format7 = BzrBranchFormat7()
2346
 
__format8 = BzrBranchFormat8()
2347
1839
BranchFormat.register_format(__format5)
2348
1840
BranchFormat.register_format(BranchReferenceFormat())
2349
1841
BranchFormat.register_format(__format6)
2350
1842
BranchFormat.register_format(__format7)
2351
 
BranchFormat.register_format(__format8)
2352
 
BranchFormat.set_default_format(__format7)
 
1843
BranchFormat.set_default_format(__format6)
2353
1844
_legacy_formats = [BzrBranchFormat4(),
2354
1845
    ]
2355
1846
network_format_registry.register(
2356
1847
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2357
1848
 
2358
1849
 
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):
 
1850
class BzrBranch(Branch):
2377
1851
    """A branch stored in the actual filesystem.
2378
1852
 
2379
1853
    Note that it's "local" in the context of the filesystem; it doesn't
2385
1859
    :ivar repository: Repository for this branch.
2386
1860
    :ivar base: The url of the base directory for this branch; the one
2387
1861
        containing the .bzr directory.
2388
 
    :ivar name: Optional colocated branch name as it exists in the control
2389
 
        directory.
2390
1862
    """
2391
1863
 
2392
1864
    def __init__(self, _format=None,
2393
 
                 _control_files=None, a_bzrdir=None, name=None,
2394
 
                 _repository=None, ignore_fallbacks=False):
 
1865
                 _control_files=None, a_bzrdir=None, _repository=None,
 
1866
                 ignore_fallbacks=False):
2395
1867
        """Create new branch object at a particular location."""
2396
1868
        if a_bzrdir is None:
2397
1869
            raise ValueError('a_bzrdir must be supplied')
2398
1870
        else:
2399
1871
            self.bzrdir = a_bzrdir
2400
1872
        self._base = self.bzrdir.transport.clone('..').base
2401
 
        self.name = name
2402
1873
        # XXX: We should be able to just do
2403
1874
        #   self.base = self.bzrdir.root_transport.base
2404
1875
        # but this does not quite work yet -- mbp 20080522
2411
1882
        Branch.__init__(self)
2412
1883
 
2413
1884
    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)
 
1885
        return '%s(%r)' % (self.__class__.__name__, self.base)
2419
1886
 
2420
1887
    __repr__ = __str__
2421
1888
 
2432
1899
        return self.control_files.is_locked()
2433
1900
 
2434
1901
    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
 
1902
        repo_token = self.repository.lock_write()
2451
1903
        try:
2452
 
            return BranchWriteLockResult(self.unlock,
2453
 
                self.control_files.lock_write(token=token))
 
1904
            token = self.control_files.lock_write(token=token)
2454
1905
        except:
2455
 
            if took_lock:
2456
 
                self.repository.unlock()
 
1906
            self.repository.unlock()
2457
1907
            raise
 
1908
        return token
2458
1909
 
2459
1910
    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
 
1911
        self.repository.lock_read()
2474
1912
        try:
2475
1913
            self.control_files.lock_read()
2476
 
            return LogicalLockResult(self.unlock)
2477
1914
        except:
2478
 
            if took_lock:
2479
 
                self.repository.unlock()
 
1915
            self.repository.unlock()
2480
1916
            raise
2481
1917
 
2482
 
    @only_raises(errors.LockNotHeld, errors.LockBroken)
2483
1918
    def unlock(self):
 
1919
        # TODO: test for failed two phase locks. This is known broken.
2484
1920
        try:
2485
1921
            self.control_files.unlock()
2486
1922
        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()
 
1923
            self.repository.unlock()
 
1924
        if not self.control_files.is_locked():
 
1925
            # we just released the lock
 
1926
            self._clear_cached_state()
2495
1927
 
2496
1928
    def peek_lock_mode(self):
2497
1929
        if self.control_files._lock_count == 0:
2616
2048
        """See Branch.basis_tree."""
2617
2049
        return self.repository.revision_tree(self.last_revision())
2618
2050
 
 
2051
    @needs_write_lock
 
2052
    def pull(self, source, overwrite=False, stop_revision=None,
 
2053
             _hook_master=None, run_hooks=True, possible_transports=None,
 
2054
             _override_hook_target=None):
 
2055
        """See Branch.pull.
 
2056
 
 
2057
        :param _hook_master: Private parameter - set the branch to
 
2058
            be supplied as the master to pull hooks.
 
2059
        :param run_hooks: Private parameter - if false, this branch
 
2060
            is being called because it's the master of the primary branch,
 
2061
            so it should not run its hooks.
 
2062
        :param _override_hook_target: Private parameter - set the branch to be
 
2063
            supplied as the target_branch to pull hooks.
 
2064
        """
 
2065
        result = PullResult()
 
2066
        result.source_branch = source
 
2067
        if _override_hook_target is None:
 
2068
            result.target_branch = self
 
2069
        else:
 
2070
            result.target_branch = _override_hook_target
 
2071
        source.lock_read()
 
2072
        try:
 
2073
            # We assume that during 'pull' the local repository is closer than
 
2074
            # the remote one.
 
2075
            graph = self.repository.get_graph(source.repository)
 
2076
            result.old_revno, result.old_revid = self.last_revision_info()
 
2077
            self.update_revisions(source, stop_revision, overwrite=overwrite,
 
2078
                                  graph=graph)
 
2079
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
 
2080
            result.new_revno, result.new_revid = self.last_revision_info()
 
2081
            if _hook_master:
 
2082
                result.master_branch = _hook_master
 
2083
                result.local_branch = result.target_branch
 
2084
            else:
 
2085
                result.master_branch = result.target_branch
 
2086
                result.local_branch = None
 
2087
            if run_hooks:
 
2088
                for hook in Branch.hooks['post_pull']:
 
2089
                    hook(result)
 
2090
        finally:
 
2091
            source.unlock()
 
2092
        return result
 
2093
 
2619
2094
    def _get_parent_location(self):
2620
2095
        _locs = ['parent', 'pull', 'x-pull']
2621
2096
        for l in _locs:
2625
2100
                pass
2626
2101
        return None
2627
2102
 
 
2103
    @needs_read_lock
 
2104
    def push(self, target, overwrite=False, stop_revision=None,
 
2105
             _override_hook_source_branch=None):
 
2106
        """See Branch.push.
 
2107
 
 
2108
        This is the basic concrete implementation of push()
 
2109
 
 
2110
        :param _override_hook_source_branch: If specified, run
 
2111
        the hooks passing this Branch as the source, rather than self.
 
2112
        This is for use of RemoteBranch, where push is delegated to the
 
2113
        underlying vfs-based Branch.
 
2114
        """
 
2115
        # TODO: Public option to disable running hooks - should be trivial but
 
2116
        # needs tests.
 
2117
        return _run_with_write_locked_target(
 
2118
            target, self._push_with_bound_branches, target, overwrite,
 
2119
            stop_revision,
 
2120
            _override_hook_source_branch=_override_hook_source_branch)
 
2121
 
 
2122
    def _push_with_bound_branches(self, target, overwrite,
 
2123
            stop_revision,
 
2124
            _override_hook_source_branch=None):
 
2125
        """Push from self into target, and into target's master if any.
 
2126
 
 
2127
        This is on the base BzrBranch class even though it doesn't support
 
2128
        bound branches because the *target* might be bound.
 
2129
        """
 
2130
        def _run_hooks():
 
2131
            if _override_hook_source_branch:
 
2132
                result.source_branch = _override_hook_source_branch
 
2133
            for hook in Branch.hooks['post_push']:
 
2134
                hook(result)
 
2135
 
 
2136
        bound_location = target.get_bound_location()
 
2137
        if bound_location and target.base != bound_location:
 
2138
            # there is a master branch.
 
2139
            #
 
2140
            # XXX: Why the second check?  Is it even supported for a branch to
 
2141
            # be bound to itself? -- mbp 20070507
 
2142
            master_branch = target.get_master_branch()
 
2143
            master_branch.lock_write()
 
2144
            try:
 
2145
                # push into the master from this branch.
 
2146
                self._basic_push(master_branch, overwrite, stop_revision)
 
2147
                # and push into the target branch from this. Note that we push from
 
2148
                # this branch again, because its considered the highest bandwidth
 
2149
                # repository.
 
2150
                result = self._basic_push(target, overwrite, stop_revision)
 
2151
                result.master_branch = master_branch
 
2152
                result.local_branch = target
 
2153
                _run_hooks()
 
2154
                return result
 
2155
            finally:
 
2156
                master_branch.unlock()
 
2157
        else:
 
2158
            # no master branch
 
2159
            result = self._basic_push(target, overwrite, stop_revision)
 
2160
            # TODO: Why set master_branch and local_branch if there's no
 
2161
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2162
            # 20070504
 
2163
            result.master_branch = target
 
2164
            result.local_branch = None
 
2165
            _run_hooks()
 
2166
            return result
 
2167
 
2628
2168
    def _basic_push(self, target, overwrite, stop_revision):
2629
2169
        """Basic implementation of push without bound branches or hooks.
2630
2170
 
2631
 
        Must be called with source read locked and target write locked.
 
2171
        Must be called with self read locked and target write locked.
2632
2172
        """
2633
2173
        result = BranchPushResult()
2634
2174
        result.source_branch = self
2635
2175
        result.target_branch = target
2636
2176
        result.old_revno, result.old_revid = target.last_revision_info()
2637
 
        self.update_references(target)
2638
2177
        if result.old_revid != self.last_revision():
2639
2178
            # We assume that during 'push' this repository is closer than
2640
2179
            # the target.
2641
2180
            graph = self.repository.get_graph(target.repository)
2642
 
            target.update_revisions(self, stop_revision,
2643
 
                overwrite=overwrite, graph=graph)
 
2181
            target.update_revisions(self, stop_revision, overwrite=overwrite,
 
2182
                                    graph=graph)
2644
2183
        if self._push_should_merge_tags():
2645
 
            result.tag_conflicts = self.tags.merge_to(target.tags,
2646
 
                overwrite)
 
2184
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2647
2185
        result.new_revno, result.new_revid = target.last_revision_info()
2648
2186
        return result
2649
2187
 
2650
2188
    def get_stacked_on_url(self):
2651
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2189
        raise errors.UnstackableBranchFormat(self._format, self.base)
2652
2190
 
2653
2191
    def set_push_location(self, location):
2654
2192
        """See Branch.set_push_location."""
2656
2194
            'push_location', location,
2657
2195
            store=_mod_config.STORE_LOCATION_NORECURSE)
2658
2196
 
 
2197
    @needs_write_lock
 
2198
    def set_parent(self, url):
 
2199
        """See Branch.set_parent."""
 
2200
        # TODO: Maybe delete old location files?
 
2201
        # URLs should never be unicode, even on the local fs,
 
2202
        # FIXUP this and get_parent in a future branch format bump:
 
2203
        # read and rewrite the file. RBC 20060125
 
2204
        if url is not None:
 
2205
            if isinstance(url, unicode):
 
2206
                try:
 
2207
                    url = url.encode('ascii')
 
2208
                except UnicodeEncodeError:
 
2209
                    raise errors.InvalidURL(url,
 
2210
                        "Urls must be 7-bit ascii, "
 
2211
                        "use bzrlib.urlutils.escape")
 
2212
            url = urlutils.relative_url(self.base, url)
 
2213
        self._set_parent_location(url)
 
2214
 
2659
2215
    def _set_parent_location(self, url):
2660
2216
        if url is None:
2661
2217
            self._transport.delete('parent')
2670
2226
    It has support for a master_branch which is the data for bound branches.
2671
2227
    """
2672
2228
 
 
2229
    @needs_write_lock
 
2230
    def pull(self, source, overwrite=False, stop_revision=None,
 
2231
             run_hooks=True, possible_transports=None,
 
2232
             _override_hook_target=None):
 
2233
        """Pull from source into self, updating my master if any.
 
2234
 
 
2235
        :param run_hooks: Private parameter - if false, this branch
 
2236
            is being called because it's the master of the primary branch,
 
2237
            so it should not run its hooks.
 
2238
        """
 
2239
        bound_location = self.get_bound_location()
 
2240
        master_branch = None
 
2241
        if bound_location and source.base != bound_location:
 
2242
            # not pulling from master, so we need to update master.
 
2243
            master_branch = self.get_master_branch(possible_transports)
 
2244
            master_branch.lock_write()
 
2245
        try:
 
2246
            if master_branch:
 
2247
                # pull from source into master.
 
2248
                master_branch.pull(source, overwrite, stop_revision,
 
2249
                    run_hooks=False)
 
2250
            return super(BzrBranch5, self).pull(source, overwrite,
 
2251
                stop_revision, _hook_master=master_branch,
 
2252
                run_hooks=run_hooks,
 
2253
                _override_hook_target=_override_hook_target)
 
2254
        finally:
 
2255
            if master_branch:
 
2256
                master_branch.unlock()
 
2257
 
2673
2258
    def get_bound_location(self):
2674
2259
        try:
2675
2260
            return self._transport.get_bytes('bound')[:-1]
2762
2347
        return None
2763
2348
 
2764
2349
 
2765
 
class BzrBranch8(BzrBranch5):
2766
 
    """A branch that stores tree-reference locations."""
 
2350
class BzrBranch7(BzrBranch5):
 
2351
    """A branch with support for a fallback repository."""
2767
2352
 
2768
2353
    def _open_hook(self):
2769
2354
        if self._ignore_fallbacks:
2785
2370
 
2786
2371
    def __init__(self, *args, **kwargs):
2787
2372
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2788
 
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
2373
        super(BzrBranch7, self).__init__(*args, **kwargs)
2789
2374
        self._last_revision_info_cache = None
2790
 
        self._reference_info = None
 
2375
        self._partial_revision_history_cache = []
2791
2376
 
2792
2377
    def _clear_cached_state(self):
2793
 
        super(BzrBranch8, self)._clear_cached_state()
 
2378
        super(BzrBranch7, self)._clear_cached_state()
2794
2379
        self._last_revision_info_cache = None
2795
 
        self._reference_info = None
 
2380
        self._partial_revision_history_cache = []
2796
2381
 
2797
2382
    def _last_revision_info(self):
2798
2383
        revision_string = self._transport.get_bytes('last-revision')
2844
2429
        if _mod_revision.is_null(last_revision):
2845
2430
            return
2846
2431
        if last_revision not in self._lefthand_history(revision_id):
2847
 
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2432
            raise errors.AppendRevisionsOnlyViolation(self.base)
2848
2433
 
2849
2434
    def _gen_revision_history(self):
2850
2435
        """Generate the revision history from last revision
2853
2438
        self._extend_partial_history(stop_index=last_revno-1)
2854
2439
        return list(reversed(self._partial_revision_history_cache))
2855
2440
 
 
2441
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
2442
        """Extend the partial history to include a given index
 
2443
 
 
2444
        If a stop_index is supplied, stop when that index has been reached.
 
2445
        If a stop_revision is supplied, stop when that revision is
 
2446
        encountered.  Otherwise, stop when the beginning of history is
 
2447
        reached.
 
2448
 
 
2449
        :param stop_index: The index which should be present.  When it is
 
2450
            present, history extension will stop.
 
2451
        :param revision_id: The revision id which should be present.  When
 
2452
            it is encountered, history extension will stop.
 
2453
        """
 
2454
        repo = self.repository
 
2455
        if len(self._partial_revision_history_cache) == 0:
 
2456
            iterator = repo.iter_reverse_revision_history(self.last_revision())
 
2457
        else:
 
2458
            start_revision = self._partial_revision_history_cache[-1]
 
2459
            iterator = repo.iter_reverse_revision_history(start_revision)
 
2460
            #skip the last revision in the list
 
2461
            next_revision = iterator.next()
 
2462
        for revision_id in iterator:
 
2463
            self._partial_revision_history_cache.append(revision_id)
 
2464
            if (stop_index is not None and
 
2465
                len(self._partial_revision_history_cache) > stop_index):
 
2466
                break
 
2467
            if revision_id == stop_revision:
 
2468
                break
 
2469
 
2856
2470
    def _write_revision_history(self, history):
2857
2471
        """Factored out of set_revision_history.
2858
2472
 
2879
2493
        """Set the parent branch"""
2880
2494
        return self._get_config_location('parent_location')
2881
2495
 
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
2496
    def set_push_location(self, location):
2958
2497
        """See Branch.set_push_location."""
2959
2498
        self._set_config_location('push_location', location)
3001
2540
            raise errors.NotStacked(self)
3002
2541
        return stacked_url
3003
2542
 
 
2543
    def set_append_revisions_only(self, enabled):
 
2544
        if enabled:
 
2545
            value = 'True'
 
2546
        else:
 
2547
            value = 'False'
 
2548
        self.get_config().set_user_option('append_revisions_only', value,
 
2549
            warn_masked=True)
 
2550
 
3004
2551
    def _get_append_revisions_only(self):
3005
 
        return self.get_config(
3006
 
            ).get_user_option_as_bool('append_revisions_only')
 
2552
        value = self.get_config().get_user_option('append_revisions_only')
 
2553
        return value == 'True'
3007
2554
 
3008
2555
    @needs_write_lock
3009
2556
    def generate_revision_history(self, revision_id, last_rev=None,
3049
2596
        return self.revno() - index
3050
2597
 
3051
2598
 
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
2599
class BzrBranch6(BzrBranch7):
3067
2600
    """See BzrBranchFormat6 for the capabilities of this branch.
3068
2601
 
3071
2604
    """
3072
2605
 
3073
2606
    def get_stacked_on_url(self):
3074
 
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2607
        raise errors.UnstackableBranchFormat(self._format, self.base)
3075
2608
 
3076
2609
 
3077
2610
######################################################################
3103
2636
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3104
2637
    """
3105
2638
 
3106
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3107
2639
    def __int__(self):
3108
 
        """Return the relative change in revno.
3109
 
 
3110
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3111
 
        """
 
2640
        # DEPRECATED: pull used to return the change in revno
3112
2641
        return self.new_revno - self.old_revno
3113
2642
 
3114
2643
    def report(self, to_file):
3139
2668
        target, otherwise it will be None.
3140
2669
    """
3141
2670
 
3142
 
    @deprecated_method(deprecated_in((2, 3, 0)))
3143
2671
    def __int__(self):
3144
 
        """Return the relative change in revno.
3145
 
 
3146
 
        :deprecated: Use `new_revno` and `old_revno` instead.
3147
 
        """
 
2672
        # DEPRECATED: push used to return the change in revno
3148
2673
        return self.new_revno - self.old_revno
3149
2674
 
3150
2675
    def report(self, to_file):
3164
2689
 
3165
2690
    def __init__(self, branch):
3166
2691
        self.branch = branch
3167
 
        self.errors = []
3168
2692
 
3169
2693
    def report_results(self, verbose):
3170
2694
        """Report the check results via trace.note.
3172
2696
        :param verbose: Requests more detailed display of what was checked,
3173
2697
            if any.
3174
2698
        """
3175
 
        note('checked branch %s format %s', self.branch.user_url,
3176
 
            self.branch._format)
3177
 
        for error in self.errors:
3178
 
            note('found error:%s', error)
 
2699
        note('checked branch %s format %s',
 
2700
             self.branch.base,
 
2701
             self.branch._format)
3179
2702
 
3180
2703
 
3181
2704
class Converter5to6(object):
3219
2742
        branch._transport.put_bytes('format', format.get_format_string())
3220
2743
 
3221
2744
 
3222
 
class Converter7to8(object):
3223
 
    """Perform an in-place upgrade of format 6 to format 7"""
3224
 
 
3225
 
    def convert(self, branch):
3226
 
        format = BzrBranchFormat8()
3227
 
        branch._transport.put_bytes('references', '')
3228
 
        # update target format
3229
 
        branch._transport.put_bytes('format', format.get_format_string())
3230
 
 
3231
2745
 
3232
2746
def _run_with_write_locked_target(target, callable, *args, **kwargs):
3233
2747
    """Run ``callable(*args, **kwargs)``, write-locking target for the
3273
2787
    _optimisers = []
3274
2788
    """The available optimised InterBranch types."""
3275
2789
 
3276
 
    @classmethod
3277
 
    def _get_branch_formats_to_test(klass):
3278
 
        """Return an iterable of format tuples for testing.
3279
 
        
3280
 
        :return: An iterable of (from_format, to_format) to use when testing
3281
 
            this InterBranch class. Each InterBranch class should define this
3282
 
            method itself.
3283
 
        """
3284
 
        raise NotImplementedError(klass._get_branch_formats_to_test)
3285
 
 
3286
 
    @needs_write_lock
3287
 
    def pull(self, overwrite=False, stop_revision=None,
3288
 
             possible_transports=None, local=False):
3289
 
        """Mirror source into target branch.
3290
 
 
3291
 
        The target branch is considered to be 'local', having low latency.
3292
 
 
3293
 
        :returns: PullResult instance
3294
 
        """
3295
 
        raise NotImplementedError(self.pull)
3296
 
 
3297
 
    @needs_write_lock
 
2790
    @staticmethod
 
2791
    def _get_branch_formats_to_test():
 
2792
        """Return a tuple with the Branch formats to use when testing."""
 
2793
        raise NotImplementedError(self._get_branch_formats_to_test)
 
2794
 
3298
2795
    def update_revisions(self, stop_revision=None, overwrite=False,
3299
2796
                         graph=None):
3300
2797
        """Pull in new perfect-fit revisions.
3308
2805
        """
3309
2806
        raise NotImplementedError(self.update_revisions)
3310
2807
 
3311
 
    @needs_write_lock
3312
 
    def push(self, overwrite=False, stop_revision=None,
3313
 
             _override_hook_source_branch=None):
3314
 
        """Mirror the source branch into the target branch.
3315
 
 
3316
 
        The source branch is considered to be 'local', having low latency.
3317
 
        """
3318
 
        raise NotImplementedError(self.push)
3319
 
 
3320
 
    @needs_write_lock
3321
 
    def copy_content_into(self, revision_id=None):
3322
 
        """Copy the content of source into target
3323
 
 
3324
 
        revision_id: if not None, the revision history in the new branch will
3325
 
                     be truncated to end with revision_id.
3326
 
        """
3327
 
        raise NotImplementedError(self.copy_content_into)
3328
 
 
3329
2808
 
3330
2809
class GenericInterBranch(InterBranch):
3331
 
    """InterBranch implementation that uses public Branch functions."""
3332
 
 
3333
 
    @classmethod
3334
 
    def is_compatible(klass, source, target):
3335
 
        # GenericBranch uses the public API, so always compatible
3336
 
        return True
3337
 
 
3338
 
    @classmethod
3339
 
    def _get_branch_formats_to_test(klass):
3340
 
        return [(BranchFormat._default_format, BranchFormat._default_format)]
3341
 
 
3342
 
    @classmethod
3343
 
    def unwrap_format(klass, format):
3344
 
        if isinstance(format, remote.RemoteBranchFormat):
3345
 
            format._ensure_real()
3346
 
            return format._custom_format
3347
 
        return format                                                                                                  
3348
 
 
3349
 
    @needs_write_lock
3350
 
    def copy_content_into(self, revision_id=None):
3351
 
        """Copy the content of source into target
3352
 
 
3353
 
        revision_id: if not None, the revision history in the new branch will
3354
 
                     be truncated to end with revision_id.
3355
 
        """
3356
 
        self.source.update_references(self.target)
3357
 
        self.source._synchronize_history(self.target, revision_id)
3358
 
        try:
3359
 
            parent = self.source.get_parent()
3360
 
        except errors.InaccessibleParent, e:
3361
 
            mutter('parent was not accessible to copy: %s', e)
3362
 
        else:
3363
 
            if parent:
3364
 
                self.target.set_parent(parent)
3365
 
        if self.source._push_should_merge_tags():
3366
 
            self.source.tags.merge_to(self.target.tags)
3367
 
 
3368
 
    @needs_write_lock
 
2810
    """InterBranch implementation that uses public Branch functions.
 
2811
    """
 
2812
 
 
2813
    @staticmethod
 
2814
    def _get_branch_formats_to_test():
 
2815
        return BranchFormat._default_format, BranchFormat._default_format
 
2816
 
3369
2817
    def update_revisions(self, stop_revision=None, overwrite=False,
3370
2818
        graph=None):
3371
2819
        """See InterBranch.update_revisions()."""
3372
 
        other_revno, other_last_revision = self.source.last_revision_info()
3373
 
        stop_revno = None # unknown
3374
 
        if stop_revision is None:
3375
 
            stop_revision = other_last_revision
3376
 
            if _mod_revision.is_null(stop_revision):
3377
 
                # if there are no commits, we're done.
3378
 
                return
3379
 
            stop_revno = other_revno
3380
 
 
3381
 
        # what's the current last revision, before we fetch [and change it
3382
 
        # possibly]
3383
 
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
3384
 
        # we fetch here so that we don't process data twice in the common
3385
 
        # case of having something to pull, and so that the check for
3386
 
        # already merged can operate on the just fetched graph, which will
3387
 
        # be cached in memory.
3388
 
        self.target.fetch(self.source, stop_revision)
3389
 
        # Check to see if one is an ancestor of the other
3390
 
        if not overwrite:
3391
 
            if graph is None:
3392
 
                graph = self.target.repository.get_graph()
3393
 
            if self.target._check_if_descendant_or_diverged(
3394
 
                    stop_revision, last_rev, graph, self.source):
3395
 
                # stop_revision is a descendant of last_rev, but we aren't
3396
 
                # overwriting, so we're done.
3397
 
                return
3398
 
        if stop_revno is None:
3399
 
            if graph is None:
3400
 
                graph = self.target.repository.get_graph()
3401
 
            this_revno, this_last_revision = \
3402
 
                    self.target.last_revision_info()
3403
 
            stop_revno = graph.find_distance_to_null(stop_revision,
3404
 
                            [(other_last_revision, other_revno),
3405
 
                             (this_last_revision, this_revno)])
3406
 
        self.target.set_last_revision_info(stop_revno, stop_revision)
3407
 
 
3408
 
    @needs_write_lock
3409
 
    def pull(self, overwrite=False, stop_revision=None,
3410
 
             possible_transports=None, run_hooks=True,
3411
 
             _override_hook_target=None, local=False):
3412
 
        """Pull from source into self, updating my master if any.
3413
 
 
3414
 
        :param run_hooks: Private parameter - if false, this branch
3415
 
            is being called because it's the master of the primary branch,
3416
 
            so it should not run its hooks.
3417
 
        """
3418
 
        bound_location = self.target.get_bound_location()
3419
 
        if local and not bound_location:
3420
 
            raise errors.LocalRequiresBoundBranch()
3421
 
        master_branch = None
3422
 
        if not local and bound_location and self.source.user_url != bound_location:
3423
 
            # not pulling from master, so we need to update master.
3424
 
            master_branch = self.target.get_master_branch(possible_transports)
3425
 
            master_branch.lock_write()
3426
 
        try:
3427
 
            if master_branch:
3428
 
                # pull from source into master.
3429
 
                master_branch.pull(self.source, overwrite, stop_revision,
3430
 
                    run_hooks=False)
3431
 
            return self._pull(overwrite,
3432
 
                stop_revision, _hook_master=master_branch,
3433
 
                run_hooks=run_hooks,
3434
 
                _override_hook_target=_override_hook_target)
3435
 
        finally:
3436
 
            if master_branch:
3437
 
                master_branch.unlock()
3438
 
 
3439
 
    def push(self, overwrite=False, stop_revision=None,
3440
 
             _override_hook_source_branch=None):
3441
 
        """See InterBranch.push.
3442
 
 
3443
 
        This is the basic concrete implementation of push()
3444
 
 
3445
 
        :param _override_hook_source_branch: If specified, run
3446
 
        the hooks passing this Branch as the source, rather than self.
3447
 
        This is for use of RemoteBranch, where push is delegated to the
3448
 
        underlying vfs-based Branch.
3449
 
        """
3450
 
        # TODO: Public option to disable running hooks - should be trivial but
3451
 
        # needs tests.
3452
 
        self.source.lock_read()
3453
 
        try:
3454
 
            return _run_with_write_locked_target(
3455
 
                self.target, self._push_with_bound_branches, overwrite,
3456
 
                stop_revision,
3457
 
                _override_hook_source_branch=_override_hook_source_branch)
3458
 
        finally:
3459
 
            self.source.unlock()
3460
 
 
3461
 
    def _push_with_bound_branches(self, overwrite, stop_revision,
3462
 
            _override_hook_source_branch=None):
3463
 
        """Push from source into target, and into target's master if any.
3464
 
        """
3465
 
        def _run_hooks():
3466
 
            if _override_hook_source_branch:
3467
 
                result.source_branch = _override_hook_source_branch
3468
 
            for hook in Branch.hooks['post_push']:
3469
 
                hook(result)
3470
 
 
3471
 
        bound_location = self.target.get_bound_location()
3472
 
        if bound_location and self.target.base != bound_location:
3473
 
            # there is a master branch.
3474
 
            #
3475
 
            # XXX: Why the second check?  Is it even supported for a branch to
3476
 
            # be bound to itself? -- mbp 20070507
3477
 
            master_branch = self.target.get_master_branch()
3478
 
            master_branch.lock_write()
3479
 
            try:
3480
 
                # push into the master from the source branch.
3481
 
                self.source._basic_push(master_branch, overwrite, stop_revision)
3482
 
                # and push into the target branch from the source. Note that we
3483
 
                # push from the source branch again, because it's considered the
3484
 
                # highest bandwidth repository.
3485
 
                result = self.source._basic_push(self.target, overwrite,
3486
 
                    stop_revision)
3487
 
                result.master_branch = master_branch
3488
 
                result.local_branch = self.target
3489
 
                _run_hooks()
3490
 
                return result
3491
 
            finally:
3492
 
                master_branch.unlock()
3493
 
        else:
3494
 
            # no master branch
3495
 
            result = self.source._basic_push(self.target, overwrite,
3496
 
                stop_revision)
3497
 
            # TODO: Why set master_branch and local_branch if there's no
3498
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
3499
 
            # 20070504
3500
 
            result.master_branch = self.target
3501
 
            result.local_branch = None
3502
 
            _run_hooks()
3503
 
            return result
3504
 
 
3505
 
    def _pull(self, overwrite=False, stop_revision=None,
3506
 
             possible_transports=None, _hook_master=None, run_hooks=True,
3507
 
             _override_hook_target=None, local=False):
3508
 
        """See Branch.pull.
3509
 
 
3510
 
        This function is the core worker, used by GenericInterBranch.pull to
3511
 
        avoid duplication when pulling source->master and source->local.
3512
 
 
3513
 
        :param _hook_master: Private parameter - set the branch to
3514
 
            be supplied as the master to pull hooks.
3515
 
        :param run_hooks: Private parameter - if false, this branch
3516
 
            is being called because it's the master of the primary branch,
3517
 
            so it should not run its hooks.
3518
 
        :param _override_hook_target: Private parameter - set the branch to be
3519
 
            supplied as the target_branch to pull hooks.
3520
 
        :param local: Only update the local branch, and not the bound branch.
3521
 
        """
3522
 
        # This type of branch can't be bound.
3523
 
        if local:
3524
 
            raise errors.LocalRequiresBoundBranch()
3525
 
        result = PullResult()
3526
 
        result.source_branch = self.source
3527
 
        if _override_hook_target is None:
3528
 
            result.target_branch = self.target
3529
 
        else:
3530
 
            result.target_branch = _override_hook_target
3531
 
        self.source.lock_read()
3532
 
        try:
3533
 
            # We assume that during 'pull' the target repository is closer than
3534
 
            # the source one.
3535
 
            self.source.update_references(self.target)
3536
 
            graph = self.target.repository.get_graph(self.source.repository)
3537
 
            # TODO: Branch formats should have a flag that indicates 
3538
 
            # that revno's are expensive, and pull() should honor that flag.
3539
 
            # -- JRV20090506
3540
 
            result.old_revno, result.old_revid = \
3541
 
                self.target.last_revision_info()
3542
 
            self.target.update_revisions(self.source, stop_revision,
3543
 
                overwrite=overwrite, graph=graph)
3544
 
            # TODO: The old revid should be specified when merging tags, 
3545
 
            # so a tags implementation that versions tags can only 
3546
 
            # pull in the most recent changes. -- JRV20090506
3547
 
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3548
 
                overwrite)
3549
 
            result.new_revno, result.new_revid = self.target.last_revision_info()
3550
 
            if _hook_master:
3551
 
                result.master_branch = _hook_master
3552
 
                result.local_branch = result.target_branch
3553
 
            else:
3554
 
                result.master_branch = result.target_branch
3555
 
                result.local_branch = None
3556
 
            if run_hooks:
3557
 
                for hook in Branch.hooks['post_pull']:
3558
 
                    hook(result)
3559
 
        finally:
3560
 
            self.source.unlock()
3561
 
        return result
 
2820
        self.source.lock_read()
 
2821
        try:
 
2822
            other_revno, other_last_revision = self.source.last_revision_info()
 
2823
            stop_revno = None # unknown
 
2824
            if stop_revision is None:
 
2825
                stop_revision = other_last_revision
 
2826
                if _mod_revision.is_null(stop_revision):
 
2827
                    # if there are no commits, we're done.
 
2828
                    return
 
2829
                stop_revno = other_revno
 
2830
 
 
2831
            # what's the current last revision, before we fetch [and change it
 
2832
            # possibly]
 
2833
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2834
            # we fetch here so that we don't process data twice in the common
 
2835
            # case of having something to pull, and so that the check for
 
2836
            # already merged can operate on the just fetched graph, which will
 
2837
            # be cached in memory.
 
2838
            self.target.fetch(self.source, stop_revision)
 
2839
            # Check to see if one is an ancestor of the other
 
2840
            if not overwrite:
 
2841
                if graph is None:
 
2842
                    graph = self.target.repository.get_graph()
 
2843
                if self.target._check_if_descendant_or_diverged(
 
2844
                        stop_revision, last_rev, graph, self.source):
 
2845
                    # stop_revision is a descendant of last_rev, but we aren't
 
2846
                    # overwriting, so we're done.
 
2847
                    return
 
2848
            if stop_revno is None:
 
2849
                if graph is None:
 
2850
                    graph = self.target.repository.get_graph()
 
2851
                this_revno, this_last_revision = \
 
2852
                        self.target.last_revision_info()
 
2853
                stop_revno = graph.find_distance_to_null(stop_revision,
 
2854
                                [(other_last_revision, other_revno),
 
2855
                                 (this_last_revision, this_revno)])
 
2856
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2857
        finally:
 
2858
            self.source.unlock()
 
2859
 
 
2860
    @classmethod
 
2861
    def is_compatible(self, source, target):
 
2862
        # GenericBranch uses the public API, so always compatible
 
2863
        return True
3562
2864
 
3563
2865
 
3564
2866
InterBranch.register_optimiser(GenericInterBranch)