~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Andrew Bennetts
  • Date: 2010-06-25 06:47:40 UTC
  • mto: (5050.3.16 2.2)
  • mto: This revision was merged to the branch mainline in revision 5365.
  • Revision ID: andrew.bennetts@canonical.com-20100625064740-k93ngat248kdcqdm
Remove merge_into_helper for now, as it currently has no callers.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
 
1
# Copyright (C) 2005-2010 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
 
 
17
 
 
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
 
 
18
from cStringIO import StringIO
18
19
import sys
19
20
 
20
21
from bzrlib.lazy_import import lazy_import
28
29
        errors,
29
30
        lockdir,
30
31
        lockable_files,
 
32
        remote,
31
33
        repository,
32
34
        revision as _mod_revision,
 
35
        rio,
 
36
        symbol_versioning,
33
37
        transport,
34
38
        tsort,
35
39
        ui,
36
40
        urlutils,
37
41
        )
38
 
from bzrlib.config import BranchConfig
 
42
from bzrlib.config import BranchConfig, TransportConfig
39
43
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
40
44
from bzrlib.tag import (
41
45
    BasicTags,
43
47
    )
44
48
""")
45
49
 
46
 
from bzrlib.decorators import needs_read_lock, needs_write_lock
47
 
from bzrlib.hooks import Hooks
 
50
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
 
51
from bzrlib.hooks import HookPoint, Hooks
 
52
from bzrlib.inter import InterObject
 
53
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
 
54
from bzrlib import registry
48
55
from bzrlib.symbol_versioning import (
49
56
    deprecated_in,
50
57
    deprecated_method,
57
64
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
58
65
 
59
66
 
60
 
# TODO: Maybe include checks for common corruption of newlines, etc?
61
 
 
62
 
# TODO: Some operations like log might retrieve the same revisions
63
 
# repeatedly to calculate deltas.  We could perhaps have a weakref
64
 
# cache in memory to make this faster.  In general anything can be
65
 
# cached in memory between lock and unlock operations. .. nb thats
66
 
# what the transaction identity map provides
67
 
 
68
 
 
69
 
######################################################################
70
 
# branch objects
71
 
 
72
 
class Branch(object):
 
67
class Branch(bzrdir.ControlComponent):
73
68
    """Branch holding a history of revisions.
74
69
 
75
 
    base
76
 
        Base directory/url of the branch.
 
70
    :ivar base:
 
71
        Base directory/url of the branch; using control_url and
 
72
        control_transport is more standardized.
77
73
 
78
74
    hooks: An instance of BranchHooks.
79
75
    """
81
77
    # - RBC 20060112
82
78
    base = None
83
79
 
84
 
    # override this to set the strategy for storing tags
85
 
    def _make_tags(self):
86
 
        return DisabledTags(self)
 
80
    @property
 
81
    def control_transport(self):
 
82
        return self._transport
 
83
 
 
84
    @property
 
85
    def user_transport(self):
 
86
        return self.bzrdir.user_transport
87
87
 
88
88
    def __init__(self, *ignored, **ignored_too):
89
 
        self.tags = self._make_tags()
 
89
        self.tags = self._format.make_tags(self)
90
90
        self._revision_history_cache = None
91
91
        self._revision_id_to_revno_cache = None
92
92
        self._partial_revision_id_to_revno_cache = {}
 
93
        self._partial_revision_history_cache = []
93
94
        self._last_revision_info_cache = None
94
95
        self._merge_sorted_revisions_cache = None
95
96
        self._open_hook()
100
101
    def _open_hook(self):
101
102
        """Called by init to allow simpler extension of the base class."""
102
103
 
 
104
    def _activate_fallback_location(self, url):
 
105
        """Activate the branch/repository from url as a fallback repository."""
 
106
        repo = self._get_fallback_repository(url)
 
107
        if repo.has_same_location(self.repository):
 
108
            raise errors.UnstackableLocationError(self.user_url, url)
 
109
        self.repository.add_fallback_repository(repo)
 
110
 
103
111
    def break_lock(self):
104
112
        """Break a lock if one is present from another instance.
105
113
 
114
122
        if master is not None:
115
123
            master.break_lock()
116
124
 
 
125
    def _check_stackable_repo(self):
 
126
        if not self.repository._format.supports_external_lookups:
 
127
            raise errors.UnstackableRepositoryFormat(self.repository._format,
 
128
                self.repository.base)
 
129
 
 
130
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
131
        """Extend the partial history to include a given index
 
132
 
 
133
        If a stop_index is supplied, stop when that index has been reached.
 
134
        If a stop_revision is supplied, stop when that revision is
 
135
        encountered.  Otherwise, stop when the beginning of history is
 
136
        reached.
 
137
 
 
138
        :param stop_index: The index which should be present.  When it is
 
139
            present, history extension will stop.
 
140
        :param stop_revision: The revision id which should be present.  When
 
141
            it is encountered, history extension will stop.
 
142
        """
 
143
        if len(self._partial_revision_history_cache) == 0:
 
144
            self._partial_revision_history_cache = [self.last_revision()]
 
145
        repository._iter_for_revno(
 
146
            self.repository, self._partial_revision_history_cache,
 
147
            stop_index=stop_index, stop_revision=stop_revision)
 
148
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
 
149
            self._partial_revision_history_cache.pop()
 
150
 
 
151
    def _get_check_refs(self):
 
152
        """Get the references needed for check().
 
153
 
 
154
        See bzrlib.check.
 
155
        """
 
156
        revid = self.last_revision()
 
157
        return [('revision-existence', revid), ('lefthand-distance', revid)]
 
158
 
117
159
    @staticmethod
118
160
    def open(base, _unsupported=False, possible_transports=None):
119
161
        """Open the branch rooted at base.
123
165
        """
124
166
        control = bzrdir.BzrDir.open(base, _unsupported,
125
167
                                     possible_transports=possible_transports)
126
 
        return control.open_branch(_unsupported)
 
168
        return control.open_branch(unsupported=_unsupported)
127
169
 
128
170
    @staticmethod
129
 
    def open_from_transport(transport, _unsupported=False):
 
171
    def open_from_transport(transport, name=None, _unsupported=False):
130
172
        """Open the branch rooted at transport"""
131
173
        control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
132
 
        return control.open_branch(_unsupported)
 
174
        return control.open_branch(name=name, unsupported=_unsupported)
133
175
 
134
176
    @staticmethod
135
177
    def open_containing(url, possible_transports=None):
136
178
        """Open an existing branch which contains url.
137
 
        
 
179
 
138
180
        This probes for a branch at url, and searches upwards from there.
139
181
 
140
182
        Basically we keep looking up until we find the control directory or
141
183
        run into the root.  If there isn't one, raises NotBranchError.
142
 
        If there is one and it is either an unrecognised format or an unsupported 
 
184
        If there is one and it is either an unrecognised format or an unsupported
143
185
        format, UnknownFormatError or UnsupportedFormatError are raised.
144
186
        If there is one, it is returned, along with the unused portion of url.
145
187
        """
147
189
                                                         possible_transports)
148
190
        return control.open_branch(), relpath
149
191
 
 
192
    def _push_should_merge_tags(self):
 
193
        """Should _basic_push merge this branch's tags into the target?
 
194
 
 
195
        The default implementation returns False if this branch has no tags,
 
196
        and True the rest of the time.  Subclasses may override this.
 
197
        """
 
198
        return self.supports_tags() and self.tags.get_tag_dict()
 
199
 
150
200
    def get_config(self):
 
201
        """Get a bzrlib.config.BranchConfig for this Branch.
 
202
 
 
203
        This can then be used to get and set configuration options for the
 
204
        branch.
 
205
 
 
206
        :return: A bzrlib.config.BranchConfig.
 
207
        """
151
208
        return BranchConfig(self)
152
209
 
 
210
    def _get_config(self):
 
211
        """Get the concrete config for just the config in this branch.
 
212
 
 
213
        This is not intended for client use; see Branch.get_config for the
 
214
        public API.
 
215
 
 
216
        Added in 1.14.
 
217
 
 
218
        :return: An object supporting get_option and set_option.
 
219
        """
 
220
        raise NotImplementedError(self._get_config)
 
221
 
 
222
    def _get_fallback_repository(self, url):
 
223
        """Get the repository we fallback to at url."""
 
224
        url = urlutils.join(self.base, url)
 
225
        a_branch = Branch.open(url,
 
226
            possible_transports=[self.bzrdir.root_transport])
 
227
        return a_branch.repository
 
228
 
 
229
    def _get_tags_bytes(self):
 
230
        """Get the bytes of a serialised tags dict.
 
231
 
 
232
        Note that not all branches support tags, nor do all use the same tags
 
233
        logic: this method is specific to BasicTags. Other tag implementations
 
234
        may use the same method name and behave differently, safely, because
 
235
        of the double-dispatch via
 
236
        format.make_tags->tags_instance->get_tags_dict.
 
237
 
 
238
        :return: The bytes of the tags file.
 
239
        :seealso: Branch._set_tags_bytes.
 
240
        """
 
241
        return self._transport.get_bytes('tags')
 
242
 
153
243
    def _get_nick(self, local=False, possible_transports=None):
154
244
        config = self.get_config()
155
245
        # explicit overrides master, but don't look for master if local is True
174
264
    def is_locked(self):
175
265
        raise NotImplementedError(self.is_locked)
176
266
 
177
 
    def lock_write(self):
 
267
    def _lefthand_history(self, revision_id, last_rev=None,
 
268
                          other_branch=None):
 
269
        if 'evil' in debug.debug_flags:
 
270
            mutter_callsite(4, "_lefthand_history scales with history.")
 
271
        # stop_revision must be a descendant of last_revision
 
272
        graph = self.repository.get_graph()
 
273
        if last_rev is not None:
 
274
            if not graph.is_ancestor(last_rev, revision_id):
 
275
                # our previous tip is not merged into stop_revision
 
276
                raise errors.DivergedBranches(self, other_branch)
 
277
        # make a new revision history from the graph
 
278
        parents_map = graph.get_parent_map([revision_id])
 
279
        if revision_id not in parents_map:
 
280
            raise errors.NoSuchRevision(self, revision_id)
 
281
        current_rev_id = revision_id
 
282
        new_history = []
 
283
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
284
        # Do not include ghosts or graph origin in revision_history
 
285
        while (current_rev_id in parents_map and
 
286
               len(parents_map[current_rev_id]) > 0):
 
287
            check_not_reserved_id(current_rev_id)
 
288
            new_history.append(current_rev_id)
 
289
            current_rev_id = parents_map[current_rev_id][0]
 
290
            parents_map = graph.get_parent_map([current_rev_id])
 
291
        new_history.reverse()
 
292
        return new_history
 
293
 
 
294
    def lock_write(self, token=None):
 
295
        """Lock the branch for write operations.
 
296
 
 
297
        :param token: A token to permit reacquiring a previously held and
 
298
            preserved lock.
 
299
        :return: A BranchWriteLockResult.
 
300
        """
178
301
        raise NotImplementedError(self.lock_write)
179
302
 
180
303
    def lock_read(self):
 
304
        """Lock the branch for read operations.
 
305
 
 
306
        :return: A bzrlib.lock.LogicalLockResult.
 
307
        """
181
308
        raise NotImplementedError(self.lock_read)
182
309
 
183
310
    def unlock(self):
228
355
    @needs_read_lock
229
356
    def revision_id_to_dotted_revno(self, revision_id):
230
357
        """Given a revision id, return its dotted revno.
231
 
        
 
358
 
232
359
        :return: a tuple like (1,) or (400,1,3).
233
360
        """
234
361
        return self._do_revision_id_to_dotted_revno(revision_id)
308
435
            * 'include' - the stop revision is the last item in the result
309
436
            * 'with-merges' - include the stop revision and all of its
310
437
              merged revisions in the result
 
438
            * 'with-merges-without-common-ancestry' - filter out revisions 
 
439
              that are in both ancestries
311
440
        :param direction: either 'reverse' or 'forward':
312
441
            * reverse means return the start_revision_id first, i.e.
313
442
              start at the most recent revision and go backwards in history
335
464
        # start_revision_id.
336
465
        if self._merge_sorted_revisions_cache is None:
337
466
            last_revision = self.last_revision()
338
 
            graph = self.repository.get_graph()
339
 
            parent_map = dict(((key, value) for key, value in
340
 
                     graph.iter_ancestry([last_revision]) if value is not None))
341
 
            revision_graph = repository._strip_NULL_ghosts(parent_map)
342
 
            revs = tsort.merge_sort(revision_graph, last_revision, None,
343
 
                generate_revno=True)
344
 
            # Drop the sequence # before caching
345
 
            self._merge_sorted_revisions_cache = [r[1:] for r in revs]
346
 
 
 
467
            known_graph = self.repository.get_known_graph_ancestry(
 
468
                [last_revision])
 
469
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
 
470
                last_revision)
347
471
        filtered = self._filter_merge_sorted_revisions(
348
472
            self._merge_sorted_revisions_cache, start_revision_id,
349
473
            stop_revision_id, stop_rule)
 
474
        # Make sure we don't return revisions that are not part of the
 
475
        # start_revision_id ancestry.
 
476
        filtered = self._filter_start_non_ancestors(filtered)
350
477
        if direction == 'reverse':
351
478
            return filtered
352
479
        if direction == 'forward':
359
486
        """Iterate over an inclusive range of sorted revisions."""
360
487
        rev_iter = iter(merge_sorted_revisions)
361
488
        if start_revision_id is not None:
362
 
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
489
            for node in rev_iter:
 
490
                rev_id = node.key[-1]
363
491
                if rev_id != start_revision_id:
364
492
                    continue
365
493
                else:
366
494
                    # The decision to include the start or not
367
495
                    # depends on the stop_rule if a stop is provided
368
 
                    rev_iter = chain(
369
 
                        iter([(rev_id, depth, revno, end_of_merge)]),
370
 
                        rev_iter)
 
496
                    # so pop this node back into the iterator
 
497
                    rev_iter = chain(iter([node]), rev_iter)
371
498
                    break
372
499
        if stop_revision_id is None:
373
 
            for rev_id, depth, revno, end_of_merge in rev_iter:
374
 
                yield rev_id, depth, revno, end_of_merge
 
500
            # Yield everything
 
501
            for node in rev_iter:
 
502
                rev_id = node.key[-1]
 
503
                yield (rev_id, node.merge_depth, node.revno,
 
504
                       node.end_of_merge)
375
505
        elif stop_rule == 'exclude':
376
 
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
506
            for node in rev_iter:
 
507
                rev_id = node.key[-1]
377
508
                if rev_id == stop_revision_id:
378
509
                    return
379
 
                yield rev_id, depth, revno, end_of_merge
 
510
                yield (rev_id, node.merge_depth, node.revno,
 
511
                       node.end_of_merge)
380
512
        elif stop_rule == 'include':
381
 
            for rev_id, depth, revno, end_of_merge in rev_iter:
382
 
                yield rev_id, depth, revno, end_of_merge
 
513
            for node in rev_iter:
 
514
                rev_id = node.key[-1]
 
515
                yield (rev_id, node.merge_depth, node.revno,
 
516
                       node.end_of_merge)
383
517
                if rev_id == stop_revision_id:
384
518
                    return
 
519
        elif stop_rule == 'with-merges-without-common-ancestry':
 
520
            # We want to exclude all revisions that are already part of the
 
521
            # stop_revision_id ancestry.
 
522
            graph = self.repository.get_graph()
 
523
            ancestors = graph.find_unique_ancestors(start_revision_id,
 
524
                                                    [stop_revision_id])
 
525
            for node in rev_iter:
 
526
                rev_id = node.key[-1]
 
527
                if rev_id not in ancestors:
 
528
                    continue
 
529
                yield (rev_id, node.merge_depth, node.revno,
 
530
                       node.end_of_merge)
385
531
        elif stop_rule == 'with-merges':
386
532
            stop_rev = self.repository.get_revision(stop_revision_id)
387
533
            if stop_rev.parent_ids:
388
534
                left_parent = stop_rev.parent_ids[0]
389
535
            else:
390
536
                left_parent = _mod_revision.NULL_REVISION
391
 
            for rev_id, depth, revno, end_of_merge in rev_iter:
 
537
            # left_parent is the actual revision we want to stop logging at,
 
538
            # since we want to show the merged revisions after the stop_rev too
 
539
            reached_stop_revision_id = False
 
540
            revision_id_whitelist = []
 
541
            for node in rev_iter:
 
542
                rev_id = node.key[-1]
392
543
                if rev_id == left_parent:
 
544
                    # reached the left parent after the stop_revision
393
545
                    return
394
 
                yield rev_id, depth, revno, end_of_merge
 
546
                if (not reached_stop_revision_id or
 
547
                        rev_id in revision_id_whitelist):
 
548
                    yield (rev_id, node.merge_depth, node.revno,
 
549
                       node.end_of_merge)
 
550
                    if reached_stop_revision_id or rev_id == stop_revision_id:
 
551
                        # only do the merged revs of rev_id from now on
 
552
                        rev = self.repository.get_revision(rev_id)
 
553
                        if rev.parent_ids:
 
554
                            reached_stop_revision_id = True
 
555
                            revision_id_whitelist.extend(rev.parent_ids)
395
556
        else:
396
557
            raise ValueError('invalid stop_rule %r' % stop_rule)
397
558
 
 
559
    def _filter_start_non_ancestors(self, rev_iter):
 
560
        # If we started from a dotted revno, we want to consider it as a tip
 
561
        # and don't want to yield revisions that are not part of its
 
