/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Richard Wilbur
  • Date: 2016-02-04 19:07:28 UTC
  • mto: This revision was merged to the branch mainline in revision 6618.
  • Revision ID: richard.wilbur@gmail.com-20160204190728-p0zvfii6zase0fw7
Update COPYING.txt from the original http://www.gnu.org/licenses/gpl-2.0.txt  (Only differences were in whitespace.)  Thanks to Petr Stodulka for pointing out the discrepancy.

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
from __future__ import absolute_import
18
18
 
19
 
from . import errors
20
 
 
21
 
from .lazy_import import lazy_import
 
19
import bzrlib.bzrdir
 
20
 
 
21
from cStringIO import StringIO
 
22
 
 
23
from bzrlib.lazy_import import lazy_import
22
24
lazy_import(globals(), """
23
25
import itertools
24
 
from breezy import (
 
26
from bzrlib import (
 
27
    bzrdir,
 
28
    controldir,
 
29
    cache_utf8,
25
30
    cleanup,
26
31
    config as _mod_config,
27
32
    debug,
 
33
    errors,
28
34
    fetch,
29
 
    memorytree,
 
35
    graph as _mod_graph,
 
36
    lockdir,
 
37
    lockable_files,
 
38
    remote,
30
39
    repository,
31
40
    revision as _mod_revision,
 
41
    rio,
 
42
    shelf,
32
43
    tag as _mod_tag,
33
44
    transport,
34
45
    ui,
35
46
    urlutils,
36
 
    )
37
 
from breezy.bzr import (
38
 
    remote,
39
47
    vf_search,
40
48
    )
41
 
from breezy.i18n import gettext, ngettext
 
49
from bzrlib.i18n import gettext, ngettext
42
50
""")
43
51
 
44
 
from . import (
 
52
# Explicitly import bzrlib.bzrdir so that the BzrProber
 
53
# is guaranteed to be registered.
 
54
import bzrlib.bzrdir
 
55
 
 
56
from bzrlib import (
 
57
    bzrdir,
45
58
    controldir,
46
 
    registry,
47
59
    )
48
 
from .decorators import (
 
60
from bzrlib.decorators import (
 
61
    needs_read_lock,
 
62
    needs_write_lock,
49
63
    only_raises,
50
64
    )
51
 
from .hooks import Hooks
52
 
from .inter import InterObject
53
 
from .lock import LogicalLockResult
54
 
from .sixish import (
55
 
    BytesIO,
56
 
    text_type,
57
 
    viewitems,
 
65
from bzrlib.hooks import Hooks
 
66
from bzrlib.inter import InterObject
 
67
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
68
from bzrlib import registry
 
69
from bzrlib.symbol_versioning import (
 
70
    deprecated_in,
 
71
    deprecated_method,
58
72
    )
59
 
from .trace import mutter, mutter_callsite, note, is_quiet
60
 
 
61
 
 
62
 
class UnstackableBranchFormat(errors.BzrError):
63
 
 
64
 
    _fmt = ("The branch '%(url)s'(%(format)s) is not a stackable format. "
65
 
        "You will need to upgrade the branch to permit branch stacking.")
66
 
 
67
 
    def __init__(self, format, url):
68
 
        errors.BzrError.__init__(self)
69
 
        self.format = format
70
 
        self.url = url
 
73
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
71
74
 
72
75
 
73
76
class Branch(controldir.ControlComponent):
90
93
 
91
94
    @property
92
95
    def user_transport(self):
93
 
        return self.controldir.user_transport
 
96
        return self.bzrdir.user_transport
94
97
 
95
98
    def __init__(self, possible_transports=None):
96
99
        self.tags = self._format.make_tags(self)
98
101
        self._revision_id_to_revno_cache = None
99
102
        self._partial_revision_id_to_revno_cache = {}
100
103
        self._partial_revision_history_cache = []
 
104
        self._tags_bytes = None
101
105
        self._last_revision_info_cache = None
102
106
        self._master_branch_cache = None
103
107
        self._merge_sorted_revisions_cache = None
114
118
        for existing_fallback_repo in self.repository._fallback_repositories:
115
119
            if existing_fallback_repo.user_url == url:
116
120
                # This fallback is already configured.  This probably only
117
 
                # happens because ControlDir.sprout is a horrible mess.  To
118
 
                # avoid confusing _unstack we don't add this a second time.
 
121
                # happens because ControlDir.sprout is a horrible mess.  To avoid
 
122
                # confusing _unstack we don't add this a second time.
119
123
                mutter('duplicate activation of fallback %r on %r', url, self)
120
124
                return
121
125
        repo = self._get_fallback_repository(url, possible_transports)
139
143
 
140
144
    def _check_stackable_repo(self):
141
145
        if not self.repository._format.supports_external_lookups:
142
 
            raise errors.UnstackableRepositoryFormat(
143
 
                self.repository._format, self.repository.base)
 
146
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
147
                self.repository.base)
144
148
 
145
149
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
146
150
        """Extend the partial history to include a given index
166
170
    def _get_check_refs(self):
167
171
        """Get the references needed for check().
168
172
 
169
 
        See breezy.check.
 
173
        See bzrlib.check.
170
174
        """
171
175
        revid = self.last_revision()
172
176
        return [('revision-existence', revid), ('lefthand-distance', revid)]
217
221
        return self.supports_tags() and self.tags.get_tag_dict()
218
222
 
219
223
    def get_config(self):
220
 
        """Get a breezy.config.BranchConfig for this Branch.
 
224
        """Get a bzrlib.config.BranchConfig for this Branch.
221
225
 
222
226
        This can then be used to get and set configuration options for the
223
227
        branch.
224
228
 
225
 
        :return: A breezy.config.BranchConfig.
 
229
        :return: A bzrlib.config.BranchConfig.
226
230
        """
227
231
        return _mod_config.BranchConfig(self)
228
232
 
229
233
    def get_config_stack(self):
230
 
        """Get a breezy.config.BranchStack for this Branch.
 
234
        """Get a bzrlib.config.BranchStack for this Branch.
231
235
 
232
236
        This can then be used to get and set configuration options for the
233
237
        branch.
234
238
 
235
 
        :return: A breezy.config.BranchStack.
 
239
        :return: A bzrlib.config.BranchStack.
236
240
        """
237
241
        return _mod_config.BranchStack(self)
238
242
 
 
243
    def _get_config(self):
 
244
        """Get the concrete config for just the config in this branch.
 
245
 
 
246
        This is not intended for client use; see Branch.get_config for the
 
247
        public API.
 
248
 
 
249
        Added in 1.14.
 
250
 
 
251
        :return: An object supporting get_option and set_option.
 
252
        """
 
253
        raise NotImplementedError(self._get_config)
 
254
 
239
255
    def store_uncommitted(self, creator):
240
256
        """Store uncommitted changes from a ShelfCreator.
241
257
 
259
275
        a_branch = Branch.open(url, possible_transports=possible_transports)
260
276
        return a_branch.repository
261
277
 
 
278
    @needs_read_lock
 
279
    def _get_tags_bytes(self):
 
280
        """Get the bytes of a serialised tags dict.
 
281
 
 
282
        Note that not all branches support tags, nor do all use the same tags
 
283
        logic: this method is specific to BasicTags. Other tag implementations
 
284
        may use the same method name and behave differently, safely, because
 
285
        of the double-dispatch via
 
286
        format.make_tags->tags_instance->get_tags_dict.
 
287
 
 
288
        :return: The bytes of the tags file.
 
289
        :seealso: Branch._set_tags_bytes.
 
290
        """
 
291
        if self._tags_bytes is None:
 
292
            self._tags_bytes = self._transport.get_bytes('tags')
 
293
        return self._tags_bytes
 
294
 
262
295
    def _get_nick(self, local=False, possible_transports=None):
263
296
        config = self.get_config()
264
297
        # explicit overrides master, but don't look for master if local is True
270
303
                if master is not None:
271
304
                    # return the master branch value
272
305
                    return master.nick
273
 
            except errors.RecursiveBind as e:
 
306
            except errors.RecursiveBind, e:
274
307
                raise e
275
 
            except errors.BzrError as e:
 
308
            except errors.BzrError, e:
276
309
                # Silently fall back to local implicit nick if the master is
277
310
                # unavailable
278
311
                mutter("Could not connect to bound branch, "
326
359
    def lock_read(self):
327
360
        """Lock the branch for read operations.
328
361
 
329
 
        :return: A breezy.lock.LogicalLockResult.
 
362
        :return: A bzrlib.lock.LogicalLockResult.
330
363
        """
331
364
        raise NotImplementedError(self.lock_read)
332
365
 
340
373
    def get_physical_lock_status(self):
341
374
        raise NotImplementedError(self.get_physical_lock_status)
342
375
 
 
376
    @needs_read_lock
343
377
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
344
378
        """Return the revision_id for a dotted revno.
345
379
 
351
385
        :return: the revision_id
352
386
        :raises errors.NoSuchRevision: if the revno doesn't exist
353
387
        """
354
 
        with self.lock_read():
355
 
            rev_id = self._do_dotted_revno_to_revision_id(revno)
356
 
            if _cache_reverse:
357
 
                self._partial_revision_id_to_revno_cache[rev_id] = revno
358
 
            return rev_id
 
388
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
389
        if _cache_reverse:
 
390
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
391
        return rev_id
359
392
 
360
393
    def _do_dotted_revno_to_revision_id(self, revno):
361
394
        """Worker function for dotted_revno_to_revision_id.
367
400
            return self.get_rev_id(revno[0])
368
401
        revision_id_to_revno = self.get_revision_id_to_revno_map()
369
402
        revision_ids = [revision_id for revision_id, this_revno
370
 
                        in viewitems(revision_id_to_revno)
 
403
                        in revision_id_to_revno.iteritems()
371
404
                        if revno == this_revno]
372
405
        if len(revision_ids) == 1:
373
406
            return revision_ids[0]
375
408
            revno_str = '.'.join(map(str, revno))
376
409
            raise errors.NoSuchRevision(self, revno_str)
377
410
 
 
411
    @needs_read_lock
378
412
    def revision_id_to_dotted_revno(self, revision_id):
379
413
        """Given a revision id, return its dotted revno.
380
414
 
381
415
        :return: a tuple like (1,) or (400,1,3).
382
416
        """
383
 
        with self.lock_read():
384
 
            return self._do_revision_id_to_dotted_revno(revision_id)
 
417
        return self._do_revision_id_to_dotted_revno(revision_id)
385
418
 
386
419
    def _do_revision_id_to_dotted_revno(self, revision_id):
387
420
        """Worker function for revision_id_to_revno."""
404
437
                raise errors.NoSuchRevision(self, revision_id)
405
438
        return result
406
439
 
 
440
    @needs_read_lock
407
441
    def get_revision_id_to_revno_map(self):
408
442
        """Return the revision_id => dotted revno map.
409
443
 
412
446
        :return: A dictionary mapping revision_id => dotted revno.
413
447
            This dictionary should not be modified by the caller.
414
448
        """
415
 
        with self.lock_read():
416
 
            if self._revision_id_to_revno_cache is not None:
417
 
                mapping = self._revision_id_to_revno_cache
418
 
            else:
419
 
                mapping = self._gen_revno_map()
420
 
                self._cache_revision_id_to_revno(mapping)
421
 
            # TODO: jam 20070417 Since this is being cached, should we be returning
422
 
            #       a copy?
423
 
            # I would rather not, and instead just declare that users should not
424
 
            # modify the return value.
425
 
            return mapping
 
449
        if self._revision_id_to_revno_cache is not None:
 
450
            mapping = self._revision_id_to_revno_cache
 
451
        else:
 
452
            mapping = self._gen_revno_map()
 
453
            self._cache_revision_id_to_revno(mapping)
 
454
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
455
        #       a copy?
 
456
        # I would rather not, and instead just declare that users should not
 
457
        # modify the return value.
 
458
        return mapping
426
459
 
427
460
    def _gen_revno_map(self):
428
461
        """Create a new mapping from revision ids to dotted revnos.
439
472
             in self.iter_merge_sorted_revisions())
440
473
        return revision_id_to_revno
441
474
 
 
475
    @needs_read_lock
442
476
    def iter_merge_sorted_revisions(self, start_revision_id=None,
443
477
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
444
478
        """Walk the revisions for a branch in merge sorted order.
483
517
            * end_of_merge: When True the next node (earlier in history) is
484
518
              part of a different merge.
485
519
        """
486
 
        with self.lock_read():
487
 
            # Note: depth and revno values are in the context of the branch so
488
 
            # we need the full graph to get stable numbers, regardless of the
489
 
            # start_revision_id.
490
 
            if self._merge_sorted_revisions_cache is None:
491
 
                last_revision = self.last_revision()
492
 
                known_graph = self.repository.get_known_graph_ancestry(
493
 
                    [last_revision])
494
 
                self._merge_sorted_revisions_cache = known_graph.merge_sort(
495
 
                    last_revision)
496
 
            filtered = self._filter_merge_sorted_revisions(
497
 
                self._merge_sorted_revisions_cache, start_revision_id,
498
 
                stop_revision_id, stop_rule)
499
 
            # Make sure we don't return revisions that are not part of the
500
 
            # start_revision_id ancestry.
501
 
            filtered = self._filter_start_non_ancestors(filtered)
502
 
            if direction == 'reverse':
503
 
                return filtered
504
 
            if direction == 'forward':
505
 
                return reversed(list(filtered))
506
 
            else:
507
 
                raise ValueError('invalid direction %r' % direction)
 
520
        # Note: depth and revno values are in the context of the branch so
 
521
        # we need the full graph to get stable numbers, regardless of the
 
522
        # start_revision_id.
 
523
        if self._merge_sorted_revisions_cache is None:
 
524
            last_revision = self.last_revision()
 
525
            known_graph = self.repository.get_known_graph_ancestry(
 
526
                [last_revision])
 
527
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
 
528
                last_revision)
 
529
        filtered = self._filter_merge_sorted_revisions(
 
530
            self._merge_sorted_revisions_cache, start_revision_id,
 
531
            stop_revision_id, stop_rule)
 
532
        # Make sure we don't return revisions that are not part of the
 
533
        # start_revision_id ancestry.
 
534
        filtered = self._filter_start_non_ancestors(filtered)
 
535
        if direction == 'reverse':
 
536
            return filtered
 
537
        if direction == 'forward':
 
538
            return reversed(list(filtered))
 
539
        else:
 
540
            raise ValueError('invalid direction %r' % direction)
508
541
 
509
542
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
510
543
        start_revision_id, stop_revision_id, stop_rule):
587
620
        # ancestry. Given the order guaranteed by the merge sort, we will see
588
621
        # uninteresting descendants of the first parent of our tip before the
589
622
        # tip itself.
590
 
        first = next(rev_iter)
 
623
        first = rev_iter.next()
591
624
        (rev_id, merge_depth, revno, end_of_merge) = first
592
625
        yield first
593
626
        if not merge_depth:
662
695
            raise errors.UpgradeRequired(self.user_url)
663
696
        self.get_config_stack().set('append_revisions_only', enabled)
664
697
 
665
 
    def set_reference_info(self, tree_path, branch_location, file_id=None):
 
698
    def set_reference_info(self, file_id, tree_path, branch_location):
666
699
        """Set the branch location to use for a tree reference."""
667
700
        raise errors.UnsupportedOperation(self.set_reference_info, self)
668
701
 
669
 
    def get_reference_info(self, path):
 
702
    def get_reference_info(self, file_id):
670
703
        """Get the tree_path and branch_location for a tree reference."""
671
704
        raise errors.UnsupportedOperation(self.get_reference_info, self)
672
705
 
 
706
    @needs_write_lock
673
707
    def fetch(self, from_branch, last_revision=None, limit=None):
674
708
        """Copy revisions from from_branch into this branch.
675
709
 
679
713
        :param limit: Optional rough limit of revisions to fetch
680
714
        :return: None
681
715
        """
682
 
        with self.lock_write():
683
 
            return InterBranch.get(from_branch, self).fetch(
684
 
                    last_revision, limit=limit)
 
716
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
685
717
 
686
718
    def get_bound_location(self):
687
719
        """Return the URL of the branch we are bound to.
726
758
        """
727
759
        return None
728
760
 
 
761
    @deprecated_method(deprecated_in((2, 5, 0)))
 
762
    def get_revision_delta(self, revno):
 
763
        """Return the delta for one revision.
 
764
 
 
765
        The delta is relative to its mainline predecessor, or the
 
766
        empty tree for revision 1.
 
767
        """
 
768
        try:
 
769
            revid = self.get_rev_id(revno)
 
770
        except errors.NoSuchRevision:
 
771
            raise errors.InvalidRevisionNumber(revno)
 
772
        return self.repository.get_revision_delta(revid)
 
773
 
729
774
    def get_stacked_on_url(self):
730
775
        """Get the URL this branch is stacked against.
731
776
 
735
780
        """
736
781
        raise NotImplementedError(self.get_stacked_on_url)
737
782
 
 
783
    def print_file(self, file, revision_id):
 
784
        """Print `file` to stdout."""
 
785
        raise NotImplementedError(self.print_file)
 
786
 
 
787
    @needs_write_lock
738
788
    def set_last_revision_info(self, revno, revision_id):
739
789
        """Set the last revision of this branch.
740
790
 
748
798
        """
749
799
        raise NotImplementedError(self.set_last_revision_info)
750
800
 
 
801
    @needs_write_lock
751
802
    def generate_revision_history(self, revision_id, last_rev=None,
752
803
                                  other_branch=None):
753
804
        """See Branch.generate_revision_history"""
754
 
        with self.lock_write():
755
 
            graph = self.repository.get_graph()
756
 
            (last_revno, last_revid) = self.last_revision_info()
757
 
            known_revision_ids = [
758
 
                (last_revid, last_revno),
759
 
                (_mod_revision.NULL_REVISION, 0),
760
 
                ]
761
 
            if last_rev is not None:
762
 
                if not graph.is_ancestor(last_rev, revision_id):
763
 
                    # our previous tip is not merged into stop_revision
764
 
                    raise errors.DivergedBranches(self, other_branch)
765
 
            revno = graph.find_distance_to_null(revision_id, known_revision_ids)
766
 
            self.set_last_revision_info(revno, revision_id)
 
805
        graph = self.repository.get_graph()
 
806
        (last_revno, last_revid) = self.last_revision_info()
 
807
        known_revision_ids = [
 
808
            (last_revid, last_revno),
 
809
            (_mod_revision.NULL_REVISION, 0),
 
810
            ]
 
811
        if last_rev is not None:
 
812
            if not graph.is_ancestor(last_rev, revision_id):
 
813
                # our previous tip is not merged into stop_revision
 
814
                raise errors.DivergedBranches(self, other_branch)
 
815
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
 
816
        self.set_last_revision_info(revno, revision_id)
767
817
 
 
818
    @needs_write_lock
768
819
    def set_parent(self, url):
769
820
        """See Branch.set_parent."""
770
821
        # TODO: Maybe delete old location files?
772
823
        # FIXUP this and get_parent in a future branch format bump:
773
824
        # read and rewrite the file. RBC 20060125
774
825
        if url is not None:
775
 
            if isinstance(url, text_type):
 
826
            if isinstance(url, unicode):
776
827
                try:
777
828
                    url = url.encode('ascii')
778
829
                except UnicodeEncodeError:
779
 
                    raise urlutils.InvalidURL(url,
 
830
                    raise errors.InvalidURL(url,
780
831
                        "Urls must be 7-bit ascii, "
781
 
                        "use breezy.urlutils.escape")
 
832
                        "use bzrlib.urlutils.escape")
782
833
            url = urlutils.relative_url(self.base, url)
783
 
        with self.lock_write():
784
 
            self._set_parent_location(url)
 
834
        self._set_parent_location(url)
785
835
 
 
836
    @needs_write_lock
786
837
    def set_stacked_on_url(self, url):
787
838
        """Set the URL this branch is stacked against.
788
839
 
792
843
            stacking.
793
844
        """
794
845
        if not self._format.supports_stacking():
795
 
            raise UnstackableBranchFormat(self._format, self.user_url)
796
 
        with self.lock_write():
797
 
            # XXX: Changing from one fallback repository to another does not check
798
 
            # that all the data you need is present in the new fallback.
799
 
            # Possibly it should.
800
 
            self._check_stackable_repo()
801
 
            if not url:
802
 
                try:
803
 
                    old_url = self.get_stacked_on_url()
804
 
                except (errors.NotStacked, UnstackableBranchFormat,
805
 
                    errors.UnstackableRepositoryFormat):
806
 
                    return
807
 
                self._unstack()
808
 
            else:
809
 
                self._activate_fallback_location(url,
810
 
                    possible_transports=[self.controldir.root_transport])
811
 
            # write this out after the repository is stacked to avoid setting a
812
 
            # stacked config that doesn't work.
813
 
            self._set_config_location('stacked_on_location', url)
 
846
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
847
        # XXX: Changing from one fallback repository to another does not check
 
848
        # that all the data you need is present in the new fallback.
 
849
        # Possibly it should.
 
850
        self._check_stackable_repo()
 
851
        if not url:
 
852
            try:
 
853
                old_url = self.get_stacked_on_url()
 
854
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
855
                errors.UnstackableRepositoryFormat):
 
