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