562
        # ancestry. Given the order guaranteed by the merge sort, we will see
 
563
        # uninteresting descendants of the first parent of our tip before the
 
564
        # tip itself.
 
565
        first = rev_iter.next()
 
566
        (rev_id, merge_depth, revno, end_of_merge) = first
 
567
        yield first
 
568
        if not merge_depth:
 
569
            # We start at a mainline revision so by definition, all others
 
570
            # revisions in rev_iter are ancestors
 
571
            for node in rev_iter:
 
572
                yield node
 
573
 
 
574
        clean = False
 
575
        whitelist = set()
 
576
        pmap = self.repository.get_parent_map([rev_id])
 
577
        parents = pmap.get(rev_id, [])
 
578
        if parents:
 
579
            whitelist.update(parents)
 
580
        else:
 
581
            # If there is no parents, there is nothing of interest left
 
582
 
 
583
            # FIXME: It's hard to test this scenario here as this code is never
 
584
            # called in that case. -- vila 20100322
 
585
            return
 
586
 
 
587
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
 
588
            if not clean:
 
589
                if rev_id in whitelist:
 
590
                    pmap = self.repository.get_parent_map([rev_id])
 
591
                    parents = pmap.get(rev_id, [])
 
592
                    whitelist.remove(rev_id)
 
593
                    whitelist.update(parents)
 
594
                    if merge_depth == 0:
 
595
                        # We've reached the mainline, there is nothing left to
 
596
                        # filter
 
597
                        clean = True
 
598
                else:
 
599
                    # A revision that is not part of the ancestry of our
 
600
                    # starting revision.
 
601
                    continue
 
602
            yield (rev_id, merge_depth, revno, end_of_merge)
 
603
 
398
604
    def leave_lock_in_place(self):
399
605
        """Tell this branch object not to release the physical lock when this
400
606
        object is unlocked.
401
 
        
 
607
 
402
608
        If lock_write doesn't return a token, then this method is not supported.
403
609
        """
404
610
        self.control_files.leave_in_place()
417
623
        :param other: The branch to bind to
418
624
        :type other: Branch
419
625
        """
420
 
        raise errors.UpgradeRequired(self.base)
 
626
        raise errors.UpgradeRequired(self.user_url)
 
627
 
 
628
    def set_append_revisions_only(self, enabled):
 
629
        if not self._format.supports_set_append_revisions_only():
 
630
            raise errors.UpgradeRequired(self.user_url)
 
631
        if enabled:
 
632
            value = 'True'
 
633
        else:
 
634
            value = 'False'
 
635
        self.get_config().set_user_option('append_revisions_only', value,
 
636
            warn_masked=True)
 
637
 
 
638
    def set_reference_info(self, file_id, tree_path, branch_location):
 
639
        """Set the branch location to use for a tree reference."""
 
640
        raise errors.UnsupportedOperation(self.set_reference_info, self)
 
641
 
 
642
    def get_reference_info(self, file_id):
 
643
        """Get the tree_path and branch_location for a tree reference."""
 
644
        raise errors.UnsupportedOperation(self.get_reference_info, self)
421
645
 
422
646
    @needs_write_lock
423
647
    def fetch(self, from_branch, last_revision=None, pb=None):
427
651
        :param last_revision: What revision to stop at (None for at the end
428
652
                              of the branch.
429
653
        :param pb: An optional progress bar to use.
430
 
 
431
 
        Returns the copied revision count and the failed revisions in a tuple:
432
 
        (copied, failures).
 
654
        :return: None
433
655
        """
434
656
        if self.base == from_branch.base:
435
657
            return (0, [])
436
 
        if pb is None:
437
 
            nested_pb = ui.ui_factory.nested_progress_bar()
438
 
            pb = nested_pb
439
 
        else:
440
 
            nested_pb = None
441
 
 
 
658
        if pb is not None:
 
659
            symbol_versioning.warn(
 
660
                symbol_versioning.deprecated_in((1, 14, 0))
 
661
                % "pb parameter to fetch()")
442
662
        from_branch.lock_read()
443
663
        try:
444
664
            if last_revision is None:
445
 
                pb.update('get source history')
446
665
                last_revision = from_branch.last_revision()
447
666
                last_revision = _mod_revision.ensure_null(last_revision)
448
667
            return self.repository.fetch(from_branch.repository,
449
668
                                         revision_id=last_revision,
450
 
                                         pb=nested_pb)
 
669
                                         pb=pb)
451
670
        finally:
452
 
            if nested_pb is not None:
453
 
                nested_pb.finished()
454
671
            from_branch.unlock()
455
672
 
456
673
    def get_bound_location(self):
460
677
        branch.
461
678
        """
462
679
        return None
463
 
    
 
680
 
464
681
    def get_old_bound_location(self):
465
682
        """Return the URL of the branch we used to be bound to
466
683
        """
467
 
        raise errors.UpgradeRequired(self.base)
 
684
        raise errors.UpgradeRequired(self.user_url)
468
685
 
469
 
    def get_commit_builder(self, parents, config=None, timestamp=None, 
470
 
                           timezone=None, committer=None, revprops=None, 
 
686
    def get_commit_builder(self, parents, config=None, timestamp=None,
 
687
                           timezone=None, committer=None, revprops=None,
471
688
                           revision_id=None):
472
689
        """Obtain a CommitBuilder for this branch.
473
 
        
 
690
 
474
691
        :param parents: Revision ids of the parents of the new revision.
475
692
        :param config: Optional configuration to use.
476
693
        :param timestamp: Optional timestamp recorded for commit.
482
699
 
483
700
        if config is None:
484
701
            config = self.get_config()
485
 
        
 
702
 
486
703
        return self.repository.get_commit_builder(self, parents, config,
487
704
            timestamp, timezone, committer, revprops, revision_id)
488
705
 
489
706
    def get_master_branch(self, possible_transports=None):
490
707
        """Return the branch we are bound to.
491
 
        
 
708
 
492
709
        :return: Either a Branch, or None
493
710
        """
494
711
        return None
520
737
    def set_revision_history(self, rev_history):
521
738
        raise NotImplementedError(self.set_revision_history)
522
739
 
 
740
    @needs_write_lock
 
741
    def set_parent(self, url):
 
742
        """See Branch.set_parent."""
 
743
        # TODO: Maybe delete old location files?
 
744
        # URLs should never be unicode, even on the local fs,
 
745
        # FIXUP this and get_parent in a future branch format bump:
 
746
        # read and rewrite the file. RBC 20060125
 
747
        if url is not None:
 
748
            if isinstance(url, unicode):
 
749
                try:
 
750
                    url = url.encode('ascii')
 
751
                except UnicodeEncodeError:
 
752
                    raise errors.InvalidURL(url,
 
753
                        "Urls must be 7-bit ascii, "
 
754
                        "use bzrlib.urlutils.escape")
 
755
            url = urlutils.relative_url(self.base, url)
 
756
        self._set_parent_location(url)
 
757
 
 
758
    @needs_write_lock
523
759
    def set_stacked_on_url(self, url):
524
760
        """Set the URL this branch is stacked against.
525
761
 
528
764
        :raises UnstackableRepositoryFormat: If the repository does not support
529
765
            stacking.
530
766
        """
531
 
        raise NotImplementedError(self.set_stacked_on_url)
 
767
        if not self._format.supports_stacking():
 
768
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
769
        # XXX: Changing from one fallback repository to another does not check
 
770
        # that all the data you need is present in the new fallback.
 
771
        # Possibly it should.
 
772
        self._check_stackable_repo()
 
773
        if not url:
 
774
            try:
 
775
                old_url = self.get_stacked_on_url()
 
776
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
777
                errors.UnstackableRepositoryFormat):
 
778
                return
 
779
            self._unstack()
 
780
        else:
 
781
            self._activate_fallback_location(url)
 
782
        # write this out after the repository is stacked to avoid setting a
 
783
        # stacked config that doesn't work.
 
784
        self._set_config_location('stacked_on_location', url)
 
785
 
 
786
    def _unstack(self):
 
787
        """Change a branch to be unstacked, copying data as needed.
 
788
        
 
789
        Don't call this directly, use set_stacked_on_url(None).
 
790
        """
 
791
        pb = ui.ui_factory.nested_progress_bar()
 
792
        try:
 
793
            pb.update("Unstacking")
 
794
            # The basic approach here is to fetch the tip of the branch,
 
795
            # including all available ghosts, from the existing stacked
 
796
            # repository into a new repository object without the fallbacks. 
 
797
            #
 
798
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
 
799
            # correct for CHKMap repostiories
 
800
            old_repository = self.repository
 
801
            if len(old_repository._fallback_repositories) != 1:
 
802
                raise AssertionError("can't cope with fallback repositories "
 
803
                    "of %r" % (self.repository,))
 
804
            # unlock it, including unlocking the fallback
 
805
            old_repository.unlock()
 
806
            old_repository.lock_read()
 
807
            try:
 
808
                # Repositories don't offer an interface to remove fallback
 
809
                # repositories today; take the conceptually simpler option and just
 
810
                # reopen it.  We reopen it starting from the URL so that we
 
811
                # get a separate connection for RemoteRepositories and can
 
812
                # stream from one of them to the other.  This does mean doing
 
813
                # separate SSH connection setup, but unstacking is not a
 
814
                # common operation so it's tolerable.
 
815
                new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
 
816
                new_repository = new_bzrdir.find_repository()
 
817
                self.repository = new_repository
 
818
                if self.repository._fallback_repositories:
 
819
                    raise AssertionError("didn't expect %r to have "
 
820
                        "fallback_repositories"
 
821
                        % (self.repository,))
 
822
                # this is not paired with an unlock because it's just restoring
 
823
                # the previous state; the lock's released when set_stacked_on_url
 
824
                # returns
 
825
                self.repository.lock_write()
 
826
                # XXX: If you unstack a branch while it has a working tree
 
827
                # with a pending merge, the pending-merged revisions will no
 
828
                # longer be present.  You can (probably) revert and remerge.
 
829
                #
 
830
                # XXX: This only fetches up to the tip of the repository; it
 
831
                # doesn't bring across any tags.  That's fairly consistent
 
832
                # with how branch works, but perhaps not ideal.
 
833
                self.repository.fetch(old_repository,
 
834
                    revision_id=self.last_revision(),
 
835
                    find_ghosts=True)
 
836
            finally:
 
837
                old_repository.unlock()
 
838
        finally:
 
839
            pb.finished()
 
840
 
 
841
    def _set_tags_bytes(self, bytes):
 
842
        """Mirror method for _get_tags_bytes.
 
843
 
 
844
        :seealso: Branch._get_tags_bytes.
 
845
        """
 
846
        return _run_with_write_locked_target(self, self._transport.put_bytes,
 
847
            'tags', bytes)
532
848
 
533
849
    def _cache_revision_history(self, rev_history):
534
850
        """Set the cached revision history to rev_history.
562
878
        self._revision_id_to_revno_cache = None
563
879
        self._last_revision_info_cache = None
564
880
        self._merge_sorted_revisions_cache = None
 
881
        self._partial_revision_history_cache = []
 
882
        self._partial_revision_id_to_revno_cache = {}
565
883
 
566
884
    def _gen_revision_history(self):
567
885
        """Return sequence of revision hashes on to this branch.
568
 
        
 
886
 
569
887
        Unlike revision_history, this method always regenerates or rereads the
570
888
        revision history, i.e. it does not cache the result, so repeated calls
571
889
        may be expensive.
572
890
 
573
891
        Concrete subclasses should override this instead of revision_history so
574
892
        that subclasses do not need to deal with caching logic.
575
 
        
 
893
 
576
894
        This API is semi-public; it only for use by subclasses, all other code
577
895
        should consider it to be private.
578
896
        """
581
899
    @needs_read_lock
582
900
    def revision_history(self):
583
901
        """Return sequence of revision ids on this branch.
584
 
        
 
902
 
585
903
        This method will cache the revision history for as long as it is safe to
586
904
        do so.
587
905
        """
604
922
 
605
923
    def unbind(self):
606
924
        """Older format branches cannot bind or unbind."""
607
 
        raise errors.UpgradeRequired(self.base)
608
 
 
609
 
    def set_append_revisions_only(self, enabled):
610
 
        """Older format branches are never restricted to append-only"""
611
 
        raise errors.UpgradeRequired(self.base)
 
925
        raise errors.UpgradeRequired(self.user_url)
612
926
 
613
927
    def last_revision(self):
614
928
        """Return last revision id, or NULL_REVISION."""
635
949
    @deprecated_method(deprecated_in((1, 6, 0)))
636
950
    def missing_revisions(self, other, stop_revision=None):
637
951
        """Return a list of new revisions that would perfectly fit.
638
 
        
 
952
 
639
953
        If self and other have not diverged, return a list of the revisions
640
954
        present in other, but missing from self.
641
955
        """
655
969
                raise errors.NoSuchRevision(self, stop_revision)
656
970
        return other_history[self_len:stop_revision]
657
971
 
658
 
    @needs_write_lock
659
972
    def update_revisions(self, other, stop_revision=None, overwrite=False,
660
973
                         graph=None):
661
974
        """Pull in new perfect-fit revisions.
668
981
            information. This can be None.
669
982
        :return: None
670
983
        """
671
 
        other.lock_read()
672
 
        try:
673
 
            other_revno, other_last_revision = other.last_revision_info()
674
 
            stop_revno = None # unknown
675
 
            if stop_revision is None:
676
 
                stop_revision = other_last_revision
677
 
                if _mod_revision.is_null(stop_revision):
678
 
                    # if there are no commits, we're done.
679
 
                    return
680
 
                stop_revno = other_revno
681
 
 
682
 
            # what's the current last revision, before we fetch [and change it
683
 
            # possibly]
684
 
            last_rev = _mod_revision.ensure_null(self.last_revision())
685
 
            # we fetch here so that we don't process data twice in the common
686
 
            # case of having something to pull, and so that the check for 
687
 
            # already merged can operate on the just fetched graph, which will
688
 
            # be cached in memory.
689
 
            self.fetch(other, stop_revision)
690
 
            # Check to see if one is an ancestor of the other
691
 
            if not overwrite:
692
 
                if graph is None:
693
 
                    graph = self.repository.get_graph()
694
 
                if self._check_if_descendant_or_diverged(
695
 
                        stop_revision, last_rev, graph, other):
696
 
                    # stop_revision is a descendant of last_rev, but we aren't
697
 
                    # overwriting, so we're done.
698
 
                    return
699
 
            if stop_revno is None:
700
 
                if graph is None:
701
 
                    graph = self.repository.get_graph()
702
 
                this_revno, this_last_revision = self.last_revision_info()
703
 
                stop_revno = graph.find_distance_to_null(stop_revision,
704
 
                                [(other_last_revision, other_revno),
705
 
                                 (this_last_revision, this_revno)])
706
 
            self.set_last_revision_info(stop_revno, stop_revision)
707
 
        finally:
708
 
            other.unlock()
 
984
        return InterBranch.get(other, self).update_revisions(stop_revision,
 
985
            overwrite, graph)
 
986
 
 
987
    def import_last_revision_info(self, source_repo, revno, revid):
 
988
        """Set the last revision info, importing from another repo if necessary.
 
989
 
 
990
        This is used by the bound branch code to upload a revision to
 
991
        the master branch first before updating the tip of the local branch.
 
992
 
 
993
        :param source_repo: Source repository to optionally fetch from
 
994
        :param revno: Revision number of the new tip
 
995
        :param revid: Revision id of the new tip
 
996
        """
 
997
        if not self.repository.has_same_location(source_repo):
 
998
            self.repository.fetch(source_repo, revision_id=revid)
 
999
        self.set_last_revision_info(revno, revid)
709
1000
 
710
1001
    def revision_id_to_revno(self, revision_id):
711
1002
        """Given a revision id, return its revno"""
717
1008
        except ValueError:
718
1009
            raise errors.NoSuchRevision(self, revision_id)
719
1010
 
 
1011
    @needs_read_lock
720
1012
    def get_rev_id(self, revno, history=None):
721
1013
        """Find the revision id of the specified revno."""
722
1014
        if revno == 0:
723
1015
            return _mod_revision.NULL_REVISION
724
 
        if history is None:
725
 
            history = self.revision_history()
726
 
        if revno <= 0 or revno > len(history):
 
1016
        last_revno, last_revid = self.last_revision_info()
 
1017
        if revno == last_revno:
 
1018
            return last_revid
 
1019
        if revno <= 0 or revno > last_revno:
727
1020
            raise errors.NoSuchRevision(self, revno)
728
 
        return history[revno - 1]
 
1021
        distance_from_last = last_revno - revno
 
1022
        if len(self._partial_revision_history_cache) <= distance_from_last:
 
1023
            self._extend_partial_history(distance_from_last)
 
1024
        return self._partial_revision_history_cache[distance_from_last]
729
1025
 
 
1026
    @needs_write_lock
730
1027
    def pull(self, source, overwrite=False, stop_revision=None,
731
 
             possible_transports=None, _override_hook_target=None):
 
1028
             possible_transports=None, *args, **kwargs):
732
1029
        """Mirror source into this branch.
733
1030
 
734
1031
        This branch is considered to be 'local', having low latency.
735
1032
 
736
1033
        :returns: PullResult instance
737
1034
        """
738
 
        raise NotImplementedError(self.pull)
 
1035
        return InterBranch.get(source, self).pull(overwrite=overwrite,
 
1036
            stop_revision=stop_revision,
 
1037
            possible_transports=possible_transports, *args, **kwargs)
739
1038
 
740
 
    def push(self, target, overwrite=False, stop_revision=None):
 
1039
    def push(self, target, overwrite=False, stop_revision=None, *args,
 
1040
        **kwargs):
741
1041
        """Mirror this branch into target.