856
                return
 
857
            self._unstack()
 
858
        else:
 
859
            self._activate_fallback_location(url,
 
860
                possible_transports=[self.bzrdir.root_transport])
 
861
        # write this out after the repository is stacked to avoid setting a
 
862
        # stacked config that doesn't work.
 
863
        self._set_config_location('stacked_on_location', url)
814
864
 
815
865
    def _unstack(self):
816
866
        """Change a branch to be unstacked, copying data as needed.
817
867
 
818
868
        Don't call this directly, use set_stacked_on_url(None).
819
869
        """
820
 
        with ui.ui_factory.nested_progress_bar() as pb:
 
870
        pb = ui.ui_factory.nested_progress_bar()
 
871
        try:
821
872
            pb.update(gettext("Unstacking"))
822
873
            # The basic approach here is to fetch the tip of the branch,
823
874
            # including all available ghosts, from the existing stacked
839
890
            # separate SSH connection setup, but unstacking is not a
840
891
            # common operation so it's tolerable.
841
892
            new_bzrdir = controldir.ControlDir.open(
842
 
                self.controldir.root_transport.base)
 
893
                self.bzrdir.root_transport.base)
843
894
            new_repository = new_bzrdir.find_repository()
844
895
            if new_repository._fallback_repositories:
845
896
                raise AssertionError("didn't expect %r to have "
879
930
            for i in range(old_lock_count-1):
880
931
                self.repository.lock_write()
881
932
            # Fetch from the old repository into the new.
882
 
            with old_repository.lock_read():
 
933
            old_repository.lock_read()
 
934
            try:
883
935
                # XXX: If you unstack a branch while it has a working tree
884
936
                # with a pending merge, the pending-merged revisions will no
885
937
                # longer be present.  You can (probably) revert and remerge.
891
943
                    old_repository, required_ids=[self.last_revision()],
892
944
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
893
945
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
946
            finally:
 
947
                old_repository.unlock()
 
948
        finally:
 
949
            pb.finished()
 
950
 
 
951
    def _set_tags_bytes(self, bytes):
 
952
        """Mirror method for _get_tags_bytes.
 
953
 
 
954
        :seealso: Branch._get_tags_bytes.
 
955
        """
 
956
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
 
957
        op.add_cleanup(self.lock_write().unlock)
 
958
        return op.run_simple(bytes)
 
959
 
 
960
    def _set_tags_bytes_locked(self, bytes):
 
961
        self._tags_bytes = bytes
 
962
        return self._transport.put_bytes('tags', bytes)
894
963
 
895
964
    def _cache_revision_history(self, rev_history):
896
965
        """Set the cached revision history to rev_history.
927
996
        self._merge_sorted_revisions_cache = None
928
997
        self._partial_revision_history_cache = []
929
998
        self._partial_revision_id_to_revno_cache = {}
 
999
        self._tags_bytes = None
930
1000
 
931
1001
    def _gen_revision_history(self):
932
1002
        """Return sequence of revision hashes on to this branch.
969
1039
        """Return last revision id, or NULL_REVISION."""
970
1040
        return self.last_revision_info()[1]
971
1041
 
 
1042
    @needs_read_lock
972
1043
    def last_revision_info(self):
973
1044
        """Return information about the last revision.
974
1045
 
975
1046
        :return: A tuple (revno, revision_id).
976
1047
        """
977
 
        with self.lock_read():
978
 
            if self._last_revision_info_cache is None:
979
 
                self._last_revision_info_cache = self._read_last_revision_info()
980
 
            return self._last_revision_info_cache
 
1048
        if self._last_revision_info_cache is None:
 
1049
            self._last_revision_info_cache = self._read_last_revision_info()
 
1050
        return self._last_revision_info_cache
981
1051
 
982
1052
    def _read_last_revision_info(self):
983
1053
        raise NotImplementedError(self._read_last_revision_info)
1013
1083
        except ValueError:
1014
1084
            raise errors.NoSuchRevision(self, revision_id)
1015
1085
 
 
1086
    @needs_read_lock
1016
1087
    def get_rev_id(self, revno, history=None):
1017
1088
        """Find the revision id of the specified revno."""
1018
 
        with self.lock_read():
1019
 
            if revno == 0:
1020
 
                return _mod_revision.NULL_REVISION
1021
 
            last_revno, last_revid = self.last_revision_info()
1022
 
            if revno == last_revno:
1023
 
                return last_revid
1024
 
            if revno <= 0 or revno > last_revno:
1025
 
                raise errors.NoSuchRevision(self, revno)
1026
 
            distance_from_last = last_revno - revno
1027
 
            if len(self._partial_revision_history_cache) <= distance_from_last:
1028
 
                self._extend_partial_history(distance_from_last)
1029
 
            return self._partial_revision_history_cache[distance_from_last]
 
1089
        if revno == 0:
 
1090
            return _mod_revision.NULL_REVISION
 
1091
        last_revno, last_revid = self.last_revision_info()
 
1092
        if revno == last_revno:
 
1093
            return last_revid
 
1094
        if revno <= 0 or revno > last_revno:
 
1095
            raise errors.NoSuchRevision(self, revno)
 
1096
        distance_from_last = last_revno - revno
 
1097
        if len(self._partial_revision_history_cache) <= distance_from_last:
 
1098
            self._extend_partial_history(distance_from_last)
 
1099
        return self._partial_revision_history_cache[distance_from_last]
1030
1100
 
1031
1101
    def pull(self, source, overwrite=False, stop_revision=None,
1032
1102
             possible_transports=None, *args, **kwargs):
1069
1139
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
1070
1140
        try:
1071
1141
            return urlutils.join(self.base[:-1], parent)
1072
 
        except urlutils.InvalidURLJoin as e:
 
1142
        except errors.InvalidURLJoin, e:
1073
1143
            raise errors.InaccessibleParent(parent, self.user_url)
1074
1144
 
1075
1145
    def _get_parent_location(self):
1161
1231
        for hook in hooks:
1162
1232
            hook(params)
1163
1233
 
 
1234
    @needs_write_lock
1164
1235
    def update(self):
1165
1236
        """Synchronise this branch with the master branch if any.
1166
1237
 
1184
1255
        if revno < 1 or revno > self.revno():
1185
1256
            raise errors.InvalidRevisionNumber(revno)
1186
1257
 
1187
 
    def clone(self, to_controldir, revision_id=None, repository_policy=None):
1188
 
        """Clone this branch into to_controldir preserving all semantic values.
 
1258
    @needs_read_lock
 
1259
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1260
        """Clone this branch into to_bzrdir preserving all semantic values.
1189
1261
 
1190
1262
        Most API users will want 'create_clone_on_transport', which creates a
1191
1263
        new bzrdir and branch on the fly.
1193
1265
        revision_id: if not None, the revision history in the new branch will
1194
1266
                     be truncated to end with revision_id.
1195
1267
        """
1196
 
        result = to_controldir.create_branch()
1197
 
        with self.lock_read(), result.lock_write():
 
1268
        result = to_bzrdir.create_branch()
 
1269
        result.lock_write()
 
1270
        try:
1198
1271
            if repository_policy is not None:
1199
1272
                repository_policy.configure_branch(result)
1200
1273
            self.copy_content_into(result, revision_id=revision_id)
 
1274
        finally:
 
1275
            result.unlock()
1201
1276
        return result
1202
1277
 
1203
 
    def sprout(self, to_controldir, revision_id=None, repository_policy=None,
1204
 
            repository=None, lossy=False):
1205
 
        """Create a new line of development from the branch, into to_controldir.
 
1278
    @needs_read_lock
 
1279
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1280
            repository=None):
 
1281
        """Create a new line of development from the branch, into to_bzrdir.
1206
1282
 
1207
 
        to_controldir controls the branch format.
 
1283
        to_bzrdir controls the branch format.
1208
1284
 
1209
1285
        revision_id: if not None, the revision history in the new branch will
1210
1286
                     be truncated to end with revision_id.
1211
1287
        """
1212
1288
        if (repository_policy is not None and
1213
1289
            repository_policy.requires_stacking()):
1214
 
            to_controldir._format.require_stacking(_skip_repo=True)
1215
 
        result = to_controldir.create_branch(repository=repository)
1216
 
        if lossy:
1217
 
            raise errors.LossyPushToSameVCS(self, result)
1218
 
        with self.lock_read(), result.lock_write():
 
1290
            to_bzrdir._format.require_stacking(_skip_repo=True)
 
1291
        result = to_bzrdir.create_branch(repository=repository)
 
1292
        result.lock_write()
 
1293
        try:
1219
1294
            if repository_policy is not None:
1220
1295
                repository_policy.configure_branch(result)
1221
1296
            self.copy_content_into(result, revision_id=revision_id)
1222
1297
            master_url = self.get_bound_location()
1223
1298
            if master_url is None:
1224
 
                result.set_parent(self.user_url)
 
1299
                result.set_parent(self.bzrdir.root_transport.base)
1225
1300
            else:
1226
1301
                result.set_parent(master_url)
 
1302
        finally:
 
1303
            result.unlock()
1227
1304
        return result
1228
1305
 
1229
1306
    def _synchronize_history(self, destination, revision_id):
1269
1346
        old_base = self.base
1270
1347
        new_base = target.base
1271
1348
        target_reference_dict = target._get_all_reference_info()
1272
 
        for tree_path, (branch_location, file_id) in viewitems(reference_dict):
 
1349
        for file_id, (tree_path, branch_location) in (
 
1350
            reference_dict.items()):
1273
1351
            branch_location = urlutils.rebase_url(branch_location,
1274
1352
                                                  old_base, new_base)
1275
1353
            target_reference_dict.setdefault(
1276
 
                tree_path, (branch_location, file_id))
 
1354
                file_id, (tree_path, branch_location))
1277
1355
        target._set_all_reference_info(target_reference_dict)
1278
1356
 
 
1357
    @needs_read_lock
1279
1358
    def check(self, refs):
1280
1359
        """Check consistency of the branch.
1281
1360
 
1289
1368
            branch._get_check_refs()
1290
1369
        :return: A BranchCheckResult.
1291
1370
        """
1292
 
        with self.lock_read():
1293
 
            result = BranchCheckResult(self)
1294
 
            last_revno, last_revision_id = self.last_revision_info()
1295
 
            actual_revno = refs[('lefthand-distance', last_revision_id)]
1296
 
            if actual_revno != last_revno:
1297
 
                result.errors.append(errors.BzrCheckError(
1298
 
                    'revno does not match len(mainline) %s != %s' % (
1299
 
                    last_revno, actual_revno)))
1300
 
            # TODO: We should probably also check that self.revision_history
1301
 
            # matches the repository for older branch formats.
1302
 
            # If looking for the code that cross-checks repository parents against
1303
 
            # the Graph.iter_lefthand_ancestry output, that is now a repository
1304
 
            # specific check.
1305
 
            return result
 
1371
        result = BranchCheckResult(self)
 
1372
        last_revno, last_revision_id = self.last_revision_info()
 
1373
        actual_revno = refs[('lefthand-distance', last_revision_id)]
 
1374
        if actual_revno != last_revno:
 
1375
            result.errors.append(errors.BzrCheckError(
 
1376
                'revno does not match len(mainline) %s != %s' % (
 
1377
                last_revno, actual_revno)))
 
1378
        # TODO: We should probably also check that self.revision_history
 
1379
        # matches the repository for older branch formats.
 
1380
        # If looking for the code that cross-checks repository parents against
 
1381
        # the Graph.iter_lefthand_ancestry output, that is now a repository
 
1382
        # specific check.
 
1383
        return result
1306
1384
 
1307
1385
    def _get_checkout_format(self, lightweight=False):
1308
1386
        """Return the most suitable metadir for a checkout of this branch.
1309
1387
        Weaves are used if this branch's repository uses weaves.
1310
1388
        """
1311
 
        format = self.repository.controldir.checkout_metadir()
 
1389
        format = self.repository.bzrdir.checkout_metadir()
1312
1390
        format.set_branch_format(self._format)
1313
1391
        return format
1314
1392
 
1331
1409
        # rather than just the default branch? 20100319 JRV
1332
1410
        if revision_id is None:
1333
1411
            revision_id = self.last_revision()
1334
 
        dir_to = self.controldir.clone_on_transport(to_transport,
 
1412
        dir_to = self.bzrdir.clone_on_transport(to_transport,
1335
1413
            revision_id=revision_id, stacked_on=stacked_on,
1336
1414
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1337
1415
            no_tree=no_tree)
1369
1447
                pass
1370
1448
            else:
1371
1449
                raise errors.AlreadyControlDirError(t.base)
1372
 
            if checkout.control_transport.base == self.controldir.control_transport.base:
 
1450
            if checkout.control_transport.base == self.bzrdir.control_transport.base:
1373
1451
                # When checking out to the same control directory,
1374
1452
                # always create a lightweight checkout
1375
1453
                lightweight = True
1390
1468
                                           accelerator_tree=accelerator_tree,
1391
1469
                                           hardlink=hardlink)
1392
1470
        basis_tree = tree.basis_tree()
1393
 
        with basis_tree.lock_read():
 
1471
        basis_tree.lock_read()
 
1472
        try:
1394
1473
            for path, file_id in basis_tree.iter_references():
1395
 
                reference_parent = self.reference_parent(path, file_id)
 
1474
                reference_parent = self.reference_parent(file_id, path)
1396
1475
                reference_parent.create_checkout(tree.abspath(path),
1397
 
                    basis_tree.get_reference_revision(path, file_id),
 
1476
                    basis_tree.get_reference_revision(file_id, path),
1398
1477
                    lightweight)
 
1478
        finally:
 
1479
            basis_tree.unlock()
1399
1480
        return tree
1400
1481
 
 
1482
    @needs_write_lock
1401
1483
    def reconcile(self, thorough=True):
1402
1484
        """Make sure the data stored in this branch is consistent."""
1403
 
        from breezy.reconcile import BranchReconciler
1404
 
        with self.lock_write():
1405
 
            reconciler = BranchReconciler(self, thorough=thorough)
1406
 
            reconciler.reconcile()
1407
 
            return reconciler
 
1485
        from bzrlib.reconcile import BranchReconciler
 
1486
        reconciler = BranchReconciler(self, thorough=thorough)
 
1487
        reconciler.reconcile()
 
1488
        return reconciler
1408
1489
 
1409
 
    def reference_parent(self, path, file_id=None, possible_transports=None):
 
1490
    def reference_parent(self, file_id, path, possible_transports=None):
1410
1491
        """Return the parent branch for a tree-reference file_id
1411
1492
 
 
1493
        :param file_id: The file_id of the tree reference
1412
1494
        :param path: The path of the file_id in the tree
1413
 
        :param file_id: Optional file_id of the tree reference
1414
1495
        :return: A branch associated with the file_id
1415
1496
        """
1416
1497
        # FIXME should provide multiple branches, based on config
1417
 
        return Branch.open(self.controldir.root_transport.clone(path).base,
 
1498
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
1418
1499
                           possible_transports=possible_transports)
1419
1500
 
1420
1501
    def supports_tags(self):
1457
1538
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1458
1539
        """
1459
1540
        heads = graph.heads([revision_a, revision_b])
1460
 
        if heads == {revision_b}:
 
1541
        if heads == set([revision_b]):
1461
1542
            return 'b_descends_from_a'
1462
 
        elif heads == {revision_a, revision_b}:
 
1543
        elif heads == set([revision_a, revision_b]):
1463
1544
            # These branches have diverged
1464
1545
            return 'diverged'
1465
 
        elif heads == {revision_a}:
 
1546
        elif heads == set([revision_a]):
1466
1547
            return 'a_descends_from_b'
1467
1548
        else:
1468
1549
            raise AssertionError("invalid heads: %r" % (heads,))
1478
1559
        """
1479
1560
        # For bzr native formats must_fetch is just the tip, and
1480
1561
        # if_present_fetch are the tags.
1481
 
        must_fetch = {self.last_revision()}
 
1562
        must_fetch = set([self.last_revision()])
1482
1563
        if_present_fetch = set()
1483
1564
        if self.get_config_stack().get('branch.fetch_tags'):
1484
1565
            try:
1489
1570
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
1490
1571
        return must_fetch, if_present_fetch
1491
1572
 
1492
 
    def create_memorytree(self):
1493
 
        """Create a memory tree for this branch.
1494
 
 
1495
 
        :return: An in-memory MutableTree instance
1496
 
        """
1497
 
        return memorytree.MemoryTree.create_on_branch(self)
1498
 
 
1499
1573
 
1500
1574
class BranchFormat(controldir.ControlComponentFormat):
1501
1575
    """An encapsulation of the initialization and open routines for a format.
1641
1715
        """True if tags can reference ghost revisions."""
1642
1716
        return True
1643
1717
 
1644
 
    def supports_store_uncommitted(self):
1645
 
        """True if uncommitted changes can be stored in this branch."""
1646
 
        return True
 
1718
 
 
1719
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
 
1720
    """A factory for a BranchFormat object, permitting simple lazy registration.
 
1721
    
 
1722
    While none of the built in BranchFormats are lazy registered yet,
 
1723
    bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
 
1724
    use it, and the bzr-loom plugin uses it as well (see
 
1725
    bzrlib.plugins.loom.formats).
 
1726
    """
 
1727
 
 
1728
    def __init__(self, format_string, module_name, member_name):
 
1729
        """Create a MetaDirBranchFormatFactory.
 
1730
 
 
1731
        :param format_string: The format string the format has.
 
1732
        :param module_name: Module to load the format class from.
 
1733
        :param member_name: Attribute name within the module for the format class.
 
1734
        """
 
1735
        registry._LazyObjectGetter.__init__(self, module_name, member_name)
 
1736
        self._format_string = format_string
 
1737
 
 
1738
    def get_format_string(self):
 
1739
        """See BranchFormat.get_format_string."""
 
1740
        return self._format_string
 
1741
 
 
1742
    def __call__(self):
 
1743
        """Used for network_format_registry support."""
 
1744
        return self.get_obj()()
1647
1745
 
1648
1746
 
1649
1747
class BranchHooks(Hooks):
1659
1757
        These are all empty initially, because by default nothing should get
1660
1758
        notified.
1661
1759
        """
1662
 
        Hooks.__init__(self, "breezy.branch", "Branch.hooks")
 
1760
        Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1663
1761
        self.add_hook('open',
1664
1762
            "Called with the Branch object that has been opened after a "
1665
1763
            "branch is opened.", (1, 8))
1666
1764
        self.add_hook('post_push',
1667
1765
            "Called after a push operation completes. post_push is called "
1668
 
            "with a breezy.branch.BranchPushResult object and only runs in the "
 
1766
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
1669
1767
            "bzr client.", (0, 15))
1670
1768
        self.add_hook('post_pull',
1671
1769
            "Called after a pull operation completes. post_pull is called "
1672
 
            "with a breezy.branch.PullResult object and only runs in the "
 
1770
            "with a bzrlib.branch.PullResult object and only runs in the "
1673
1771
            "bzr client.", (0, 15))
1674
1772
        self.add_hook('pre_commit',
1675
1773
            "Called after a commit is calculated but before it is "
1680
1778
            "basis revision. hooks MUST NOT modify this delta. "
1681
1779
            " future_tree is an in-memory tree obtained from "
1682
1780
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1683
 
            "tree.", (0, 91))
 
1781
            "tree.", (0,91))
1684
1782
        self.add_hook('post_commit',
1685
1783
            "Called in the bzr client after a commit has completed. "
1686
1784
            "post_commit is called with (local, master, old_revno, old_revid, "
1695
1793
        self.add_hook('pre_change_branch_tip',
1696
1794
            "Called in bzr client and server before a change to the tip of a "
1697
1795
            "branch is made. pre_change_branch_tip is called with a "
1698
 
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1796
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1699
1797
            "commit, uncommit will all trigger this hook.", (1, 6))
1700
1798
        self.add_hook('post_change_branch_tip',
1701
1799
            "Called in bzr client and server after a change to the tip of a "
1702
1800
            "branch is made. post_change_branch_tip is called with a "
1703
 
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1801
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1704
1802
            "commit, uncommit will all trigger this hook.", (1, 4))
1705
1803
        self.add_hook('transform_fallback_location',
1706
1804
            "Called when a stacked branch is activating its fallback "
1723
1821
        self.add_hook('post_branch_init',
1724
1822
            "Called after new branch initialization completes. "
1725
1823
            "post_branch_init is called with a "
1726
 
            "breezy.branch.BranchInitHookParams. "
 
1824
            "bzrlib.branch.BranchInitHookParams. "
1727
1825
            "Note that init, branch and checkout (both heavyweight and "
1728
1826
            "lightweight) will all trigger this hook.", (2, 2))
1729
1827
        self.add_hook('post_switch',
1730
1828
            "Called after a checkout switches branch. "
1731
1829
            "post_switch is called with a "
1732
 
            "breezy.branch.SwitchHookParams.", (2, 2))
 
1830
            "bzrlib.branch.SwitchHookParams.", (2, 2))
1733
1831
 
1734
1832
 
1735
1833
 
1804
1902
        in branch, which refer to the original branch.
1805
1903
        """
1806
1904
        self.format = format
1807
 
        self.controldir = controldir
 
1905
        self.bzrdir = controldir
1808
1906
        self.name = name
1809
1907
        self.branch = branch
1810
1908
 
1848
1946
            self.revision_id)
