/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 breezy/branch.py

  • Committer: Jelmer Vernooij
  • Date: 2017-06-08 23:30:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6690.
  • Revision ID: jelmer@jelmer.uk-20170608233031-3qavls2o7a1pqllj
Update imports.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2012 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
from . import errors
 
20
 
 
21
from .lazy_import import lazy_import
 
22
lazy_import(globals(), """
 
23
import itertools
 
24
from breezy import (
 
25
    cleanup,
 
26
    config as _mod_config,
 
27
    debug,
 
28
    fetch,
 
29
    remote,
 
30
    repository,
 
31
    revision as _mod_revision,
 
32
    tag as _mod_tag,
 
33
    transport,
 
34
    ui,
 
35
    urlutils,
 
36
    vf_search,
 
37
    )
 
38
from breezy.i18n import gettext, ngettext
 
39
""")
 
40
 
 
41
from . import (
 
42
    controldir,
 
43
    registry,
 
44
    )
 
45
from .decorators import (
 
46
    needs_read_lock,
 
47
    needs_write_lock,
 
48
    only_raises,
 
49
    )
 
50
from .hooks import Hooks
 
51
from .inter import InterObject
 
52
from .lock import LogicalLockResult
 
53
from .sixish import (
 
54
    BytesIO,
 
55
    viewitems,
 
56
    )
 
57
from .trace import mutter, mutter_callsite, note, is_quiet
 
58
 
 
59
 
 
60
class Branch(controldir.ControlComponent):
 
61
    """Branch holding a history of revisions.
 
62
 
 
63
    :ivar base:
 
64
        Base directory/url of the branch; using control_url and
 
65
        control_transport is more standardized.
 
66
    :ivar hooks: An instance of BranchHooks.
 
67
    :ivar _master_branch_cache: cached result of get_master_branch, see
 
68
        _clear_cached_state.
 
69
    """
 
70
    # this is really an instance variable - FIXME move it there
 
71
    # - RBC 20060112
 
72
    base = None
 
73
 
 
74
    @property
 
75
    def control_transport(self):
 
76
        return self._transport
 
77
 
 
78
    @property
 
79
    def user_transport(self):
 
80
        return self.bzrdir.user_transport
 
81
 
 
82
    def __init__(self, possible_transports=None):
 
83
        self.tags = self._format.make_tags(self)
 
84
        self._revision_history_cache = None
 
85
        self._revision_id_to_revno_cache = None
 
86
        self._partial_revision_id_to_revno_cache = {}
 
87
        self._partial_revision_history_cache = []
 
88
        self._tags_bytes = None
 
89
        self._last_revision_info_cache = None
 
90
        self._master_branch_cache = None
 
91
        self._merge_sorted_revisions_cache = None
 
92
        self._open_hook(possible_transports)
 
93
        hooks = Branch.hooks['open']
 
94
        for hook in hooks:
 
95
            hook(self)
 
96
 
 
97
    def _open_hook(self, possible_transports):
 
98
        """Called by init to allow simpler extension of the base class."""
 
99
 
 
100
    def _activate_fallback_location(self, url, possible_transports):
 
101
        """Activate the branch/repository from url as a fallback repository."""
 
102
        for existing_fallback_repo in self.repository._fallback_repositories:
 
103
            if existing_fallback_repo.user_url == url:
 
104
                # This fallback is already configured.  This probably only
 
105
                # happens because ControlDir.sprout is a horrible mess.  To
 
106
                # avoid confusing _unstack we don't add this a second time.
 
107
                mutter('duplicate activation of fallback %r on %r', url, self)
 
108
                return
 
109
        repo = self._get_fallback_repository(url, possible_transports)
 
110
        if repo.has_same_location(self.repository):
 
111
            raise errors.UnstackableLocationError(self.user_url, url)
 
112
        self.repository.add_fallback_repository(repo)
 
113
 
 
114
    def break_lock(self):
 
115
        """Break a lock if one is present from another instance.
 
116
 
 
117
        Uses the ui factory to ask for confirmation if the lock may be from
 
118
        an active process.
 
119
 
 
120
        This will probe the repository for its lock as well.
 
121
        """
 
122
        self.control_files.break_lock()
 
123
        self.repository.break_lock()
 
124
        master = self.get_master_branch()
 
125
        if master is not None:
 
126
            master.break_lock()
 
127
 
 
128
    def _check_stackable_repo(self):
 
129
        if not self.repository._format.supports_external_lookups:
 
130
            raise errors.UnstackableRepositoryFormat(
 
131
                self.repository._format, self.repository.base)
 
132
 
 
133
    def _extend_partial_history(self, stop_index=None, stop_revision=None):
 
134
        """Extend the partial history to include a given index
 
135
 
 
136
        If a stop_index is supplied, stop when that index has been reached.
 
137
        If a stop_revision is supplied, stop when that revision is
 
138
        encountered.  Otherwise, stop when the beginning of history is
 
139
        reached.
 
140
 
 
141
        :param stop_index: The index which should be present.  When it is
 
142
            present, history extension will stop.
 
143
        :param stop_revision: The revision id which should be present.  When
 
144
            it is encountered, history extension will stop.
 
145
        """
 
146
        if len(self._partial_revision_history_cache) == 0:
 
147
            self._partial_revision_history_cache = [self.last_revision()]
 
148
        repository._iter_for_revno(
 
149
            self.repository, self._partial_revision_history_cache,
 
150
            stop_index=stop_index, stop_revision=stop_revision)
 
151
        if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
 
152
            self._partial_revision_history_cache.pop()
 
153
 
 
154
    def _get_check_refs(self):
 
155
        """Get the references needed for check().
 
156
 
 
157
        See breezy.check.
 
158
        """
 
159
        revid = self.last_revision()
 
160
        return [('revision-existence', revid), ('lefthand-distance', revid)]
 
161
 
 
162
    @staticmethod
 
163
    def open(base, _unsupported=False, possible_transports=None):
 
164
        """Open the branch rooted at base.
 
165
 
 
166
        For instance, if the branch is at URL/.bzr/branch,
 
167
        Branch.open(URL) -> a Branch instance.
 
168
        """
 
169
        control = controldir.ControlDir.open(base,
 
170
            possible_transports=possible_transports, _unsupported=_unsupported)
 
171
        return control.open_branch(unsupported=_unsupported,
 
172
            possible_transports=possible_transports)
 
173
 
 
174
    @staticmethod
 
175
    def open_from_transport(transport, name=None, _unsupported=False,
 
176
            possible_transports=None):
 
177
        """Open the branch rooted at transport"""
 
178
        control = controldir.ControlDir.open_from_transport(transport, _unsupported)
 
179
        return control.open_branch(name=name, unsupported=_unsupported,
 
180
            possible_transports=possible_transports)
 
181
 
 
182
    @staticmethod
 
183
    def open_containing(url, possible_transports=None):
 
184
        """Open an existing branch which contains url.
 
185
 
 
186
        This probes for a branch at url, and searches upwards from there.
 
187
 
 
188
        Basically we keep looking up until we find the control directory or
 
189
        run into the root.  If there isn't one, raises NotBranchError.
 
190
        If there is one and it is either an unrecognised format or an unsupported
 
191
        format, UnknownFormatError or UnsupportedFormatError are raised.
 
192
        If there is one, it is returned, along with the unused portion of url.
 
193
        """
 
194
        control, relpath = controldir.ControlDir.open_containing(url,
 
195
                                                         possible_transports)
 
196
        branch = control.open_branch(possible_transports=possible_transports)
 
197
        return (branch, relpath)
 
198
 
 
199
    def _push_should_merge_tags(self):
 
200
        """Should _basic_push merge this branch's tags into the target?
 
201
 
 
202
        The default implementation returns False if this branch has no tags,
 
203
        and True the rest of the time.  Subclasses may override this.
 
204
        """
 
205
        return self.supports_tags() and self.tags.get_tag_dict()
 
206
 
 
207
    def get_config(self):
 
208
        """Get a breezy.config.BranchConfig for this Branch.
 
209
 
 
210
        This can then be used to get and set configuration options for the
 
211
        branch.
 
212
 
 
213
        :return: A breezy.config.BranchConfig.
 
214
        """
 
215
        return _mod_config.BranchConfig(self)
 
216
 
 
217
    def get_config_stack(self):
 
218
        """Get a breezy.config.BranchStack for this Branch.
 
219
 
 
220
        This can then be used to get and set configuration options for the
 
221
        branch.
 
222
 
 
223
        :return: A breezy.config.BranchStack.
 
224
        """
 
225
        return _mod_config.BranchStack(self)
 
226
 
 
227
    def _get_config(self):
 
228
        """Get the concrete config for just the config in this branch.
 
229
 
 
230
        This is not intended for client use; see Branch.get_config for the
 
231
        public API.
 
232
 
 
233
        Added in 1.14.
 
234
 
 
235
        :return: An object supporting get_option and set_option.
 
236
        """
 
237
        raise NotImplementedError(self._get_config)
 
238
 
 
239
    def store_uncommitted(self, creator):
 
240
        """Store uncommitted changes from a ShelfCreator.
 
241
 
 
242
        :param creator: The ShelfCreator containing uncommitted changes, or
 
243
            None to delete any stored changes.
 
244
        :raises: ChangesAlreadyStored if the branch already has changes.
 
245
        """
 
246
        raise NotImplementedError(self.store_uncommitted)
 
247
 
 
248
    def get_unshelver(self, tree):
 
249
        """Return a shelf.Unshelver for this branch and tree.
 
250
 
 
251
        :param tree: The tree to use to construct the Unshelver.
 
252
        :return: an Unshelver or None if no changes are stored.
 
253
        """
 
254
        raise NotImplementedError(self.get_unshelver)
 
255
 
 
256
    def _get_fallback_repository(self, url, possible_transports):
 
257
        """Get the repository we fallback to at url."""
 
258
        url = urlutils.join(self.base, url)
 
259
        a_branch = Branch.open(url, possible_transports=possible_transports)
 
260
        return a_branch.repository
 
261
 
 
262
    @needs_read_lock
 
263
    def _get_tags_bytes(self):
 
264
        """Get the bytes of a serialised tags dict.
 
265
 
 
266
        Note that not all branches support tags, nor do all use the same tags
 
267
        logic: this method is specific to BasicTags. Other tag implementations
 
268
        may use the same method name and behave differently, safely, because
 
269
        of the double-dispatch via
 
270
        format.make_tags->tags_instance->get_tags_dict.
 
271
 
 
272
        :return: The bytes of the tags file.
 
273
        :seealso: Branch._set_tags_bytes.
 
274
        """
 
275
        if self._tags_bytes is None:
 
276
            self._tags_bytes = self._transport.get_bytes('tags')
 
277
        return self._tags_bytes
 
278
 
 
279
    def _get_nick(self, local=False, possible_transports=None):
 
280
        config = self.get_config()
 
281
        # explicit overrides master, but don't look for master if local is True
 
282
        if not local and not config.has_explicit_nickname():
 
283
            try:
 
284
                master = self.get_master_branch(possible_transports)
 
285
                if master and self.user_url == master.user_url:
 
286
                    raise errors.RecursiveBind(self.user_url)
 
287
                if master is not None:
 
288
                    # return the master branch value
 
289
                    return master.nick
 
290
            except errors.RecursiveBind as e:
 
291
                raise e
 
292
            except errors.BzrError as e:
 
293
                # Silently fall back to local implicit nick if the master is
 
294
                # unavailable
 
295
                mutter("Could not connect to bound branch, "
 
296
                    "falling back to local nick.\n " + str(e))
 
297
        return config.get_nickname()
 
298
 
 
299
    def _set_nick(self, nick):
 
300
        self.get_config().set_user_option('nickname', nick, warn_masked=True)
 
301
 
 
302
    nick = property(_get_nick, _set_nick)
 
303
 
 
304
    def is_locked(self):
 
305
        raise NotImplementedError(self.is_locked)
 
306
 
 
307
    def _lefthand_history(self, revision_id, last_rev=None,
 
308
                          other_branch=None):
 
309
        if 'evil' in debug.debug_flags:
 
310
            mutter_callsite(4, "_lefthand_history scales with history.")
 
311
        # stop_revision must be a descendant of last_revision
 
312
        graph = self.repository.get_graph()
 
313
        if last_rev is not None:
 
314
            if not graph.is_ancestor(last_rev, revision_id):
 
315
                # our previous tip is not merged into stop_revision
 
316
                raise errors.DivergedBranches(self, other_branch)
 
317
        # make a new revision history from the graph
 
318
        parents_map = graph.get_parent_map([revision_id])
 
319
        if revision_id not in parents_map:
 
320
            raise errors.NoSuchRevision(self, revision_id)
 
321
        current_rev_id = revision_id
 
322
        new_history = []
 
323
        check_not_reserved_id = _mod_revision.check_not_reserved_id
 
324
        # Do not include ghosts or graph origin in revision_history
 
325
        while (current_rev_id in parents_map and
 
326
               len(parents_map[current_rev_id]) > 0):
 
327
            check_not_reserved_id(current_rev_id)
 
328
            new_history.append(current_rev_id)
 
329
            current_rev_id = parents_map[current_rev_id][0]
 