742
1042
 
743
1043
        This branch is considered to be 'local', having low latency.
744
1044
        """
745
 
        raise NotImplementedError(self.push)
 
1045
        return InterBranch.get(self, target).push(overwrite, stop_revision,
 
1046
            *args, **kwargs)
 
1047
 
 
1048
    def lossy_push(self, target, stop_revision=None):
 
1049
        """Push deltas into another branch.
 
1050
 
 
1051
        :note: This does not, like push, retain the revision ids from 
 
1052
            the source branch and will, rather than adding bzr-specific 
 
1053
            metadata, push only those semantics of the revision that can be 
 
1054
            natively represented by this branch' VCS.
 
1055
 
 
1056
        :param target: Target branch
 
1057
        :param stop_revision: Revision to push, defaults to last revision.
 
1058
        :return: BranchPushResult with an extra member revidmap: 
 
1059
            A dictionary mapping revision ids from the target branch 
 
1060
            to new revision ids in the target branch, for each 
 
1061
            revision that was pushed.
 
1062
        """
 
1063
        inter = InterBranch.get(self, target)
 
1064
        lossy_push = getattr(inter, "lossy_push", None)
 
1065
        if lossy_push is None:
 
1066
            raise errors.LossyPushToSameVCS(self, target)
 
1067
        return lossy_push(stop_revision)
746
1068
 
747
1069
    def basis_tree(self):
748
1070
        """Return `Tree` object for last revision."""
751
1073
    def get_parent(self):
752
1074
        """Return the parent location of the branch.
753
1075
 
754
 
        This is the default location for push/pull/missing.  The usual
 
1076
        This is the default location for pull/missing.  The usual
755
1077
        pattern is that the user can override it by specifying a
756
1078
        location.
757
1079
        """
758
 
        raise NotImplementedError(self.get_parent)
 
1080
        parent = self._get_parent_location()
 
1081
        if parent is None:
 
1082
            return parent
 
1083
        # This is an old-format absolute path to a local branch
 
1084
        # turn it into a url
 
1085
        if parent.startswith('/'):
 
1086
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1087
        try:
 
1088
            return urlutils.join(self.base[:-1], parent)
 
1089
        except errors.InvalidURLJoin, e:
 
1090
            raise errors.InaccessibleParent(parent, self.user_url)
 
1091
 
 
1092
    def _get_parent_location(self):
 
1093
        raise NotImplementedError(self._get_parent_location)
759
1094
 
760
1095
    def _set_config_location(self, name, url, config=None,
761
1096
                             make_relative=False):
775
1110
            location = None
776
1111
        return location
777
1112
 
 
1113
    def get_child_submit_format(self):
 
1114
        """Return the preferred format of submissions to this branch."""
 
1115
        return self.get_config().get_user_option("child_submit_format")
 
1116
 
778
1117
    def get_submit_branch(self):
779
1118
        """Return the submit location of the branch.
780
1119
 
797
1136
    def get_public_branch(self):
798
1137
        """Return the public location of the branch.
799
1138
 
800
 
        This is is used by merge directives.
 
1139
        This is used by merge directives.
801
1140
        """
802
1141
        return self._get_config_location('public_branch')
803
1142
 
819
1158
        """Set a new push location for this branch."""
820
1159
        raise NotImplementedError(self.set_push_location)
821
1160
 
822
 
    def set_parent(self, url):
823
 
        raise NotImplementedError(self.set_parent)
 
1161
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
 
1162
        """Run the post_change_branch_tip hooks."""
 
1163
        hooks = Branch.hooks['post_change_branch_tip']
 
1164
        if not hooks:
 
1165
            return
 
1166
        new_revno, new_revid = self.last_revision_info()
 
1167
        params = ChangeBranchTipParams(
 
1168
            self, old_revno, new_revno, old_revid, new_revid)
 
1169
        for hook in hooks:
 
1170
            hook(params)
 
1171
 
 
1172
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
 
1173
        """Run the pre_change_branch_tip hooks."""
 
1174
        hooks = Branch.hooks['pre_change_branch_tip']
 
1175
        if not hooks:
 
1176
            return
 
1177
        old_revno, old_revid = self.last_revision_info()
 
1178
        params = ChangeBranchTipParams(
 
1179
            self, old_revno, new_revno, old_revid, new_revid)
 
1180
        for hook in hooks:
 
1181
            hook(params)
824
1182
 
825
1183
    @needs_write_lock
826
1184
    def update(self):
827
 
        """Synchronise this branch with the master branch if any. 
 
1185
        """Synchronise this branch with the master branch if any.
828
1186
 
829
1187
        :return: None or the last_revision pivoted out during the update.
830
1188
        """
837
1195
        """
838
1196
        if revno != 0:
839
1197
            self.check_real_revno(revno)
840
 
            
 
1198
 
841
1199
    def check_real_revno(self, revno):
842
1200
        """\
843
1201
        Check whether a revno corresponds to a real revision.
847
1205
            raise errors.InvalidRevisionNumber(revno)
848
1206
 
849
1207
    @needs_read_lock
850
 
    def clone(self, to_bzrdir, revision_id=None):
 
1208
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
851
1209
        """Clone this branch into to_bzrdir preserving all semantic values.
852
 
        
 
1210
 
 
1211
        Most API users will want 'create_clone_on_transport', which creates a
 
1212
        new bzrdir and branch on the fly.
 
1213
 
853
1214
        revision_id: if not None, the revision history in the new branch will
854
1215
                     be truncated to end with revision_id.
855
1216
        """
856
1217
        result = to_bzrdir.create_branch()
857
 
        self.copy_content_into(result, revision_id=revision_id)
858
 
        return  result
 
1218
        result.lock_write()
 
1219
        try:
 
1220
            if repository_policy is not None:
 
1221
                repository_policy.configure_branch(result)
 
1222
            self.copy_content_into(result, revision_id=revision_id)
 
1223
        finally:
 
1224
            result.unlock()
 
1225
        return result
859
1226
 
860
1227
    @needs_read_lock
861
 
    def sprout(self, to_bzrdir, revision_id=None):
 
1228
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
862
1229
        """Create a new line of development from the branch, into to_bzrdir.
863
1230
 
864
1231
        to_bzrdir controls the branch format.
866
1233
        revision_id: if not None, the revision history in the new branch will
867
1234
                     be truncated to end with revision_id.
868
1235
        """
 
1236
        if (repository_policy is not None and
 
1237
            repository_policy.requires_stacking()):
 
1238
            to_bzrdir._format.require_stacking(_skip_repo=True)
869
1239
        result = to_bzrdir.create_branch()
870
 
        self.copy_content_into(result, revision_id=revision_id)
871
 
        result.set_parent(self.bzrdir.root_transport.base)
 
1240
        result.lock_write()
 
1241
        try:
 
1242
            if repository_policy is not None:
 
1243
                repository_policy.configure_branch(result)
 
1244
            self.copy_content_into(result, revision_id=revision_id)
 
1245
            result.set_parent(self.bzrdir.root_transport.base)
 
1246
        finally:
 
1247
            result.unlock()
872
1248
        return result
873
1249
 
874
1250
    def _synchronize_history(self, destination, revision_id):
886
1262
        source_revno, source_revision_id = self.last_revision_info()
887
1263
        if revision_id is None:
888
1264
            revno, revision_id = source_revno, source_revision_id
889
 
        elif source_revision_id == revision_id:
890
 
            # we know the revno without needing to walk all of history
891
 
            revno = source_revno
892
1265
        else:
893
 
            # To figure out the revno for a random revision, we need to build
894
 
            # the revision history, and count its length.
895
 
            # We don't care about the order, just how long it is.
896
 
            # Alternatively, we could start at the current location, and count
897
 
            # backwards. But there is no guarantee that we will find it since
898
 
            # it may be a merged revision.
899
 
            revno = len(list(self.repository.iter_reverse_revision_history(
900
 
                                                                revision_id)))
 
1266
            graph = self.repository.get_graph()
 
1267
            try:
 
1268
                revno = graph.find_distance_to_null(revision_id, 
 
1269
                    [(source_revision_id, source_revno)])
 
1270
            except errors.GhostRevisionsHaveNoRevno:
 
1271
                # Default to 1, if we can't find anything else
 
1272
                revno = 1
901
1273
        destination.set_last_revision_info(revno, revision_id)
902
 
    
903
 
    @needs_read_lock
 
1274
 
904
1275
    def copy_content_into(self, destination, revision_id=None):
905
1276
        """Copy the content of self into destination.
906
1277
 
907
1278
        revision_id: if not None, the revision history in the new branch will
908
1279
                     be truncated to end with revision_id.
909
1280
        """
910
 
        self._synchronize_history(destination, revision_id)
911
 
        try:
912
 
            parent = self.get_parent()
913
 
        except errors.InaccessibleParent, e:
914
 
            mutter('parent was not accessible to copy: %s', e)
915
 
        else:
916
 
            if parent:
917
 
                destination.set_parent(parent)
918
 
        self.tags.merge_to(destination.tags)
 
1281
        return InterBranch.get(self, destination).copy_content_into(
 
1282
            revision_id=revision_id)
 
1283
 
 
1284
    def update_references(self, target):
 
1285
        if not getattr(self._format, 'supports_reference_locations', False):
 
1286
            return
 
1287
        reference_dict = self._get_all_reference_info()
 
1288
        if len(reference_dict) == 0:
 
1289
            return
 
1290
        old_base = self.base
 
1291
        new_base = target.base
 
1292
        target_reference_dict = target._get_all_reference_info()
 
1293
        for file_id, (tree_path, branch_location) in (
 
1294
            reference_dict.items()):
 
1295
            branch_location = urlutils.rebase_url(branch_location,
 
1296
                                                  old_base, new_base)
 
1297
            target_reference_dict.setdefault(
 
1298
                file_id, (tree_path, branch_location))
 
1299
        target._set_all_reference_info(target_reference_dict)
919
1300
 
920
1301
    @needs_read_lock
921
 
    def check(self):
 
1302
    def check(self, refs):
922
1303
        """Check consistency of the branch.
923
1304
 
924
1305
        In particular this checks that revisions given in the revision-history
925
 
        do actually match up in the revision graph, and that they're all 
 
1306
        do actually match up in the revision graph, and that they're all
926
1307
        present in the repository.
927
 
        
 
1308
 
928
1309
        Callers will typically also want to check the repository.
929
1310
 
 
1311
        :param refs: Calculated refs for this branch as specified by
 
1312
            branch._get_check_refs()
930
1313
        :return: A BranchCheckResult.
931
1314
        """
932
 
        mainline_parent_id = None
 
1315
        result = BranchCheckResult(self)
933
1316
        last_revno, last_revision_id = self.last_revision_info()
934
 
        real_rev_history = list(self.repository.iter_reverse_revision_history(
935
 
                                last_revision_id))
936
 
        real_rev_history.reverse()
937
 
        if len(real_rev_history) != last_revno:
938
 
            raise errors.BzrCheckError('revno does not match len(mainline)'
939
 
                ' %s != %s' % (last_revno, len(real_rev_history)))
940
 
        # TODO: We should probably also check that real_rev_history actually
941
 
        #       matches self.revision_history()
942
 
        for revision_id in real_rev_history:
943
 
            try:
944
 
                revision = self.repository.get_revision(revision_id)
945
 
            except errors.NoSuchRevision, e:
946
 
                raise errors.BzrCheckError("mainline revision {%s} not in repository"
947
 
                            % revision_id)
948
 
            # In general the first entry on the revision history has no parents.
949
 
            # But it's not illegal for it to have parents listed; this can happen
950
 
            # in imports from Arch when the parents weren't reachable.
951
 
            if mainline_parent_id is not None:
952
 
                if mainline_parent_id not in revision.parent_ids:
953
 
                    raise errors.BzrCheckError("previous revision {%s} not listed among "
954
 
                                        "parents of {%s}"
955
 
                                        % (mainline_parent_id, revision_id))
956
 
            mainline_parent_id = revision_id
957
 
        return BranchCheckResult(self)
 
1317
        actual_revno = refs[('lefthand-distance', last_revision_id)]
 
1318
        if actual_revno != last_revno:
 
1319
            result.errors.append(errors.BzrCheckError(
 
1320
                'revno does not match len(mainline) %s != %s' % (
 
1321
                last_revno, actual_revno)))
 
1322
        # TODO: We should probably also check that self.revision_history
 
1323
        # matches the repository for older branch formats.
 
1324
        # If looking for the code that cross-checks repository parents against
 
1325
        # the iter_reverse_revision_history output, that is now a repository
 
1326
        # specific check.
 
1327
        return result
958
1328
 
959
1329
    def _get_checkout_format(self):
960
1330
        """Return the most suitable metadir for a checkout of this branch.
969
1339
            format.set_branch_format(self._format)
970
1340
        return format
971
1341
 
 
1342
    def create_clone_on_transport(self, to_transport, revision_id=None,
 
1343
        stacked_on=None, create_prefix=False, use_existing_dir=False):
 
1344
        """Create a clone of this branch and its bzrdir.
 
1345
 
 
1346
        :param to_transport: The transport to clone onto.
 
1347
        :param revision_id: The revision id to use as tip in the new branch.
 
1348
            If None the tip is obtained from this branch.
 
1349
        :param stacked_on: An optional URL to stack the clone on.
 
1350
        :param create_prefix: Create any missing directories leading up to
 
1351
            to_transport.
 
1352
        :param use_existing_dir: Use an existing directory if one exists.
 
1353
        """
 
1354
        # XXX: Fix the bzrdir API to allow getting the branch back from the
 
1355
        # clone call. Or something. 20090224 RBC/spiv.
 
1356
        # XXX: Should this perhaps clone colocated branches as well, 
 
1357
        # rather than just the default branch? 20100319 JRV
 
1358
        if revision_id is None:
 
1359
            revision_id = self.last_revision()
 
1360
        dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1361
            revision_id=revision_id, stacked_on=stacked_on,
 
1362
            create_prefix=create_prefix, use_existing_dir=use_existing_dir)
 
1363
        return dir_to.open_branch()
 
1364
 
972
1365
    def create_checkout(self, to_location, revision_id=None,
973
1366
                        lightweight=False, accelerator_tree=None,
974
1367
                        hardlink=False):
975
1368
        """Create a checkout of a branch.
976
 
        
 
1369
 
977
1370
        :param to_location: The url to produce the checkout at
978
1371
        :param revision_id: The revision to check out
979
1372
        :param lightweight: If True, produce a lightweight checkout, otherwise,
991
1384
        if lightweight:
992
1385
            format = self._get_checkout_format()
993
1386
            checkout = format.initialize_on_transport(t)
994
 
            from_branch = BranchReferenceFormat().initialize(checkout, self)
 
1387
            from_branch = BranchReferenceFormat().initialize(checkout, 
 
1388
                target_branch=self)
995
1389
        else:
996
1390
            format = self._get_checkout_format()
997
1391
            checkout_branch = bzrdir.BzrDir.create_branch_convenience(
998
1392
                to_location, force_new_tree=False, format=format)
999
1393
            checkout = checkout_branch.bzrdir
1000
1394
            checkout_branch.bind(self)
1001
 
            # pull up to the specified revision_id to set the initial 
 
1395
            # pull up to the specified revision_id to set the initial
1002
1396
            # branch tip correctly, and seed it with history.
1003
1397
            checkout_branch.pull(self, stop_revision=revision_id)
1004
1398
            from_branch=None
1026
1420
        reconciler.reconcile()
1027
1421
        return reconciler
1028
1422
 
1029
 
    def reference_parent(self, file_id, path):
 
1423
    def reference_parent(self, file_id, path, possible_transports=None):
1030
1424
        """Return the parent branch for a tree-reference file_id
1031
1425
        :param file_id: The file_id of the tree reference
1032
1426
        :param path: The path of the file_id in the tree
1033
1427
        :return: A branch associated with the file_id
1034
1428
        """
1035
1429
        # FIXME should provide multiple branches, based on config
1036
 
        return Branch.open(self.bzrdir.root_transport.clone(path).base)
 
1430
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
 
1431
                           possible_transports=possible_transports)
1037
1432
 
1038
1433
    def supports_tags(self):
1039
1434
        return self._format.supports_tags()
1040
1435
 
 
1436
    def automatic_tag_name(self, revision_id):
 
1437
        """Try to automatically find the tag name for a revision.
 
1438
 
 
1439
        :param revision_id: Revision id of the revision.
 
1440
        :return: A tag name or None if no tag name could be determined.
 
1441
        """
 
1442
        for hook in Branch.hooks['automatic_tag_name']:
 
1443
            ret = hook(self, revision_id)
 
1444
            if ret is not None:
 
1445
                return ret
 
1446
        return None
 
1447
 
1041
1448
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1042
1449
                                         other_branch):
1043
1450
        """Ensure that revision_b is a descendant of revision_a.
1044
1451
 
1045
1452
        This is a helper function for update_revisions.
1046
 
        
 
1453
 
1047
1454
        :raises: DivergedBranches if revision_b has diverged from revision_a.
1048
1455
        :returns: True if revision_b is a descendant of revision_a.
1049
1456
        """
1059
1466
 
1060
1467
    def _revision_relations(self, revision_a, revision_b, graph):
1061
1468
        """Determine the relationship between two revisions.
1062
 
        
 
1469
 
