/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: 2019-10-20 15:03:13 UTC
  • mto: This revision was merged to the branch mainline in revision 7407.
  • Revision ID: jelmer@jelmer.uk-20191020150313-q06o6pncwr6ndu3t
Fix send with git.

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