330
            parents_map = graph.get_parent_map([current_rev_id])
 
331
        new_history.reverse()
 
332
        return new_history
 
333
 
 
334
    def lock_write(self, token=None):
 
335
        """Lock the branch for write operations.
 
336
 
 
337
        :param token: A token to permit reacquiring a previously held and
 
338
            preserved lock.
 
339
        :return: A BranchWriteLockResult.
 
340
        """
 
341
        raise NotImplementedError(self.lock_write)
 
342
 
 
343
    def lock_read(self):
 
344
        """Lock the branch for read operations.
 
345
 
 
346
        :return: A breezy.lock.LogicalLockResult.
 
347
        """
 
348
        raise NotImplementedError(self.lock_read)
 
349
 
 
350
    def unlock(self):
 
351
        raise NotImplementedError(self.unlock)
 
352
 
 
353
    def peek_lock_mode(self):
 
354
        """Return lock mode for the Branch: 'r', 'w' or None"""
 
355
        raise NotImplementedError(self.peek_lock_mode)
 
356
 
 
357
    def get_physical_lock_status(self):
 
358
        raise NotImplementedError(self.get_physical_lock_status)
 
359
 
 
360
    @needs_read_lock
 
361
    def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
 
362
        """Return the revision_id for a dotted revno.
 
363
 
 
364
        :param revno: a tuple like (1,) or (1,1,2)
 
365
        :param _cache_reverse: a private parameter enabling storage
 
366
           of the reverse mapping in a top level cache. (This should
 
367
           only be done in selective circumstances as we want to
 
368
           avoid having the mapping cached multiple times.)
 
369
        :return: the revision_id
 
370
        :raises errors.NoSuchRevision: if the revno doesn't exist
 
371
        """
 
372
        rev_id = self._do_dotted_revno_to_revision_id(revno)
 
373
        if _cache_reverse:
 
374
            self._partial_revision_id_to_revno_cache[rev_id] = revno
 
375
        return rev_id
 
376
 
 
377
    def _do_dotted_revno_to_revision_id(self, revno):
 
378
        """Worker function for dotted_revno_to_revision_id.
 
379
 
 
380
        Subclasses should override this if they wish to
 
381
        provide a more efficient implementation.
 
382
        """
 
383
        if len(revno) == 1:
 
384
            return self.get_rev_id(revno[0])
 
385
        revision_id_to_revno = self.get_revision_id_to_revno_map()
 
386
        revision_ids = [revision_id for revision_id, this_revno
 
387
                        in viewitems(revision_id_to_revno)
 
388
                        if revno == this_revno]
 
389
        if len(revision_ids) == 1:
 
390
            return revision_ids[0]
 
391
        else:
 
392
            revno_str = '.'.join(map(str, revno))
 
393
            raise errors.NoSuchRevision(self, revno_str)
 
394
 
 
395
    @needs_read_lock
 
396
    def revision_id_to_dotted_revno(self, revision_id):
 
397
        """Given a revision id, return its dotted revno.
 
398
 
 
399
        :return: a tuple like (1,) or (400,1,3).
 
400
        """
 
401
        return self._do_revision_id_to_dotted_revno(revision_id)
 
402
 
 
403
    def _do_revision_id_to_dotted_revno(self, revision_id):
 
404
        """Worker function for revision_id_to_revno."""
 
405
        # Try the caches if they are loaded
 
406
        result = self._partial_revision_id_to_revno_cache.get(revision_id)
 
407
        if result is not None:
 
408
            return result
 
409
        if self._revision_id_to_revno_cache:
 
410
            result = self._revision_id_to_revno_cache.get(revision_id)
 
411
            if result is None:
 
412
                raise errors.NoSuchRevision(self, revision_id)
 
413
        # Try the mainline as it's optimised
 
414
        try:
 
415
            revno = self.revision_id_to_revno(revision_id)
 
416
            return (revno,)
 
417
        except errors.NoSuchRevision:
 
418
            # We need to load and use the full revno map after all
 
419
            result = self.get_revision_id_to_revno_map().get(revision_id)
 
420
            if result is None:
 
421
                raise errors.NoSuchRevision(self, revision_id)
 
422
        return result
 
423
 
 
424
    @needs_read_lock
 
425
    def get_revision_id_to_revno_map(self):
 
426
        """Return the revision_id => dotted revno map.
 
427
 
 
428
        This will be regenerated on demand, but will be cached.
 
429
 
 
430
        :return: A dictionary mapping revision_id => dotted revno.
 
431
            This dictionary should not be modified by the caller.
 
432
        """
 
433
        if self._revision_id_to_revno_cache is not None:
 
434
            mapping = self._revision_id_to_revno_cache
 
435
        else:
 
436
            mapping = self._gen_revno_map()
 
437
            self._cache_revision_id_to_revno(mapping)
 
438
        # TODO: jam 20070417 Since this is being cached, should we be returning
 
439
        #       a copy?
 
440
        # I would rather not, and instead just declare that users should not
 
441
        # modify the return value.
 
442
        return mapping
 
443
 
 
444
    def _gen_revno_map(self):
 
445
        """Create a new mapping from revision ids to dotted revnos.
 
446
 
 
447
        Dotted revnos are generated based on the current tip in the revision
 
448
        history.
 
449
        This is the worker function for get_revision_id_to_revno_map, which
 
450
        just caches the return value.
 
451
 
 
452
        :return: A dictionary mapping revision_id => dotted revno.
 
453
        """
 
454
        revision_id_to_revno = dict((rev_id, revno)
 
455
            for rev_id, depth, revno, end_of_merge
 
456
             in self.iter_merge_sorted_revisions())
 
457
        return revision_id_to_revno
 
458
 
 
459
    @needs_read_lock
 
460
    def iter_merge_sorted_revisions(self, start_revision_id=None,
 
461
            stop_revision_id=None, stop_rule='exclude', direction='reverse'):
 
462
        """Walk the revisions for a branch in merge sorted order.
 
463
 
 
464
        Merge sorted order is the output from a merge-aware,
 
465
        topological sort, i.e. all parents come before their
 
466
        children going forward; the opposite for reverse.
 
467
 
 
468
        :param start_revision_id: the revision_id to begin walking from.
 
469
            If None, the branch tip is used.
 
470
        :param stop_revision_id: the revision_id to terminate the walk
 
471
            after. If None, the rest of history is included.
 
472
        :param stop_rule: if stop_revision_id is not None, the precise rule
 
473
            to use for termination:
 
474
 
 
475
            * 'exclude' - leave the stop revision out of the result (default)
 
476
            * 'include' - the stop revision is the last item in the result
 
477
            * 'with-merges' - include the stop revision and all of its
 
478
              merged revisions in the result
 
479
            * 'with-merges-without-common-ancestry' - filter out revisions 
 
480
              that are in both ancestries
 
481
        :param direction: either 'reverse' or 'forward':
 
482
 
 
483
            * reverse means return the start_revision_id first, i.e.
 
484
              start at the most recent revision and go backwards in history
 
485
            * forward returns tuples in the opposite order to reverse.
 
486
              Note in particular that forward does *not* do any intelligent
 
487
              ordering w.r.t. depth as some clients of this API may like.
 
488
              (If required, that ought to be done at higher layers.)
 
489
 
 
490
        :return: an iterator over (revision_id, depth, revno, end_of_merge)
 
491
            tuples where:
 
492
 
 
493
            * revision_id: the unique id of the revision
 
494
            * depth: How many levels of merging deep this node has been
 
495
              found.
 
496
            * revno_sequence: This field provides a sequence of
 
497
              revision numbers for all revisions. The format is:
 
498
              (REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
 
499
              branch that the revno is on. From left to right the REVNO numbers
 
500
              are the sequence numbers within that branch of the revision.
 
501
            * end_of_merge: When True the next node (earlier in history) is
 
502
              part of a different merge.
 
503
        """
 
504
        # Note: depth and revno values are in the context of the branch so
 
505
        # we need the full graph to get stable numbers, regardless of the
 
506
        # start_revision_id.
 
507
        if self._merge_sorted_revisions_cache is None:
 
508
            last_revision = self.last_revision()
 
509
            known_graph = self.repository.get_known_graph_ancestry(
 
510
                [last_revision])
 
511
            self._merge_sorted_revisions_cache = known_graph.merge_sort(
 
512
                last_revision)
 
513
        filtered = self._filter_merge_sorted_revisions(
 
514
            self._merge_sorted_revisions_cache, start_revision_id,
 
515
            stop_revision_id, stop_rule)
 
516
        # Make sure we don't return revisions that are not part of the
 
517
        # start_revision_id ancestry.
 
518
        filtered = self._filter_start_non_ancestors(filtered)
 
519
        if direction == 'reverse':
 
520
            return filtered
 
521
        if direction == 'forward':
 
522
            return reversed(list(filtered))
 
523
        else:
 
524
            raise ValueError('invalid direction %r' % direction)
 
525
 
 
526
    def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
 
527
        start_revision_id, stop_revision_id, stop_rule):
 
528
        """Iterate over an inclusive range of sorted revisions."""
 
529
        rev_iter = iter(merge_sorted_revisions)
 
530
        if start_revision_id is not None:
 
531
            for node in rev_iter:
 
532
                rev_id = node.key
 
533
                if rev_id != start_revision_id:
 
534
                    continue
 
535
                else:
 
536
                    # The decision to include the start or not
 
537
                    # depends on the stop_rule if a stop is provided
 
538
                    # so pop this node back into the iterator
 
539
                    rev_iter = itertools.chain(iter([node]), rev_iter)
 
540
                    break
 
541
        if stop_revision_id is None:
 
542
            # Yield everything
 
543
            for node in rev_iter:
 
544
                rev_id = node.key
 
545
                yield (rev_id, node.merge_depth, node.revno,
 
546
                       node.end_of_merge)
 
547
        elif stop_rule == 'exclude':
 
548
            for node in rev_iter:
 
549
                rev_id = node.key
 
550
                if rev_id == stop_revision_id:
 
551
                    return
 
552
                yield (rev_id, node.merge_depth, node.revno,
 
553
                       node.end_of_merge)
 
554
        elif stop_rule == 'include':
 
555
            for node in rev_iter:
 
556
                rev_id = node.key
 
557
                yield (rev_id, node.merge_depth, node.revno,
 
558
                       node.end_of_merge)
 
559
                if rev_id == stop_revision_id:
 
560
                    return
 
561
        elif stop_rule == 'with-merges-without-common-ancestry':
 
562
            # We want to exclude all revisions that are already part of the
 
563
            # stop_revision_id ancestry.
 
564
            graph = self.repository.get_graph()
 
565
            ancestors = graph.find_unique_ancestors(start_revision_id,
 
566
                                                    [stop_revision_id])
 
567
            for node in rev_iter:
 
568
                rev_id = node.key
 
569
                if rev_id not in ancestors:
 
570
                    continue
 
571
                yield (rev_id, node.merge_depth, node.revno,
 
572
                       node.end_of_merge)
 
573
        elif stop_rule == 'with-merges':
 
574
            stop_rev = self.repository.get_revision(stop_revision_id)
 
575
            if stop_rev.parent_ids:
 
576
                left_parent = stop_rev.parent_ids[0]
 
577
            else:
 
578
                left_parent = _mod_revision.NULL_REVISION
 
579
            # left_parent is the actual revision we want to stop logging at,
 
580
            # since we want to show the merged revisions after the stop_rev too
 
581
            reached_stop_revision_id = False
 
582
            revision_id_whitelist = []
 
583
            for node in rev_iter:
 
584
                rev_id = node.key
 
585
                if rev_id == left_parent:
 
586
                    # reached the left parent after the stop_revision
 
587
                    return
 
588
                if (not reached_stop_revision_id or
 
589
                        rev_id in revision_id_whitelist):
 
590
                    yield (rev_id, node.merge_depth, node.revno,
 
591
                       node.end_of_merge)
 
592
                    if reached_stop_revision_id or rev_id == stop_revision_id:
 
593
                        # only do the merged revs of rev_id from now on
 
594
                        rev = self.repository.get_revision(rev_id)
 
595
                        if rev.parent_ids:
 
596
                            reached_stop_revision_id = True
 
597
                            revision_id_whitelist.extend(rev.parent_ids)
 
598
        else:
 
599
            raise ValueError('invalid stop_rule %r' % stop_rule)
 
600
 
 
601
    def _filter_start_non_ancestors(self, rev_iter):
 
602
        # If we started from a dotted revno, we want to consider it as a tip
 
603
        # and don't want to yield revisions that are not part of its
 
604
        # ancestry. Given the order guaranteed by the merge sort, we will see
 
605
        # uninteresting descendants of the first parent of our tip before the
 
606
        # tip itself.
 
607
        first = next(rev_iter)
 
608
        (rev_id, merge_depth, revno, end_of_merge) = first
 
609
        yield first
 
610
        if not merge_depth:
 
611
            # We start at a mainline revision so by definition, all others
 
612
            # revisions in rev_iter are ancestors
 
613
            for node in rev_iter:
 
614
                yield node
 
615
 
 
616
        clean = False
 
617
        whitelist = set()
 