1063
1470
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1064
1471
        """
1065
1472
        heads = graph.heads([revision_a, revision_b])
1082
1489
     * a format string,
1083
1490
     * an open routine.
1084
1491
 
1085
 
    Formats are placed in an dict by their format string for reference 
 
1492
    Formats are placed in an dict by their format string for reference
1086
1493
    during branch opening. Its not required that these be instances, they
1087
 
    can be classes themselves with class methods - it simply depends on 
 
1494
    can be classes themselves with class methods - it simply depends on
1088
1495
    whether state is needed for a given format or not.
1089
1496
 
1090
1497
    Once a format is deprecated, just deprecate the initialize and open
1091
 
    methods on the format class. Do not deprecate the object, as the 
 
1498
    methods on the format class. Do not deprecate the object, as the
1092
1499
    object will be created every time regardless.
1093
1500
    """
1094
1501
 
1098
1505
    _formats = {}
1099
1506
    """The known formats."""
1100
1507
 
 
1508
    can_set_append_revisions_only = True
 
1509
 
1101
1510
    def __eq__(self, other):
1102
1511
        return self.__class__ is other.__class__
1103
1512
 
1105
1514
        return not (self == other)
1106
1515
 
1107
1516
    @classmethod
1108
 
    def find_format(klass, a_bzrdir):
 
1517
    def find_format(klass, a_bzrdir, name=None):
1109
1518
        """Return the format for the branch object in a_bzrdir."""
1110
1519
        try:
1111
 
            transport = a_bzrdir.get_branch_transport(None)
1112
 
            format_string = transport.get("format").read()
 
1520
            transport = a_bzrdir.get_branch_transport(None, name=name)
 
1521
            format_string = transport.get_bytes("format")
1113
1522
            return klass._formats[format_string]
1114
1523
        except errors.NoSuchFile:
1115
 
            raise errors.NotBranchError(path=transport.base)
 
1524
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1116
1525
        except KeyError:
1117
1526
            raise errors.UnknownFormatError(format=format_string, kind='branch')
1118
1527
 
1121
1530
        """Return the current default format."""
1122
1531
        return klass._default_format
1123
1532
 
1124
 
    def get_reference(self, a_bzrdir):
 
1533
    def get_reference(self, a_bzrdir, name=None):
1125
1534
        """Get the target reference of the branch in a_bzrdir.
1126
1535
 
1127
1536
        format probing must have been completed before calling
1129
1538
        in a_bzrdir is correct.
1130
1539
 
1131
1540
        :param a_bzrdir: The bzrdir to get the branch data from.
 
1541
        :param name: Name of the colocated branch to fetch
1132
1542
        :return: None if the branch is not a reference branch.
1133
1543
        """
1134
1544
        return None
1135
1545
 
1136
1546
    @classmethod
1137
 
    def set_reference(self, a_bzrdir, to_branch):
 
1547
    def set_reference(self, a_bzrdir, name, to_branch):
1138
1548
        """Set the target reference of the branch in a_bzrdir.
1139
1549
 
1140
1550
        format probing must have been completed before calling
1142
1552
        in a_bzrdir is correct.
1143
1553
 
1144
1554
        :param a_bzrdir: The bzrdir to set the branch reference for.
 
1555
        :param name: Name of colocated branch to set, None for default
1145
1556
        :param to_branch: branch that the checkout is to reference
1146
1557
        """
1147
1558
        raise NotImplementedError(self.set_reference)
1154
1565
        """Return the short format description for this format."""
1155
1566
        raise NotImplementedError(self.get_format_description)
1156
1567
 
1157
 
    def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1158
 
                           set_format=True):
 
1568
    def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
 
1569
        hooks = Branch.hooks['post_branch_init']
 
1570
        if not hooks:
 
1571
            return
 
1572
        params = BranchInitHookParams(self, a_bzrdir, name, branch)
 
1573
        for hook in hooks:
 
1574
            hook(params)
 
1575
 
 
1576
    def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
 
1577
                           lock_type='metadir', set_format=True):
1159
1578
        """Initialize a branch in a bzrdir, with specified files
1160
1579
 
1161
1580
        :param a_bzrdir: The bzrdir to initialize the branch in
1162
1581
        :param utf8_files: The files to create as a list of
1163
1582
            (filename, content) tuples
 
1583
        :param name: Name of colocated branch to create, if any
1164
1584
        :param set_format: If True, set the format with
1165
1585
            self.get_format_string.  (BzrBranch4 has its format set
1166
1586
            elsewhere)
1167
1587
        :return: a branch in this format
1168
1588
        """
1169
 
        mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1170
 
        branch_transport = a_bzrdir.get_branch_transport(self)
 
1589
        mutter('creating branch %r in %s', self, a_bzrdir.user_url)
 
1590
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1171
1591
        lock_map = {
1172
1592
            'metadir': ('lock', lockdir.LockDir),
1173
1593
            'branch4': ('branch-lock', lockable_files.TransportLock),
1176
1596
        control_files = lockable_files.LockableFiles(branch_transport,
1177
1597
            lock_name, lock_class)
1178
1598
        control_files.create_lock()
1179
 
        control_files.lock_write()
 
1599
        try:
 
1600
            control_files.lock_write()
 
1601
        except errors.LockContention:
 
1602
            if lock_type != 'branch4':
 
1603
                raise
 
1604
            lock_taken = False
 
1605
        else:
 
1606
            lock_taken = True
1180
1607
        if set_format:
1181
1608
            utf8_files += [('format', self.get_format_string())]
1182
1609
        try:
1185
1612
                    filename, content,
1186
1613
                    mode=a_bzrdir._get_file_mode())
1187
1614
        finally:
1188
 
            control_files.unlock()
1189
 
        return self.open(a_bzrdir, _found=True)
 
1615
            if lock_taken:
 
1616
                control_files.unlock()
 
1617
        branch = self.open(a_bzrdir, name, _found=True)
 
1618
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
1619
        return branch
1190
1620
 
1191
 
    def initialize(self, a_bzrdir):
1192
 
        """Create a branch of this format in a_bzrdir."""
 
1621
    def initialize(self, a_bzrdir, name=None):
 
1622
        """Create a branch of this format in a_bzrdir.
 
1623
        
 
1624
        :param name: Name of the colocated branch to create.
 
1625
        """
1193
1626
        raise NotImplementedError(self.initialize)
1194
1627
 
1195
1628
    def is_supported(self):
1196
1629
        """Is this format supported?
1197
1630
 
1198
1631
        Supported formats can be initialized and opened.
1199
 
        Unsupported formats may not support initialization or committing or 
 
1632
        Unsupported formats may not support initialization or committing or
1200
1633
        some other features depending on the reason for not being supported.
1201
1634
        """
1202
1635
        return True
1203
1636
 
1204
 
    def open(self, a_bzrdir, _found=False):
 
1637
    def make_tags(self, branch):
 
1638
        """Create a tags object for branch.
 
1639
 
 
1640
        This method is on BranchFormat, because BranchFormats are reflected
 
1641
        over the wire via network_name(), whereas full Branch instances require
 
1642
        multiple VFS method calls to operate at all.
 
1643
 
 
1644
        The default implementation returns a disabled-tags instance.
 
1645
 
 
1646
        Note that it is normal for branch to be a RemoteBranch when using tags
 
1647
        on a RemoteBranch.
 
1648
        """
 
1649
        return DisabledTags(branch)
 
1650
 
 
1651
    def network_name(self):
 
1652
        """A simple byte string uniquely identifying this format for RPC calls.
 
1653
 
 
1654
        MetaDir branch formats use their disk format string to identify the
 
1655
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1656
        foreign formats like svn/git and hg should use some marker which is
 
1657
        unique and immutable.
 
1658
        """
 
1659
        raise NotImplementedError(self.network_name)
 
1660
 
 
1661
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1205
1662
        """Return the branch object for a_bzrdir
1206
1663
 
1207
 
        _found is a private parameter, do not use it. It is used to indicate
1208
 
               if format probing has already be done.
 
1664
        :param a_bzrdir: A BzrDir that contains a branch.
 
1665
        :param name: Name of colocated branch to open
 
1666
        :param _found: a private parameter, do not use it. It is used to
 
1667
            indicate if format probing has already be done.
 
1668
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1669
            (if there are any).  Default is to open fallbacks.
1209
1670
        """
1210
1671
        raise NotImplementedError(self.open)
1211
1672
 
1212
1673
    @classmethod
1213
1674
    def register_format(klass, format):
 
1675
        """Register a metadir format."""
1214
1676
        klass._formats[format.get_format_string()] = format
 
1677
        # Metadir formats have a network name of their format string, and get
 
1678
        # registered as class factories.
 
1679
        network_format_registry.register(format.get_format_string(), format.__class__)
1215
1680
 
1216
1681
    @classmethod
1217
1682
    def set_default_format(klass, format):
1218
1683
        klass._default_format = format
1219
1684
 
 
1685
    def supports_set_append_revisions_only(self):
 
1686
        """True if this format supports set_append_revisions_only."""
 
1687
        return False
 
1688
 
1220
1689
    def supports_stacking(self):
1221
1690
        """True if this format records a stacked-on branch."""
1222
1691
        return False
1226
1695
        del klass._formats[format.get_format_string()]
1227
1696
 
1228
1697
    def __str__(self):
1229
 
        return self.get_format_string().rstrip()
 
1698
        return self.get_format_description().rstrip()
1230
1699
 
1231
1700
    def supports_tags(self):
1232
1701
        """True if this format supports tags stored in the branch"""
1235
1704
 
1236
1705
class BranchHooks(Hooks):
1237
1706
    """A dictionary mapping hook name to a list of callables for branch hooks.
1238
 
    
 
1707
 
1239
1708
    e.g. ['set_rh'] Is the list of items to be called when the
1240
1709
    set_revision_history function is invoked.
1241
1710
    """
1247
1716
        notified.
1248
1717
        """
1249
1718
        Hooks.__init__(self)
1250
 
        # Introduced in 0.15:
1251
 
        # invoked whenever the revision history has been set
1252
 
        # with set_revision_history. The api signature is
1253
 
        # (branch, revision_history), and the branch will
1254
 
        # be write-locked.
1255
 
        self['set_rh'] = []
1256
 
        # Invoked after a branch is opened. The api signature is (branch).
1257
 
        self['open'] = []
1258
 
        # invoked after a push operation completes.
1259
 
        # the api signature is
1260
 
        # (push_result)
1261
 
        # containing the members
1262
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1263
 
        # where local is the local target branch or None, master is the target 
1264
 
        # master branch, and the rest should be self explanatory. The source
1265
 
        # is read locked and the target branches write locked. Source will
1266
 
        # be the local low-latency branch.
1267
 
        self['post_push'] = []
1268
 
        # invoked after a pull operation completes.
1269
 
        # the api signature is
1270
 
        # (pull_result)
1271
 
        # containing the members
1272
 
        # (source, local, master, old_revno, old_revid, new_revno, new_revid)
1273
 
        # where local is the local branch or None, master is the target 
1274
 
        # master branch, and the rest should be self explanatory. The source
1275
 
        # is read locked and the target branches write locked. The local
1276
 
        # branch is the low-latency branch.
1277
 
        self['post_pull'] = []
1278
 
        # invoked before a commit operation takes place.
1279
 
        # the api signature is
1280
 
        # (local, master, old_revno, old_revid, future_revno, future_revid,
1281
 
        #  tree_delta, future_tree).
1282
 
        # old_revid is NULL_REVISION for the first commit to a branch
1283
 
        # tree_delta is a TreeDelta object describing changes from the basis
1284
 
        # revision, hooks MUST NOT modify this delta
1285
 
        # future_tree is an in-memory tree obtained from
1286
 
        # CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1287
 
        self['pre_commit'] = []
1288
 
        # invoked after a commit operation completes.
1289
 
        # the api signature is 
1290
 
        # (local, master, old_revno, old_revid, new_revno, new_revid)
1291
 
        # old_revid is NULL_REVISION for the first commit to a branch.
1292
 
        self['post_commit'] = []
1293
 
        # invoked after a uncommit operation completes.
1294
 
        # the api signature is
1295
 
        # (local, master, old_revno, old_revid, new_revno, new_revid) where
1296
 
        # local is the local branch or None, master is the target branch,
1297
 
        # and an empty branch recieves new_revno of 0, new_revid of None.
1298
 
        self['post_uncommit'] = []
1299
 
        # Introduced in 1.6
1300
 
        # Invoked before the tip of a branch changes.
1301
 
        # the api signature is
1302
 
        # (params) where params is a ChangeBranchTipParams with the members
1303
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1304
 
        self['pre_change_branch_tip'] = []
1305
 
        # Introduced in 1.4
1306
 
        # Invoked after the tip of a branch changes.
1307
 
        # the api signature is
1308
 
        # (params) where params is a ChangeBranchTipParams with the members
1309
 
        # (branch, old_revno, new_revno, old_revid, new_revid)
1310
 
        self['post_change_branch_tip'] = []
1311
 
        # Introduced in 1.9
1312
 
        # Invoked when a stacked branch activates its fallback locations and
1313
 
        # allows the transformation of the url of said location.
1314
 
        # the api signature is
1315
 
        # (branch, url) where branch is the branch having its fallback
1316
 
        # location activated and url is the url for the fallback location.
1317
 
        # The hook should return a url.
1318
 
        self['transform_fallback_location'] = []
 
1719
        self.create_hook(HookPoint('set_rh',
 
1720
            "Invoked whenever the revision history has been set via "
 
1721
            "set_revision_history. The api signature is (branch, "
 
1722
            "revision_history), and the branch will be write-locked. "
 
1723
            "The set_rh hook can be expensive for bzr to trigger, a better "
 
1724
            "hook to use is Branch.post_change_branch_tip.", (0, 15), None))
 
1725
        self.create_hook(HookPoint('open',
 
1726
            "Called with the Branch object that has been opened after a "
 
1727
            "branch is opened.", (1, 8), None))
 
1728
        self.create_hook(HookPoint('post_push',
 
1729
            "Called after a push operation completes. post_push is called "
 
1730
            "with a bzrlib.branch.BranchPushResult object and only runs in the "
 
1731
            "bzr client.", (0, 15), None))
 
1732
        self.create_hook(HookPoint('post_pull',
 
1733
            "Called after a pull operation completes. post_pull is called "
 
1734
            "with a bzrlib.branch.PullResult object and only runs in the "
 
1735
            "bzr client.", (0, 15), None))
 
1736
        self.create_hook(HookPoint('pre_commit',
 
1737
            "Called after a commit is calculated but before it is is "
 
1738
            "completed. pre_commit is called with (local, master, old_revno, "
 
1739
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
 
1740
            "). old_revid is NULL_REVISION for the first commit to a branch, "
 
1741
            "tree_delta is a TreeDelta object describing changes from the "
 
1742
            "basis revision. hooks MUST NOT modify this delta. "
 
1743
            " future_tree is an in-memory tree obtained from "
 
1744
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
 
1745
            "tree.", (0,91), None))
 
1746
        self.create_hook(HookPoint('post_commit',
 
1747
            "Called in the bzr client after a commit has completed. "
 
1748
            "post_commit is called with (local, master, old_revno, old_revid, "
 
1749
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
 
1750
            "commit to a branch.", (0, 15), None))
 
1751
        self.create_hook(HookPoint('post_uncommit',
 
1752
            "Called in the bzr client after an uncommit completes. "
 
1753
            "post_uncommit is called with (local, master, old_revno, "
 
1754
            "old_revid, new_revno, new_revid) where local is the local branch "
 
1755
            "or None, master is the target branch, and an empty branch "
 
1756
            "receives new_revno of 0, new_revid of None.", (0, 15), None))
 
1757
        self.create_hook(HookPoint('pre_change_branch_tip',
 
1758
            "Called in bzr client and server before a change to the tip of a "
 
1759
            "branch is made. pre_change_branch_tip is called with a "
 
1760
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1761
            "commit, uncommit will all trigger this hook.", (1, 6), None))
 
1762
        self.create_hook(HookPoint('post_change_branch_tip',
 
1763
            "Called in bzr client and server after a change to the tip of a "
 
1764
            "branch is made. post_change_branch_tip is called with a "
 
1765
            "bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
 
1766
            "commit, uncommit will all trigger this hook.", (1, 4), None))
 
1767
        self.create_hook(HookPoint('transform_fallback_location',
 
1768
            "Called when a stacked branch is activating its fallback "
 
1769
            "locations. transform_fallback_location is called with (branch, "
 
1770
            "url), and should return a new url. Returning the same url "
 
1771
            "allows it to be used as-is, returning a different one can be "
 
1772
            "used to cause the branch to stack on a closer copy of that "
 
1773
            "fallback_location. Note that the branch cannot have history "
 
1774
            "accessing methods called on it during this hook because the "
 
1775
            "fallback locations have not been activated. When there are "
 
1776
            "multiple hooks installed for transform_fallback_location, "
 
1777
            "all are called with the url returned from the previous hook."
 
1778
            "The order is however undefined.", (1, 9), None))
 
1779
        self.create_hook(HookPoint('automatic_tag_name',
 
1780
            "Called to determine an automatic tag name for a revision."
 
1781
            "automatic_tag_name is called with (branch, revision_id) and "
 
1782
            "should return a tag name or None if no tag name could be "
 
1783
            "determined. The first non-None tag name returned will be used.",
 
1784
            (2, 2), None))
 
1785
        self.create_hook(HookPoint('post_branch_init',
 
1786
            "Called after new branch initialization completes. "
 
1787
            "post_branch_init is called with a "
 
1788
            "bzrlib.branch.BranchInitHookParams. "
 
1789
            "Note that init, branch and checkout (both heavyweight and "
 
1790
            "lightweight) will all trigger this hook.", (2, 2), None))
 
1791
        self.create_hook(HookPoint('post_switch',
 
1792
            "Called after a checkout switches branch. "
 
1793
            "post_switch is called with a "
 
1794
            "bzrlib.branch.SwitchHookParams.", (2, 2), None))
 
1795
 
1319
1796
 
1320
1797
 
1321
1798
# install the default hooks into the Branch class.
1353
1830
 
1354
1831
    def __eq__(self, other):
1355
1832
        return self.__dict__ == other.__dict__
1356
 
    
 
1833
 
1357
1834
    def __repr__(self):
1358
1835
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1359
 
            self.__class__.__name__, self.branch, 
 
1836
            self.__class__.__name__, self.branch,
1360
1837
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1361
1838
 
1362
1839
 
 
1840
class BranchInitHookParams(object):
 
1841
    """Object holding parameters passed to *_branch_init hooks.
 
