~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

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