618
        pmap = self.repository.get_parent_map([rev_id])
 
619
        parents = pmap.get(rev_id, [])
 
620
        if parents:
 
621
            whitelist.update(parents)
 
622
        else:
 
623
            # If there is no parents, there is nothing of interest left
 
624
 
 
625
            # FIXME: It's hard to test this scenario here as this code is never
 
626
            # called in that case. -- vila 20100322
 
627
            return
 
628
 
 
629
        for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
 
630
            if not clean:
 
631
                if rev_id in whitelist:
 
632
                    pmap = self.repository.get_parent_map([rev_id])
 
633
                    parents = pmap.get(rev_id, [])
 
634
                    whitelist.remove(rev_id)
 
635
                    whitelist.update(parents)
 
636
                    if merge_depth == 0:
 
637
                        # We've reached the mainline, there is nothing left to
 
638
                        # filter
 
639
                        clean = True
 
640
                else:
 
641
                    # A revision that is not part of the ancestry of our
 
642
                    # starting revision.
 
643
                    continue
 
644
            yield (rev_id, merge_depth, revno, end_of_merge)
 
645
 
 
646
    def leave_lock_in_place(self):
 
647
        """Tell this branch object not to release the physical lock when this
 
648
        object is unlocked.
 
649
 
 
650
        If lock_write doesn't return a token, then this method is not supported.
 
651
        """
 
652
        self.control_files.leave_in_place()
 
653
 
 
654
    def dont_leave_lock_in_place(self):
 
655
        """Tell this branch object to release the physical lock when this
 
656
        object is unlocked, even if it didn't originally acquire it.
 
657
 
 
658
        If lock_write doesn't return a token, then this method is not supported.
 
659
        """
 
660
        self.control_files.dont_leave_in_place()
 
661
 
 
662
    def bind(self, other):
 
663
        """Bind the local branch the other branch.
 
664
 
 
665
        :param other: The branch to bind to
 
666
        :type other: Branch
 
667
        """
 
668
        raise errors.UpgradeRequired(self.user_url)
 
669
 
 
670
    def get_append_revisions_only(self):
 
671
        """Whether it is only possible to append revisions to the history.
 
672
        """
 
673
        if not self._format.supports_set_append_revisions_only():
 
674
            return False
 
675
        return self.get_config_stack().get('append_revisions_only')
 
676
 
 
677
    def set_append_revisions_only(self, enabled):
 
678
        if not self._format.supports_set_append_revisions_only():
 
679
            raise errors.UpgradeRequired(self.user_url)
 
680
        self.get_config_stack().set('append_revisions_only', enabled)
 
681
 
 
682
    def set_reference_info(self, file_id, tree_path, branch_location):
 
683
        """Set the branch location to use for a tree reference."""
 
684
        raise errors.UnsupportedOperation(self.set_reference_info, self)
 
685
 
 
686
    def get_reference_info(self, file_id):
 
687
        """Get the tree_path and branch_location for a tree reference."""
 
688
        raise errors.UnsupportedOperation(self.get_reference_info, self)
 
689
 
 
690
    @needs_write_lock
 
691
    def fetch(self, from_branch, last_revision=None, limit=None):
 
692
        """Copy revisions from from_branch into this branch.
 
693
 
 
694
        :param from_branch: Where to copy from.
 
695
        :param last_revision: What revision to stop at (None for at the end
 
696
                              of the branch.
 
697
        :param limit: Optional rough limit of revisions to fetch
 
698
        :return: None
 
699
        """
 
700
        return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
 
701
 
 
702
    def get_bound_location(self):
 
703
        """Return the URL of the branch we are bound to.
 
704
 
 
705
        Older format branches cannot bind, please be sure to use a metadir
 
706
        branch.
 
707
        """
 
708
        return None
 
709
 
 
710
    def get_old_bound_location(self):
 
711
        """Return the URL of the branch we used to be bound to
 
712
        """
 
713
        raise errors.UpgradeRequired(self.user_url)
 
714
 
 
715
    def get_commit_builder(self, parents, config_stack=None, timestamp=None,
 
716
                           timezone=None, committer=None, revprops=None,
 
717
                           revision_id=None, lossy=False):
 
718
        """Obtain a CommitBuilder for this branch.
 
719
 
 
720
        :param parents: Revision ids of the parents of the new revision.
 
721
        :param config: Optional configuration to use.
 
722
        :param timestamp: Optional timestamp recorded for commit.
 
723
        :param timezone: Optional timezone for timestamp.
 
724
        :param committer: Optional committer to set for commit.
 
725
        :param revprops: Optional dictionary of revision properties.
 
726
        :param revision_id: Optional revision id.
 
727
        :param lossy: Whether to discard data that can not be natively
 
728
            represented, when pushing to a foreign VCS 
 
729
        """
 
730
 
 
731
        if config_stack is None:
 
732
            config_stack = self.get_config_stack()
 
733
 
 
734
        return self.repository.get_commit_builder(self, parents, config_stack,
 
735
            timestamp, timezone, committer, revprops, revision_id,
 
736
            lossy)
 
737
 
 
738
    def get_master_branch(self, possible_transports=None):
 
739
        """Return the branch we are bound to.
 
740
 
 
741
        :return: Either a Branch, or None
 
742
        """
 
743
        return None
 
744
 
 
745
    def get_stacked_on_url(self):
 
746
        """Get the URL this branch is stacked against.
 
747
 
 
748
        :raises NotStacked: If the branch is not stacked.
 
749
        :raises UnstackableBranchFormat: If the branch does not support
 
750
            stacking.
 
751
        """
 
752
        raise NotImplementedError(self.get_stacked_on_url)
 
753
 
 
754
    def print_file(self, file, revision_id):
 
755
        """Print `file` to stdout."""
 
756
        raise NotImplementedError(self.print_file)
 
757
 
 
758
    @needs_write_lock
 
759
    def set_last_revision_info(self, revno, revision_id):
 
760
        """Set the last revision of this branch.
 
761
 
 
762
        The caller is responsible for checking that the revno is correct
 
763
        for this revision id.
 
764
 
 
765
        It may be possible to set the branch last revision to an id not
 
766
        present in the repository.  However, branches can also be
 
767
        configured to check constraints on history, in which case this may not
 
768
        be permitted.
 
769
        """
 
770
        raise NotImplementedError(self.set_last_revision_info)
 
771
 
 
772
    @needs_write_lock
 
773
    def generate_revision_history(self, revision_id, last_rev=None,
 
774
                                  other_branch=None):
 
775
        """See Branch.generate_revision_history"""
 
776
        graph = self.repository.get_graph()
 
777
        (last_revno, last_revid) = self.last_revision_info()
 
778
        known_revision_ids = [
 
779
            (last_revid, last_revno),
 
780
            (_mod_revision.NULL_REVISION, 0),
 
781
            ]
 
782
        if last_rev is not None:
 
783
            if not graph.is_ancestor(last_rev, revision_id):
 
784
                # our previous tip is not merged into stop_revision
 
785
                raise errors.DivergedBranches(self, other_branch)
 
786
        revno = graph.find_distance_to_null(revision_id, known_revision_ids)
 
787
        self.set_last_revision_info(revno, revision_id)
 
788
 
 
789
    @needs_write_lock
 
790
    def set_parent(self, url):
 
791
        """See Branch.set_parent."""
 
792
        # TODO: Maybe delete old location files?
 
793
        # URLs should never be unicode, even on the local fs,
 
794
        # FIXUP this and get_parent in a future branch format bump:
 
795
        # read and rewrite the file. RBC 20060125
 
796
        if url is not None:
 
797
            if isinstance(url, unicode):
 
798
                try:
 
799
                    url = url.encode('ascii')
 
800
                except UnicodeEncodeError:
 
801
                    raise errors.InvalidURL(url,
 
802
                        "Urls must be 7-bit ascii, "
 
803
                        "use breezy.urlutils.escape")
 
804
            url = urlutils.relative_url(self.base, url)
 
805
        self._set_parent_location(url)
 
806
 
 
807
    @needs_write_lock
 
808
    def set_stacked_on_url(self, url):
 
809
        """Set the URL this branch is stacked against.
 
810
 
 
811
        :raises UnstackableBranchFormat: If the branch does not support
 
812
            stacking.
 
813
        :raises UnstackableRepositoryFormat: If the repository does not support
 
814
            stacking.
 
815
        """
 
816
        if not self._format.supports_stacking():
 
817
            raise errors.UnstackableBranchFormat(self._format, self.user_url)
 
818
        # XXX: Changing from one fallback repository to another does not check
 
819
        # that all the data you need is present in the new fallback.
 
820
        # Possibly it should.
 
821
        self._check_stackable_repo()
 
822
        if not url:
 
823
            try:
 
824
                old_url = self.get_stacked_on_url()
 
825
            except (errors.NotStacked, errors.UnstackableBranchFormat,
 
826
                errors.UnstackableRepositoryFormat):
 
827
                return
 
828
            self._unstack()
 
829
        else:
 
830
            self._activate_fallback_location(url,
 
831
                possible_transports=[self.bzrdir.root_transport])
 
832
        # write this out after the repository is stacked to avoid setting a
 
833
        # stacked config that doesn't work.
 
834
        self._set_config_location('stacked_on_location', url)
 
835
 
 
836
    def _unstack(self):
 
837
        """Change a branch to be unstacked, copying data as needed.
 
838
 
 
839
        Don't call this directly, use set_stacked_on_url(None).
 
840
        """
 
841
        pb = ui.ui_factory.nested_progress_bar()
 
842
        try:
 
843
            pb.update(gettext("Unstacking"))
 
844
            # The basic approach here is to fetch the tip of the branch,
 
845
            # including all available ghosts, from the existing stacked
 
846
            # repository into a new repository object without the fallbacks. 
 
847
            #
 
848
            # XXX: See <https://launchpad.net/bugs/397286> - this may not be
 
849
            # correct for CHKMap repostiories
 
850
            old_repository = self.repository
 
851
            if len(old_repository._fallback_repositories) != 1:
 
852
                raise AssertionError("can't cope with fallback repositories "
 
853
                    "of %r (fallbacks: %r)" % (old_repository,
 
854
                        old_repository._fallback_repositories))
 
855
            # Open the new repository object.
 
856
            # Repositories don't offer an interface to remove fallback
 
857
            # repositories today; take the conceptually simpler option and just
 
858
            # reopen it.  We reopen it starting from the URL so that we
 
859
            # get a separate connection for RemoteRepositories and can
 
860
            # stream from one of them to the other.  This does mean doing
 
861
            # separate SSH connection setup, but unstacking is not a
 
862
            # common operation so it's tolerable.
 
863
            new_bzrdir = controldir.ControlDir.open(
 
864
                self.bzrdir.root_transport.base)
 
865
            new_repository = new_bzrdir.find_repository()
 
866
            if new_repository._fallback_repositories:
 
867
                raise AssertionError("didn't expect %r to have "
 
868
                    "fallback_repositories"
 
869
                    % (self.repository,))
 
870
            # Replace self.repository with the new repository.
 
871
            # Do our best to transfer the lock state (i.e. lock-tokens and
 
872
            # lock count) of self.repository to the new repository.
 
873
            lock_token = old_repository.lock_write().repository_token
 
874
            self.repository = new_repository
 
875
            if isinstance(self, remote.RemoteBranch):
 
876
                # Remote branches can have a second reference to the old
 
877
                # repository that need to be replaced.
 
878
                if self._real_branch is not None:
 
879
                    self._real_branch.repository = new_repository
 
880
            self.repository.lock_write(token=lock_token)
 
881
            if lock_token is not None:
 
882
                old_repository.leave_lock_in_place()
 
883
            old_repository.unlock()
 
884
            if lock_token is not None:
 
885
                # XXX: self.repository.leave_lock_in_place() before this
 
886
                # function will not be preserved.  Fortunately that doesn't
 
887
                # affect the current default format (2a), and would be a
 
888
                # corner-case anyway.
 
889
                #  - Andrew Bennetts, 2010/06/30
 
890
                self.repository.dont_leave_lock_in_place()
 
891
            old_lock_count = 0
 
892
            while True:
 
893
                try:
 
894
                    old_repository.unlock()
 
895
                except errors.LockNotHeld:
 
896
                    break
 
897
                old_lock_count += 1
 
898
            if old_lock_count == 0:
 
899
                raise AssertionError(
 
900
                    'old_repository should have been locked at least once.')
 
901
            for i in range(old_lock_count-1):
 
902
                self.repository.lock_write()
 
903
            # Fetch from the old repository into the new.
 
904
            old_repository.lock_read()
 
905
            try:
 
906
                # XXX: If you unstack a branch while it has a working tree
 
907
                # with a pending merge, the pending-merged revisions will no
 
908
                # longer be present.  You can (probably) revert and remerge.
 
909
                try:
 
910
                    tags_to_fetch = set(self.tags.get_reverse_tag_dict())
 
911
                except errors.TagsNotSupported:
 
912
                    tags_to_fetch = set()
 
913
                fetch_spec = vf_search.NotInOtherForRevs(self.repository,
 
914
                    old_repository, required_ids=[self.last_revision()],
 
915
                    if_present_ids=tags_to_fetch, find_ghosts=True).execute()
 