1842
 
 
1843
    There are 4 fields that hooks may wish to access:
 
1844
 
 
1845
    :ivar format: the branch format
 
1846
    :ivar bzrdir: the BzrDir where the branch will be/has been initialized
 
1847
    :ivar name: name of colocated branch, if any (or None)
 
1848
    :ivar branch: the branch created
 
1849
 
 
1850
    Note that for lightweight checkouts, the bzrdir and format fields refer to
 
1851
    the checkout, hence they are different from the corresponding fields in
 
1852
    branch, which refer to the original branch.
 
1853
    """
 
1854
 
 
1855
    def __init__(self, format, a_bzrdir, name, branch):
 
1856
        """Create a group of BranchInitHook parameters.
 
1857
 
 
1858
        :param format: the branch format
 
1859
        :param a_bzrdir: the BzrDir where the branch will be/has been
 
1860
            initialized
 
1861
        :param name: name of colocated branch, if any (or None)
 
1862
        :param branch: the branch created
 
1863
 
 
1864
        Note that for lightweight checkouts, the bzrdir and format fields refer
 
1865
        to the checkout, hence they are different from the corresponding fields
 
1866
        in branch, which refer to the original branch.
 
1867
        """
 
1868
        self.format = format
 
1869
        self.bzrdir = a_bzrdir
 
1870
        self.name = name
 
1871
        self.branch = branch
 
1872
 
 
1873
    def __eq__(self, other):
 
1874
        return self.__dict__ == other.__dict__
 
1875
 
 
1876
    def __repr__(self):
 
1877
        if self.branch:
 
1878
            return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1879
        else:
 
1880
            return "<%s of format:%s bzrdir:%s>" % (
 
1881
                self.__class__.__name__, self.branch,
 
1882
                self.format, self.bzrdir)
 
1883
 
 
1884
 
 
1885
class SwitchHookParams(object):
 
1886
    """Object holding parameters passed to *_switch hooks.
 
1887
 
 
1888
    There are 4 fields that hooks may wish to access:
 
1889
 
 
1890
    :ivar control_dir: BzrDir of the checkout to change
 
1891
    :ivar to_branch: branch that the checkout is to reference
 
1892
    :ivar force: skip the check for local commits in a heavy checkout
 
1893
    :ivar revision_id: revision ID to switch to (or None)
 
1894
    """
 
1895
 
 
1896
    def __init__(self, control_dir, to_branch, force, revision_id):
 
1897
        """Create a group of SwitchHook parameters.
 
1898
 
 
1899
        :param control_dir: BzrDir of the checkout to change
 
1900
        :param to_branch: branch that the checkout is to reference
 
1901
        :param force: skip the check for local commits in a heavy checkout
 
1902
        :param revision_id: revision ID to switch to (or None)
 
1903
        """
 
1904
        self.control_dir = control_dir
 
1905
        self.to_branch = to_branch
 
1906
        self.force = force
 
1907
        self.revision_id = revision_id
 
1908
 
 
1909
    def __eq__(self, other):
 
1910
        return self.__dict__ == other.__dict__
 
1911
 
 
1912
    def __repr__(self):
 
1913
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
 
1914
            self.control_dir, self.to_branch,
 
1915
            self.revision_id)
 
1916
 
 
1917
 
1363
1918
class BzrBranchFormat4(BranchFormat):
1364
1919
    """Bzr branch format 4.
1365
1920
 
1372
1927
        """See BranchFormat.get_format_description()."""
1373
1928
        return "Branch format 4"
1374
1929
 
1375
 
    def initialize(self, a_bzrdir):
 
1930
    def initialize(self, a_bzrdir, name=None):
1376
1931
        """Create a branch of this format in a_bzrdir."""
1377
1932
        utf8_files = [('revision-history', ''),
1378
1933
                      ('branch-name', ''),
1379
1934
                      ]
1380
 
        return self._initialize_helper(a_bzrdir, utf8_files,
 
1935
        return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1381
1936
                                       lock_type='branch4', set_format=False)
1382
1937
 
1383
1938
    def __init__(self):
1384
1939
        super(BzrBranchFormat4, self).__init__()
1385
1940
        self._matchingbzrdir = bzrdir.BzrDirFormat6()
1386
1941
 
1387
 
    def open(self, a_bzrdir, _found=False):
1388
 
        """Return the branch object for a_bzrdir
 
1942
    def network_name(self):
 
1943
        """The network name for this format is the control dirs disk label."""
 
1944
        return self._matchingbzrdir.get_format_string()
1389
1945
 
1390
 
        _found is a private parameter, do not use it. It is used to indicate
1391
 
               if format probing has already be done.
1392
 
        """
 
1946
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1947
        """See BranchFormat.open()."""
1393
1948
        if not _found:
1394
1949
            # we are being called directly and must probe.
1395
1950
            raise NotImplementedError
1396
1951
        return BzrBranch(_format=self,
1397
1952
                         _control_files=a_bzrdir._control_files,
1398
1953
                         a_bzrdir=a_bzrdir,
 
1954
                         name=name,
1399
1955
                         _repository=a_bzrdir.open_repository())
1400
1956
 
1401
1957
    def __str__(self):
1409
1965
        """What class to instantiate on open calls."""
1410
1966
        raise NotImplementedError(self._branch_class)
1411
1967
 
1412
 
    def open(self, a_bzrdir, _found=False):
1413
 
        """Return the branch object for a_bzrdir.
 
1968
    def network_name(self):
 
1969
        """A simple byte string uniquely identifying this format for RPC calls.
1414
1970
 
1415
 
        _found is a private parameter, do not use it. It is used to indicate
1416
 
               if format probing has already be done.
 
1971
        Metadir branch formats use their format string.
1417
1972
        """
 
1973
        return self.get_format_string()
 
1974
 
 
1975
    def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
 
1976
        """See BranchFormat.open()."""
1418
1977
        if not _found:
1419
 
            format = BranchFormat.find_format(a_bzrdir)
 
1978
            format = BranchFormat.find_format(a_bzrdir, name=name)
1420
1979
            if format.__class__ != self.__class__:
1421
1980
                raise AssertionError("wrong format %r found for %r" %
1422
1981
                    (format, self))
 
1982
        transport = a_bzrdir.get_branch_transport(None, name=name)
1423
1983
        try:
1424
 
            transport = a_bzrdir.get_branch_transport(None)
1425
1984
            control_files = lockable_files.LockableFiles(transport, 'lock',
1426
1985
                                                         lockdir.LockDir)
1427
1986
            return self._branch_class()(_format=self,
1428
1987
                              _control_files=control_files,
 
1988
                              name=name,
1429
1989
                              a_bzrdir=a_bzrdir,
1430
 
                              _repository=a_bzrdir.find_repository())
 
1990
                              _repository=a_bzrdir.find_repository(),
 
1991
                              ignore_fallbacks=ignore_fallbacks)
1431
1992
        except errors.NoSuchFile:
1432
 
            raise errors.NotBranchError(path=transport.base)
 
1993
            raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1433
1994
 
1434
1995
    def __init__(self):
1435
1996
        super(BranchFormatMetadir, self).__init__()
1463
2024
    def get_format_description(self):
1464
2025
        """See BranchFormat.get_format_description()."""
1465
2026
        return "Branch format 5"
1466
 
        
1467
 
    def initialize(self, a_bzrdir):
 
2027
 
 
2028
    def initialize(self, a_bzrdir, name=None):
1468
2029
        """Create a branch of this format in a_bzrdir."""
1469
2030
        utf8_files = [('revision-history', ''),
1470
2031
                      ('branch-name', ''),
1471
2032
                      ]
1472
 
        return self._initialize_helper(a_bzrdir, utf8_files)
 
2033
        return self._initialize_helper(a_bzrdir, utf8_files, name)
1473
2034
 
1474
2035
    def supports_tags(self):
1475
2036
        return False
1497
2058
        """See BranchFormat.get_format_description()."""
1498
2059
        return "Branch format 6"
1499
2060
 
1500
 
    def initialize(self, a_bzrdir):
1501
 
        """Create a branch of this format in a_bzrdir."""
1502
 
        utf8_files = [('last-revision', '0 null:\n'),
1503
 
                      ('branch.conf', ''),
1504
 
                      ('tags', ''),
1505
 
                      ]
1506
 
        return self._initialize_helper(a_bzrdir, utf8_files)
1507
 
 
1508
 
 
1509
 
class BzrBranchFormat7(BranchFormatMetadir):
 
2061
    def initialize(self, a_bzrdir, name=None):
 
2062
        """Create a branch of this format in a_bzrdir."""
 
2063
        utf8_files = [('last-revision', '0 null:\n'),
 
2064
                      ('branch.conf', ''),
 
2065
                      ('tags', ''),
 
2066
                      ]
 
2067
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2068
 
 
2069
    def make_tags(self, branch):
 
2070
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2071
        return BasicTags(branch)
 
2072
 
 
2073
    def supports_set_append_revisions_only(self):
 
2074
        return True
 
2075
 
 
2076
 
 
2077
class BzrBranchFormat8(BranchFormatMetadir):
 
2078
    """Metadir format supporting storing locations of subtree branches."""
 
2079
 
 
2080
    def _branch_class(self):
 
2081
        return BzrBranch8
 
2082
 
 
2083
    def get_format_string(self):
 
2084
        """See BranchFormat.get_format_string()."""
 
2085
        return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
 
2086
 
 
2087
    def get_format_description(self):
 
2088
        """See BranchFormat.get_format_description()."""
 
2089
        return "Branch format 8"
 
2090
 
 
2091
    def initialize(self, a_bzrdir, name=None):
 
2092
        """Create a branch of this format in a_bzrdir."""
 
2093
        utf8_files = [('last-revision', '0 null:\n'),
 
2094
                      ('branch.conf', ''),
 
2095
                      ('tags', ''),
 
2096
                      ('references', '')
 
2097
                      ]
 
2098
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2099
 
 
2100
    def __init__(self):
 
2101
        super(BzrBranchFormat8, self).__init__()
 
2102
        self._matchingbzrdir.repository_format = \
 
2103
            RepositoryFormatKnitPack5RichRoot()
 
2104
 
 
2105
    def make_tags(self, branch):
 
2106
        """See bzrlib.branch.BranchFormat.make_tags()."""
 
2107
        return BasicTags(branch)
 
2108
 
 
2109
    def supports_set_append_revisions_only(self):
 
2110
        return True
 
2111
 
 
2112
    def supports_stacking(self):
 
2113
        return True
 
2114
 
 
2115
    supports_reference_locations = True
 
2116
 
 
2117
 
 
2118
class BzrBranchFormat7(BzrBranchFormat8):
1510
2119
    """Branch format with last-revision, tags, and a stacked location pointer.
1511
2120
 
1512
2121
    The stacked location pointer is passed down to the repository and requires
1515
2124
    This format was introduced in bzr 1.6.
1516
2125
    """
1517
2126
 
 
2127
    def initialize(self, a_bzrdir, name=None):
 
2128
        """Create a branch of this format in a_bzrdir."""
 
2129
        utf8_files = [('last-revision', '0 null:\n'),
 
2130
                      ('branch.conf', ''),
 
2131
                      ('tags', ''),
 
2132
                      ]
 
2133
        return self._initialize_helper(a_bzrdir, utf8_files, name)
 
2134
 
1518
2135
    def _branch_class(self):
1519
2136
        return BzrBranch7
1520
2137
 
1526
2143
        """See BranchFormat.get_format_description()."""
1527
2144
        return "Branch format 7"
1528
2145
 
1529
 
    def initialize(self, a_bzrdir):
1530
 
        """Create a branch of this format in a_bzrdir."""
1531
 
        utf8_files = [('last-revision', '0 null:\n'),
1532
 
                      ('branch.conf', ''),
1533
 
                      ('tags', ''),
1534
 
                      ]
1535
 
        return self._initialize_helper(a_bzrdir, utf8_files)
1536
 
 
1537
 
    def __init__(self):
1538
 
        super(BzrBranchFormat7, self).__init__()
1539
 
        self._matchingbzrdir.repository_format = \
1540
 
            RepositoryFormatKnitPack5RichRoot()
1541
 
 
1542
 
    def supports_stacking(self):
 
2146
    def supports_set_append_revisions_only(self):
1543
2147
        return True
1544
2148
 
 
2149
    supports_reference_locations = False
 
2150
 
1545
2151
 
1546
2152
class BranchReferenceFormat(BranchFormat):
1547
2153
    """Bzr branch reference format.
1562
2168
        """See BranchFormat.get_format_description()."""
1563
2169
        return "Checkout reference format 1"
1564
2170
 
1565
 
    def get_reference(self, a_bzrdir):
 
2171
    def get_reference(self, a_bzrdir, name=None):
1566
2172
        """See BranchFormat.get_reference()."""
1567
 
        transport = a_bzrdir.get_branch_transport(None)
1568
 
        return transport.get('location').read()
 
2173
        transport = a_bzrdir.get_branch_transport(None, name=name)
 
2174
        return transport.get_bytes('location')
1569
2175
 
1570
 
    def set_reference(self, a_bzrdir, to_branch):
 
2176
    def set_reference(self, a_bzrdir, name, to_branch):
1571
2177
        """See BranchFormat.set_reference()."""
1572
 
        transport = a_bzrdir.get_branch_transport(None)
 
2178
        transport = a_bzrdir.get_branch_transport(None, name=name)
1573
2179
        location = transport.put_bytes('location', to_branch.base)
1574
2180
 
1575
 
    def initialize(self, a_bzrdir, target_branch=None):
 
2181
    def initialize(self, a_bzrdir, name=None, target_branch=None):
1576
2182
        """Create a branch of this format in a_bzrdir."""
1577
2183
        if target_branch is None:
1578
2184
            # this format does not implement branch itself, thus the implicit
1579
2185
            # creation contract must see it as uninitializable
1580
2186
            raise errors.UninitializableFormat(self)
1581
 
        mutter('creating branch reference in %s', a_bzrdir.transport.base)
1582
 
        branch_transport = a_bzrdir.get_branch_transport(self)
 
2187
        mutter('creating branch reference in %s', a_bzrdir.user_url)
 
2188
        branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1583
2189
        branch_transport.put_bytes('location',
1584
 
            target_branch.bzrdir.root_transport.base)
 
2190
            target_branch.bzrdir.user_url)
1585
2191
        branch_transport.put_bytes('format', self.get_format_string())
