~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Florian Dorn
  • Date: 2012-04-03 14:49:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6546.
  • Revision ID: florian.dorn@boku.ac.at-20120403144922-b8y59csy8l1rzs5u
updated developer docs

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