916
                self.repository.fetch(old_repository, fetch_spec=fetch_spec)
 
917
            finally:
 
918
                old_repository.unlock()
 
919
        finally:
 
920
            pb.finished()
 
921
 
 
922
    def _set_tags_bytes(self, bytes):
 
923
        """Mirror method for _get_tags_bytes.
 
924
 
 
925
        :seealso: Branch._get_tags_bytes.
 
926
        """
 
927
        op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
 
928
        op.add_cleanup(self.lock_write().unlock)
 
929
        return op.run_simple(bytes)
 
930
 
 
931
    def _set_tags_bytes_locked(self, bytes):
 
932
        self._tags_bytes = bytes
 
933
        return self._transport.put_bytes('tags', bytes)
 
934
 
 
935
    def _cache_revision_history(self, rev_history):
 
936
        """Set the cached revision history to rev_history.
 
937
 
 
938
        The revision_history method will use this cache to avoid regenerating
 
939
        the revision history.
 
940
 
 
941
        This API is semi-public; it only for use by subclasses, all other code
 
942
        should consider it to be private.
 
943
        """
 
944
        self._revision_history_cache = rev_history
 
945
 
 
946
    def _cache_revision_id_to_revno(self, revision_id_to_revno):
 
947
        """Set the cached revision_id => revno map to revision_id_to_revno.
 
948
 
 
949
        This API is semi-public; it only for use by subclasses, all other code
 
950
        should consider it to be private.
 
951
        """
 
952
        self._revision_id_to_revno_cache = revision_id_to_revno
 
953
 
 
954
    def _clear_cached_state(self):
 
955
        """Clear any cached data on this branch, e.g. cached revision history.
 
956
 
 
957
        This means the next call to revision_history will need to call
 
958
        _gen_revision_history.
 
959
 
 
960
        This API is semi-public; it is only for use by subclasses, all other
 
961
        code should consider it to be private.
 
962
        """
 
963
        self._revision_history_cache = None
 
964
        self._revision_id_to_revno_cache = None
 
965
        self._last_revision_info_cache = None
 
966
        self._master_branch_cache = None
 
967
        self._merge_sorted_revisions_cache = None
 
968
        self._partial_revision_history_cache = []
 
969
        self._partial_revision_id_to_revno_cache = {}
 
970
        self._tags_bytes = None
 
971
 
 
972
    def _gen_revision_history(self):
 
973
        """Return sequence of revision hashes on to this branch.
 
974
 
 
975
        Unlike revision_history, this method always regenerates or rereads the
 
976
        revision history, i.e. it does not cache the result, so repeated calls
 
977
        may be expensive.
 
978
 
 
979
        Concrete subclasses should override this instead of revision_history so
 
980
        that subclasses do not need to deal with caching logic.
 
981
 
 
982
        This API is semi-public; it only for use by subclasses, all other code
 
983
        should consider it to be private.
 
984
        """
 
985
        raise NotImplementedError(self._gen_revision_history)
 
986
 
 
987
    def _revision_history(self):
 
988
        if 'evil' in debug.debug_flags:
 
989
            mutter_callsite(3, "revision_history scales with history.")
 
990
        if self._revision_history_cache is not None:
 
991
            history = self._revision_history_cache
 
992
        else:
 
993
            history = self._gen_revision_history()
 
994
            self._cache_revision_history(history)
 
995
        return list(history)
 
996
 
 
997
    def revno(self):
 
998
        """Return current revision number for this branch.
 
999
 
 
1000
        That is equivalent to the number of revisions committed to
 
1001
        this branch.
 
1002
        """
 
1003
        return self.last_revision_info()[0]
 
1004
 
 
1005
    def unbind(self):
 
1006
        """Older format branches cannot bind or unbind."""
 
1007
        raise errors.UpgradeRequired(self.user_url)
 
1008
 
 
1009
    def last_revision(self):
 
1010
        """Return last revision id, or NULL_REVISION."""
 
1011
        return self.last_revision_info()[1]
 
1012
 
 
1013
    @needs_read_lock
 
1014
    def last_revision_info(self):
 
1015
        """Return information about the last revision.
 
1016
 
 
1017
        :return: A tuple (revno, revision_id).
 
1018
        """
 
1019
        if self._last_revision_info_cache is None:
 
1020
            self._last_revision_info_cache = self._read_last_revision_info()
 
1021
        return self._last_revision_info_cache
 
1022
 
 
1023
    def _read_last_revision_info(self):
 
1024
        raise NotImplementedError(self._read_last_revision_info)
 
1025
 
 
1026
    def import_last_revision_info_and_tags(self, source, revno, revid,
 
1027
                                           lossy=False):
 
1028
        """Set the last revision info, importing from another repo if necessary.
 
1029
 
 
1030
        This is used by the bound branch code to upload a revision to
 
1031
        the master branch first before updating the tip of the local branch.
 
1032
        Revisions referenced by source's tags are also transferred.
 
1033
 
 
1034
        :param source: Source branch to optionally fetch from
 
1035
        :param revno: Revision number of the new tip
 
1036
        :param revid: Revision id of the new tip
 
1037
        :param lossy: Whether to discard metadata that can not be
 
1038
            natively represented
 
1039
        :return: Tuple with the new revision number and revision id
 
1040
            (should only be different from the arguments when lossy=True)
 
1041
        """
 
1042
        if not self.repository.has_same_location(source.repository):
 
1043
            self.fetch(source, revid)
 
1044
        self.set_last_revision_info(revno, revid)
 
1045
        return (revno, revid)
 
1046
 
 
1047
    def revision_id_to_revno(self, revision_id):
 
1048
        """Given a revision id, return its revno"""
 
1049
        if _mod_revision.is_null(revision_id):
 
1050
            return 0
 
1051
        history = self._revision_history()
 
1052
        try:
 
1053
            return history.index(revision_id) + 1
 
1054
        except ValueError:
 
1055
            raise errors.NoSuchRevision(self, revision_id)
 
1056
 
 
1057
    @needs_read_lock
 
1058
    def get_rev_id(self, revno, history=None):
 
1059
        """Find the revision id of the specified revno."""
 
1060
        if revno == 0:
 
1061
            return _mod_revision.NULL_REVISION
 
1062
        last_revno, last_revid = self.last_revision_info()
 
1063
        if revno == last_revno:
 
1064
            return last_revid
 
1065
        if revno <= 0 or revno > last_revno:
 
1066
            raise errors.NoSuchRevision(self, revno)
 
1067
        distance_from_last = last_revno - revno
 
1068
        if len(self._partial_revision_history_cache) <= distance_from_last:
 
1069
            self._extend_partial_history(distance_from_last)
 
1070
        return self._partial_revision_history_cache[distance_from_last]
 
1071
 
 
1072
    def pull(self, source, overwrite=False, stop_revision=None,
 
1073
             possible_transports=None, *args, **kwargs):
 
1074
        """Mirror source into this branch.
 
1075
 
 
1076
        This branch is considered to be 'local', having low latency.
 
1077
 
 
1078
        :returns: PullResult instance
 
1079
        """
 
1080
        return InterBranch.get(source, self).pull(overwrite=overwrite,
 
1081
            stop_revision=stop_revision,
 
1082
            possible_transports=possible_transports, *args, **kwargs)
 
1083
 
 
1084
    def push(self, target, overwrite=False, stop_revision=None, lossy=False,
 
1085
            *args, **kwargs):
 
1086
        """Mirror this branch into target.
 
1087
 
 
1088
        This branch is considered to be 'local', having low latency.
 
1089
        """
 
1090
        return InterBranch.get(self, target).push(overwrite, stop_revision,
 
1091
            lossy, *args, **kwargs)
 
1092
 
 
1093
    def basis_tree(self):
 
1094
        """Return `Tree` object for last revision."""
 
1095
        return self.repository.revision_tree(self.last_revision())
 
1096
 
 
1097
    def get_parent(self):
 
1098
        """Return the parent location of the branch.
 
1099
 
 
1100
        This is the default location for pull/missing.  The usual
 
1101
        pattern is that the user can override it by specifying a
 
1102
        location.
 
1103
        """
 
1104
        parent = self._get_parent_location()
 
1105
        if parent is None:
 
1106
            return parent
 
1107
        # This is an old-format absolute path to a local branch
 
1108
        # turn it into a url
 
1109
        if parent.startswith('/'):
 
1110
            parent = urlutils.local_path_to_url(parent.decode('utf8'))
 
1111
        try:
 
1112
            return urlutils.join(self.base[:-1], parent)
 
1113
        except errors.InvalidURLJoin as e:
 
1114
            raise errors.InaccessibleParent(parent, self.user_url)
 
1115
 
 
1116
    def _get_parent_location(self):
 
1117
        raise NotImplementedError(self._get_parent_location)
 
1118
 
 
1119
    def _set_config_location(self, name, url, config=None,
 
1120
                             make_relative=False):
 
1121
        if config is None:
 
1122
            config = self.get_config_stack()
 
1123
        if url is None:
 
1124
            url = ''
 
1125
        elif make_relative:
 
1126
            url = urlutils.relative_url(self.base, url)
 
1127
        config.set(name, url)
 
1128
 
 
1129
    def _get_config_location(self, name, config=None):
 
1130
        if config is None:
 
1131
            config = self.get_config_stack()
 
1132
        location = config.get(name)
 
1133
        if location == '':
 
1134
            location = None
 
1135
        return location
 
1136
 
 
1137
    def get_child_submit_format(self):
 
1138
        """Return the preferred format of submissions to this branch."""
 
1139
        return self.get_config_stack().get('child_submit_format')
 
1140
 
 
1141
    def get_submit_branch(self):
 
1142
        """Return the submit location of the branch.
 
1143
 
 
1144
        This is the default location for bundle.  The usual
 
1145
        pattern is that the user can override it by specifying a
 
1146
        location.
 
1147
        """
 
1148
        return self.get_config_stack().get('submit_branch')
 
1149
 
 
1150
    def set_submit_branch(self, location):
 
1151
        """Return the submit location of the branch.
 
1152
 
 
1153
        This is the default location for bundle.  The usual
 
1154
        pattern is that the user can override it by specifying a
 
1155
        location.
 
1156
        """
 
1157
        self.get_config_stack().set('submit_branch', location)
 
1158
 
 
1159
    def get_public_branch(self):
 
1160
        """Return the public location of the branch.
 
1161
 
 
1162
        This is used by merge directives.
 
1163
        """
 
1164
        return self._get_config_location('public_branch')
 
1165
 
 
1166
    def set_public_branch(self, location):
 
1167
        """Return the submit location of the branch.
 
1168
 
 
1169
        This is the default location for bundle.  The usual
 
1170
        pattern is that the user can override it by specifying a
 
1171
        location.
 
1172
        """
 
1173
        self._set_config_location('public_branch', location)
 
1174
 
 
1175
    def get_push_location(self):
 
1176
        """Return None or the location to push this branch to."""
 
1177
        return self.get_config_stack().get('push_location')
 
1178
 
 
1179
    def set_push_location(self, location):
 
1180
        """Set a new push location for this branch."""
 
1181
        raise NotImplementedError(self.set_push_location)
 
1182
 
 
1183
    def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
 
1184
        """Run the post_change_branch_tip hooks."""
 
1185
        hooks = Branch.hooks['post_change_branch_tip']
 
1186
        if not hooks:
 
1187
            return
 
1188
        new_revno, new_revid = self.last_revision_info()
 
1189
        params = ChangeBranchTipParams(
 
1190
            self, old_revno, new_revno, old_revid, new_revid)
 
1191
        for hook in hooks:
 
1192
            hook(params)
 
1193
 
 
1194
    def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
 
1195
        """Run the pre_change_branch_tip hooks."""
 
1196
        hooks = Branch.hooks['pre_change_branch_tip']
 
1197
        if not hooks:
 
1198
            return
 
1199
        old_revno, old_revid = self.last_revision_info()
 
1200
        params = ChangeBranchTipParams(
 
1201
            self, old_revno, new_revno, old_revid, new_revid)
 
1202
        for hook in hooks:
 
1203
            hook(params)
 
1204
 
 
1205
    @needs_write_lock
 
1206
    def update(self):
 
1207
        """Synchronise this branch with the master branch if any.
 
1208
 
 
1209
        :return: None or the last_revision pivoted out during the update.
 
1210
        """
 
1211
        return None
 
1212
 
 
1213
    def check_revno(self, revno):
 
1214
        """\
 
1215
        Check whether a revno corresponds to any revision.
 
1216
        Zero (the NULL revision) is considered valid.
 
1217
        """
 
1218
        if revno != 0:
 
1219
            self.check_real_revno(revno)
 
1220
 
 
1221
    def check_real_revno(self, revno):
 
1222
        """\
 
1223
        Check whether a revno corresponds to a real revision.
 
1224
        Zero (the NULL revision) is considered invalid
 
1225
        """
 
1226
        if revno < 1 or revno > self.revno():
 
1227
            raise errors.InvalidRevisionNumber(revno)
 
1228
 
 
1229
    @needs_read_lock
 
1230
    def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
 