1849
1947
 
1850
1948
 
 
1949
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
 
1950
    """Base class for branch formats that live in meta directories.
 
1951
    """
 
1952
 
 
1953
    def __init__(self):
 
1954
        BranchFormat.__init__(self)
 
1955
        bzrdir.BzrFormat.__init__(self)
 
1956
 
 
1957
    @classmethod
 
1958
    def find_format(klass, controldir, name=None):
 
1959
        """Return the format for the branch object in controldir."""
 
1960
        try:
 
1961
            transport = controldir.get_branch_transport(None, name=name)
 
1962
        except errors.NoSuchFile:
 
1963
            raise errors.NotBranchError(path=name, bzrdir=controldir)
 
1964
        try:
 
1965
            format_string = transport.get_bytes("format")
 
1966
        except errors.NoSuchFile:
 
1967
            raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
 
1968
        return klass._find_format(format_registry, 'branch', format_string)
 
1969
 
 
1970
    def _branch_class(self):
 
1971
        """What class to instantiate on open calls."""
 
1972
        raise NotImplementedError(self._branch_class)
 
1973
 
 
1974
    def _get_initial_config(self, append_revisions_only=None):
 
1975
        if append_revisions_only:
 
1976
            return "append_revisions_only = True\n"
 
1977
        else:
 