1586
 
        return self.open(
1587
 
            a_bzrdir, _found=True,
 
2192
        branch = self.open(
 
2193
            a_bzrdir, name, _found=True,
1588
2194
            possible_transports=[target_branch.bzrdir.root_transport])
 
2195
        self._run_post_branch_init_hooks(a_bzrdir, name, branch)
 
2196
        return branch
1589
2197
 
1590
2198
    def __init__(self):
1591
2199
        super(BranchReferenceFormat, self).__init__()
1594
2202
 
1595
2203
    def _make_reference_clone_function(format, a_branch):
1596
2204
        """Create a clone() routine for a branch dynamically."""
1597
 
        def clone(to_bzrdir, revision_id=None):
 
2205
        def clone(to_bzrdir, revision_id=None,
 
2206
            repository_policy=None):
1598
2207
            """See Branch.clone()."""
1599
 
            return format.initialize(to_bzrdir, a_branch)
 
2208
            return format.initialize(to_bzrdir, target_branch=a_branch)
1600
2209
            # cannot obey revision_id limits when cloning a reference ...
1601
2210
            # FIXME RBC 20060210 either nuke revision_id for clone, or
1602
2211
            # emit some sort of warning/error to the caller ?!
1603
2212
        return clone
1604
2213
 
1605
 
    def open(self, a_bzrdir, _found=False, location=None,
1606
 
             possible_transports=None):
 
2214
    def open(self, a_bzrdir, name=None, _found=False, location=None,
 
2215
             possible_transports=None, ignore_fallbacks=False):
1607
2216
        """Return the branch that the branch reference in a_bzrdir points at.
1608
2217
 
1609
 
        _found is a private parameter, do not use it. It is used to indicate
1610
 
               if format probing has already be done.
 
2218
        :param a_bzrdir: A BzrDir that contains a branch.
 
2219
        :param name: Name of colocated branch to open, if any
 
2220
        :param _found: a private parameter, do not use it. It is used to
 
2221
            indicate if format probing has already be done.
 
2222
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
2223
            (if there are any).  Default is to open fallbacks.
 
2224
        :param location: The location of the referenced branch.  If
 
2225
            unspecified, this will be determined from the branch reference in
 
2226
            a_bzrdir.
 
2227
        :param possible_transports: An optional reusable transports list.
1611
2228
        """
1612
2229
        if not _found:
1613
 
            format = BranchFormat.find_format(a_bzrdir)
 
2230
            format = BranchFormat.find_format(a_bzrdir, name=name)
1614
2231
            if format.__class__ != self.__class__:
1615
2232
                raise AssertionError("wrong format %r found for %r" %
1616
2233
                    (format, self))
1617
2234
        if location is None:
1618
 
            location = self.get_reference(a_bzrdir)
 
2235
            location = self.get_reference(a_bzrdir, name)
1619
2236
        real_bzrdir = bzrdir.BzrDir.open(
1620
2237
            location, possible_transports=possible_transports)
1621
 
        result = real_bzrdir.open_branch()
 
2238
        result = real_bzrdir.open_branch(name=name, 
 
2239
            ignore_fallbacks=ignore_fallbacks)
1622
2240
        # this changes the behaviour of result.clone to create a new reference
1623
2241
        # rather than a copy of the content of the branch.
1624
2242
        # I did not use a proxy object because that needs much more extensive
1631
2249
        return result
1632
2250
 
1633
2251
 
 
2252
network_format_registry = registry.FormatRegistry()
 
2253
"""Registry of formats indexed by their network name.
 
2254
 
 
2255
The network name for a branch format is an identifier that can be used when
 
2256
referring to formats with smart server operations. See
 
2257
BranchFormat.network_name() for more detail.
 
2258
"""
 
2259
 
 
2260
 
1634
2261
# formats which have no format string are not discoverable
1635
2262
# and not independently creatable, so are not registered.
1636
2263
__format5 = BzrBranchFormat5()
1637
2264
__format6 = BzrBranchFormat6()
1638
2265
__format7 = BzrBranchFormat7()
 
2266
__format8 = BzrBranchFormat8()
1639
2267
BranchFormat.register_format(__format5)
1640
2268
BranchFormat.register_format(BranchReferenceFormat())
1641
2269
BranchFormat.register_format(__format6)
1642
2270
BranchFormat.register_format(__format7)
1643
 
BranchFormat.set_default_format(__format6)
 
2271
BranchFormat.register_format(__format8)
 
2272
BranchFormat.set_default_format(__format7)
1644
2273
_legacy_formats = [BzrBranchFormat4(),
1645
 
                   ]
1646
 
 
1647
 
class BzrBranch(Branch):
 
2274
    ]
 
2275
network_format_registry.register(
 
2276
    _legacy_formats[0].network_name(), _legacy_formats[0].__class__)
 
2277
 
 
2278
 
 
2279
class BranchWriteLockResult(LogicalLockResult):
 
2280
    """The result of write locking a branch.
 
2281
 
 
2282
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
2283
        None.
 
2284
    :ivar unlock: A callable which will unlock the lock.
 
2285
    """
 
2286
 
 
2287
    def __init__(self, unlock, branch_token):
 
2288
        LogicalLockResult.__init__(self, unlock)
 
2289
        self.branch_token = branch_token
 
2290
 
 
2291
    def __repr__(self):
 
2292
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
2293
            self.unlock)
 
2294
 
 
2295
 
 
2296
class BzrBranch(Branch, _RelockDebugMixin):
1648
2297
    """A branch stored in the actual filesystem.
1649
2298
 
1650
2299
    Note that it's "local" in the context of the filesystem; it doesn't
1651
2300
    really matter if it's on an nfs/smb/afs/coda/... share, as long as
1652
2301
    it's writable, and can be accessed via the normal filesystem API.
1653
2302
 
1654
 
    :ivar _transport: Transport for file operations on this branch's 
 
2303
    :ivar _transport: Transport for file operations on this branch's
1655
2304
        control files, typically pointing to the .bzr/branch directory.
1656
2305
    :ivar repository: Repository for this branch.
1657
 
    :ivar base: The url of the base directory for this branch; the one 
 
2306
    :ivar base: The url of the base directory for this branch; the one
1658
2307
        containing the .bzr directory.
 
2308
    :ivar name: Optional colocated branch name as it exists in the control
 
2309
        directory.
1659
2310
    """
1660
 
    
 
2311
 
1661
2312
    def __init__(self, _format=None,
1662
 
                 _control_files=None, a_bzrdir=None, _repository=None):
 
2313
                 _control_files=None, a_bzrdir=None, name=None,
 
2314
                 _repository=None, ignore_fallbacks=False):
1663
2315
        """Create new branch object at a particular location."""
1664
2316
        if a_bzrdir is None:
1665
2317
            raise ValueError('a_bzrdir must be supplied')
1666
2318
        else:
1667
2319
            self.bzrdir = a_bzrdir
1668
2320
        self._base = self.bzrdir.transport.clone('..').base
 
2321
        self.name = name
1669
2322
        # XXX: We should be able to just do
1670
2323
        #   self.base = self.bzrdir.root_transport.base
1671
2324
        # but this does not quite work yet -- mbp 20080522
1678
2331
        Branch.__init__(self)
1679
2332
 
1680
2333
    def __str__(self):
1681
 
        return '%s(%r)' % (self.__class__.__name__, self.base)
 
2334
        if self.name is None:
 
2335
            return '%s(%s)' % (self.__class__.__name__, self.user_url)
 
2336
        else:
 
2337
            return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
 
2338
                self.name)
1682
2339
 
1683
2340
    __repr__ = __str__
1684
2341
 
1688
2345
 
1689
2346
    base = property(_get_base, doc="The URL for the root of this branch.")
1690
2347
 
 
2348
    def _get_config(self):
 
2349
        return TransportConfig(self._transport, 'branch.conf')
 
2350
 
1691
2351
    def is_locked(self):
1692
2352
        return self.control_files.is_locked()
1693
2353
 
1694
2354
    def lock_write(self, token=None):
1695
 
        repo_token = self.repository.lock_write()
 
2355
        """Lock the branch for write operations.
 
2356
 
 
2357
        :param token: A token to permit reacquiring a previously held and
 
2358
            preserved lock.
 
2359
        :return: A BranchWriteLockResult.
 
2360
        """
 
2361
        if not self.is_locked():
 
2362
            self._note_lock('w')
 
2363
        # All-in-one needs to always unlock/lock.
 
2364
        repo_control = getattr(self.repository, 'control_files', None)
 
2365
        if self.control_files == repo_control or not self.is_locked():
 
2366
            self.repository._warn_if_deprecated(self)
 
2367
            self.repository.lock_write()
 
2368
            took_lock = True
 
2369
        else:
 
2370
            took_lock = False
1696
2371
        try:
1697
 
            token = self.control_files.lock_write(token=token)
 
2372
            return BranchWriteLockResult(self.unlock,
 
2373
                self.control_files.lock_write(token=token))
1698
2374
        except:
1699
 
            self.repository.unlock()
 
2375
            if took_lock:
 
2376
                self.repository.unlock()
1700
2377
            raise
1701
 
        return token
1702
2378
 
1703
2379
    def lock_read(self):
1704
 
        self.repository.lock_read()
 
2380
        """Lock the branch for read operations.
 
2381
 
 
2382
        :return: A bzrlib.lock.LogicalLockResult.
 
2383
        """
 
2384
        if not self.is_locked():
 
2385
            self._note_lock('r')
 
2386
        # All-in-one needs to always unlock/lock.
 
2387
        repo_control = getattr(self.repository, 'control_files', None)
 
2388
        if self.control_files == repo_control or not self.is_locked():
 
2389
            self.repository._warn_if_deprecated(self)
 
2390
            self.repository.lock_read()
 
2391
            took_lock = True
 
2392
        else:
 
2393
            took_lock = False
1705
2394
        try:
1706
2395
            self.control_files.lock_read()
 
2396
            return LogicalLockResult(self.unlock)
1707
2397
        except:
1708
 
            self.repository.unlock()
 
2398
            if took_lock:
 
2399
                self.repository.unlock()
1709
2400
            raise
1710
2401
 
 
2402
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1711
2403
    def unlock(self):
1712
 
        # TODO: test for failed two phase locks. This is known broken.
1713
2404
        try:
1714
2405
            self.control_files.unlock()
1715
2406
        finally:
1716
 
            self.repository.unlock()
1717
 
        if not self.control_files.is_locked():
1718
 
            # we just released the lock
1719
 
            self._clear_cached_state()
1720
 
        
 
2407
            # All-in-one needs to always unlock/lock.
 
2408
            repo_control = getattr(self.repository, 'control_files', None)
 
2409
            if (self.control_files == repo_control or
 
2410
                not self.control_files.is_locked()):
 
2411
                self.repository.unlock()
 
2412
            if not self.control_files.is_locked():
 
2413
                # we just released the lock
 
2414
                self._clear_cached_state()
 
2415
 
1721
2416
    def peek_lock_mode(self):
1722
2417
        if self.control_files._lock_count == 0:
1723
2418
            return None
1795
2490
                new_history = rev.get_history(self.repository)[1:]
1796
2491
        destination.set_revision_history(new_history)
1797
2492
 
1798
 
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1799
 
        """Run the pre_change_branch_tip hooks."""
1800
 
        hooks = Branch.hooks['pre_change_branch_tip']
1801
 
        if not hooks:
1802
 
            return
1803
 
        old_revno, old_revid = self.last_revision_info()
1804
 
        params = ChangeBranchTipParams(
1805
 
            self, old_revno, new_revno, old_revid, new_revid)
1806
 
        for hook in hooks:
1807
 
            try:
1808
 
                hook(params)
1809
 
            except errors.TipChangeRejected:
1810
 
                raise
1811
 
            except Exception:
1812
 
                exc_info = sys.exc_info()
1813
 
                hook_name = Branch.hooks.get_hook_name(hook)
1814
 
                raise errors.HookFailed(
1815
 
                    'pre_change_branch_tip', hook_name, exc_info)
1816
 
 
1817
 
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1818
 
        """Run the post_change_branch_tip hooks."""
1819
 
        hooks = Branch.hooks['post_change_branch_tip']
1820
 
        if not hooks:
1821
 
            return
1822
 
        new_revno, new_revid = self.last_revision_info()
1823
 
        params = ChangeBranchTipParams(
1824
 
            self, old_revno, new_revno, old_revid, new_revid)
1825
 
        for hook in hooks:
1826
 
            hook(params)
1827
 
 
1828
2493
    @needs_write_lock
1829
2494
    def set_last_revision_info(self, revno, revision_id):
1830
2495
        """Set the last revision of this branch.
1833
2498
        for this revision id.
1834
2499
 
1835
2500
        It may be possible to set the branch last revision to an id not
1836
 
        present in the repository.  However, branches can also be 
 
2501
        present in the repository.  However, branches can also be
1837
2502
        configured to check constraints on history, in which case this may not
1838
2503
        be permitted.
1839
2504
        """
1853
2518
            history.pop()
1854
2519
        return history
1855
2520
 
1856
 
    def _lefthand_history(self, revision_id, last_rev=None,
1857
 
                          other_branch=None):
1858
 
        if 'evil' in debug.debug_flags:
1859
 
            mutter_callsite(4, "_lefthand_history scales with history.")
1860
 
        # stop_revision must be a descendant of last_revision
1861
 
        graph = self.repository.get_graph()
1862
 
        if last_rev is not None:
1863
 
            if not graph.is_ancestor(last_rev, revision_id):
1864
 
                # our previous tip is not merged into stop_revision
1865
 
                raise errors.DivergedBranches(self, other_branch)
1866
 
        # make a new revision history from the graph
1867
 
        parents_map = graph.get_parent_map([revision_id])
1868
 
        if revision_id not in parents_map:
1869
 
            raise errors.NoSuchRevision(self, revision_id)
1870
 
        current_rev_id = revision_id
1871
 
        new_history = []
1872
 
        check_not_reserved_id = _mod_revision.check_not_reserved_id
1873
 
        # Do not include ghosts or graph origin in revision_history
1874
 
        while (current_rev_id in parents_map and
1875
 
               len(parents_map[current_rev_id]) > 0):
1876
 
            check_not_reserved_id(current_rev_id)
1877
 
            new_history.append(current_rev_id)
1878
 
            current_rev_id = parents_map[current_rev_id][0]
1879
 
            parents_map = graph.get_parent_map([current_rev_id])
1880
 
        new_history.reverse()
1881
 
        return new_history
1882
 
 
1883
2521
    @needs_write_lock
1884
2522
    def generate_revision_history(self, revision_id, last_rev=None,
1885
2523
        other_branch=None):
1898
2536
        """See Branch.basis_tree."""
1899
2537
        return self.repository.revision_tree(self.last_revision())
1900
2538
 
1901
 
    @needs_write_lock
1902
 
    def pull(self, source, overwrite=False, stop_revision=None,
1903
 
             _hook_master=None, run_hooks=True, possible_transports=None,
1904
 
             _override_hook_target=None):
1905
 
        """See Branch.pull.
1906
 
 
1907
 
        :param _hook_master: Private parameter - set the branch to 
1908
 
            be supplied as the master to pull hooks.
1909
 
        :param run_hooks: Private parameter - if false, this branch
1910
 
            is being called because it's the master of the primary branch,
1911
 
            so it should not run its hooks.
1912
 
        :param _override_hook_target: Private parameter - set the branch to be
1913
 
            supplied as the target_branch to pull hooks.
1914
 
        """
1915
 
        result = PullResult()
1916
 
        result.source_branch = source
1917
 
        if _override_hook_target is None:
1918
 
            result.target_branch = self
1919
 
        else:
1920
 
            result.target_branch = _override_hook_target
1921
 
        source.lock_read()
1922
 
        try:
1923
 
            # We assume that during 'pull' the local repository is closer than
1924
 
            # the remote one.
1925
 
            graph = self.repository.get_graph(source.repository)
1926
 
            result.old_revno, result.old_revid = self.last_revision_info()
1927
 
            self.update_revisions(source, stop_revision, overwrite=overwrite,
1928
 
                                  graph=graph)
1929
 
            result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1930
 
            result.new_revno, result.new_revid = self.last_revision_info()
1931
 
            if _hook_master:
1932
 
                result.master_branch = _hook_master
1933
 
                result.local_branch = result.target_branch
1934
 
            else:
1935
 
                result.master_branch = result.target_branch
1936
 
                result.local_branch = None
1937
 
            if run_hooks:
1938
 
                for hook in Branch.hooks['post_pull']:
1939
 
                    hook(result)
1940
 
        finally:
1941
 
            source.unlock()
1942
 
        return result
1943
 
 
1944
2539
    def _get_parent_location(self):
1945
2540
        _locs = ['parent', 'pull', 'x-pull']
1946
2541
        for l in _locs:
1950
2545
                pass
1951
2546
        return None
1952
2547
 
1953
 
    @needs_read_lock
1954
 
    def push(self, target, overwrite=False, stop_revision=None,
1955
 
             _override_hook_source_branch=None):
1956
 
        """See Branch.push.
1957
 
 
1958
 
        This is the basic concrete implementation of push()
1959
 
 
1960
 
        :param _override_hook_source_branch: If specified, run
1961
 
        the hooks passing this Branch as the source, rather than self.  
1962
 
        This is for use of RemoteBranch, where push is delegated to the
1963
 
        underlying vfs-based Branch. 
1964
 
        """
1965
 
        # TODO: Public option to disable running hooks - should be trivial but
1966
 
        # needs tests.
1967
 
        return _run_with_write_locked_target(
1968
 
            target, self._push_with_bound_branches, target, overwrite,
1969
 
            stop_revision,
1970
 
            _override_hook_source_branch=_override_hook_source_branch)
1971
 
 
1972
 
    def _push_with_bound_branches(self, target, overwrite,
1973
 
            stop_revision,
1974
 
            _override_hook_source_branch=None):
1975
 
        """Push from self into target, and into target's master if any.
1976
 
        
1977
 
        This is on the base BzrBranch class even though it doesn't support 
1978
 
        bound branches because the *target* might be bound.
1979
 
        """
1980
 
        def _run_hooks():
1981
 
            if _override_hook_source_branch:
1982
 
                result.source_branch = _override_hook_source_branch
1983
 
            for hook in Branch.hooks['post_push']:
1984
 
                hook(result)
1985
 
 
1986
 
        bound_location = target.get_bound_location()
1987
 
        if bound_location and target.base != bound_location:
1988
 
            # there is a master branch.
1989
 
            #
1990
 
            # XXX: Why the second check?  Is it even supported for a branch to
1991
 
            # be bound to itself? -- mbp 20070507
1992
 
            master_branch = target.get_master_branch()
1993
 
            master_branch.lock_write()
1994
 
            try:
1995
 
                # push into the master from this branch.
1996
 
                self._basic_push(master_branch, overwrite, stop_revision)
1997
 
                # and push into the target branch from this. Note that we push from
1998
 
                # this branch again, because its considered the highest bandwidth
1999
 
                # repository.
2000
 
                result = self._basic_push(target, overwrite, stop_revision)
2001
 
                result.master_branch = master_branch
2002
 
                result.local_branch = target
2003
 
                _run_hooks()
2004
 
                return result
2005
 
            finally:
2006
 
                master_branch.unlock()
2007
 
        else:
2008
 
            # no master branch
2009
 
            result = self._basic_push(target, overwrite, stop_revision)
2010
 
            # TODO: Why set master_branch and local_branch if there's no
2011
 
            # binding?  Maybe cleaner to just leave them unset? -- mbp
2012
 
            # 20070504
2013
 
            result.master_branch = target
2014
 
            result.local_branch = None