1231
        """Clone this branch into to_bzrdir preserving all semantic values.
 
1232
 
 
1233
        Most API users will want 'create_clone_on_transport', which creates a
 
1234
        new bzrdir and branch on the fly.
 
1235
 
 
1236
        revision_id: if not None, the revision history in the new branch will
 
1237
                     be truncated to end with revision_id.
 
1238
        """
 
1239
        result = to_bzrdir.create_branch()
 
1240
        result.lock_write()
 
1241
        try:
 
1242
            if repository_policy is not None:
 
1243
                repository_policy.configure_branch(result)
 
1244
            self.copy_content_into(result, revision_id=revision_id)
 
1245
        finally:
 
1246
            result.unlock()
 
1247
        return result
 
1248
 
 
1249
    @needs_read_lock
 
1250
    def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
 
1251
            repository=None):
 
1252
        """Create a new line of development from the branch, into to_bzrdir.
 
1253
 
 
1254
        to_bzrdir controls the branch format.
 
1255
 
 
1256
        revision_id: if not None, the revision history in the new branch will
 
1257
                     be truncated to end with revision_id.
 
1258
        """
 
1259
        if (repository_policy is not None and
 
1260
            repository_policy.requires_stacking()):
 
1261
            to_bzrdir._format.require_stacking(_skip_repo=True)
 
1262
        result = to_bzrdir.create_branch(repository=repository)
 
1263
        result.lock_write()
 
1264
        try:
 
1265
            if repository_policy is not None:
 
1266
                repository_policy.configure_branch(result)
 
1267
            self.copy_content_into(result, revision_id=revision_id)
 
1268
            master_url = self.get_bound_location()
 
1269
            if master_url is None:
 
1270
                result.set_parent(self.bzrdir.root_transport.base)
 
1271
            else:
 
1272
                result.set_parent(master_url)
 
1273
        finally:
 
1274
            result.unlock()
 
1275
        return result
 
1276
 
 
1277
    def _synchronize_history(self, destination, revision_id):
 
1278
        """Synchronize last revision and revision history between branches.
 
1279
 
 
1280
        This version is most efficient when the destination is also a
 
1281
        BzrBranch6, but works for BzrBranch5, as long as the destination's
 
1282
        repository contains all the lefthand ancestors of the intended
 
1283
        last_revision.  If not, set_last_revision_info will fail.
 
1284
 
 
1285
        :param destination: The branch to copy the history into
 
1286
        :param revision_id: The revision-id to truncate history at.  May
 
1287
          be None to copy complete history.
 
1288
        """
 
1289
        source_revno, source_revision_id = self.last_revision_info()
 
1290
        if revision_id is None:
 
1291
            revno, revision_id = source_revno, source_revision_id
 
1292
        else:
 
1293
            graph = self.repository.get_graph()
 
1294
            try:
 
1295
                revno = graph.find_distance_to_null(revision_id, 
 
1296
                    [(source_revision_id, source_revno)])
 
1297
            except errors.GhostRevisionsHaveNoRevno:
 
1298
                # Default to 1, if we can't find anything else
 
1299
                revno = 1
 
1300
        destination.set_last_revision_info(revno, revision_id)
 
1301
 
 
1302
    def copy_content_into(self, destination, revision_id=None):
 
1303
        """Copy the content of self into destination.
 
1304
 
 
1305
        revision_id: if not None, the revision history in the new branch will
 
1306
                     be truncated to end with revision_id.
 
1307
        """
 
1308
        return InterBranch.get(self, destination).copy_content_into(
 
1309
            revision_id=revision_id)
 
1310
 
 
1311
    def update_references(self, target):
 
1312
        if not getattr(self._format, 'supports_reference_locations', False):
 
1313
            return
 
1314
        reference_dict = self._get_all_reference_info()
 
1315
        if len(reference_dict) == 0:
 
1316
            return
 
1317
        old_base = self.base
 
1318
        new_base = target.base
 
1319
        target_reference_dict = target._get_all_reference_info()
 
1320
        for file_id, (tree_path, branch_location) in viewitems(reference_dict):
 
1321
            branch_location = urlutils.rebase_url(branch_location,
 
1322
                                                  old_base, new_base)
 
1323
            target_reference_dict.setdefault(
 
1324
                file_id, (tree_path, branch_location))
 
1325
        target._set_all_reference_info(target_reference_dict)
 
1326
 
 
1327
    @needs_read_lock
 
1328
    def check(self, refs):
 
1329
        """Check consistency of the branch.
 
1330
 
 
1331
        In particular this checks that revisions given in the revision-history
 
1332
        do actually match up in the revision graph, and that they're all
 
1333
        present in the repository.
 
1334
 
 
1335
        Callers will typically also want to check the repository.
 
1336
 
 
1337
        :param refs: Calculated refs for this branch as specified by
 
1338
            branch._get_check_refs()
 
1339
        :return: A BranchCheckResult.
 
1340
        """
 
1341
        result = BranchCheckResult(self)
 
1342
        last_revno, last_revision_id = self.last_revision_info()
 
1343
        actual_revno = refs[('lefthand-distance', last_revision_id)]
 
1344
        if actual_revno != last_revno:
 
1345
            result.errors.append(errors.BzrCheckError(
 
1346
                'revno does not match len(mainline) %s != %s' % (
 
1347
                last_revno, actual_revno)))
 
1348
        # TODO: We should probably also check that self.revision_history
 
1349
        # matches the repository for older branch formats.
 
1350
        # If looking for the code that cross-checks repository parents against
 
1351
        # the Graph.iter_lefthand_ancestry output, that is now a repository
 
1352
        # specific check.
 
1353
        return result
 
1354
 
 
1355
    def _get_checkout_format(self, lightweight=False):
 
1356
        """Return the most suitable metadir for a checkout of this branch.
 
1357
        Weaves are used if this branch's repository uses weaves.
 
1358
        """
 
1359
        format = self.repository.bzrdir.checkout_metadir()
 
1360
        format.set_branch_format(self._format)
 
1361
        return format
 
1362
 
 
1363
    def create_clone_on_transport(self, to_transport, revision_id=None,
 
1364
        stacked_on=None, create_prefix=False, use_existing_dir=False,
 
1365
        no_tree=None):
 
1366
        """Create a clone of this branch and its bzrdir.
 
1367
 
 
1368
        :param to_transport: The transport to clone onto.
 
1369
        :param revision_id: The revision id to use as tip in the new branch.
 
1370
            If None the tip is obtained from this branch.
 
1371
        :param stacked_on: An optional URL to stack the clone on.
 
1372
        :param create_prefix: Create any missing directories leading up to
 
1373
            to_transport.
 
1374
        :param use_existing_dir: Use an existing directory if one exists.
 
1375
        """
 
1376
        # XXX: Fix the bzrdir API to allow getting the branch back from the
 
1377
        # clone call. Or something. 20090224 RBC/spiv.
 
1378
        # XXX: Should this perhaps clone colocated branches as well, 
 
1379
        # rather than just the default branch? 20100319 JRV
 
1380
        if revision_id is None:
 
1381
            revision_id = self.last_revision()
 
1382
        dir_to = self.bzrdir.clone_on_transport(to_transport,
 
1383
            revision_id=revision_id, stacked_on=stacked_on,
 
1384
            create_prefix=create_prefix, use_existing_dir=use_existing_dir,
 
1385
            no_tree=no_tree)
 
1386
        return dir_to.open_branch()
 
1387
 
 
1388
    def create_checkout(self, to_location, revision_id=None,
 
1389
                        lightweight=False, accelerator_tree=None,
 
1390
                        hardlink=False):
 
1391
        """Create a checkout of a branch.
 
1392
 
 
1393
        :param to_location: The url to produce the checkout at
 
1394
        :param revision_id: The revision to check out
 
1395
        :param lightweight: If True, produce a lightweight checkout, otherwise,
 
1396
            produce a bound branch (heavyweight checkout)
 
1397
        :param accelerator_tree: A tree which can be used for retrieving file
 
1398
            contents more quickly than the revision tree, i.e. a workingtree.
 
1399
            The revision tree will be used for cases where accelerator_tree's
 
1400
            content is different.
 
1401
        :param hardlink: If true, hard-link files from accelerator_tree,
 
1402
            where possible.
 
1403
        :return: The tree of the created checkout
 
1404
        """
 
1405
        t = transport.get_transport(to_location)
 
1406
        t.ensure_base()
 
1407
        format = self._get_checkout_format(lightweight=lightweight)
 
1408
        try:
 
1409
            checkout = format.initialize_on_transport(t)
 
1410
        except errors.AlreadyControlDirError:
 
1411
            # It's fine if the control directory already exists,
 
1412
            # as long as there is no existing branch and working tree.
 
1413
            checkout = controldir.ControlDir.open_from_transport(t)
 
1414
            try:
 
1415
                checkout.open_branch()
 
1416
            except errors.NotBranchError:
 
1417
                pass
 
1418
            else:
 
1419
                raise errors.AlreadyControlDirError(t.base)
 
1420
            if checkout.control_transport.base == self.bzrdir.control_transport.base:
 
1421
                # When checking out to the same control directory,
 
1422
                # always create a lightweight checkout
 
1423
                lightweight = True
 
1424
 
 
1425
        if lightweight:
 
1426
            from_branch = checkout.set_branch_reference(target_branch=self)
 
1427
        else:
 
1428
            policy = checkout.determine_repository_policy()
 
1429
            repo = policy.acquire_repository()[0]
 
1430
            checkout_branch = checkout.create_branch()
 
1431
            checkout_branch.bind(self)
 
1432
            # pull up to the specified revision_id to set the initial
 
1433
            # branch tip correctly, and seed it with history.
 
1434
            checkout_branch.pull(self, stop_revision=revision_id)
 
1435
            from_branch = None
 
1436
        tree = checkout.create_workingtree(revision_id,
 
1437
                                           from_branch=from_branch,
 
1438
                                           accelerator_tree=accelerator_tree,
 
1439
                                           hardlink=hardlink)
 
1440
        basis_tree = tree.basis_tree()
 
1441
        basis_tree.lock_read()
 
1442
        try:
 
1443
            for path, file_id in basis_tree.iter_references():
 
1444
                reference_parent = self.reference_parent(file_id, path)
 
1445
                reference_parent.create_checkout(tree.abspath(path),
 
1446
                    basis_tree.get_reference_revision(file_id, path),
 
1447
                    lightweight)
 
1448
        finally:
 
1449
            basis_tree.unlock()
 
1450
        return tree
 
1451
 
 
1452
    @needs_write_lock
 
1453
    def reconcile(self, thorough=True):
 
1454
        """Make sure the data stored in this branch is consistent."""
 
1455
        from breezy.reconcile import BranchReconciler
 
1456
        reconciler = BranchReconciler(self, thorough=thorough)
 
1457
        reconciler.reconcile()
 
1458
        return reconciler
 
1459
 
 
1460
    def reference_parent(self, file_id, path, possible_transports=None):
 
1461
        """Return the parent branch for a tree-reference file_id
 
1462
 
 
1463
        :param file_id: The file_id of the tree reference
 
1464
        :param path: The path of the file_id in the tree
 
1465
        :return: A branch associated with the file_id
 
1466
        """
 
1467
        # FIXME should provide multiple branches, based on config
 
1468
        return Branch.open(self.bzrdir.root_transport.clone(path).base,
 
1469
                           possible_transports=possible_transports)
 
1470
 
 
1471
    def supports_tags(self):
 
1472
        return self._format.supports_tags()
 
1473
 
 
1474
    def automatic_tag_name(self, revision_id):
 
1475
        """Try to automatically find the tag name for a revision.
 
1476
 
 
1477
        :param revision_id: Revision id of the revision.
 
1478
        :return: A tag name or None if no tag name could be determined.
 
1479
        """
 
1480
        for hook in Branch.hooks['automatic_tag_name']:
 
1481
            ret = hook(self, revision_id)
 
1482
            if ret is not None:
 
1483
                return ret
 
1484
        return None
 
1485
 
 
1486
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
 
1487
                                         other_branch):
 
1488
        """Ensure that revision_b is a descendant of revision_a.
 
1489
 
 
1490
        This is a helper function for update_revisions.
 
1491
 
 
1492
        :raises: DivergedBranches if revision_b has diverged from revision_a.
 
1493
        :returns: True if revision_b is a descendant of revision_a.
 
1494
        """
 
1495
        relation = self._revision_relations(revision_a, revision_b, graph)
 
1496
        if relation == 'b_descends_from_a':
 
1497
            return True
 
1498
        elif relation == 'diverged':
 
1499
            raise errors.DivergedBranches(self, other_branch)
 
1500
        elif relation == 'a_descends_from_b':
 
1501
            return False
 
1502
        else:
 
1503
            raise AssertionError("invalid relation: %r" % (relation,))
 
1504
 
 
1505
    def _revision_relations(self, revision_a, revision_b, graph):
 
1506
        """Determine the relationship between two revisions.
 
1507
 
 
1508
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
 
1509
        """
 
1510
        heads = graph.heads([revision_a, revision_b])
 
1511
        if heads == {revision_b}:
 
1512
            return 'b_descends_from_a'
 
1513
        elif heads == {revision_a, revision_b}:
 