1978
            # Avoid writing anything if append_revisions_only is disabled,
 
1979
            # as that is the default.
 
1980
            return ""
 
1981
 
 
1982
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1983
                           repository=None):
 
1984
        """Initialize a branch in a control dir, with specified files
 
1985
 
 
1986
        :param a_bzrdir: The bzrdir to initialize the branch in
 
1987
        :param utf8_files: The files to create as a list of
 
1988
            (filename, content) tuples
 
1989
        :param name: Name of colocated branch to create, if any
 
1990
        :return: a branch in this format
 
1991
        """
 
1992
        if name is None:
 
1993
            name = a_bzrdir._get_selected_branch()
 
1994
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1995
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
1996
        control_files = lockable_files.LockableFiles(branch_transport,
 
1997
            'lock', lockdir.LockDir)
 
1998
        control_files.create_lock()
 
1999
        control_files.lock_write()
 
2000
        try:
 
2001
            utf8_files += [('format', self.as_string())]
 
2002
            for (filename, content) in utf8_files:
 
2003
                branch_transport.put_bytes(
 
2004
                    filename, content,
 
2005
                    mode=a_bzrdir._get_file_mode())
 
2006
        finally:
 
2007
            control_files.unlock()
 
2008
        branch = self.open(a_bzrdir, name, _found=True,
 
2009
                found_repository=repository)
 
2010
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2011
        return branch
 
2012
 
 
2013
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
 
2014
            found_repository=None, possible_transports=None):
 
2015
        """See BranchFormat.open()."""
 
2016
        if name is None:
 
2017
            name = a_bzrdir._get_selected_branch()
 
2018
        if not _found:
 
2019
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2020
            if format.__class__ != self.__class__:
 
2021
                raise AssertionError("wrong format %r found for %r" %
 
2022
                    (format, self))
 
2023
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2024
        try:
 
2025
            control_files = lockable_files.LockableFiles(transport, 'lock',
 
2026
                                                         lockdir.LockDir)
 
2027
            if found_repository is None:
 
2028
                found_repository = a_bzrdir.find_repository()
 
2029
            return self._branch_class()(_format=self,
 
2030
                              _control_files=control_files,
 
2031
                              name=name,
 
2032
                              a_bzrdir=a_bzrdir,
 
2033
                              _repository=found_repository,
 
2034
                              ignore_fallbacks=ignore_fallbacks,
 
2035
                              possible_transports=possible_transports)
 
2036
        except errors.NoSuchFile:
 
2037
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
 
2038
 
 
2039
    @property
 
2040
    def _matchingbzrdir(self):
 
2041
        ret = bzrdir.BzrDirMetaFormat1()
 
2042
        ret.set_branch_format(self)
 
2043
        return ret
 
2044
 
 
2045
    def supports_tags(self):
 
2046
        return True
 
2047
 
 
2048
    def supports_leaving_lock(self):
 
2049
        return True
 
2050
 
 
2051
    def check_support_status(self, allow_unsupported, recommend_upgrade=True,
 
2052
            basedir=None):
 
2053
        BranchFormat.check_support_status(self,
 
2054
            allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
 
2055
            basedir=basedir)
 
2056
        bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
 
2057
            recommend_upgrade=recommend_upgrade, basedir=basedir)
 
2058
 
 
2059
 
 
2060
class BzrBranchFormat6(BranchFormatMetadir):
 
2061
    """Branch format with last-revision and tags.
 
2062
 
 
2063
    Unlike previous formats, this has no explicit revision history. Instead,
 
2064
    this just stores the last-revision, and the left-hand history leading
 
2065
    up to there is the history.
 
2066
 
 
2067
    This format was introduced in bzr 0.15
 
2068
    and became the default in 0.91.
 
2069
    """
 
2070
 
 
2071
    def _branch_class(self):
 
2072
        return BzrBranch6
 
2073
 
 
2074
    @classmethod
 
2075
    def get_format_string(cls):
 
2076
        """See BranchFormat.get_format_string()."""
 
2077
        return "Bazaar Branch Format 6 (bzr 0.15)\n"
 
2078
 
 
2079
    def get_format_description(self):
 
2080
        """See BranchFormat.get_format_description()."""
 
2081
        return "Branch format 6"
 
2082
 
 
2083
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2084
                   append_revisions_only=None):
 
2085
        """Create a branch of this format in a_bzrdir."""
 
2086
        utf8_files = [('last-revision', '0 null:\n'),
 
2087
                      ('branch.conf',
 
2088
                          self._get_initial_config(append_revisions_only)),
 
2089
                      ('tags', ''),
 
2090
                      ]
 
2091
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2092
 
 
2093
    def make_tags(self, branch):
 
2094
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2095
        return _mod_tag.BasicTags(branch)
 
2096
 
 
2097
    def supports_set_append_revisions_only(self):
 
2098
        return True
 
2099
 
 
2100
 
 
2101
class BzrBranchFormat8(BranchFormatMetadir):
 
2102
    """Metadir format supporting storing locations of subtree branches."""
 
2103
 
 
2104
    def _branch_class(self):
 
2105
        return BzrBranch8
 
2106
 
 
2107
    @classmethod
 
2108
    def get_format_string(cls):
 
2109
        """See BranchFormat.get_format_string()."""
 
2110
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
 
2111
 
 
2112
    def get_format_description(self):
 
2113
        """See BranchFormat.get_format_description()."""
 
2114
        return "Branch format 8"
 
2115
 
 
2116
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2117
                   append_revisions_only=None):
 
2118
        """Create a branch of this format in a_bzrdir."""
 
