/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-06-03 23:48:08 UTC
  • mfrom: (7316 work)
  • mto: This revision was merged to the branch mainline in revision 7328.
  • Revision ID: jelmer@jelmer.uk-20190603234808-15yk5c7054tj8e2b
Merge trunk.

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