1514
            # These branches have diverged
 
1515
            return 'diverged'
 
1516
        elif heads == {revision_a}:
 
1517
            return 'a_descends_from_b'
 
1518
        else:
 
1519
            raise AssertionError("invalid heads: %r" % (heads,))
 
1520
 
 
1521
    def heads_to_fetch(self):
 
1522
        """Return the heads that must and that should be fetched to copy this
 
1523
        branch into another repo.
 
1524
 
 
1525
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1526
            set of heads that must be fetched.  if_present_fetch is a set of
 
1527
            heads that must be fetched if present, but no error is necessary if
 
1528
            they are not present.
 
1529
        """
 
1530
        # For bzr native formats must_fetch is just the tip, and
 
1531
        # if_present_fetch are the tags.
 
1532
        must_fetch = {self.last_revision()}
 
1533
        if_present_fetch = set()
 
1534
        if self.get_config_stack().get('branch.fetch_tags'):
 
1535
            try:
 
1536
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1537
            except errors.TagsNotSupported:
 
1538
                pass
 
1539
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1540
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1541
        return must_fetch, if_present_fetch
 
1542
 
 
1543
 
 
1544
class BranchFormat(controldir.ControlComponentFormat):
 
1545
    """An encapsulation of the initialization and open routines for a format.
 
1546
 
 
1547
    Formats provide three things:
 
1548
     * An initialization routine,
 
1549
     * a format description
 
1550
     * an open routine.
 
1551
 
 
1552
    Formats are placed in an dict by their format string for reference
 
1553
    during branch opening. It's not required that these be instances, they
 
1554
    can be classes themselves with class methods - it simply depends on
 
1555
    whether state is needed for a given format or not.
 
1556
 
 
1557
    Once a format is deprecated, just deprecate the initialize and open
 
1558
    methods on the format class. Do not deprecate the object, as the
 
1559
    object will be created every time regardless.
 
1560
    """
 
1561
 
 
1562
    def __eq__(self, other):
 
1563
        return self.__class__ is other.__class__
 
1564
 
 
1565
    def __ne__(self, other):
 
1566
        return not (self == other)
 
1567
 
 
1568
    def get_reference(self, controldir, name=None):
 
1569
        """Get the target reference of the branch in controldir.
 
1570
 
 
1571
        format probing must have been completed before calling
 
1572
        this method - it is assumed that the format of the branch
 
1573
        in controldir is correct.
 
1574
 
 
1575
        :param controldir: The controldir to get the branch data from.
 
1576
        :param name: Name of the colocated branch to fetch
 
1577
        :return: None if the branch is not a reference branch.
 
1578
        """
 
1579
        return None
 
1580
 
 
1581
    @classmethod
 
1582
    def set_reference(self, controldir, name, to_branch):
 
1583
        """Set the target reference of the branch in controldir.
 
1584
 
 
1585
        format probing must have been completed before calling
 
1586
        this method - it is assumed that the format of the branch
 
1587
        in controldir is correct.
 
1588
 
 
1589
        :param controldir: The controldir to set the branch reference for.
 
1590
        :param name: Name of colocated branch to set, None for default
 
1591
        :param to_branch: branch that the checkout is to reference
 
1592
        """
 
1593
        raise NotImplementedError(self.set_reference)
 
1594
 
 
1595
    def get_format_description(self):
 
1596
        """Return the short format description for this format."""
 
1597
        raise NotImplementedError(self.get_format_description)
 
1598
 
 
1599
    def _run_post_branch_init_hooks(self, controldir, name, branch):
 
1600
        hooks = Branch.hooks['post_branch_init']
 
1601
        if not hooks:
 
1602
            return
 
1603
        params = BranchInitHookParams(self, controldir, name, branch)
 
1604
        for hook in hooks:
 
1605
            hook(params)
 
1606
 
 
1607
    def initialize(self, controldir, name=None, repository=None,
 
1608
                   append_revisions_only=None):
 
1609
        """Create a branch of this format in controldir.
 
1610
 
 
1611
        :param name: Name of the colocated branch to create.
 
1612
        """
 
1613
        raise NotImplementedError(self.initialize)
 
1614
 
 
1615
    def is_supported(self):
 
1616
        """Is this format supported?
 
1617
 
 
1618
        Supported formats can be initialized and opened.
 
1619
        Unsupported formats may not support initialization or committing or
 
1620
        some other features depending on the reason for not being supported.
 
1621
        """
 
1622
        return True
 
1623
 
 
1624
    def make_tags(self, branch):
 
1625
        """Create a tags object for branch.
 
1626
 
 
1627
        This method is on BranchFormat, because BranchFormats are reflected
 
1628
        over the wire via network_name(), whereas full Branch instances require
 
1629
        multiple VFS method calls to operate at all.
 
1630
 
 
1631
        The default implementation returns a disabled-tags instance.
 
1632
 
 
1633
        Note that it is normal for branch to be a RemoteBranch when using tags
 
1634
        on a RemoteBranch.
 
1635
        """
 
1636
        return _mod_tag.DisabledTags(branch)
 
1637
 
 
1638
    def network_name(self):
 
1639
        """A simple byte string uniquely identifying this format for RPC calls.
 
1640
 
 
1641
        MetaDir branch formats use their disk format string to identify the
 
1642
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1643
        foreign formats like svn/git and hg should use some marker which is
 
1644
        unique and immutable.
 
1645
        """
 
1646
        raise NotImplementedError(self.network_name)
 
1647
 
 
1648
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
 
1649
            found_repository=None, possible_transports=None):
 
1650
        """Return the branch object for controldir.
 
1651
 
 
1652
        :param controldir: A ControlDir that contains a branch.
 
1653
        :param name: Name of colocated branch to open
 
1654
        :param _found: a private parameter, do not use it. It is used to
 
1655
            indicate if format probing has already be done.
 
1656
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1657
            (if there are any).  Default is to open fallbacks.
 
1658
        """
 
1659
        raise NotImplementedError(self.open)
 
1660
 
 
1661
    def supports_set_append_revisions_only(self):
 
1662
        """True if this format supports set_append_revisions_only."""
 
1663
        return False
 
1664
 
 
1665
    def supports_stacking(self):
 
1666
        """True if this format records a stacked-on branch."""
 
1667
        return False
 
1668
 
 
1669
    def supports_leaving_lock(self):
 
1670
        """True if this format supports leaving locks in place."""
 
1671
        return False # by default
 
1672
 
 
1673
    def __str__(self):
 
1674
        return self.get_format_description().rstrip()
 
1675
 
 
1676
    def supports_tags(self):
 
1677
        """True if this format supports tags stored in the branch"""
 
1678
        return False  # by default
 
1679
 
 
1680
    def tags_are_versioned(self):
 
1681
        """Whether the tag container for this branch versions tags."""
 
1682
        return False
 
1683
 
 
1684
    def supports_tags_referencing_ghosts(self):
 
1685
        """True if tags can reference ghost revisions."""
 
1686
        return True
 
1687
 
 
1688
 
 
1689
class BranchHooks(Hooks):
 
1690
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
1691
 
 
1692
    e.g. ['post_push'] Is the list of items to be called when the
 
1693
    push function is invoked.
 
1694
    """
 
1695
 
 
1696
    def __init__(self):
 
1697
        """Create the default hooks.
 
1698
 
 
1699
        These are all empty initially, because by default nothing should get
 
1700
        notified.
 
1701
        """
 
1702
        Hooks.__init__(self, "breezy.branch", "Branch.hooks")
 
1703
        self.add_hook('open',
 
1704
            "Called with the Branch object that has been opened after a "
 
1705
            "branch is opened.", (1, 8))
 
1706
        self.add_hook('post_push',
 
1707
            "Called after a push operation completes. post_push is called "
 
1708
            "with a breezy.branch.BranchPushResult object and only runs in the "
 
1709
            "bzr client.", (0, 15))
 
1710
        self.add_hook('post_pull',
 
1711
            "Called after a pull operation completes. post_pull is called "
 
1712
            "with a breezy.branch.PullResult object and only runs in the "
 
1713
            "bzr client.", (0, 15))
 
1714
        self.add_hook('pre_commit',
 
1715
            "Called after a commit is calculated but before it is "
 
1716
            "completed. pre_commit is called with (local, master, old_revno, "
 
1717
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
 
1718
            "). old_revid is NULL_REVISION for the first commit to a branch, "
 
1719
            "tree_delta is a TreeDelta object describing changes from the "
 
1720
            "basis revision. hooks MUST NOT modify this delta. "
 
1721
            " future_tree is an in-memory tree obtained from "
 
1722
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
 
1723
            "tree.", (0,91))
 
1724
        self.add_hook('post_commit',
 
1725
            "Called in the bzr client after a commit has completed. "
 
1726
            "post_commit is called with (local, master, old_revno, old_revid, "
 
1727
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
 
1728
            "commit to a branch.", (0, 15))
 
1729
        self.add_hook('post_uncommit',
 
1730
            "Called in the bzr client after an uncommit completes. "
 
1731
            "post_uncommit is called with (local, master, old_revno, "
 
1732
            "old_revid, new_revno, new_revid) where local is the local branch "
 
1733
            "or None, master is the target branch, and an empty branch "
 
1734
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1735
        self.add_hook('pre_change_branch_tip',
 
1736
            "Called in bzr client and server before a change to the tip of a "
 
1737
            "branch is made. pre_change_branch_tip is called with a "
 
1738
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1739
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1740
        self.add_hook('post_change_branch_tip',
 
1741
            "Called in bzr client and server after a change to the tip of a "
 
1742
            "branch is made. post_change_branch_tip is called with a "
 
1743
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1744
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1745
        self.add_hook('transform_fallback_location',
 
1746
            "Called when a stacked branch is activating its fallback "
 
1747
            "locations. transform_fallback_location is called with (branch, "
 
1748
            "url), and should return a new url. Returning the same url "
 
1749
            "allows it to be used as-is, returning a different one can be "
 
1750
            "used to cause the branch to stack on a closer copy of that "
 
1751
            "fallback_location. Note that the branch cannot have history "
 
1752
            "accessing methods called on it during this hook because the "
 
1753
            "fallback locations have not been activated. When there are "
 
1754
            "multiple hooks installed for transform_fallback_location, "
 
1755
            "all are called with the url returned from the previous hook."
 
1756
            "The order is however undefined.", (1, 9))
 
1757
        self.add_hook('automatic_tag_name',
 
1758
            "Called to determine an automatic tag name for a revision. "
 
1759
            "automatic_tag_name is called with (branch, revision_id) and "
 
1760
            "should return a tag name or None if no tag name could be "
 
1761
            "determined. The first non-None tag name returned will be used.",
 
1762
            (2, 2))
 
1763
        self.add_hook('post_branch_init',
 
1764
            "Called after new branch initialization completes. "
 
1765
            "post_branch_init is called with a "
 
1766
            "breezy.branch.BranchInitHookParams. "
 
1767
            "Note that init, branch and checkout (both heavyweight and "
 
1768
            "lightweight) will all trigger this hook.", (2, 2))
 
1769
        self.add_hook('post_switch',
 
1770
            "Called after a checkout switches branch. "
 
1771
            "post_switch is called with a "
 
1772
            "breezy.branch.SwitchHookParams.", (2, 2))
 
1773
 
 
1774
 
 
1775
 
 
1776
# install the default hooks into the Branch class.
 
1777
Branch.hooks = BranchHooks()
 
1778
 
 
1779
 
 
1780
class ChangeBranchTipParams(object):
 
1781
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1782
 
 
1783
    There are 5 fields that hooks may wish to access:
 
1784
 
 
1785
    :ivar branch: the branch being changed
 
1786
    :ivar old_revno: revision number before the change
 
1787
    :ivar new_revno: revision number after the change
 
1788
    :ivar old_revid: revision id before the change
 
1789
    :ivar new_revid: revision id after the change
 
1790
 
 
1791
    The revid fields are strings. The revno fields are integers.
 
1792
    """
 
1793
 
 
1794
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
 
1795
        """Create a group of ChangeBranchTip parameters.
 
1796
 
 
1797
        :param branch: The branch being changed.
 
1798
        :param old_revno: Revision number before the change.
 
1799
        :param new_revno: Revision number after the change.
 
1800
        :param old_revid: Tip revision id before the change.
 
1801
        :param new_revid: Tip revision id after the change.
 
1802
        """
 
1803
        self.branch = branch
 
1804
        self.old_revno = old_revno
 
1805
        self.new_revno = new_revno
 
1806
        self.old_revid = old_revid
 
1807
        self.new_revid = new_revid
 
1808
 
 
1809
    def __eq__(self, other):
 
1810
        return self.__dict__ == other.__dict__
 
1811
 
 
1812
    def __repr__(self):
 
1813
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
 
1814
            self.__class__.__name__, self.branch,
 
1815
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
 
1816
 
 
1817
 
 
1818
class BranchInitHookParams(object):
 