2015
 
            _run_hooks()
2016
 
            return result
2017
 
 
2018
2548
    def _basic_push(self, target, overwrite, stop_revision):
2019
2549
        """Basic implementation of push without bound branches or hooks.
2020
2550
 
2021
 
        Must be called with self read locked and target write locked.
 
2551
        Must be called with source read locked and target write locked.
2022
2552
        """
2023
 
        result = PushResult()
 
2553
        result = BranchPushResult()
2024
2554
        result.source_branch = self
2025
2555
        result.target_branch = target
2026
2556
        result.old_revno, result.old_revid = target.last_revision_info()
 
2557
        self.update_references(target)
2027
2558
        if result.old_revid != self.last_revision():
2028
2559
            # We assume that during 'push' this repository is closer than
2029
2560
            # the target.
2030
2561
            graph = self.repository.get_graph(target.repository)
2031
 
            target.update_revisions(self, stop_revision, overwrite=overwrite,
2032
 
                                    graph=graph)
 
2562
            target.update_revisions(self, stop_revision,
 
2563
                overwrite=overwrite, graph=graph)
2033
2564
        if self._push_should_merge_tags():
2034
 
            result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
 
2565
            result.tag_conflicts = self.tags.merge_to(target.tags,
 
2566
                overwrite)
2035
2567
        result.new_revno, result.new_revid = target.last_revision_info()
2036
2568
        return result
2037
2569
 
2038
 
    def _push_should_merge_tags(self):
2039
 
        """Should _basic_push merge this branch's tags into the target?
2040
 
        
2041
 
        The default implementation returns False if this branch has no tags,
2042
 
        and True the rest of the time.  Subclasses may override this.
2043
 
        """
2044
 
        return self.tags.supports_tags() and self.tags.get_tag_dict()
2045
 
 
2046
 
    def get_parent(self):
2047
 
        """See Branch.get_parent."""
2048
 
        parent = self._get_parent_location()
2049
 
        if parent is None:
2050
 
            return parent
2051
 
        # This is an old-format absolute path to a local branch
2052
 
        # turn it into a url
2053
 
        if parent.startswith('/'):
2054
 
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
2055
 
        try:
2056
 
            return urlutils.join(self.base[:-1], parent)
2057
 
        except errors.InvalidURLJoin, e:
2058
 
            raise errors.InaccessibleParent(parent, self.base)
2059
 
 
2060
2570
    def get_stacked_on_url(self):
2061
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2571
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2062
2572
 
2063
2573
    def set_push_location(self, location):
2064
2574
        """See Branch.set_push_location."""
2066
2576
            'push_location', location,
2067
2577
            store=_mod_config.STORE_LOCATION_NORECURSE)
2068
2578
 
2069
 
    @needs_write_lock
2070
 
    def set_parent(self, url):
2071
 
        """See Branch.set_parent."""
2072
 
        # TODO: Maybe delete old location files?
2073
 
        # URLs should never be unicode, even on the local fs,
2074
 
        # FIXUP this and get_parent in a future branch format bump:
2075
 
        # read and rewrite the file. RBC 20060125
2076
 
        if url is not None:
2077
 
            if isinstance(url, unicode):
2078
 
                try:
2079
 
                    url = url.encode('ascii')
2080
 
                except UnicodeEncodeError:
2081
 
                    raise errors.InvalidURL(url,
2082
 
                        "Urls must be 7-bit ascii, "
2083
 
                        "use bzrlib.urlutils.escape")
2084
 
            url = urlutils.relative_url(self.base, url)
2085
 
        self._set_parent_location(url)
2086
 
 
2087
2579
    def _set_parent_location(self, url):
2088
2580
        if url is None:
2089
2581
            self._transport.delete('parent')
2091
2583
            self._transport.put_bytes('parent', url + '\n',
2092
2584
                mode=self.bzrdir._get_file_mode())
2093
2585
 
2094
 
    def set_stacked_on_url(self, url):
2095
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
2096
 
 
2097
2586
 
2098
2587
class BzrBranch5(BzrBranch):
2099
2588
    """A format 5 branch. This supports new features over plain branches.
2101
2590
    It has support for a master_branch which is the data for bound branches.
2102
2591
    """
2103
2592
 
2104
 
    @needs_write_lock
2105
 
    def pull(self, source, overwrite=False, stop_revision=None,
2106
 
             run_hooks=True, possible_transports=None,
2107
 
             _override_hook_target=None):
2108
 
        """Pull from source into self, updating my master if any.
2109
 
        
2110
 
        :param run_hooks: Private parameter - if false, this branch
2111
 
            is being called because it's the master of the primary branch,
2112
 
            so it should not run its hooks.
2113
 
        """
2114
 
        bound_location = self.get_bound_location()
2115
 
        master_branch = None
2116
 
        if bound_location and source.base != bound_location:
2117
 
            # not pulling from master, so we need to update master.
2118
 
            master_branch = self.get_master_branch(possible_transports)
2119
 
            master_branch.lock_write()
2120
 
        try:
2121
 
            if master_branch:
2122
 
                # pull from source into master.
2123
 
                master_branch.pull(source, overwrite, stop_revision,
2124
 
                    run_hooks=False)
2125
 
            return super(BzrBranch5, self).pull(source, overwrite,
2126
 
                stop_revision, _hook_master=master_branch,
2127
 
                run_hooks=run_hooks,
2128
 
                _override_hook_target=_override_hook_target)
2129
 
        finally:
2130
 
            if master_branch:
2131
 
                master_branch.unlock()
2132
 
 
2133
2593
    def get_bound_location(self):
2134
2594
        try:
2135
2595
            return self._transport.get_bytes('bound')[:-1]
2139
2599
    @needs_read_lock
2140
2600
    def get_master_branch(self, possible_transports=None):
2141
2601
        """Return the branch we are bound to.
2142
 
        
 
2602
 
2143
2603
        :return: Either a Branch, or None
2144
2604
 
2145
2605
        This could memoise the branch, but if thats done
2181
2641
        check for divergence to raise an error when the branches are not
2182
2642
        either the same, or one a prefix of the other. That behaviour may not
2183
2643
        be useful, so that check may be removed in future.
2184
 
        
 
2644
 
2185
2645
        :param other: The branch to bind to
2186
2646
        :type other: Branch
2187
2647
        """
2206
2666
 
2207
2667
    @needs_write_lock
2208
2668
    def update(self, possible_transports=None):
2209
 
        """Synchronise this branch with the master branch if any. 
 
2669
        """Synchronise this branch with the master branch if any.
2210
2670
 
2211
2671
        :return: None or the last_revision that was pivoted out during the
2212
2672
                 update.
2222
2682
        return None
2223
2683
 
2224
2684
 
2225
 
class BzrBranch7(BzrBranch5):
2226
 
    """A branch with support for a fallback repository."""
2227
 
 
2228
 
    def _get_fallback_repository(self, url):
2229
 
        """Get the repository we fallback to at url."""
2230
 
        url = urlutils.join(self.base, url)
2231
 
        a_bzrdir = bzrdir.BzrDir.open(url,
2232
 
                                      possible_transports=[self._transport])
2233
 
        return a_bzrdir.open_branch().repository
2234
 
 
2235
 
    def _activate_fallback_location(self, url):
2236
 
        """Activate the branch/repository from url as a fallback repository."""
2237
 
        self.repository.add_fallback_repository(
2238
 
            self._get_fallback_repository(url))
 
2685
class BzrBranch8(BzrBranch5):
 
2686
    """A branch that stores tree-reference locations."""
2239
2687
 
2240
2688
    def _open_hook(self):
 
2689
        if self._ignore_fallbacks:
 
2690
            return
2241
2691
        try:
2242
2692
            url = self.get_stacked_on_url()
2243
2693
        except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2253
2703
                        "None, not a URL." % hook_name)
2254
2704
            self._activate_fallback_location(url)
2255
2705
 
2256
 
    def _check_stackable_repo(self):
2257
 
        if not self.repository._format.supports_external_lookups:
2258
 
            raise errors.UnstackableRepositoryFormat(self.repository._format,
2259
 
                self.repository.base)
2260
 
 
2261
2706
    def __init__(self, *args, **kwargs):
2262
 
        super(BzrBranch7, self).__init__(*args, **kwargs)
 
2707
        self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
 
2708
        super(BzrBranch8, self).__init__(*args, **kwargs)
2263
2709
        self._last_revision_info_cache = None
2264
 
        self._partial_revision_history_cache = []
 
2710
        self._reference_info = None
2265
2711
 
2266
2712
    def _clear_cached_state(self):
2267
 
        super(BzrBranch7, self)._clear_cached_state()
 
2713
        super(BzrBranch8, self)._clear_cached_state()
2268
2714
        self._last_revision_info_cache = None
2269
 
        self._partial_revision_history_cache = []
 
2715
        self._reference_info = None
2270
2716
 
2271
2717
    def _last_revision_info(self):
2272
2718
        revision_string = self._transport.get_bytes('last-revision')
2303
2749
 
2304
2750
    def _synchronize_history(self, destination, revision_id):
2305
2751
        """Synchronize last revision and revision history between branches.
2306
 
        
 
2752
 
2307
2753
        :see: Branch._synchronize_history
2308
2754
        """
2309
2755
        # XXX: The base Branch has a fast implementation of this method based
2318
2764
        if _mod_revision.is_null(last_revision):
2319
2765
            return
2320
2766
        if last_revision not in self._lefthand_history(revision_id):
2321
 
            raise errors.AppendRevisionsOnlyViolation(self.base)
 
2767
            raise errors.AppendRevisionsOnlyViolation(self.user_url)
2322
2768
 
2323
2769
    def _gen_revision_history(self):
2324
2770
        """Generate the revision history from last revision
2327
2773
        self._extend_partial_history(stop_index=last_revno-1)
2328
2774
        return list(reversed(self._partial_revision_history_cache))
2329
2775
 
2330
 
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
2331
 
        """Extend the partial history to include a given index
2332
 
 
2333
 
        If a stop_index is supplied, stop when that index has been reached.
2334
 
        If a stop_revision is supplied, stop when that revision is
2335
 
        encountered.  Otherwise, stop when the beginning of history is
2336
 
        reached.
2337
 
 
2338
 
        :param stop_index: The index which should be present.  When it is
2339
 
            present, history extension will stop.
2340
 
        :param revision_id: The revision id which should be present.  When
2341
 
            it is encountered, history extension will stop.
2342
 
        """
2343
 
        repo = self.repository
2344
 
        if len(self._partial_revision_history_cache) == 0:
2345
 
            iterator = repo.iter_reverse_revision_history(self.last_revision())
2346
 
        else:
2347
 
            start_revision = self._partial_revision_history_cache[-1]
2348
 
            iterator = repo.iter_reverse_revision_history(start_revision)
2349
 
            #skip the last revision in the list
2350
 
            next_revision = iterator.next()
2351
 
        for revision_id in iterator:
2352
 
            self._partial_revision_history_cache.append(revision_id)
2353
 
            if (stop_index is not None and
2354
 
                len(self._partial_revision_history_cache) > stop_index):
2355
 
                break
2356
 
            if revision_id == stop_revision:
2357
 
                break
2358
 
 
2359
2776
    def _write_revision_history(self, history):
2360
2777
        """Factored out of set_revision_history.
2361
2778
 
2382
2799
        """Set the parent branch"""
2383
2800
        return self._get_config_location('parent_location')
2384
2801
 
 
2802
    @needs_write_lock
 
2803
    def _set_all_reference_info(self, info_dict):
 
2804
        """Replace all reference info stored in a branch.
 
2805
 
 
2806
        :param info_dict: A dict of {file_id: (tree_path, branch_location)}
 
2807
        """
 
2808
        s = StringIO()
 
2809
        writer = rio.RioWriter(s)
 
2810
        for key, (tree_path, branch_location) in info_dict.iteritems():
 
2811
            stanza = rio.Stanza(file_id=key, tree_path=tree_path,
 
2812
                                branch_location=branch_location)
 
2813
            writer.write_stanza(stanza)
 
2814
        self._transport.put_bytes('references', s.getvalue())
 
2815
        self._reference_info = info_dict
 
2816
 
 
2817
    @needs_read_lock
 
2818
    def _get_all_reference_info(self):
 
2819
        """Return all the reference info stored in a branch.
 
2820
 
 
2821
        :return: A dict of {file_id: (tree_path, branch_location)}
 
2822
        """
 
2823
        if self._reference_info is not None:
 
2824
            return self._reference_info
 
2825
        rio_file = self._transport.get('references')
 
2826
        try:
 
2827
            stanzas = rio.read_stanzas(rio_file)
 
2828
            info_dict = dict((s['file_id'], (s['tree_path'],
 
2829
                             s['branch_location'])) for s in stanzas)
 
2830
        finally:
 
2831
            rio_file.close()
 
2832
        self._reference_info = info_dict
 
2833
        return info_dict
 
2834
 
 
2835
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2836
        """Set the branch location to use for a tree reference.
 
2837
 
 
2838
        :param file_id: The file-id of the tree reference.
 
2839
        :param tree_path: The path of the tree reference in the tree.
 
2840
        :param branch_location: The location of the branch to retrieve tree
 
2841
            references from.
 
2842
        """
 
2843
        info_dict = self._get_all_reference_info()
 
2844
        info_dict[file_id] = (tree_path, branch_location)
 
2845
        if None in (tree_path, branch_location):
 
2846
            if tree_path is not None:
 
2847
                raise ValueError('tree_path must be None when branch_location'
 
2848
                                 ' is None.')
 
2849
            if branch_location is not None:
 
2850
                raise ValueError('branch_location must be None when tree_path'
 
2851
                                 ' is None.')
 
2852
            del info_dict[file_id]
 
2853
        self._set_all_reference_info(info_dict)
 
2854
 
 
2855
    def get_reference_info(self, file_id):
 
2856
        """Get the tree_path and branch_location for a tree reference.
 
2857
 
 
2858
        :return: a tuple of (tree_path, branch_location)
 
2859
        """
 
2860
        return self._get_all_reference_info().get(file_id, (None, None))
 
2861
 
 
2862
    def reference_parent(self, file_id, path, possible_transports=None):
 
2863
        """Return the parent branch for a tree-reference file_id.
 
2864
 
 
2865
        :param file_id: The file_id of the tree reference
 
2866
        :param path: The path of the file_id in the tree
 
2867
        :return: A branch associated with the file_id
 
2868
        """
 
2869
        branch_location = self.get_reference_info(file_id)[1]
 
2870
        if branch_location is None:
 
2871
            return Branch.reference_parent(self, file_id, path,
 
2872
                                           possible_transports)
 
2873
        branch_location = urlutils.join(self.user_url, branch_location)
 
2874
        return Branch.open(branch_location,
 
2875
                           possible_transports=possible_transports)
 
2876
 
2385
2877
    def set_push_location(self, location):
2386
2878
        """See Branch.set_push_location."""
2387
2879
        self._set_config_location('push_location', location)
2429
2921
            raise errors.NotStacked(self)
2430
2922
        return stacked_url
2431
2923
 
2432
 
    def set_append_revisions_only(self, enabled):
2433
 
        if enabled:
2434
 
            value = 'True'
2435
 
        else:
2436
 
            value = 'False'
2437
 
        self.get_config().set_user_option('append_revisions_only', value,
2438
 
            warn_masked=True)
2439
 
 
2440
 
    def set_stacked_on_url(self, url):
2441
 
        self._check_stackable_repo()
2442
 
        if not url:
2443
 
            try:
2444
 
                old_url = self.get_stacked_on_url()
2445
 
            except (errors.NotStacked, errors.UnstackableBranchFormat,
2446
 
                errors.UnstackableRepositoryFormat):
2447
 
                return
2448
 
            url = ''
2449
 
            # repositories don't offer an interface to remove fallback
2450
 
            # repositories today; take the conceptually simpler option and just
2451
 
            # reopen it.
2452
 
            self.repository = self.bzrdir.find_repository()
2453
 
            # for every revision reference the branch has, ensure it is pulled
2454
 
            # in.
2455
 
            source_repository = self._get_fallback_repository(old_url)
2456
 
            for revision_id in chain([self.last_revision()],
2457
 
                self.tags.get_reverse_tag_dict()):
2458
 
                self.repository.fetch(source_repository, revision_id,
2459
 
                    find_ghosts=True)
2460
 
        else:
2461
 
            self._activate_fallback_location(url)
2462
 
        # write this out after the repository is stacked to avoid setting a
2463
 
        # stacked config that doesn't work.
2464
 
        self._set_config_location('stacked_on_location', url)
2465
 
 
2466
2924
    def _get_append_revisions_only(self):
2467
 
        value = self.get_config().get_user_option('append_revisions_only')
2468
 
        return value == 'True'
2469
 
 
2470
 
    def _make_tags(self):
2471
 
        return BasicTags(self)
 
2925
        return self.get_config(
 
2926
            ).get_user_option_as_bool('append_revisions_only')
2472
2927
 
2473
2928
    @needs_write_lock