2119
        utf8_files = [('last-revision', '0 null:\n'),
 
2120
                      ('branch.conf',
 
2121
                          self._get_initial_config(append_revisions_only)),
 
2122
                      ('tags', ''),
 
2123
                      ('references', '')
 
2124
                      ]
 
2125
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2126
 
 
2127
    def make_tags(self, branch):
 
2128
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2129
        return _mod_tag.BasicTags(branch)
 
2130
 
 
2131
    def supports_set_append_revisions_only(self):
 
2132
        return True
 
2133
 
 
2134
    def supports_stacking(self):
 
2135
        return True
 
2136
 
 
2137
    supports_reference_locations = True
 
2138
 
 
2139
 
 
2140
class BzrBranchFormat7(BranchFormatMetadir):
 
2141
    """Branch format with last-revision, tags, and a stacked location pointer.
 
2142
 
 
2143
    The stacked location pointer is passed down to the repository and requires
 
2144
    a repository format with supports_external_lookups = True.
 
2145
 
 
2146
    This format was introduced in bzr 1.6.
 
2147
    """
 
2148
 
 
2149
    def initialize(self, a_bzrdir, name=None, repository=None,
 
2150
                   append_revisions_only=None):
 
2151
        """Create a branch of this format in a_bzrdir."""
 
2152
        utf8_files = [('last-revision', '0 null:\n'),
 
2153
                      ('branch.conf',
 
2154
                          self._get_initial_config(append_revisions_only)),
 
2155
                      ('tags', ''),
 
2156
                      ]
 
2157
        return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
 
2158
 
 
2159
    def _branch_class(self):
 
2160
        return BzrBranch7
 
2161
 
 
2162
    @classmethod
 
2163
    def get_format_string(cls):
 
2164
        """See BranchFormat.get_format_string()."""
 
2165
        return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
 
2166
 
 
2167
    def get_format_description(self):
 
2168
        """See BranchFormat.get_format_description()."""
 
2169
        return "Branch format 7"
 
2170
 
 
2171
    def supports_set_append_revisions_only(self):
 
2172
        return True
 
2173
 
 
2174
    def supports_stacking(self):
 
2175
        return True
 
2176
 
 
2177
    def make_tags(self, branch):
 
2178
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2179
        return _mod_tag.BasicTags(branch)
 
2180
 
 
2181
    supports_reference_locations = False
 
2182
 
 
2183
 
 
2184
class BranchReferenceFormat(BranchFormatMetadir):
 
2185
    """Bzr branch reference format.
 
2186
 
 
2187
    Branch references are used in implementing checkouts, they
 
2188
    act as an alias to the real branch which is at some other url.
 
2189
 
 
2190
    This format has:
 
2191
     - A location file
 
2192
     - a format string
 
2193
    """
 
2194
 
 
2195
    @classmethod
 
2196
    def get_format_string(cls):
 
2197
        """See BranchFormat.get_format_string()."""
 
2198
        return "Bazaar-NG Branch Reference Format 1\n"
 
2199
 
 
2200
    def get_format_description(self):
 
2201
        """See BranchFormat.get_format_description()."""
 
2202
        return "Checkout reference format 1"
 
2203
 
 
2204
    def get_reference(self, a_bzrdir, name=None):
 
2205
        """See BranchFormat.get_reference()."""
 
2206
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2207
        return transport.get_bytes('location')
 
2208
 
 
2209
    def set_reference(self, a_bzrdir, name, to_branch):
 
2210
        """See BranchFormat.set_reference()."""
 
2211
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2212
        location = transport.put_bytes('location', to_branch.base)
 
2213
 
 
2214
    def initialize(self, a_bzrdir, name=None, target_branch=None,
 
2215
            repository=None, append_revisions_only=None):
 
2216
        """Create a branch of this format in a_bzrdir."""
 
2217
        if target_branch is None:
 
2218
            # this format does not implement branch itself, thus the implicit
 
2219
            # creation contract must see it as uninitializable
 
2220
            raise errors.UninitializableFormat(self)
 
2221
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2222
        if a_bzrdir._format.fixed_components:
 
2223
            raise errors.IncompatibleFormat(self, a_bzrdir._format)
 
2224
        if name is None:
 
2225
            name = a_bzrdir._get_selected_branch()
 
2226
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
 
2227
        branch_transport.put_bytes('location',
 
2228
            target_branch.user_url)
 
2229
        branch_transport.put_bytes('format', self.as_string())
 
2230
        branch = self.open(a_bzrdir, name, _found=True,
 
2231
            possible_transports=[target_branch.bzrdir.root_transport])
 
2232
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2233
        return branch
 
2234
 
 
2235
    def _make_reference_clone_function(format, a_branch):
 
2236
        """Create a clone() routine for a branch dynamically."""
 
2237
        def clone(to_bzrdir, revision_id=None,
 
2238
            repository_policy=None):
 
2239
            """See Branch.clone()."""
 
2240
            return format.initialize(to_bzrdir, target_branch=a_branch)
 
2241
            # cannot obey revision_id limits when cloning a reference ...
 
2242
            # FIXME RBC 20060210 either nuke revision_id for clone, or
 
2243
            # emit some sort of warning/error to the caller ?!
 
2244
        return clone
 
2245
 
 
2246
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2247
             possible_transports=None, ignore_fallbacks=False,
 
2248
             found_repository=None):
 
2249
        """Return the branch that the branch reference in a_bzrdir points at.
 
2250
 
 
2251
        :param a_bzrdir: A BzrDir that contains a branch.
 
2252
        :param name: Name of colocated branch to open, if any
 
2253
        :param _found: a private parameter, do not use it. It is used to
 
2254
            indicate if format probing has already be done.
 
2255
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
2256
            (if there are any).  Default is to open fallbacks.
 
2257
        :param location: The location of the referenced branch.  If
 
2258
            unspecified, this will be determined from the branch reference in
 
2259
            a_bzrdir.
 
2260
        :param possible_transports: An optional reusable transports list.
 
2261
        """
 
2262
        if name is None:
 
2263
            name = a_bzrdir._get_selected_branch()
 
2264
        if not _found:
 
2265
            format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
 
2266
            if format.__class__ != self.__class__:
 
2267
                raise AssertionError("wrong format %r found for %r" %
 
2268
                    (format, self))
 
2269
        if location is None:
 
2270
            location = self.get_reference(a_bzrdir, name)
 
2271
        real_bzrdir = controldir.ControlDir.open(
 
2272
            location, possible_transports=possible_transports)
 
2273
        result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
 
2274
            possible_transports=possible_transports)
 
2275
        # this changes the behaviour of result.clone to create a new reference
 
2276
        # rather than a copy of the content of the branch.
 
2277
        # I did not use a proxy object because that needs much more extensive
 
2278
        # testing, and we are only changing one behaviour at the moment.
 
2279
        # If we decide to alter more behaviours - i.e. the implicit nickname
 
2280
        # then this should be refactored to introduce a tested proxy branch
 
2281
        # and a subclass of that for use in overriding clone() and ....
 
2282
        # - RBC 20060210
 
2283
        result.clone = self._make_reference_clone_function(result)
 
2284
        return result
 
2285
 
 
2286
 
1851
2287
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1852
2288
    """Branch format registry."""
1853
2289
 
1854
2290
    def __init__(self, other_registry=None):
1855
2291
        super(BranchFormatRegistry, self).__init__(other_registry)
1856
2292
        self._default_format = None
1857
 
        self._default_format_key = None
 
2293
 
 
2294
    def set_default(self, format):
 
2295
        self._default_format = format
1858
2296
 
1859
2297
    def get_default(self):
1860
 
        """Return the current default format."""
1861
 
        if (self._default_format_key is not None and
1862
 
            self._default_format is None):
1863
 
            self._default_format = self.get(self._default_format_key)
1864
2298
        return self._default_format
1865
2299
 
1866
 
    def set_default(self, format):
1867
 
        """Set the default format."""
1868
 
        self._default_format = format
1869
 
        self._default_format_key = None
1870
 
 
1871
 
    def set_default_key(self, format_string):
1872
 
        """Set the default format by its format string."""
1873
 
        self._default_format_key = format_string
1874
 
        self._default_format = None
1875
 
 
1876
2300
 
1877
2301
network_format_registry = registry.FormatRegistry()
1878
2302
"""Registry of formats indexed by their network name.
1887
2311
 
1888
2312
# formats which have no format string are not discoverable
1889
2313
# and not independently creatable, so are not registered.
1890
 
format_registry.register_lazy(
1891
 
    b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1892
 
    "BzrBranchFormat5")
1893
 
format_registry.register_lazy(
1894
 
    b"Bazaar Branch Format 6 (bzr 0.15)\n",
1895
 
    "breezy.bzr.branch", "BzrBranchFormat6")
1896
 
format_registry.register_lazy(
1897
 
    b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1898
 
    "breezy.bzr.branch", "BzrBranchFormat7")
1899
 
format_registry.register_lazy(
1900
 
    b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1901
 
    "breezy.bzr.branch", "BzrBranchFormat8")
1902
 
format_registry.register_lazy(
1903
 
    b"Bazaar-NG Branch Reference Format 1\n",
1904
 
    "breezy.bzr.branch", "BranchReferenceFormat")
1905
 
 
1906
 
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
 
2314
__format6 = BzrBranchFormat6()
 
2315
__format7 = BzrBranchFormat7()
 
2316
__format8 = BzrBranchFormat8()
 
2317
format_registry.register_lazy(
 
2318
    "Bazaar-NG branch format 5\n", "bzrlib.branchfmt.fullhistory", "BzrBranchFormat5")
 
2319
format_registry.register(BranchReferenceFormat())
 
2320
format_registry.register(__format6)
 
2321
format_registry.register(__format7)
 
2322
format_registry.register(__format8)
 
2323
format_registry.set_default(__format7)
1907
2324
 
1908
2325
 
1909
2326
class BranchWriteLockResult(LogicalLockResult):
1910
2327
    """The result of write locking a branch.
1911
2328
 
1912
 
    :ivar token: The token obtained from the underlying branch lock, or
 
2329
    :ivar branch_token: The token obtained from the underlying branch lock, or
1913
2330
        None.
1914
2331
    :ivar unlock: A callable which will unlock the lock.
1915
2332
    """
1916
2333
 
 
2334
    def __init__(self, unlock, branch_token):
 
2335
        LogicalLockResult.__init__(self, unlock)
 
2336
        self.branch_token = branch_token
 
2337
 
1917
2338
    def __repr__(self):
1918
 
        return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
 
2339
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2340
            self.unlock)
 
2341
 
 
2342
 
 
2343
class BzrBranch(Branch, _RelockDebugMixin):
 
2344
    """A branch stored in the actual filesystem.
 
2345
 
 
2346
    Note that it's "local" in the context of the filesystem; it doesn't
 
2347
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
 
2348
    it's writable, and can be accessed via the normal filesystem API.
 
2349
 
 
2350
    :ivar _transport: Transport for file operations on this branch's
 
2351
        control files, typically pointing to the .bzr/branch directory.
 
2352
    :ivar repository: Repository for this branch.
 
2353
    :ivar base: The url of the base directory for this branch; the one
 
2354
        containing the .bzr directory.
 
2355
    :ivar name: Optional colocated branch name as it exists in the control
 
2356
        directory.
 