1819
    """Object holding parameters passed to `*_branch_init` hooks.
 
1820
 
 
1821
    There are 4 fields that hooks may wish to access:
 
1822
 
 
1823
    :ivar format: the branch format
 
1824
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
 
1825
    :ivar name: name of colocated branch, if any (or None)
 
1826
    :ivar branch: the branch created
 
1827
 
 
1828
    Note that for lightweight checkouts, the bzrdir and format fields refer to
 
1829
    the checkout, hence they are different from the corresponding fields in
 
1830
    branch, which refer to the original branch.
 
1831
    """
 
1832
 
 
1833
    def __init__(self, format, controldir, name, branch):
 
1834
        """Create a group of BranchInitHook parameters.
 
1835
 
 
1836
        :param format: the branch format
 
1837
        :param controldir: the ControlDir where the branch will be/has been
 
1838
            initialized
 
1839
        :param name: name of colocated branch, if any (or None)
 
1840
        :param branch: the branch created
 
1841
 
 
1842
        Note that for lightweight checkouts, the bzrdir and format fields refer
 
1843
        to the checkout, hence they are different from the corresponding fields
 
1844
        in branch, which refer to the original branch.
 
1845
        """
 
1846
        self.format = format
 
1847
        self.bzrdir = controldir
 
1848
        self.name = name
 
1849
        self.branch = branch
 
1850
 
 
1851
    def __eq__(self, other):
 
1852
        return self.__dict__ == other.__dict__
 
1853
 
 
1854
    def __repr__(self):
 
1855
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1856
 
 
1857
 
 
1858
class SwitchHookParams(object):
 
1859
    """Object holding parameters passed to `*_switch` hooks.
 
1860
 
 
1861
    There are 4 fields that hooks may wish to access:
 
1862
 
 
1863
    :ivar control_dir: ControlDir of the checkout to change
 
1864
    :ivar to_branch: branch that the checkout is to reference
 
1865
    :ivar force: skip the check for local commits in a heavy checkout
 
1866
    :ivar revision_id: revision ID to switch to (or None)
 
1867
    """
 
1868
 
 
1869
    def __init__(self, control_dir, to_branch, force, revision_id):
 
1870
        """Create a group of SwitchHook parameters.
 
1871
 
 
1872
        :param control_dir: ControlDir of the checkout to change
 
1873
        :param to_branch: branch that the checkout is to reference
 
1874
        :param force: skip the check for local commits in a heavy checkout
 
1875
        :param revision_id: revision ID to switch to (or None)
 
1876
        """
 
1877
        self.control_dir = control_dir
 
1878
        self.to_branch = to_branch
 
1879
        self.force = force
 
1880
        self.revision_id = revision_id
 
1881
 
 
1882
    def __eq__(self, other):
 
1883
        return self.__dict__ == other.__dict__
 
1884
 
 
1885
    def __repr__(self):
 
1886
        return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
 
1887
            self.control_dir, self.to_branch,
 
1888
            self.revision_id)
 
1889
 
 
1890
 
 
1891
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
1892
    """Branch format registry."""
 
1893
 
 
1894
    def __init__(self, other_registry=None):
 
1895
        super(BranchFormatRegistry, self).__init__(other_registry)
 
1896
        self._default_format = None
 
1897
        self._default_format_key = None
 
1898
 
 
1899
    def get_default(self):
 
1900
        """Return the current default format."""
 
1901
        if (self._default_format_key is not None and
 
1902
            self._default_format is None):
 
1903
            self._default_format = self.get(self._default_format_key)
 
1904
        return self._default_format
 
1905
 
 
1906
    def set_default(self, format):
 
1907
        """Set the default format."""
 
1908
        self._default_format = format
 
1909
        self._default_format_key = None
 
1910
 
 
1911
    def set_default_key(self, format_string):
 
1912
        """Set the default format by its format string."""
 
1913
        self._default_format_key = format_string
 
1914
        self._default_format = None
 
1915
 
 
1916
 
 
1917
network_format_registry = registry.FormatRegistry()
 
1918
"""Registry of formats indexed by their network name.
 
1919
 
 
1920
The network name for a branch format is an identifier that can be used when
 
1921
referring to formats with smart server operations. See
 
1922
BranchFormat.network_name() for more detail.
 
1923
"""
 
1924
 
 
1925
format_registry = BranchFormatRegistry(network_format_registry)
 
1926
 
 
1927
 
 
1928
# formats which have no format string are not discoverable
 
1929
# and not independently creatable, so are not registered.
 
1930
format_registry.register_lazy(
 
1931
    "Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
 
1932
    "BzrBranchFormat5")
 
1933
format_registry.register_lazy(
 
1934
    "Bazaar Branch Format 6 (bzr 0.15)\n",
 
1935
    "breezy.bzr.branch", "BzrBranchFormat6")
 
1936
format_registry.register_lazy(
 
1937
    "Bazaar Branch Format 7 (needs bzr 1.6)\n",
 
1938
    "breezy.bzr.branch", "BzrBranchFormat7")
 
1939
format_registry.register_lazy(
 
1940
    "Bazaar Branch Format 8 (needs bzr 1.15)\n",
 
1941
    "breezy.bzr.branch", "BzrBranchFormat8")
 
1942
format_registry.register_lazy(
 
1943
    "Bazaar-NG Branch Reference Format 1\n",
 
1944
    "breezy.bzr.branch", "BranchReferenceFormat")
 
1945
 
 
1946
format_registry.set_default_key("Bazaar Branch Format 7 (needs bzr 1.6)\n")
 
1947
 
 
1948
 
 
1949
class BranchWriteLockResult(LogicalLockResult):
 
1950
    """The result of write locking a branch.
 
1951
 
 
1952
    :ivar branch_token: The token obtained from the underlying branch lock, or
 
1953
        None.
 
1954
    :ivar unlock: A callable which will unlock the lock.
 
1955
    """
 
1956
 
 
1957
    def __init__(self, unlock, branch_token):
 
1958
        LogicalLockResult.__init__(self, unlock)
 
1959
        self.branch_token = branch_token
 
1960
 
 
1961
    def __repr__(self):
 
1962
        return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
 
1963
            self.unlock)
 
1964
 
 
1965
 
 
1966
######################################################################
 
1967
# results of operations
 
1968
 
 
1969
 
 
1970
class _Result(object):
 
1971
 
 
1972
    def _show_tag_conficts(self, to_file):
 
1973
        if not getattr(self, 'tag_conflicts', None):
 
1974
            return
 
1975
        to_file.write('Conflicting tags:\n')
 
1976
        for name, value1, value2 in self.tag_conflicts:
 
1977
            to_file.write('    %s\n' % (name, ))
 
1978
 
 
1979
 
 
1980
class PullResult(_Result):
 
1981
    """Result of a Branch.pull operation.
 
1982
 
 
1983
    :ivar old_revno: Revision number before pull.
 
1984
    :ivar new_revno: Revision number after pull.
 
1985
    :ivar old_revid: Tip revision id before pull.
 
1986
    :ivar new_revid: Tip revision id after pull.
 
1987
    :ivar source_branch: Source (local) branch object. (read locked)
 
1988
    :ivar master_branch: Master branch of the target, or the target if no
 
1989
        Master
 
1990
    :ivar local_branch: target branch if there is a Master, else None
 
1991
    :ivar target_branch: Target/destination branch object. (write locked)
 
1992
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
 
1993
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
 
1994
    """
 
1995
 
 
1996
    def report(self, to_file):
 
1997
        tag_conflicts = getattr(self, "tag_conflicts", None)
 
1998
        tag_updates = getattr(self, "tag_updates", None)
 
1999
        if not is_quiet():
 
2000
            if self.old_revid != self.new_revid:
 
2001
                to_file.write('Now on revision %d.\n' % self.new_revno)
 
2002
            if tag_updates:
 
2003
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
 
2004
            if self.old_revid == self.new_revid and not tag_updates:
 
2005
                if not tag_conflicts:
 
2006
                    to_file.write('No revisions or tags to pull.\n')
 
2007
                else:
 
2008
                    to_file.write('No revisions to pull.\n')
 
2009
        self._show_tag_conficts(to_file)
 
2010
 
 
2011
 
 
2012
class BranchPushResult(_Result):
 
2013
    """Result of a Branch.push operation.
 
2014
 
 
2015
    :ivar old_revno: Revision number (eg 10) of the target before push.
 
2016
    :ivar new_revno: Revision number (eg 12) of the target after push.
 
2017
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
 
2018
        before the push.
 
2019
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
 
2020
        after the push.
 
2021
    :ivar source_branch: Source branch object that the push was from. This is
 
2022
        read locked, and generally is a local (and thus low latency) branch.
 
2023
    :ivar master_branch: If target is a bound branch, the master branch of
 
2024
        target, or target itself. Always write locked.
 
2025
    :ivar target_branch: The direct Branch where data is being sent (write
 
2026
        locked).
 
2027
    :ivar local_branch: If the target is a bound branch this will be the
 
2028
        target, otherwise it will be None.
 
2029
    """
 
2030
 
 
2031
    def report(self, to_file):
 
2032
        # TODO: This function gets passed a to_file, but then
 
2033
        # ignores it and calls note() instead. This is also
 
2034
        # inconsistent with PullResult(), which writes to stdout.
 
2035
        # -- JRV20110901, bug #838853
 
2036
        tag_conflicts = getattr(self, "tag_conflicts", None)
 
2037
        tag_updates = getattr(self, "tag_updates", None)
 
2038
        if not is_quiet():
 
2039
            if self.old_revid != self.new_revid:
 
2040
                note(gettext('Pushed up to revision %d.') % self.new_revno)
 
2041
            if tag_updates:
 
2042
                note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
 
2043
            if self.old_revid == self.new_revid and not tag_updates:
 
2044
                if not tag_conflicts:
 
2045
                    note(gettext('No new revisions or tags to push.'))
 
2046
                else:
 
2047
                    note(gettext('No new revisions to push.'))
 
2048
        self._show_tag_conficts(to_file)
 
2049
 
 
2050
 
 
2051
class BranchCheckResult(object):
 
2052
    """Results of checking branch consistency.
 
2053
 
 
2054
    :see: Branch.check
 
2055
    """
 
2056
 
 
2057
    def __init__(self, branch):
 
2058
        self.branch = branch
 
2059
        self.errors = []
 
2060
 
 
2061
    def report_results(self, verbose):
 
2062
        """Report the check results via trace.note.
 
2063
 
 
2064
        :param verbose: Requests more detailed display of what was checked,
 
2065
            if any.
 
2066
        """
 
2067
        note(gettext('checked branch {0} format {1}').format(
 
2068
                                self.branch.user_url, self.branch._format))
 
2069
        for error in self.errors:
 
2070
            note(gettext('found error:%s'), error)
 
2071
 
 
2072
 
 
2073
class InterBranch(InterObject):
 
2074
    """This class represents operations taking place between two branches.
 
2075
 
 
2076
    Its instances have methods like pull() and push() and contain
 
2077
    references to the source and target repositories these operations
 
2078
    can be carried out on.
 
2079
    """
 
2080
 
 
2081
    _optimisers = []
 
2082
    """The available optimised InterBranch types."""
 
2083
 
 
2084
    @classmethod
 
2085
    def _get_branch_formats_to_test(klass):
 
2086
        """Return an iterable of format tuples for testing.
 
2087
        
 
2088
        :return: An iterable of (from_format, to_format) to use when testing
 
2089
            this InterBranch class. Each InterBranch class should define this
 
2090
            method itself.
 
2091
        """
 
2092
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2093
 
 
2094
    @needs_write_lock
 
2095
    def pull(self, overwrite=False, stop_revision=None,
 
2096
             possible_transports=None, local=False):
 
2097
        """Mirror source into target branch.
 
2098
 
 
2099
        The target branch is considered to be 'local', having low latency.
 
2100
 
 
2101
        :returns: PullResult instance
 
2102
        """
 
2103
        raise NotImplementedError(self.pull)
 
2104
 
 
2105
    @needs_write_lock
 
2106
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2107
             _override_hook_source_branch=None):
 
2108
        """Mirror the source branch into the target branch.
 
2109
 
 
2110
        The source branch is considered to be 'local', having low latency.
 
2111
        """
 
2112
        raise NotImplementedError(self.push)
 
2113
 
 
2114
    @needs_write_lock
 
2115
    def copy_content_into(self, revision_id=None):
 
2116
        """Copy the content of source into target
 
2117
 
 
2118
        revision_id: if not None, the revision history in the new branch will
 
2119
                     be truncated to end with revision_id.
 
2120
        """
 
2121
        raise NotImplementedError(self.copy_content_into)
 
2122
 
 
2123
    @needs_write_lock
 
2124
    def fetch(self, stop_revision=None, limit=None):
 
2125
        """Fetch revisions.
 
2126
 
 
2127
        :param stop_revision: Last revision to fetch
 
2128
        :param limit: Optional rough limit of revisions to fetch
 
2129
        """
 
2130
        raise NotImplementedError(self.fetch)
 
2131
 
 
2132
 
 
2133
def _fix_overwrite_type(overwrite):
 
2134
    if isinstance(overwrite, bool):
 
2135
        if overwrite:
 
2136
            return ["history", "tags"]
 
2137
        else:
 
2138
            return []
 
2139
    return overwrite
 
2140
 
 
2141
 
 
2142
class GenericInterBranch(InterBranch):
 