2474
2929
    def generate_revision_history(self, revision_id, last_rev=None,
2514
2969
        return self.revno() - index
2515
2970
 
2516
2971
 
 
2972
class BzrBranch7(BzrBranch8):
 
2973
    """A branch with support for a fallback repository."""
 
2974
 
 
2975
    def set_reference_info(self, file_id, tree_path, branch_location):
 
2976
        Branch.set_reference_info(self, file_id, tree_path, branch_location)
 
2977
 
 
2978
    def get_reference_info(self, file_id):
 
2979
        Branch.get_reference_info(self, file_id)
 
2980
 
 
2981
    def reference_parent(self, file_id, path, possible_transports=None):
 
2982
        return Branch.reference_parent(self, file_id, path,
 
2983
                                       possible_transports)
 
2984
 
 
2985
 
2517
2986
class BzrBranch6(BzrBranch7):
2518
2987
    """See BzrBranchFormat6 for the capabilities of this branch.
2519
2988
 
2522
2991
    """
2523
2992
 
2524
2993
    def get_stacked_on_url(self):
2525
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
2526
 
 
2527
 
    def set_stacked_on_url(self, url):
2528
 
        raise errors.UnstackableBranchFormat(self._format, self.base)
 
2994
        raise errors.UnstackableBranchFormat(self._format, self.user_url)
2529
2995
 
2530
2996
 
2531
2997
######################################################################
2549
3015
    :ivar new_revno: Revision number after pull.
2550
3016
    :ivar old_revid: Tip revision id before pull.
2551
3017
    :ivar new_revid: Tip revision id after pull.
2552
 
    :ivar source_branch: Source (local) branch object.
 
3018
    :ivar source_branch: Source (local) branch object. (read locked)
2553
3019
    :ivar master_branch: Master branch of the target, or the target if no
2554
3020
        Master
2555
3021
    :ivar local_branch: target branch if there is a Master, else None
2556
 
    :ivar target_branch: Target/destination branch object.
 
3022
    :ivar target_branch: Target/destination branch object. (write locked)
2557
3023
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2558
3024
    """
2559
3025
 
2570
3036
        self._show_tag_conficts(to_file)
2571
3037
 
2572
3038
 
2573
 
class PushResult(_Result):
 
3039
class BranchPushResult(_Result):
2574
3040
    """Result of a Branch.push operation.
2575
3041
 
2576
 
    :ivar old_revno: Revision number before push.
2577
 
    :ivar new_revno: Revision number after push.
2578
 
    :ivar old_revid: Tip revision id before push.
2579
 
    :ivar new_revid: Tip revision id after push.
2580
 
    :ivar source_branch: Source branch object.
2581
 
    :ivar master_branch: Master branch of the target, or None.
2582
 
    :ivar target_branch: Target/destination branch object.
 
3042
    :ivar old_revno: Revision number (eg 10) of the target before push.
 
3043
    :ivar new_revno: Revision number (eg 12) of the target after push.
 
3044
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
 
3045
        before the push.
 
3046
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
 
3047
        after the push.
 
3048
    :ivar source_branch: Source branch object that the push was from. This is
 
3049
        read locked, and generally is a local (and thus low latency) branch.
 
3050
    :ivar master_branch: If target is a bound branch, the master branch of
 
3051
        target, or target itself. Always write locked.
 
3052
    :ivar target_branch: The direct Branch where data is being sent (write
 
3053
        locked).
 
3054
    :ivar local_branch: If the target is a bound branch this will be the
 
3055
        target, otherwise it will be None.
2583
3056
    """
2584
3057
 
2585
3058
    def __int__(self):
2589
3062
    def report(self, to_file):
2590
3063
        """Write a human-readable description of the result."""
2591
3064
        if self.old_revid == self.new_revid:
2592
 
            to_file.write('No new revisions to push.\n')
 
3065
            note('No new revisions to push.')
2593
3066
        else:
2594
 
            to_file.write('Pushed up to revision %d.\n' % self.new_revno)
 
3067
            note('Pushed up to revision %d.' % self.new_revno)
2595
3068
        self._show_tag_conficts(to_file)
2596
3069
 
2597
3070
 
2603
3076
 
2604
3077
    def __init__(self, branch):
2605
3078
        self.branch = branch
 
3079
        self.errors = []
2606
3080
 
2607
3081
    def report_results(self, verbose):
2608
3082
        """Report the check results via trace.note.
2609
 
        
 
3083
 
2610
3084
        :param verbose: Requests more detailed display of what was checked,
2611
3085
            if any.
2612
3086
        """
2613
 
        note('checked branch %s format %s',
2614
 
             self.branch.base,
2615
 
             self.branch._format)
 
3087
        note('checked branch %s format %s', self.branch.user_url,
 
3088
            self.branch._format)
 
3089
        for error in self.errors:
 
3090
            note('found error:%s', error)
2616
3091
 
2617
3092
 
2618
3093
class Converter5to6(object):
2656
3131
        branch._transport.put_bytes('format', format.get_format_string())
2657
3132
 
2658
3133
 
 
3134
class Converter7to8(object):
 
3135
    """Perform an in-place upgrade of format 6 to format 7"""
 
3136
 
 
3137
    def convert(self, branch):
 
3138
        format = BzrBranchFormat8()
 
3139
        branch._transport.put_bytes('references', '')
 
3140
        # update target format
 
3141
        branch._transport.put_bytes('format', format.get_format_string())
 
3142
 
2659
3143
 
2660
3144
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2661
3145
    """Run ``callable(*args, **kwargs)``, write-locking target for the
2672
3156
            return callable(*args, **kwargs)
2673
3157
        finally:
2674
3158
            target.unlock()
2675
 
    
 
3159
 
2676
3160
    """
2677
3161
    # This is very similar to bzrlib.decorators.needs_write_lock.  Perhaps they
2678
3162
    # should share code?
2688
3172
    else:
2689
3173
        target.unlock()
2690
3174
        return result
 
3175
 
 
3176
 
 
3177
class InterBranch(InterObject):
 
3178
    """This class represents operations taking place between two branches.
 
3179
 
 
3180
    Its instances have methods like pull() and push() and contain
 
3181
    references to the source and target repositories these operations
 
3182
    can be carried out on.
 
3183
    """
 
3184
 
 
3185
    _optimisers = []
 
3186
    """The available optimised InterBranch types."""
 
3187
 
 
3188
    @staticmethod
 
3189
    def _get_branch_formats_to_test():
 
3190
        """Return a tuple with the Branch formats to use when testing."""
 
3191
        raise NotImplementedError(InterBranch._get_branch_formats_to_test)
 
3192
 
 
3193
    def pull(self, overwrite=False, stop_revision=None,
 
3194
             possible_transports=None, local=False):
 
3195
        """Mirror source into target branch.
 
3196
 
 
3197
        The target branch is considered to be 'local', having low latency.
 
3198
 
 
3199
        :returns: PullResult instance
 
3200
        """
 
3201
        raise NotImplementedError(self.pull)
 
3202
 
 
3203
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3204
                         graph=None):
 
3205
        """Pull in new perfect-fit revisions.
 
3206
 
 
3207
        :param stop_revision: Updated until the given revision
 
3208
        :param overwrite: Always set the branch pointer, rather than checking
 
3209
            to see if it is a proper descendant.
 
3210
        :param graph: A Graph object that can be used to query history
 
3211
            information. This can be None.
 
3212
        :return: None
 
3213
        """
 
3214
        raise NotImplementedError(self.update_revisions)
 
3215
 
 
3216
    def push(self, overwrite=False, stop_revision=None,
 
3217
             _override_hook_source_branch=None):
 
3218
        """Mirror the source branch into the target branch.
 
3219
 
 
3220
        The source branch is considered to be 'local', having low latency.
 
3221
        """
 
3222
        raise NotImplementedError(self.push)
 
3223
 
 
3224
 
 
3225
class GenericInterBranch(InterBranch):
 
3226
    """InterBranch implementation that uses public Branch functions."""
 
3227
 
 
3228
    @classmethod
 
3229
    def is_compatible(klass, source, target):
 
3230
        # GenericBranch uses the public API, so always compatible
 
3231
        return True
 
3232
 
 
3233
    @staticmethod
 
3234
    def _get_branch_formats_to_test():
 
3235
        return BranchFormat._default_format, BranchFormat._default_format
 
3236
 
 
3237
    @classmethod
 
3238
    def unwrap_format(klass, format):
 
3239
        if isinstance(format, remote.RemoteBranchFormat):
 
3240
            format._ensure_real()
 
3241
            return format._custom_format
 
3242
        return format                                                                                                  
 
3243
 
 
3244
    @needs_write_lock
 
3245
    def copy_content_into(self, revision_id=None):
 
3246
        """Copy the content of source into target
 
3247
 
 
3248
        revision_id: if not None, the revision history in the new branch will
 
3249
                     be truncated to end with revision_id.
 
3250
        """
 
3251
        self.source.update_references(self.target)
 
3252
        self.source._synchronize_history(self.target, revision_id)
 
3253
        try:
 
3254
            parent = self.source.get_parent()
 
3255
        except errors.InaccessibleParent, e:
 
3256
            mutter('parent was not accessible to copy: %s', e)
 
3257
        else:
 
3258
            if parent:
 
3259
                self.target.set_parent(parent)
 
3260
        if self.source._push_should_merge_tags():
 
3261
            self.source.tags.merge_to(self.target.tags)
 
3262
 
 
3263
    @needs_write_lock
 
3264
    def update_revisions(self, stop_revision=None, overwrite=False,
 
3265
        graph=None):
 
3266
        """See InterBranch.update_revisions()."""
 
3267
        other_revno, other_last_revision = self.source.last_revision_info()
 
3268
        stop_revno = None # unknown
 
3269
        if stop_revision is None:
 
3270
            stop_revision = other_last_revision
 
3271
            if _mod_revision.is_null(stop_revision):
 
3272
                # if there are no commits, we're done.
 
3273
                return
 
3274
            stop_revno = other_revno
 
3275
 
 
3276
        # what's the current last revision, before we fetch [and change it
 
3277
        # possibly]
 
3278
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
3279
        # we fetch here so that we don't process data twice in the common
 
3280
        # case of having something to pull, and so that the check for
 
3281
        # already merged can operate on the just fetched graph, which will
 
3282
        # be cached in memory.
 
3283
        self.target.fetch(self.source, stop_revision)
 
3284
        # Check to see if one is an ancestor of the other
 
3285
        if not overwrite:
 
3286
            if graph is None:
 
3287
                graph = self.target.repository.get_graph()
 
3288
            if self.target._check_if_descendant_or_diverged(
 
3289
                    stop_revision, last_rev, graph, self.source):
 
3290
                # stop_revision is a descendant of last_rev, but we aren't
 
3291
                # overwriting, so we're done.
 
3292
                return
 
3293
        if stop_revno is None:
 
3294
            if graph is None:
 
3295
                graph = self.target.repository.get_graph()
 
3296
            this_revno, this_last_revision = \
 
3297
                    self.target.last_revision_info()
 
3298
            stop_revno = graph.find_distance_to_null(stop_revision,
 
3299
                            [(other_last_revision, other_revno),
 
3300
                             (this_last_revision, this_revno)])
 
3301
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
3302
 
 
3303
    def pull(self, overwrite=False, stop_revision=None,
 
3304
             possible_transports=None, run_hooks=True,
 
3305
             _override_hook_target=None, local=False):
 
3306
        """Pull from source into self, updating my master if any.
 
3307
 
 
3308
        :param run_hooks: Private parameter - if false, this branch
 
3309
            is being called because it's the master of the primary branch,
 
3310
            so it should not run its hooks.
 
3311
        """
 
3312
        bound_location = self.target.get_bound_location()
 
3313
        if local and not bound_location:
 
3314
            raise errors.LocalRequiresBoundBranch()
 
3315
        master_branch = None
 
3316
        if not local and bound_location and self.source.user_url != bound_location:
 
3317
            # not pulling from master, so we need to update master.
 
3318
            master_branch = self.target.get_master_branch(possible_transports)
 
3319
            master_branch.lock_write()
 
3320
        try:
 
3321
            if master_branch:
 
3322
                # pull from source into master.
 
3323
                master_branch.pull(self.source, overwrite, stop_revision,
 
3324
                    run_hooks=False)
 
3325
            return self._pull(overwrite,
 
3326
                stop_revision, _hook_master=master_branch,
 
3327
                run_hooks=run_hooks,
 
3328
                _override_hook_target=_override_hook_target)
 
3329
        finally:
 
3330
            if master_branch:
 
3331
                master_branch.unlock()
 
3332
 
 
3333
    def push(self, overwrite=False, stop_revision=None,
 
3334
             _override_hook_source_branch=None):
 
3335
        """See InterBranch.push.
 
3336
 
 
3337
        This is the basic concrete implementation of push()
 
3338
 
 
3339
        :param _override_hook_source_branch: If specified, run
 
3340
        the hooks passing this Branch as the source, rather than self.
 
3341
        This is for use of RemoteBranch, where push is delegated to the
 
3342
        underlying vfs-based Branch.
 
3343
        """
 
3344
        # TODO: Public option to disable running hooks - should be trivial but
 
3345
        # needs tests.
 
3346
        self.source.lock_read()
 
3347
        try:
 
3348
            return _run_with_write_locked_target(
 
3349
                self.target, self._push_with_bound_branches, overwrite,
 
3350
                stop_revision,
 
3351
                _override_hook_source_branch=_override_hook_source_branch)
 
3352
        finally:
 
3353
            self.source.unlock()
 
3354
 
 
3355
    def _push_with_bound_branches(self, overwrite, stop_revision,
 
3356
            _override_hook_source_branch=None):
 
3357
        """Push from source into target, and into target's master if any.
 
3358
        """
 
3359
        def _run_hooks():
 
3360
            if _override_hook_source_branch:
 
3361
                result.source_branch = _override_hook_source_branch
 
3362
            for hook in Branch.hooks['post_push']:
 
3363
                hook(result)
 
3364
 
 
3365
        bound_location = self.target.get_bound_location()
 
3366
        if bound_location and self.target.base != bound_location:
 
3367
            # there is a master branch.
 
3368
            #
 
3369
            # XXX: Why the second check?  Is it even supported for a branch to
 
3370
            # be bound to itself? -- mbp 20070507
 
3371
            master_branch = self.target.get_master_branch()
 
3372
            master_branch.lock_write()
 
3373
            try:
 
3374
                # push into the master from the source branch.
 
3375
                self.source._basic_push(master_branch, overwrite, stop_revision)
 
3376
                # and push into the target branch from the source. Note that we
 
3377
                # push from the source branch again, because its considered the
 
3378
                # highest bandwidth repository.
 
3379
                result = self.source._basic_push(self.target, overwrite,
 
3380
                    stop_revision)
 
3381
                result.master_branch = master_branch
 
3382
                result.local_branch = self.target
 
3383
                _run_hooks()
 
3384
                return result
 
3385
            finally:
 
3386
                master_branch.unlock()
 
3387
        else:
 
3388
            # no master branch
 
3389
            result = self.source._basic_push(self.target, overwrite,
 
3390
                stop_revision)
 
3391
            # TODO: Why set master_branch and local_branch if there's no
 
3392
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
3393
            # 20070504
 
3394
            result.master_branch = self.target
 
3395
            result.local_branch = None
 
3396
            _run_hooks()
 
3397
            return result
 
3398
 
 
3399
    def _pull(self, overwrite=False, stop_revision=None,
 
3400
             possible_transports=None, _hook_master=None, run_hooks=True,
 
3401
             _override_hook_target=None, local=False):
 
3402
        """See Branch.pull.
 
3403
 
 
3404
        This function is the core worker, used by GenericInterBranch.pull to
 
3405
        avoid duplication when pulling source->master and source->local.
 
3406
 
 
3407
        :param _hook_master: Private parameter - set the branch to
 
3408
            be supplied as the master to pull hooks.
 
3409
        :param run_hooks: Private parameter - if false, this branch
 
3410
            is being called because it's the master of the primary branch,
 
3411
            so it should not run its hooks.
 
3412
        :param _override_hook_target: Private parameter - set the branch to be
 
3413
            supplied as the target_branch to pull hooks.
 
3414
        :param local: Only update the local branch, and not the bound branch.
 
3415
        """
 
3416
        # This type of branch can't be bound.
 
3417
        if local:
 
3418
            raise errors.LocalRequiresBoundBranch()
 
3419
        result = PullResult()
 
3420
        result.source_branch = self.source
 
3421
        if _override_hook_target is None:
 
3422
            result.target_branch = self.target
 
3423
        else:
 
3424
            result.target_branch = _override_hook_target
 
3425
        self.source.lock_read()
 
3426
        try:
 
3427
            # We assume that during 'pull' the target repository is closer than
 
3428
            # the source one.
 
3429
            self.source.update_references(self.target)
 
3430
            graph = self.target.repository.get_graph(self.source.repository)
 
3431
            # TODO: Branch formats should have a flag that indicates 
 
3432
            # that revno's are expensive, and pull() should honor that flag.
 
3433
            # -- JRV20090506
 
3434
            result.old_revno, result.old_revid = \
 
3435
                self.target.last_revision_info()
 
3436
            self.target.update_revisions(self.source, stop_revision,
 
3437
                overwrite=overwrite, graph=graph)
 
3438
            # TODO: The old revid should be specified when merging tags, 
 
3439
            # so a tags implementation that versions tags can only 
 
3440
            # pull in the most recent changes. -- JRV20090506
 
3441
            result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
 
3442
                overwrite)
 
3443
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
3444
            if _hook_master:
 
3445
                result.master_branch = _hook_master
 
3446
                result.local_branch = result.target_branch
 
3447
            else:
 
3448
                result.master_branch = result.target_branch
 
3449
                result.local_branch = None
 
3450
            if run_hooks:
 
3451
                for hook in Branch.hooks['post_pull']:
 
3452
                    hook(result)
 
3453
        finally:
 
3454
            self.source.unlock()
 
3455
        return result
 
3456
 
 
3457
 
 
3458
InterBranch.register_optimiser(GenericInterBranch)