~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Andrew Bennetts
  • Date: 2009-04-02 05:53:12 UTC
  • mto: This revision was merged to the branch mainline in revision 4242.
  • Revision ID: andrew.bennetts@canonical.com-20090402055312-h7mvgumvm7e620mj
Fix nits in spelling and naming.

Show diffs side-by-side

added added

removed removed

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