2143
    """InterBranch implementation that uses public Branch functions."""
 
2144
 
 
2145
    @classmethod
 
2146
    def is_compatible(klass, source, target):
 
2147
        # GenericBranch uses the public API, so always compatible
 
2148
        return True
 
2149
 
 
2150
    @classmethod
 
2151
    def _get_branch_formats_to_test(klass):
 
2152
        return [(format_registry.get_default(), format_registry.get_default())]
 
2153
 
 
2154
    @classmethod
 
2155
    def unwrap_format(klass, format):
 
2156
        if isinstance(format, remote.RemoteBranchFormat):
 
2157
            format._ensure_real()
 
2158
            return format._custom_format
 
2159
        return format
 
2160
 
 
2161
    @needs_write_lock
 
2162
    def copy_content_into(self, revision_id=None):
 
2163
        """Copy the content of source into target
 
2164
 
 
2165
        revision_id: if not None, the revision history in the new branch will
 
2166
                     be truncated to end with revision_id.
 
2167
        """
 
2168
        self.source.update_references(self.target)
 
2169
        self.source._synchronize_history(self.target, revision_id)
 
2170
        try:
 
2171
            parent = self.source.get_parent()
 
2172
        except errors.InaccessibleParent as e:
 
2173
            mutter('parent was not accessible to copy: %s', e)
 
2174
        else:
 
2175
            if parent:
 
2176
                self.target.set_parent(parent)
 
2177
        if self.source._push_should_merge_tags():
 
2178
            self.source.tags.merge_to(self.target.tags)
 
2179
 
 
2180
    @needs_write_lock
 
2181
    def fetch(self, stop_revision=None, limit=None):
 
2182
        if self.target.base == self.source.base:
 
2183
            return (0, [])
 
2184
        self.source.lock_read()
 
2185
        try:
 
2186
            fetch_spec_factory = fetch.FetchSpecFactory()
 
2187
            fetch_spec_factory.source_branch = self.source
 
2188
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
2189
            fetch_spec_factory.source_repo = self.source.repository
 
2190
            fetch_spec_factory.target_repo = self.target.repository
 
2191
            fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
 
2192
            fetch_spec_factory.limit = limit
 
2193
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
2194
            return self.target.repository.fetch(self.source.repository,
 
2195
                fetch_spec=fetch_spec)
 
2196
        finally:
 
2197
            self.source.unlock()
 
2198
 
 
2199
    @needs_write_lock
 
2200
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
2201
            graph=None):
 
2202
        other_revno, other_last_revision = self.source.last_revision_info()
 
2203
        stop_revno = None # unknown
 
2204
        if stop_revision is None:
 
2205
            stop_revision = other_last_revision
 
2206
            if _mod_revision.is_null(stop_revision):
 
2207
                # if there are no commits, we're done.
 
2208
                return
 
2209
            stop_revno = other_revno
 
2210
 
 
2211
        # what's the current last revision, before we fetch [and change it
 
2212
        # possibly]
 
2213
        last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2214
        # we fetch here so that we don't process data twice in the common
 
2215
        # case of having something to pull, and so that the check for
 
2216
        # already merged can operate on the just fetched graph, which will
 
2217
        # be cached in memory.
 
2218
        self.fetch(stop_revision=stop_revision)
 
2219
        # Check to see if one is an ancestor of the other
 
2220
        if not overwrite:
 
2221
            if graph is None:
 
2222
                graph = self.target.repository.get_graph()
 
2223
            if self.target._check_if_descendant_or_diverged(
 
2224
                    stop_revision, last_rev, graph, self.source):
 
2225
                # stop_revision is a descendant of last_rev, but we aren't
 
2226
                # overwriting, so we're done.
 
2227
                return
 
2228
        if stop_revno is None:
 
2229
            if graph is None:
 
2230
                graph = self.target.repository.get_graph()
 
2231
            this_revno, this_last_revision = \
 
2232
                    self.target.last_revision_info()
 
2233
            stop_revno = graph.find_distance_to_null(stop_revision,
 
2234
                            [(other_last_revision, other_revno),
 
2235
                             (this_last_revision, this_revno)])
 
2236
        self.target.set_last_revision_info(stop_revno, stop_revision)
 
2237
 
 
2238
    @needs_write_lock
 
2239
    def pull(self, overwrite=False, stop_revision=None,
 
2240
             possible_transports=None, run_hooks=True,
 
2241
             _override_hook_target=None, local=False):
 
2242
        """Pull from source into self, updating my master if any.
 
2243
 
 
2244
        :param run_hooks: Private parameter - if false, this branch
 
2245
            is being called because it's the master of the primary branch,
 
2246
            so it should not run its hooks.
 
2247
        """
 
2248
        bound_location = self.target.get_bound_location()
 
2249
        if local and not bound_location:
 
2250
            raise errors.LocalRequiresBoundBranch()
 
2251
        master_branch = None
 
2252
        source_is_master = False
 
2253
        if bound_location:
 
2254
            # bound_location comes from a config file, some care has to be
 
2255
            # taken to relate it to source.user_url
 
2256
            normalized = urlutils.normalize_url(bound_location)
 
2257
            try:
 
2258
                relpath = self.source.user_transport.relpath(normalized)
 
2259
                source_is_master = (relpath == '')
 
2260
            except (errors.PathNotChild, errors.InvalidURL):
 
2261
                source_is_master = False
 
2262
        if not local and bound_location and not source_is_master:
 
2263
            # not pulling from master, so we need to update master.
 
2264
            master_branch = self.target.get_master_branch(possible_transports)
 
2265
            master_branch.lock_write()
 
2266
        try:
 
2267
            if master_branch:
 
2268
                # pull from source into master.
 
2269
                master_branch.pull(self.source, overwrite, stop_revision,
 
2270
                    run_hooks=False)
 
2271
            return self._pull(overwrite,
 
2272
                stop_revision, _hook_master=master_branch,
 
2273
                run_hooks=run_hooks,
 
2274
                _override_hook_target=_override_hook_target,
 
2275
                merge_tags_to_master=not source_is_master)
 
2276
        finally:
 
2277
            if master_branch:
 
2278
                master_branch.unlock()
 
2279
 
 
2280
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2281
             _override_hook_source_branch=None):
 
2282
        """See InterBranch.push.
 
2283
 
 
2284
        This is the basic concrete implementation of push()
 
2285
 
 
2286
        :param _override_hook_source_branch: If specified, run the hooks
 
2287
            passing this Branch as the source, rather than self.  This is for
 
2288
            use of RemoteBranch, where push is delegated to the underlying
 
2289
            vfs-based Branch.
 
2290
        """
 
2291
        if lossy:
 
2292
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
2293
        # TODO: Public option to disable running hooks - should be trivial but
 
2294
        # needs tests.
 
2295
 
 
2296
        op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
 
2297
        op.add_cleanup(self.source.lock_read().unlock)
 
2298
        op.add_cleanup(self.target.lock_write().unlock)
 
2299
        return op.run(overwrite, stop_revision,
 
2300
            _override_hook_source_branch=_override_hook_source_branch)
 
2301
 
 
2302
    def _basic_push(self, overwrite, stop_revision):
 
2303
        """Basic implementation of push without bound branches or hooks.
 
2304
 
 
2305
        Must be called with source read locked and target write locked.
 
2306
        """
 
2307
        result = BranchPushResult()
 
2308
        result.source_branch = self.source
 
2309
        result.target_branch = self.target
 
2310
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
2311
        self.source.update_references(self.target)
 
2312
        overwrite = _fix_overwrite_type(overwrite)
 
2313
        if result.old_revid != stop_revision:
 
2314
            # We assume that during 'push' this repository is closer than
 
2315
            # the target.
 
2316
            graph = self.source.repository.get_graph(self.target.repository)
 
2317
            self._update_revisions(stop_revision,
 
2318
                overwrite=("history" in overwrite),
 
2319
                graph=graph)
 
2320
        if self.source._push_should_merge_tags():
 
2321
            result.tag_updates, result.tag_conflicts = (
 
2322
                self.source.tags.merge_to(
 
2323
                self.target.tags, "tags" in overwrite))
 
2324
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
2325
        return result
 
2326
 
 
2327
    def _push_with_bound_branches(self, operation, overwrite, stop_revision,
 
2328
            _override_hook_source_branch=None):
 
2329
        """Push from source into target, and into target's master if any.
 
2330
        """
 
2331
        def _run_hooks():
 
2332
            if _override_hook_source_branch:
 
2333
                result.source_branch = _override_hook_source_branch
 
2334
            for hook in Branch.hooks['post_push']:
 
2335
                hook(result)
 
2336
 
 
2337
        bound_location = self.target.get_bound_location()
 
2338
        if bound_location and self.target.base != bound_location:
 
2339
            # there is a master branch.
 
2340
            #
 
2341
            # XXX: Why the second check?  Is it even supported for a branch to
 
2342
            # be bound to itself? -- mbp 20070507
 
2343
            master_branch = self.target.get_master_branch()
 
2344
            master_branch.lock_write()
 
2345
            operation.add_cleanup(master_branch.unlock)
 
2346
            # push into the master from the source branch.
 
2347
            master_inter = InterBranch.get(self.source, master_branch)
 
2348
            master_inter._basic_push(overwrite, stop_revision)
 
2349
            # and push into the target branch from the source. Note that
 
2350
            # we push from the source branch again, because it's considered
 
2351
            # the highest bandwidth repository.
 
2352
            result = self._basic_push(overwrite, stop_revision)
 
2353
            result.master_branch = master_branch
 
2354
            result.local_branch = self.target
 
2355
        else:
 
2356
            master_branch = None
 
2357
            # no master branch
 
2358
            result = self._basic_push(overwrite, stop_revision)
 
2359
            # TODO: Why set master_branch and local_branch if there's no
 
2360
            # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2361
            # 20070504
 
2362
            result.master_branch = self.target
 
2363
            result.local_branch = None
 
2364
        _run_hooks()
 
2365
        return result
 
2366
 
 
2367
    def _pull(self, overwrite=False, stop_revision=None,
 
2368
             possible_transports=None, _hook_master=None, run_hooks=True,
 
2369
             _override_hook_target=None, local=False,
 
2370
             merge_tags_to_master=True):
 
2371
        """See Branch.pull.
 
2372
 
 
2373
        This function is the core worker, used by GenericInterBranch.pull to
 
2374
        avoid duplication when pulling source->master and source->local.
 
2375
 
 
2376
        :param _hook_master: Private parameter - set the branch to
 
2377
            be supplied as the master to pull hooks.
 
2378
        :param run_hooks: Private parameter - if false, this branch
 
2379
            is being called because it's the master of the primary branch,
 
2380
            so it should not run its hooks.
 
2381
            is being called because it's the master of the primary branch,
 
2382
            so it should not run its hooks.
 
2383
        :param _override_hook_target: Private parameter - set the branch to be
 
2384
            supplied as the target_branch to pull hooks.
 
2385
        :param local: Only update the local branch, and not the bound branch.
 
2386
        """
 
2387
        # This type of branch can't be bound.
 
2388
        if local:
 
2389
            raise errors.LocalRequiresBoundBranch()
 
2390
        result = PullResult()
 
2391
        result.source_branch = self.source
 
2392
        if _override_hook_target is None:
 
2393
            result.target_branch = self.target
 
2394
        else:
 
2395
            result.target_branch = _override_hook_target
 
2396
        self.source.lock_read()
 
2397
        try:
 
2398
            # We assume that during 'pull' the target repository is closer than
 
2399
            # the source one.
 
2400
            self.source.update_references(self.target)
 
2401
            graph = self.target.repository.get_graph(self.source.repository)
 
2402
            # TODO: Branch formats should have a flag that indicates 
 
2403
            # that revno's are expensive, and pull() should honor that flag.
 
2404
            # -- JRV20090506
 
2405
            result.old_revno, result.old_revid = \
 
2406
                self.target.last_revision_info()
 
2407
            overwrite = _fix_overwrite_type(overwrite)
 
2408
            self._update_revisions(stop_revision,
 
2409
                overwrite=("history" in overwrite),
 
2410
                graph=graph)
 
2411
            # TODO: The old revid should be specified when merging tags, 
 
2412
            # so a tags implementation that versions tags can only 
 
2413
            # pull in the most recent changes. -- JRV20090506
 
2414
            result.tag_updates, result.tag_conflicts = (
 
2415
                self.source.tags.merge_to(self.target.tags,
 
2416
                    "tags" in overwrite,
 
2417
                    ignore_master=not merge_tags_to_master))
 
2418
            result.new_revno, result.new_revid = self.target.last_revision_info()
 
2419
            if _hook_master:
 
2420
                result.master_branch = _hook_master
 
2421
                result.local_branch = result.target_branch
 
2422
            else:
 
2423
                result.master_branch = result.target_branch
 
2424
                result.local_branch = None
 
2425
            if run_hooks:
 
2426
                for hook in Branch.hooks['post_pull']:
 
2427
                    hook(result)
 
2428
        finally:
 
2429
            self.source.unlock()
 
2430
        return result
 
2431
 
 
2432
 
 
2433
InterBranch.register_optimiser(GenericInterBranch)