2357
    """
 
2358
 
 
2359
    def __init__(self, _format=None,
 
2360
                 _control_files=None, a_bzrdir=None, name=None,
 
2361
                 _repository=None, ignore_fallbacks=False,
 
2362
                 possible_transports=None):
 
2363
        """Create new branch object at a particular location."""
 
2364
        if a_bzrdir is None:
 
2365
            raise ValueError('a_bzrdir must be supplied')
 
2366
        if name is None:
 
2367
            raise ValueError('name must be supplied')
 
2368
        self.bzrdir = a_bzrdir
 
2369
        self._user_transport = self.bzrdir.transport.clone('..')
 
2370
        if name != "":
 
2371
            self._user_transport.set_segment_parameter(
 
2372
                "branch", urlutils.escape(name))
 
2373
        self._base = self._user_transport.base
 
2374
        self.name = name
 
2375
        self._format = _format
 
2376
        if _control_files is None:
 
2377
            raise ValueError('BzrBranch _control_files is None')
 
2378
        self.control_files = _control_files
 
2379
        self._transport = _control_files._transport
 
2380
        self.repository = _repository
 
2381
        self.conf_store = None
 
2382
        Branch.__init__(self, possible_transports)
 
2383
 
 
2384
    def __str__(self):
 
2385
        return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2386
 
 
2387
    __repr__ = __str__
 
2388
 
 
2389
    def _get_base(self):
 
2390
        """Returns the directory containing the control directory."""
 
2391
        return self._base
 
2392
 
 
2393
    base = property(_get_base, doc="The URL for the root of this branch.")
 
2394
 
 
2395
    @property
 
2396
    def user_transport(self):
 
2397
        return self._user_transport
 
2398
 
 
2399
    def _get_config(self):
 
2400
        return _mod_config.TransportConfig(self._transport, 'branch.conf')
 
2401
 
 
2402
    def _get_config_store(self):
 
2403
        if self.conf_store is None:
 
2404
            self.conf_store =  _mod_config.BranchStore(self)
 
2405
        return self.conf_store
 
2406
 
 
2407
    def _uncommitted_branch(self):
 
2408
        """Return the branch that may contain uncommitted changes."""
 
2409
        master = self.get_master_branch()
 
2410
        if master is not None:
 
2411
            return master
 
2412
        else:
 
2413
            return self
 
2414
 
 
2415
    def store_uncommitted(self, creator):
 
2416
        """Store uncommitted changes from a ShelfCreator.
 
2417
 
 
2418
        :param creator: The ShelfCreator containing uncommitted changes, or
 
2419
            None to delete any stored changes.
 
2420
        :raises: ChangesAlreadyStored if the branch already has changes.
 
2421
        """
 
2422
        branch = self._uncommitted_branch()
 
2423
        if creator is None:
 
2424
            branch._transport.delete('stored-transform')
 
2425
            return
 
2426
        if branch._transport.has('stored-transform'):
 
2427
            raise errors.ChangesAlreadyStored
 
2428
        transform = StringIO()
 
2429
        creator.write_shelf(transform)
 
2430
        transform.seek(0)
 
2431
        branch._transport.put_file('stored-transform', transform)
 
2432
 
 
2433
    def get_unshelver(self, tree):
 
2434
        """Return a shelf.Unshelver for this branch and tree.
 
2435
 
 
2436
        :param tree: The tree to use to construct the Unshelver.
 
2437
        :return: an Unshelver or None if no changes are stored.
 
2438
        """
 
2439
        branch = self._uncommitted_branch()
 
2440
        try:
 
2441
            transform = branch._transport.get('stored-transform')
 
2442
        except errors.NoSuchFile:
 
2443
            return None
 
2444
        return shelf.Unshelver.from_tree_and_shelf(tree, transform)
 
2445
 
 
2446
    def is_locked(self):
 
2447
        return self.control_files.is_locked()
 
2448
 
 
2449
    def lock_write(self, token=None):
 
2450
        """Lock the branch for write operations.
 
2451
 
 
2452
        :param token: A token to permit reacquiring a previously held and
 
2453
            preserved lock.
 
2454
        :return: A BranchWriteLockResult.
 
2455
        """
 
2456
        if not self.is_locked():
 
2457
            self._note_lock('w')
 
2458
            self.repository._warn_if_deprecated(self)
 
2459
            self.repository.lock_write()
 
2460
            took_lock = True
 
2461
        else:
 
2462
            took_lock = False
 
2463
        try:
 
2464
            return BranchWriteLockResult(self.unlock,
 
2465
                self.control_files.lock_write(token=token))
 
2466
        except:
 
2467
            if took_lock:
 
2468
                self.repository.unlock()
 
2469
            raise
 
2470
 
 
2471
    def lock_read(self):
 
2472
        """Lock the branch for read operations.
 
2473
 
 
2474
        :return: A bzrlib.lock.LogicalLockResult.
 
2475
        """
 
2476
        if not self.is_locked():
 
2477
            self._note_lock('r')
 
2478
            self.repository._warn_if_deprecated(self)
 
2479
            self.repository.lock_read()
 
2480
            took_lock = True
 
2481
        else:
 
2482
            took_lock = False
 
2483
        try:
 
2484
            self.control_files.lock_read()
 
2485
            return LogicalLockResult(self.unlock)
 
2486
        except:
 
2487
            if took_lock:
 
2488
                self.repository.unlock()
 
2489
            raise
 
2490
 
 
2491
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
2492
    def unlock(self):
 
2493
        if self.control_files._lock_count == 1 and self.conf_store is not None:
 
2494
            self.conf_store.save_changes()
 
2495
        try:
 
2496
            self.control_files.unlock()
 
2497
        finally:
 
2498
            if not self.control_files.is_locked():
 
2499
                self.repository.unlock()
 
2500
                # we just released the lock
 
2501
                self._clear_cached_state()
 
2502
 
 
2503
    def peek_lock_mode(self):
 
2504
        if self.control_files._lock_count == 0:
 
2505
            return None
 
2506
        else:
 
2507
            return self.control_files._lock_mode
 
2508
 
 
2509
    def get_physical_lock_status(self):
 
2510
        return self.control_files.get_physical_lock_status()
 
2511
 
 
2512
    @needs_read_lock
 
2513
    def print_file(self, file, revision_id):
 
2514
        """See Branch.print_file."""
 
2515
        return self.repository.print_file(file, revision_id)
 
2516
 
 
2517
    @needs_write_lock
 
2518
    def set_last_revision_info(self, revno, revision_id):
 
2519
        if not revision_id or not isinstance(revision_id, basestring):
 
2520
            raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
 
2521
        revision_id = _mod_revision.ensure_null(revision_id)
 
2522
        old_revno, old_revid = self.last_revision_info()
 
2523
        if self.get_append_revisions_only():
 
2524
            self._check_history_violation(revision_id)
 
2525
        self._run_pre_change_branch_tip_hooks(revno, revision_id)
 
2526
        self._write_last_revision_info(revno, revision_id)
 
2527
        self._clear_cached_state()
 
2528
        self._last_revision_info_cache = revno, revision_id
 
2529
        self._run_post_change_branch_tip_hooks(old_revno, old_revid)
 
2530
 
 
2531
    def basis_tree(self):
 
2532
        """See Branch.basis_tree."""
 
2533
        return self.repository.revision_tree(self.last_revision())
 
2534
 
 
2535
    def _get_parent_location(self):
 
2536
        _locs = ['parent', 'pull', 'x-pull']
 
2537
        for l in _locs:
 
2538
            try:
 
2539
                return self._transport.get_bytes(l).strip('\n')
 
2540
            except errors.NoSuchFile:
 
2541
                pass
 
2542
        return None
 
2543
 
 
2544
    def get_stacked_on_url(self):
 
2545
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
2546
 
 
2547
    def set_push_location(self, location):
 
2548
        """See Branch.set_push_location."""
 
2549
        self.get_config().set_user_option(
 
2550
            'push_location', location,
 
2551
            store=_mod_config.STORE_LOCATION_NORECURSE)
 
2552
 
 
2553
    def _set_parent_location(self, url):
 
2554
        if url is None:
 
2555
            self._transport.delete('parent')
 
2556
        else:
 
2557
            self._transport.put_bytes('parent', url + '\n',
 
2558
                mode=self.bzrdir._get_file_mode())
 
2559
 
 
2560
    @needs_write_lock
 
2561
    def unbind(self):
 
2562
        """If bound, unbind"""
 
2563
        return self.set_bound_location(None)
 
2564
 
 
2565
    @needs_write_lock
 
2566
    def bind(self, other):
 
2567
        """Bind this branch to the branch other.
 
2568
 
 
2569
        This does not push or pull data between the branches, though it does
 
2570
        check for divergence to raise an error when the branches are not
 
2571
        either the same, or one a prefix of the other. That behaviour may not
 
2572
        be useful, so that check may be removed in future.
 
2573
 
 
2574
        :param other: The branch to bind to
 
2575
        :type other: Branch
 
2576
        """
 
2577
        # TODO: jam 20051230 Consider checking if the target is bound
 
2578
        #       It is debatable whether you should be able to bind to
 
2579
        #       a branch which is itself bound.
 
2580
        #       Committing is obviously forbidden,
 
2581
        #       but binding itself may not be.
 
2582
        #       Since we *have* to check at commit time, we don't
 
2583
        #       *need* to check here
 
2584
 
 
2585
        # we want to raise diverged if:
 
2586
        # last_rev is not in the other_last_rev history, AND
 
2587
        # other_last_rev is not in our history, and do it without pulling
 
2588
        # history around
 
2589
        self.set_bound_location(other.base)
 
2590
 
 
2591
    def get_bound_location(self):
 
2592
        try:
 
2593
            return self._transport.get_bytes('bound')[:-1]
 
2594
        except errors.NoSuchFile:
 
2595
            return None
 
2596
 
 
2597
    @needs_read_lock
 
2598
    def get_master_branch(self, possible_transports=None):
 
2599
        """Return the branch we are bound to.
 
2600
 
 
2601
        :return: Either a Branch, or None
 
2602
        """
 
2603
        if self._master_branch_cache is None:
 
2604
            self._master_branch_cache = self._get_master_branch(
 
2605
                possible_transports)
 
2606
        return self._master_branch_cache
 
2607
 
 
2608
    def _get_master_branch(self, possible_transports):
 
2609
        bound_loc = self.get_bound_location()
 
2610
        if not bound_loc:
 
2611
            return None
 
2612
        try:
 
2613
            return Branch.open(bound_loc,
 
2614
                               possible_transports=possible_transports)
 
2615
        except (errors.NotBranchError, errors.ConnectionError), e:
 
2616
            raise errors.BoundBranchConnectionFailure(
 
2617
                    self, bound_loc, e)
 
2618
 
 
2619
    @needs_write_lock
 
2620
    def set_bound_location(self, location):
 
2621
        """Set the target where this branch is bound to.
 
2622
 
 
2623
        :param location: URL to the target branch
 
2624
        """
 
2625
        self._master_branch_cache = None
 
2626
        if location:
 
2627
            self._transport.put_bytes('bound', location+'\n',
 
2628
                mode=self.bzrdir._get_file_mode())
 
2629
        else:
 
2630
            try:
 
2631
                self._transport.delete('bound')
 
2632
            except errors.NoSuchFile:
 
2633
                return False
 
2634
            return True
 
2635
 
 
2636
    @needs_write_lock
 
2637
    def update(self, possible_transports=None):
 
2638
        """Synchronise this branch with the master branch if any.
 
2639
 
 
2640
        :return: None or the last_revision that was pivoted out during the
 
2641
                 update.
 
2642
        """
 
2643
        master = self.get_master_branch(possible_transports)
 
2644
        if master is not None:
 
2645
            old_tip = _mod_revision.ensure_null(self.last_revision())
 
2646
            self.pull(master, overwrite=True)
 
2647
            if self.repository.get_graph().is_ancestor(old_tip,
 
2648
                _mod_revision.ensure_null(self.last_revision())):
 
2649
                return None
 
2650
            return old_tip
 
2651
        return None
 
2652
 
 
2653
    def _read_last_revision_info(self):
 
2654
        revision_string = self._transport.get_bytes('last-revision')
 
2655
        revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
 
2656
        revision_id = cache_utf8.get_cached_utf8(revision_id)
 
2657
        revno = int(revno)
 
2658
        return revno, revision_id
 
2659
 
 
2660
    def _write_last_revision_info(self, revno, revision_id):
 
2661
        """Simply write out the revision id, with no checks.
 
2662
 
 
2663
        Use set_last_revision_info to perform this safely.
 
2664
 
 
2665
        Does not update the revision_history cache.
 
2666
        """
 
2667
        revision_id = _mod_revision.ensure_null(revision_id)
 
2668
        out_string = '%d %s\n' % (revno, revision_id)
 
2669
        self._transport.put_bytes('last-revision', out_string,
 
2670
            mode=self.bzrdir._get_file_mode())
 
2671
 
 
2672
    @needs_write_lock
 
2673
    def update_feature_flags(self, updated_flags):
 
2674
        """Update the feature flags for this branch.
 
2675
 
 
2676
        :param updated_flags: Dictionary mapping feature names to necessities
 
2677
            A necessity can be None to indicate the feature should be removed
 
