/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-18 12:46:49 UTC
  • mto: This revision was merged to the branch mainline in revision 6386.
  • Revision ID: jelmer@samba.org-20111218124649-nf7i69ocg3k2roz3
Import absolute_import in a few places.

Show diffs side-by-side

added added

removed removed

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