2678
        """
 
2679
        self._format._update_feature_flags(updated_flags)
 
2680
        self.control_transport.put_bytes('format', self._format.as_string())
 
2681
 
 
2682
 
 
2683
class BzrBranch8(BzrBranch):
 
2684
    """A branch that stores tree-reference locations."""
 
2685
 
 
2686
    def _open_hook(self, possible_transports=None):
 
2687
        if self._ignore_fallbacks:
 
2688
            return
 
2689
        if possible_transports is None:
 
2690
            possible_transports = [self.bzrdir.root_transport]
 
2691
        try:
 
2692
            url = self.get_stacked_on_url()
 
2693
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
 
2694
            errors.UnstackableBranchFormat):
 
2695
            pass
 
2696
        else:
 
2697
            for hook in Branch.hooks['transform_fallback_location']:
 
2698
                url = hook(self, url)
 
2699
                if url is None:
 
2700
                    hook_name = Branch.hooks.get_hook_name(hook)
 
2701
                    raise AssertionError(
 
2702
                        "'transform_fallback_location' hook %s returned "
 
2703
                        "None, not a URL." % hook_name)
 
2704
            self._activate_fallback_location(url,
 
2705
                possible_transports=possible_transports)
 
2706
 
 
2707
    def __init__(self, *args, **kwargs):
 
2708
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
 
2709
        super(BzrBranch8, self).__init__(*args, **kwargs)
 
2710
        self._last_revision_info_cache = None
 
2711
        self._reference_info = None
 
2712
 
 
2713
    def _clear_cached_state(self):
 
2714
        super(BzrBranch8, self)._clear_cached_state()
 
2715
        self._last_revision_info_cache = None
 
2716
        self._reference_info = None
 
2717
 
 
2718
    def _check_history_violation(self, revision_id):
 
2719
        current_revid = self.last_revision()
 
2720
        last_revision = _mod_revision.ensure_null(current_revid)
 
2721
        if _mod_revision.is_null(last_revision):
 
2722
            return
 
2723
        graph = self.repository.get_graph()
 
2724
        for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
 
2725
            if lh_ancestor == current_revid:
 
2726
                return
 
2727
        raise errors.AppendRevisionsOnlyViolation(self.user_url)
 
2728
 
 
2729
    def _gen_revision_history(self):
 
2730
        """Generate the revision history from last revision
 
2731
        """
 
2732
        last_revno, last_revision = self.last_revision_info()
 
2733
        self._extend_partial_history(stop_index=last_revno-1)
 
2734
        return list(reversed(self._partial_revision_history_cache))
 
2735
 
 
2736
    @needs_write_lock
 
2737
    def _set_parent_location(self, url):
 
2738
        """Set the parent branch"""
 
2739
        self._set_config_location('parent_location', url, make_relative=True)
 
2740
 
 
2741
    @needs_read_lock
 
2742
    def _get_parent_location(self):
 
2743
        """Set the parent branch"""
 
2744
        return self._get_config_location('parent_location')
 
2745
 
 
2746
    @needs_write_lock
 
2747
    def _set_all_reference_info(self, info_dict):
 
2748
        """Replace all reference info stored in a branch.
 
2749
 
 
2750
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
 
2751
        """
 
2752
        s = StringIO()
 
2753
        writer = rio.RioWriter(s)
 
2754
        for key, (tree_path, branch_location) in info_dict.iteritems():
 
2755
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
 
2756
                                branch_location=branch_location)
 
2757
            writer.write_stanza(stanza)
 
2758
        self._transport.put_bytes('references', s.getvalue())
 
2759
        self._reference_info = info_dict
 
2760
 
 
2761
    @needs_read_lock
 
2762
    def _get_all_reference_info(self):
 
2763
        """Return all the reference info stored in a branch.
 
2764
 
 
2765
        :return: A dict of {file_id: (tree_path, branch_location)}
 
2766
        """
 
2767
        if self._reference_info is not None:
 
2768
            return self._reference_info
 
2769
        rio_file = self._transport.get('references')
 
2770
        try:
 
2771
            stanzas = rio.read_stanzas(rio_file)
 
2772
            info_dict = dict((s['file_id'], (s['tree_path'],
 
2773
                             s['branch_location'])) for s in stanzas)
 
2774
        finally:
 
2775
            rio_file.close()
 
2776
        self._reference_info = info_dict
 
2777
        return info_dict
 
2778
 
 
2779
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2780
        """Set the branch location to use for a tree reference.
 
2781
 
 
2782
        :param file_id: The file-id of the tree reference.
 
2783
        :param tree_path: The path of the tree reference in the tree.
 
2784
        :param branch_location: The location of the branch to retrieve tree
 
2785
            references from.
 
2786
        """
 
2787
        info_dict = self._get_all_reference_info()
 
2788
        info_dict[file_id] = (tree_path, branch_location)
 
2789
        if None in (tree_path, branch_location):
 
2790
            if tree_path is not None:
 
2791
                raise ValueError('tree_path must be None when branch_location'
 
2792
                                 ' is None.')
 
2793
            if branch_location is not None:
 
2794
                raise ValueError('branch_location must be None when tree_path'
 
2795
                                 ' is None.')
 
2796
            del info_dict[file_id]
 
2797
        self._set_all_reference_info(info_dict)
 
2798
 
 
2799
    def get_reference_info(self, file_id):
 
2800
        """Get the tree_path and branch_location for a tree reference.
 
2801
 
 
2802
        :return: a tuple of (tree_path, branch_location)
 
2803
        """
 
2804
        return self._get_all_reference_info().get(file_id, (None, None))
 
2805
 
 
2806
    def reference_parent(self, file_id, path, possible_transports=None):
 
2807
        """Return the parent branch for a tree-reference file_id.
 
2808
 
 
2809
        :param file_id: The file_id of the tree reference
 
2810
        :param path: The path of the file_id in the tree
 
2811
        :return: A branch associated with the file_id
 
2812
        """
 
2813
        branch_location = self.get_reference_info(file_id)[1]
 
2814
        if branch_location is None:
 
2815
            return Branch.reference_parent(self, file_id, path,
 
2816
                                           possible_transports)
 
2817
        branch_location = urlutils.join(self.user_url, branch_location)
 
2818
        return Branch.open(branch_location,
 
2819
                           possible_transports=possible_transports)
 
2820
 
 
2821
    def set_push_location(self, location):
 
2822
        """See Branch.set_push_location."""
 
2823
        self._set_config_location('push_location', location)
 
2824
 
 
2825
    def set_bound_location(self, location):
 
2826
        """See Branch.set_push_location."""
 
2827
        self._master_branch_cache = None
 
2828
        result = None
 
2829
        conf = self.get_config_stack()
 
2830
        if location is None:
 
2831
            if not conf.get('bound'):
 
2832
                return False
 
2833
            else:
 
2834
                conf.set('bound', 'False')
 
2835
                return True
 
2836
        else:
 
2837
            self._set_config_location('bound_location', location,
 
2838
                                      config=conf)
 
2839
            conf.set('bound', 'True')
 
2840
        return True
 
2841
 
 
2842
    def _get_bound_location(self, bound):
 
2843
        """Return the bound location in the config file.
 
2844
 
 
2845
        Return None if the bound parameter does not match"""
 
2846
        conf = self.get_config_stack()
 
2847
        if conf.get('bound') != bound:
 
2848
            return None
 
2849
        return self._get_config_location('bound_location', config=conf)
 
2850
 
 
2851
    def get_bound_location(self):
 
2852
        """See Branch.get_bound_location."""
 
2853
        return self._get_bound_location(True)
 
2854
 
 
2855
    def get_old_bound_location(self):
 
2856
        """See Branch.get_old_bound_location"""
 
2857
        return self._get_bound_location(False)
 
2858
 
 
2859
    def get_stacked_on_url(self):
 
2860
        # you can always ask for the URL; but you might not be able to use it
 
2861
        # if the repo can't support stacking.
 
2862
        ## self._check_stackable_repo()
 
2863
        # stacked_on_location is only ever defined in branch.conf, so don't
 
2864
        # waste effort reading the whole stack of config files.
 
2865
        conf = _mod_config.BranchOnlyStack(self)
 
2866
        stacked_url = self._get_config_location('stacked_on_location',
 
2867
                                                config=conf)
 
2868
        if stacked_url is None:
 
2869
            raise errors.NotStacked(self)
 
2870
        return stacked_url.encode('utf-8')
 
2871
 
 
2872
    @needs_read_lock
 
2873
    def get_rev_id(self, revno, history=None):
 
2874
        """Find the revision id of the specified revno."""
 
2875
        if revno == 0:
 
2876
            return _mod_revision.NULL_REVISION
 
2877
 
 
2878
        last_revno, last_revision_id = self.last_revision_info()
 
2879
        if revno <= 0 or revno > last_revno:
 
2880
            raise errors.NoSuchRevision(self, revno)
 
2881
 
 
2882
        if history is not None:
 
2883
            return history[revno - 1]
 
2884
 
 
2885
        index = last_revno - revno
 
2886
        if len(self._partial_revision_history_cache) <= index:
 
2887
            self._extend_partial_history(stop_index=index)
 
2888
        if len(self._partial_revision_history_cache) > index:
 
2889
            return self._partial_revision_history_cache[index]
 
2890
        else:
 
2891
            raise errors.NoSuchRevision(self, revno)
 
2892
 
 
2893
    @needs_read_lock
 
2894
    def revision_id_to_revno(self, revision_id):
 
2895
        """Given a revision id, return its revno"""
 
2896
        if _mod_revision.is_null(revision_id):
 
2897
            return 0
 
2898
        try:
 
2899
            index = self._partial_revision_history_cache.index(revision_id)
 
2900
        except ValueError:
 
2901
            try:
 
2902
                self._extend_partial_history(stop_revision=revision_id)
 
2903
            except errors.RevisionNotPresent, e:
 
2904
                raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
 
2905
            index = len(self._partial_revision_history_cache) - 1
 
2906
            if index < 0:
 
2907
                raise errors.NoSuchRevision(self, revision_id)
 
2908
            if self._partial_revision_history_cache[index] != revision_id:
 
2909
                raise errors.NoSuchRevision(self, revision_id)
 
2910
        return self.revno() - index
 
2911
 
 
2912
 
 
2913
class BzrBranch7(BzrBranch8):
 
2914
    """A branch with support for a fallback repository."""
 
2915
 
 
2916
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2917
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
 
2918
 
 
2919
    def get_reference_info(self, file_id):
 
2920
        Branch.get_reference_info(self, file_id)
 
2921
 
 
2922
    def reference_parent(self, file_id, path, possible_transports=None):
 
2923
        return Branch.reference_parent(self, file_id, path,
 
2924
                                       possible_transports)
 
2925
 
 
2926
 
 
2927
class BzrBranch6(BzrBranch7):
 
2928
    """See BzrBranchFormat6 for the capabilities of this branch.
 
2929
 
 
2930
    This subclass of BzrBranch7 disables the new features BzrBranch7 added,
 
2931
    i.e. stacking.
 
2932
    """
 
2933
 
 
2934
    def get_stacked_on_url(self):
 
2935
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
1919
2936
 
1920
2937
 
1921
2938
######################################################################
2025
3042
            note(gettext('found error:%s'), error)
2026
3043
 
2027
3044
 
 
3045
class Converter5to6(object):
 
3046
    """Perform an in-place upgrade of format 5 to format 6"""
 
3047
 
 
3048
    def convert(self, branch):
 
3049
        # Data for 5 and 6 can peacefully coexist.
 
3050
        format = BzrBranchFormat6()
 
3051
        new_branch = format.open(branch.bzrdir, _found=True)
 
3052
 
 
3053
        # Copy source data into target
 
3054
        new_branch._write_last_revision_info(*branch.last_revision_info())
 
3055
        new_branch.lock_write()
 
3056
        try:
 
3057
            new_branch.set_parent(branch.get_parent())
 
3058
            new_branch.set_bound_location(branch.get_bound_location())
 
3059
            new_branch.set_push_location(branch.get_push_location())
 
3060
        finally:
 
3061
            new_branch.unlock()
 
3062
 
 
3063
        # New branch has no tags by default
 
3064
        new_branch.tags._set_tag_dict({})
 
3065
 
 
3066
        # Copying done; now update target format
 
3067
        new_branch._transport.put_bytes('format',
 
3068
            format.as_string(),
 
3069
            mode=new_branch.bzrdir._get_file_mode())
 
3070
 
 
3071
        # Clean up old files
 
3072
        new_branch._transport.delete('revision-history')
 
3073
        branch.lock_write()
 
3074
        try:
 
3075
            try:
 
3076
                branch.set_parent(None)
 
3077
            except errors.NoSuchFile:
 
3078
                pass
 
3079
            branch.set_bound_location(None)
 
3080
        finally:
 
3081
            branch.unlock()
 
3082
 
 
3083
 
 
3084
class Converter6to7(object):
 
3085
    """Perform an in-place upgrade of format 6 to format 7"""
 
3086
 
 
3087
    def convert(self, branch):
 
3088
        format = BzrBranchFormat7()
 
3089
        branch._set_config_location('stacked_on_location', '')
 
3090
        # update target format
 
3091
        branch._transport.put_bytes('format', format.as_string())
 
3092
 
 
3093
 
 
3094
class Converter7to8(object):
 
3095
    """Perform an in-place upgrade of format 7 to format 8"""
 
3096
 
 
3097
    def convert(self, branch):
 
3098
        format = BzrBranchFormat8()
 
3099
        branch._transport.put_bytes('references', '')
 
3100
        # update target format
 
3101
        branch._transport.put_bytes('format', format.as_string())
 
3102
 
 
3103
 
2028
3104
class InterBranch(InterObject):
2029
3105
    """This class represents operations taking place between two branches.
2030
3106
 
2046
3122
        """
2047
3123
        raise NotImplementedError(klass._get_branch_formats_to_test)
2048
3124
 
 
3125
    @needs_write_lock
2049
3126
    def pull(self, overwrite=False, stop_revision=None,
2050
3127
             possible_transports=None, local=False):
2051
3128
        """Mirror source into target branch.
2056
3133
        """
2057
3134
        raise NotImplementedError(self.pull)
2058
3135
 
 
3136
    @needs_write_lock
2059
3137
    def push(self, overwrite=False, stop_revision=None, lossy=False,
2060
3138
             _override_hook_source_branch=None):
2061
3139
        """Mirror the source branch into the target branch.
2064
3142
        """
2065
3143
        raise NotImplementedError(self.push)
2066
3144
 
 
3145
    @needs_write_lock
2067
3146
    def copy_content_into(self, revision_id=None):
2068
3147
        """Copy the content of source into target
2069
3148
 
2072
3151
        """
2073
3152
        raise NotImplementedError(self.copy_content_into)
2074
3153
 
 
3154
    @needs_write_lock
2075
3155
    def fetch(self, stop_revision=None, limit=None):
2076
3156
        """Fetch revisions.
2077
3157
 
2109
3189
            return format._custom_format
2110
3190
        return format
2111
3191
 
 
3192
    @needs_write_lock
2112
3193
    def copy_content_into(self, revision_id=None):
2113
3194
        """Copy the content of source into target
2114
3195
 
2115
3196
        revision_id: if not None, the revision history in the new branch will
2116
3197
                     be truncated to end with revision_id.
2117
3198
        """
2118
 
        with self.source.lock_read(), self.target.lock_write():
2119
 
            self.source.update_references(self.target)
2120
 
            self.source._synchronize_history(self.target, revision_id)
2121
 
            try:
2122
 
                parent = self.source.get_parent()
2123
 
            except errors.InaccessibleParent as e:
2124
 
                mutter('parent was not accessible to copy: %s', e)
2125
 
            else:
2126
 
                if parent:
2127
 
                    self.target.set_parent(parent)
2128
 
            if self.source._push_should_merge_tags():
2129
 
                self.source.tags.merge_to(self.target.tags)
 
3199
        self.source.update_references(self.target)
 
3200
        self.source._synchronize_history(self.target, revision_id)
 
3201
        try:
 
3202
            parent = self.source.get_parent()
 
3203
        except errors.InaccessibleParent, e:
 
3204
            mutter('parent was not accessible to copy: %s', e)
 
3205
        else:
 
3206
            if parent:
 
3207
                self.target.set_parent(parent)
 
3208
        if self.source._push_should_merge_tags():
 
3209
            self.source.tags.merge_to(self.target.tags)
2130
3210
 
 
3211
    @needs_write_lock
2131
3212
    def fetch(self, stop_revision=None, limit=None):
2132
3213
        if self.target.base == self.source.base:
2133
3214
            return (0, [])
2134
 
        with self.source.lock_read(), self.target.lock_write():
 
3215
        self.source.lock_read()
 
3216
        try:
2135
3217
            fetch_spec_factory = fetch.FetchSpecFactory()
2136
3218
            fetch_spec_factory.source_branch = self.source
2137
3219
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
2140
3222
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
2141
3223
            fetch_spec_factory.limit = limit
2142
3224
            fetch_spec = fetch_spec_factory.make_fetch_spec()
2143
 
            return self.target.repository.fetch(
2144
 
                    self.source.repository,
2145
 
                    fetch_spec=fetch_spec)
 
3225
            return self.target.repository.fetch(self.source.repository,
 
3226
                fetch_spec=fetch_spec)
 
3227
        finally:
 
3228
            self.source.unlock()
2146
3229
 
 
3230
    @needs_write_lock
2147
3231
    def _update_revisions(self, stop_revision=None, overwrite=False,
2148
3232
            graph=None):
2149
 
        with self.source.lock_read(), self.target.lock_write():
2150
 
            other_revno, other_last_revision = self.source.last_revision_info()
2151
 
            stop_revno = None # unknown
2152
 
            if stop_revision is None:
2153
 
                stop_revision = other_last_revision
2154
 
                if _mod_revision.is_null(stop_revision):
2155
 
                    # if there are no commits, we're done.
2156
 
                    return
2157
 
                stop_revno = other_revno
2158
 
 
2159
 
            # what's the current last revision, before we fetch [and change it
2160
 
            # possibly]
2161
 
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
2162
 
            # we fetch here so that we don't process data twice in the common
2163
 
            # case of having something to pull, and so that the check for
2164
 
            # already merged can operate on the just fetched graph, which will
2165
 
            # be cached in memory.
2166
 
            self.fetch(stop_revision=stop_revision)
2167
 
            # Check to see if one is an ancestor of the other
2168
 
            if not overwrite:
2169
 
                if graph is None:
2170
 
                    graph = self.target.repository.get_graph()
2171
 
                if self.target._check_if_descendant_or_diverged(
2172
 
                        stop_revision, last_rev, graph, self.source):
2173
 
                    # stop_revision is a descendant of last_rev, but we aren't
2174
 
                    # overwriting, so we're done.
2175
 
                    return
2176
 
            if stop_revno is None:
2177
 
                if graph is None:
2178
 
                    graph = self.target.repository.get_graph()
2179
 
                this_revno, this_last_revision = \
2180
 
                        self.target.last_revision_info()
2181
 
                stop_revno = graph.find_distance_to_null(stop_revision,
2182
 
                                [(other_last_revision, other_revno),
2183
 
                                 (this_last_revision, this_revno)])
2184
 
            self.target.set_last_revision_info(stop_revno, stop_revision)
2185
 
 
 
3233
        other_revno, other_last_revision = self.source.last_revision_info()
 
3234
        stop_revno = None # unknown
 
3235
        if stop_revision is None:
 
3236
            stop_revision = other_last_revision
 
3237
            if _mod_revision.is_null(stop_revision):
 
3238
                # if there are no commits, we're done.
 
3239
                return
 
3240
            stop_revno = other_revno
 
3241
 
 
3242
        # what's the current last revision, before we fetch [and change it
 
3243
        # possibly]
 
3244
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3245
        # we fetch here so that we don't process data twice in the common
 
3246
        # case of having something to pull, and so that the check for
 
3247
        # already merged can operate on the just fetched graph, which will
 
3248
        # be cached in memory.
 
3249
        self.fetch(stop_revision=stop_revision)
 
3250
        # Check to see if one is an ancestor of the other
 
3251
        if not overwrite:
 
3252
            if graph is None:
 
3253
                graph = self.target.repository.get_graph()
 
3254
            if self.target._check_if_descendant_or_diverged(
 
3255
                    stop_revision, last_rev, graph, self.source):
 
3256
                # stop_revision is a descendant of last_rev, but we aren't
 
3257
                # overwriting, so we're done.
 
3258
                return
 
3259
        if stop_revno is None:
 
3260
            if graph is None:
 
3261
                graph = self.target.repository.get_graph()
 
3262
            this_revno, this_last_revision = \
 
3263
                    self.target.last_revision_info()
 
3264
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3265
                            [(other_last_revision, other_revno),
 
3266
                             (this_last_revision, this_revno)])
 
3267
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3268
 
 
3269
    @needs_write_lock
2186
3270
    def pull(self, overwrite=False, stop_revision=None,
2187
3271
             possible_transports=None, run_hooks=True,
2188
3272
             _override_hook_target=None, local=False):
2192
3276
            is being called because it's the master of the primary branch,
2193
3277
            so it should not run its hooks.
2194
3278
        """
2195
 
        with self.target.lock_write():
2196
 
            bound_location = self.target.get_bound_location()
2197
 
            if local and not bound_location:
2198
 
                raise errors.LocalRequiresBoundBranch()
2199
 
            master_branch = None
2200
 
            source_is_master = False
2201
 
            if bound_location:
2202
 
                # bound_location comes from a config file, some care has to be
2203
 
                # taken to relate it to source.user_url
2204
 
                normalized = urlutils.normalize_url(bound_location)
2205
 
                try:
2206
 
                    relpath = self.source.user_transport.relpath(normalized)
2207
 
                    source_is_master = (relpath == '')
2208
 
                except (errors.PathNotChild, urlutils.InvalidURL):
2209
 
                    source_is_master = False
2210
 
            if not local and bound_location and not source_is_master:
2211
 
                # not pulling from master, so we need to update master.
2212
 
                master_branch = self.target.get_master_branch(possible_transports)
2213
 
                master_branch.lock_write()
 
3279
        bound_location = self.target.get_bound_location()
 
3280
        if local and not bound_location:
 
3281
            raise errors.LocalRequiresBoundBranch()
 
3282
        master_branch = None
 
3283
        source_is_master = False
 
3284
        if bound_location:
 
3285
            # bound_location comes from a config file, some care has to be
 
3286
            # taken to relate it to source.user_url
 
3287
            normalized = urlutils.normalize_url(bound_location)
2214
3288
            try:
2215
 
                if master_branch:
2216
 
                    # pull from source into master.
2217
 
                    master_branch.pull(self.source, overwrite, stop_revision,
2218
 
                        run_hooks=False)
2219
 
                return self._pull(overwrite,
2220
 
                    stop_revision, _hook_master=master_branch,
2221
 
                    run_hooks=run_hooks,
2222
 
                    _override_hook_target=_override_hook_target,
2223
 
                    merge_tags_to_master=not source_is_master)
2224
 
            finally:
2225
 
                if master_branch:
2226
 
                    master_branch.unlock()
 
3289
                relpath = self.source.user_transport.relpath(normalized)
 
3290
                source_is_master = (relpath == '')
 
3291
            except (errors.PathNotChild, errors.InvalidURL):
 
3292
                source_is_master = False
 
3293
        if not local and bound_location and not source_is_master:
 
3294
            # not pulling from master, so we need to update master.
 
3295
            master_branch = self.target.get_master_branch(possible_transports)
 
3296
            master_branch.lock_write()
 
3297
        try:
 
3298
            if master_branch:
 
3299
                # pull from source into master.
 
3300
                master_branch.pull(self.source, overwrite, stop_revision,
 
3301
                    run_hooks=False)
 
3302
            return self._pull(overwrite,
 
3303
                stop_revision, _hook_master=master_branch,
 
3304
                run_hooks=run_hooks,
 
3305
                _override_hook_target=_override_hook_target,
 
3306
                merge_tags_to_master=not source_is_master)
 
3307
        finally:
 
3308
            if master_branch:
 
3309
                master_branch.unlock()
2227
3310
 
2228
3311
    def push(self, overwrite=False, stop_revision=None, lossy=False,
2229
3312
             _override_hook_source_branch=None):
2341
3424
            result.target_branch = self.target
2342
3425
        else:
2343
3426
            result.target_branch = _override_hook_target
2344
 
        with self.source.lock_read():
 
3427
        self.source.lock_read()
 
3428
        try:
2345
3429
            # We assume that during 'pull' the target repository is closer than
2346
3430
            # the source one.
2347
3431
            self.source.update_references(self.target)
2372
3456
            if run_hooks:
2373
3457
                for hook in Branch.hooks['post_pull']:
2374
3458
                    hook(result)
2375
 
            return result
 
3459
        finally:
 
3460
            self.source.unlock()
 
3461
        return result
2376
3462
 
2377
3463
 
2378
3464
InterBranch.register_optimiser(GenericInterBranch)