/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: 2018-11-23 01:35:56 UTC
  • mto: (7211.10.3 git-empty-dirs)
  • mto: This revision was merged to the branch mainline in revision 7215.
  • Revision ID: jelmer@jelmer.uk-20181123013556-mu7ct9ovl7fozjc2
Update comment about ssl.

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
        from breezy.reconcile import BranchReconciler
 
1419
        with self.lock_write():
 
1420
            reconciler = BranchReconciler(self, thorough=thorough)
 
1421
            reconciler.reconcile()
 
1422
            return reconciler
 
1423
 
 
1424
    def reference_parent(self, path, file_id=None, possible_transports=None):
 
1425
        """Return the parent branch for a tree-reference file_id
 
1426
 
 
1427
        :param path: The path of the file_id in the tree
 
1428
        :param file_id: Optional file_id of the tree reference
 
1429
        :return: A branch associated with the file_id
 
1430
        """
 
1431
        # FIXME should provide multiple branches, based on config
 
1432
        return Branch.open(self.controldir.root_transport.clone(path).base,
 
1433
                           possible_transports=possible_transports)
 
1434
 
 
1435
    def supports_tags(self):
 
1436
        return self._format.supports_tags()
 
1437
 
 
1438
    def automatic_tag_name(self, revision_id):
 
1439
        """Try to automatically find the tag name for a revision.
 
1440
 
 
1441
        :param revision_id: Revision id of the revision.
 
1442
        :return: A tag name or None if no tag name could be determined.
 
1443
        """
 
1444
        for hook in Branch.hooks['automatic_tag_name']:
 
1445
            ret = hook(self, revision_id)
 
1446
            if ret is not None:
 
1447
                return ret
 
1448
        return None
 
1449
 
 
1450
    def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
 
1451
                                         other_branch):
 
1452
        """Ensure that revision_b is a descendant of revision_a.
 
1453
 
 
1454
        This is a helper function for update_revisions.
 
1455
 
 
1456
        :raises: DivergedBranches if revision_b has diverged from revision_a.
 
1457
        :returns: True if revision_b is a descendant of revision_a.
 
1458
        """
 
1459
        relation = self._revision_relations(revision_a, revision_b, graph)
 
1460
        if relation == 'b_descends_from_a':
 
1461
            return True
 
1462
        elif relation == 'diverged':
 
1463
            raise errors.DivergedBranches(self, other_branch)
 
1464
        elif relation == 'a_descends_from_b':
 
1465
            return False
 
1466
        else:
 
1467
            raise AssertionError("invalid relation: %r" % (relation,))
 
1468
 
 
1469
    def _revision_relations(self, revision_a, revision_b, graph):
 
1470
        """Determine the relationship between two revisions.
 
1471
 
 
1472
        :returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
 
1473
        """
 
1474
        heads = graph.heads([revision_a, revision_b])
 
1475
        if heads == {revision_b}:
 
1476
            return 'b_descends_from_a'
 
1477
        elif heads == {revision_a, revision_b}:
 
1478
            # These branches have diverged
 
1479
            return 'diverged'
 
1480
        elif heads == {revision_a}:
 
1481
            return 'a_descends_from_b'
 
1482
        else:
 
1483
            raise AssertionError("invalid heads: %r" % (heads,))
 
1484
 
 
1485
    def heads_to_fetch(self):
 
1486
        """Return the heads that must and that should be fetched to copy this
 
1487
        branch into another repo.
 
1488
 
 
1489
        :returns: a 2-tuple of (must_fetch, if_present_fetch).  must_fetch is a
 
1490
            set of heads that must be fetched.  if_present_fetch is a set of
 
1491
            heads that must be fetched if present, but no error is necessary if
 
1492
            they are not present.
 
1493
        """
 
1494
        # For bzr native formats must_fetch is just the tip, and
 
1495
        # if_present_fetch are the tags.
 
1496
        must_fetch = {self.last_revision()}
 
1497
        if_present_fetch = set()
 
1498
        if self.get_config_stack().get('branch.fetch_tags'):
 
1499
            try:
 
1500
                if_present_fetch = set(self.tags.get_reverse_tag_dict())
 
1501
            except errors.TagsNotSupported:
 
1502
                pass
 
1503
        must_fetch.discard(_mod_revision.NULL_REVISION)
 
1504
        if_present_fetch.discard(_mod_revision.NULL_REVISION)
 
1505
        return must_fetch, if_present_fetch
 
1506
 
 
1507
    def create_memorytree(self):
 
1508
        """Create a memory tree for this branch.
 
1509
 
 
1510
        :return: An in-memory MutableTree instance
 
1511
        """
 
1512
        return memorytree.MemoryTree.create_on_branch(self)
 
1513
 
 
1514
 
 
1515
class BranchFormat(controldir.ControlComponentFormat):
 
1516
    """An encapsulation of the initialization and open routines for a format.
 
1517
 
 
1518
    Formats provide three things:
 
1519
     * An initialization routine,
 
1520
     * a format description
 
1521
     * an open routine.
 
1522
 
 
1523
    Formats are placed in an dict by their format string for reference
 
1524
    during branch opening. It's not required that these be instances, they
 
1525
    can be classes themselves with class methods - it simply depends on
 
1526
    whether state is needed for a given format or not.
 
1527
 
 
1528
    Once a format is deprecated, just deprecate the initialize and open
 
1529
    methods on the format class. Do not deprecate the object, as the
 
1530
    object will be created every time regardless.
 
1531
    """
 
1532
 
 
1533
    def __eq__(self, other):
 
1534
        return self.__class__ is other.__class__
 
1535
 
 
1536
    def __ne__(self, other):
 
1537
        return not (self == other)
 
1538
 
 
1539
    def get_reference(self, controldir, name=None):
 
1540
        """Get the target reference of the branch in controldir.
 
1541
 
 
1542
        format probing must have been completed before calling
 
1543
        this method - it is assumed that the format of the branch
 
1544
        in controldir is correct.
 
1545
 
 
1546
        :param controldir: The controldir to get the branch data from.
 
1547
        :param name: Name of the colocated branch to fetch
 
1548
        :return: None if the branch is not a reference branch.
 
1549
        """
 
1550
        return None
 
1551
 
 
1552
    @classmethod
 
1553
    def set_reference(self, controldir, name, to_branch):
 
1554
        """Set the target reference of the branch in controldir.
 
1555
 
 
1556
        format probing must have been completed before calling
 
1557
        this method - it is assumed that the format of the branch
 
1558
        in controldir is correct.
 
1559
 
 
1560
        :param controldir: The controldir to set the branch reference for.
 
1561
        :param name: Name of colocated branch to set, None for default
 
1562
        :param to_branch: branch that the checkout is to reference
 
1563
        """
 
1564
        raise NotImplementedError(self.set_reference)
 
1565
 
 
1566
    def get_format_description(self):
 
1567
        """Return the short format description for this format."""
 
1568
        raise NotImplementedError(self.get_format_description)
 
1569
 
 
1570
    def _run_post_branch_init_hooks(self, controldir, name, branch):
 
1571
        hooks = Branch.hooks['post_branch_init']
 
1572
        if not hooks:
 
1573
            return
 
1574
        params = BranchInitHookParams(self, controldir, name, branch)
 
1575
        for hook in hooks:
 
1576
            hook(params)
 
1577
 
 
1578
    def initialize(self, controldir, name=None, repository=None,
 
1579
                   append_revisions_only=None):
 
1580
        """Create a branch of this format in controldir.
 
1581
 
 
1582
        :param name: Name of the colocated branch to create.
 
1583
        """
 
1584
        raise NotImplementedError(self.initialize)
 
1585
 
 
1586
    def is_supported(self):
 
1587
        """Is this format supported?
 
1588
 
 
1589
        Supported formats can be initialized and opened.
 
1590
        Unsupported formats may not support initialization or committing or
 
1591
        some other features depending on the reason for not being supported.
 
1592
        """
 
1593
        return True
 
1594
 
 
1595
    def make_tags(self, branch):
 
1596
        """Create a tags object for branch.
 
1597
 
 
1598
        This method is on BranchFormat, because BranchFormats are reflected
 
1599
        over the wire via network_name(), whereas full Branch instances require
 
1600
        multiple VFS method calls to operate at all.
 
1601
 
 
1602
        The default implementation returns a disabled-tags instance.
 
1603
 
 
1604
        Note that it is normal for branch to be a RemoteBranch when using tags
 
1605
        on a RemoteBranch.
 
1606
        """
 
1607
        return _mod_tag.DisabledTags(branch)
 
1608
 
 
1609
    def network_name(self):
 
1610
        """A simple byte string uniquely identifying this format for RPC calls.
 
1611
 
 
1612
        MetaDir branch formats use their disk format string to identify the
 
1613
        repository over the wire. All in one formats such as bzr < 0.8, and
 
1614
        foreign formats like svn/git and hg should use some marker which is
 
1615
        unique and immutable.
 
1616
        """
 
1617
        raise NotImplementedError(self.network_name)
 
1618
 
 
1619
    def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
 
1620
             found_repository=None, possible_transports=None):
 
1621
        """Return the branch object for controldir.
 
1622
 
 
1623
        :param controldir: A ControlDir that contains a branch.
 
1624
        :param name: Name of colocated branch to open
 
1625
        :param _found: a private parameter, do not use it. It is used to
 
1626
            indicate if format probing has already be done.
 
1627
        :param ignore_fallbacks: when set, no fallback branches will be opened
 
1628
            (if there are any).  Default is to open fallbacks.
 
1629
        """
 
1630
        raise NotImplementedError(self.open)
 
1631
 
 
1632
    def supports_set_append_revisions_only(self):
 
1633
        """True if this format supports set_append_revisions_only."""
 
1634
        return False
 
1635
 
 
1636
    def supports_stacking(self):
 
1637
        """True if this format records a stacked-on branch."""
 
1638
        return False
 
1639
 
 
1640
    def supports_leaving_lock(self):
 
1641
        """True if this format supports leaving locks in place."""
 
1642
        return False  # by default
 
1643
 
 
1644
    def __str__(self):
 
1645
        return self.get_format_description().rstrip()
 
1646
 
 
1647
    def supports_tags(self):
 
1648
        """True if this format supports tags stored in the branch"""
 
1649
        return False  # by default
 
1650
 
 
1651
    def tags_are_versioned(self):
 
1652
        """Whether the tag container for this branch versions tags."""
 
1653
        return False
 
1654
 
 
1655
    def supports_tags_referencing_ghosts(self):
 
1656
        """True if tags can reference ghost revisions."""
 
1657
        return True
 
1658
 
 
1659
    def supports_store_uncommitted(self):
 
1660
        """True if uncommitted changes can be stored in this branch."""
 
1661
        return True
 
1662
 
 
1663
 
 
1664
class BranchHooks(Hooks):
 
1665
    """A dictionary mapping hook name to a list of callables for branch hooks.
 
1666
 
 
1667
    e.g. ['post_push'] Is the list of items to be called when the
 
1668
    push function is invoked.
 
1669
    """
 
1670
 
 
1671
    def __init__(self):
 
1672
        """Create the default hooks.
 
1673
 
 
1674
        These are all empty initially, because by default nothing should get
 
1675
        notified.
 
1676
        """
 
1677
        Hooks.__init__(self, "breezy.branch", "Branch.hooks")
 
1678
        self.add_hook(
 
1679
            'open',
 
1680
            "Called with the Branch object that has been opened after a "
 
1681
            "branch is opened.", (1, 8))
 
1682
        self.add_hook(
 
1683
            'post_push',
 
1684
            "Called after a push operation completes. post_push is called "
 
1685
            "with a breezy.branch.BranchPushResult object and only runs in "
 
1686
            "the bzr client.", (0, 15))
 
1687
        self.add_hook(
 
1688
            'post_pull',
 
1689
            "Called after a pull operation completes. post_pull is called "
 
1690
            "with a breezy.branch.PullResult object and only runs in the "
 
1691
            "bzr client.", (0, 15))
 
1692
        self.add_hook(
 
1693
            'pre_commit',
 
1694
            "Called after a commit is calculated but before it is "
 
1695
            "completed. pre_commit is called with (local, master, old_revno, "
 
1696
            "old_revid, future_revno, future_revid, tree_delta, future_tree"
 
1697
            "). old_revid is NULL_REVISION for the first commit to a branch, "
 
1698
            "tree_delta is a TreeDelta object describing changes from the "
 
1699
            "basis revision. hooks MUST NOT modify this delta. "
 
1700
            " future_tree is an in-memory tree obtained from "
 
1701
            "CommitBuilder.revision_tree() and hooks MUST NOT modify this "
 
1702
            "tree.", (0, 91))
 
1703
        self.add_hook(
 
1704
            'post_commit',
 
1705
            "Called in the bzr client after a commit has completed. "
 
1706
            "post_commit is called with (local, master, old_revno, old_revid, "
 
1707
            "new_revno, new_revid). old_revid is NULL_REVISION for the first "
 
1708
            "commit to a branch.", (0, 15))
 
1709
        self.add_hook(
 
1710
            'post_uncommit',
 
1711
            "Called in the bzr client after an uncommit completes. "
 
1712
            "post_uncommit is called with (local, master, old_revno, "
 
1713
            "old_revid, new_revno, new_revid) where local is the local branch "
 
1714
            "or None, master is the target branch, and an empty branch "
 
1715
            "receives new_revno of 0, new_revid of None.", (0, 15))
 
1716
        self.add_hook(
 
1717
            'pre_change_branch_tip',
 
1718
            "Called in bzr client and server before a change to the tip of a "
 
1719
            "branch is made. pre_change_branch_tip is called with a "
 
1720
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1721
            "commit, uncommit will all trigger this hook.", (1, 6))
 
1722
        self.add_hook(
 
1723
            'post_change_branch_tip',
 
1724
            "Called in bzr client and server after a change to the tip of a "
 
1725
            "branch is made. post_change_branch_tip is called with a "
 
1726
            "breezy.branch.ChangeBranchTipParams. Note that push, pull, "
 
1727
            "commit, uncommit will all trigger this hook.", (1, 4))
 
1728
        self.add_hook(
 
1729
            'transform_fallback_location',
 
1730
            "Called when a stacked branch is activating its fallback "
 
1731
            "locations. transform_fallback_location is called with (branch, "
 
1732
            "url), and should return a new url. Returning the same url "
 
1733
            "allows it to be used as-is, returning a different one can be "
 
1734
            "used to cause the branch to stack on a closer copy of that "
 
1735
            "fallback_location. Note that the branch cannot have history "
 
1736
            "accessing methods called on it during this hook because the "
 
1737
            "fallback locations have not been activated. When there are "
 
1738
            "multiple hooks installed for transform_fallback_location, "
 
1739
            "all are called with the url returned from the previous hook."
 
1740
            "The order is however undefined.", (1, 9))
 
1741
        self.add_hook(
 
1742
            'automatic_tag_name',
 
1743
            "Called to determine an automatic tag name for a revision. "
 
1744
            "automatic_tag_name is called with (branch, revision_id) and "
 
1745
            "should return a tag name or None if no tag name could be "
 
1746
            "determined. The first non-None tag name returned will be used.",
 
1747
            (2, 2))
 
1748
        self.add_hook(
 
1749
            'post_branch_init',
 
1750
            "Called after new branch initialization completes. "
 
1751
            "post_branch_init is called with a "
 
1752
            "breezy.branch.BranchInitHookParams. "
 
1753
            "Note that init, branch and checkout (both heavyweight and "
 
1754
            "lightweight) will all trigger this hook.", (2, 2))
 
1755
        self.add_hook(
 
1756
            'post_switch',
 
1757
            "Called after a checkout switches branch. "
 
1758
            "post_switch is called with a "
 
1759
            "breezy.branch.SwitchHookParams.", (2, 2))
 
1760
 
 
1761
 
 
1762
# install the default hooks into the Branch class.
 
1763
Branch.hooks = BranchHooks()
 
1764
 
 
1765
 
 
1766
class ChangeBranchTipParams(object):
 
1767
    """Object holding parameters passed to `*_change_branch_tip` hooks.
 
1768
 
 
1769
    There are 5 fields that hooks may wish to access:
 
1770
 
 
1771
    :ivar branch: the branch being changed
 
1772
    :ivar old_revno: revision number before the change
 
1773
    :ivar new_revno: revision number after the change
 
1774
    :ivar old_revid: revision id before the change
 
1775
    :ivar new_revid: revision id after the change
 
1776
 
 
1777
    The revid fields are strings. The revno fields are integers.
 
1778
    """
 
1779
 
 
1780
    def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
 
1781
        """Create a group of ChangeBranchTip parameters.
 
1782
 
 
1783
        :param branch: The branch being changed.
 
1784
        :param old_revno: Revision number before the change.
 
1785
        :param new_revno: Revision number after the change.
 
1786
        :param old_revid: Tip revision id before the change.
 
1787
        :param new_revid: Tip revision id after the change.
 
1788
        """
 
1789
        self.branch = branch
 
1790
        self.old_revno = old_revno
 
1791
        self.new_revno = new_revno
 
1792
        self.old_revid = old_revid
 
1793
        self.new_revid = new_revid
 
1794
 
 
1795
    def __eq__(self, other):
 
1796
        return self.__dict__ == other.__dict__
 
1797
 
 
1798
    def __repr__(self):
 
1799
        return "<%s of %s from (%s, %s) to (%s, %s)>" % (
 
1800
            self.__class__.__name__, self.branch,
 
1801
            self.old_revno, self.old_revid, self.new_revno, self.new_revid)
 
1802
 
 
1803
 
 
1804
class BranchInitHookParams(object):
 
1805
    """Object holding parameters passed to `*_branch_init` hooks.
 
1806
 
 
1807
    There are 4 fields that hooks may wish to access:
 
1808
 
 
1809
    :ivar format: the branch format
 
1810
    :ivar bzrdir: the ControlDir where the branch will be/has been initialized
 
1811
    :ivar name: name of colocated branch, if any (or None)
 
1812
    :ivar branch: the branch created
 
1813
 
 
1814
    Note that for lightweight checkouts, the bzrdir and format fields refer to
 
1815
    the checkout, hence they are different from the corresponding fields in
 
1816
    branch, which refer to the original branch.
 
1817
    """
 
1818
 
 
1819
    def __init__(self, format, controldir, name, branch):
 
1820
        """Create a group of BranchInitHook parameters.
 
1821
 
 
1822
        :param format: the branch format
 
1823
        :param controldir: the ControlDir where the branch will be/has been
 
1824
            initialized
 
1825
        :param name: name of colocated branch, if any (or None)
 
1826
        :param branch: the branch created
 
1827
 
 
1828
        Note that for lightweight checkouts, the bzrdir and format fields refer
 
1829
        to the checkout, hence they are different from the corresponding fields
 
1830
        in branch, which refer to the original branch.
 
1831
        """
 
1832
        self.format = format
 
1833
        self.controldir = controldir
 
1834
        self.name = name
 
1835
        self.branch = branch
 
1836
 
 
1837
    def __eq__(self, other):
 
1838
        return self.__dict__ == other.__dict__
 
1839
 
 
1840
    def __repr__(self):
 
1841
        return "<%s of %s>" % (self.__class__.__name__, self.branch)
 
1842
 
 
1843
 
 
1844
class SwitchHookParams(object):
 
1845
    """Object holding parameters passed to `*_switch` hooks.
 
1846
 
 
1847
    There are 4 fields that hooks may wish to access:
 
1848
 
 
1849
    :ivar control_dir: ControlDir of the checkout to change
 
1850
    :ivar to_branch: branch that the checkout is to reference
 
1851
    :ivar force: skip the check for local commits in a heavy checkout
 
1852
    :ivar revision_id: revision ID to switch to (or None)
 
1853
    """
 
1854
 
 
1855
    def __init__(self, control_dir, to_branch, force, revision_id):
 
1856
        """Create a group of SwitchHook parameters.
 
1857
 
 
1858
        :param control_dir: ControlDir of the checkout to change
 
1859
        :param to_branch: branch that the checkout is to reference
 
1860
        :param force: skip the check for local commits in a heavy checkout
 
1861
        :param revision_id: revision ID to switch to (or None)
 
1862
        """
 
1863
        self.control_dir = control_dir
 
1864
        self.to_branch = to_branch
 
1865
        self.force = force
 
1866
        self.revision_id = revision_id
 
1867
 
 
1868
    def __eq__(self, other):
 
1869
        return self.__dict__ == other.__dict__
 
1870
 
 
1871
    def __repr__(self):
 
1872
        return "<%s for %s to (%s, %s)>" % (
 
1873
            self.__class__.__name__, self.control_dir, self.to_branch,
 
1874
            self.revision_id)
 
1875
 
 
1876
 
 
1877
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
 
1878
    """Branch format registry."""
 
1879
 
 
1880
    def __init__(self, other_registry=None):
 
1881
        super(BranchFormatRegistry, self).__init__(other_registry)
 
1882
        self._default_format = None
 
1883
        self._default_format_key = None
 
1884
 
 
1885
    def get_default(self):
 
1886
        """Return the current default format."""
 
1887
        if (self._default_format_key is not None
 
1888
                and self._default_format is None):
 
1889
            self._default_format = self.get(self._default_format_key)
 
1890
        return self._default_format
 
1891
 
 
1892
    def set_default(self, format):
 
1893
        """Set the default format."""
 
1894
        self._default_format = format
 
1895
        self._default_format_key = None
 
1896
 
 
1897
    def set_default_key(self, format_string):
 
1898
        """Set the default format by its format string."""
 
1899
        self._default_format_key = format_string
 
1900
        self._default_format = None
 
1901
 
 
1902
 
 
1903
network_format_registry = registry.FormatRegistry()
 
1904
"""Registry of formats indexed by their network name.
 
1905
 
 
1906
The network name for a branch format is an identifier that can be used when
 
1907
referring to formats with smart server operations. See
 
1908
BranchFormat.network_name() for more detail.
 
1909
"""
 
1910
 
 
1911
format_registry = BranchFormatRegistry(network_format_registry)
 
1912
 
 
1913
 
 
1914
# formats which have no format string are not discoverable
 
1915
# and not independently creatable, so are not registered.
 
1916
format_registry.register_lazy(
 
1917
    b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
 
1918
    "BzrBranchFormat5")
 
1919
format_registry.register_lazy(
 
1920
    b"Bazaar Branch Format 6 (bzr 0.15)\n",
 
1921
    "breezy.bzr.branch", "BzrBranchFormat6")
 
1922
format_registry.register_lazy(
 
1923
    b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
 
1924
    "breezy.bzr.branch", "BzrBranchFormat7")
 
1925
format_registry.register_lazy(
 
1926
    b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
 
1927
    "breezy.bzr.branch", "BzrBranchFormat8")
 
1928
format_registry.register_lazy(
 
1929
    b"Bazaar-NG Branch Reference Format 1\n",
 
1930
    "breezy.bzr.branch", "BranchReferenceFormat")
 
1931
 
 
1932
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
 
1933
 
 
1934
 
 
1935
class BranchWriteLockResult(LogicalLockResult):
 
1936
    """The result of write locking a branch.
 
1937
 
 
1938
    :ivar token: The token obtained from the underlying branch lock, or
 
1939
        None.
 
1940
    :ivar unlock: A callable which will unlock the lock.
 
1941
    """
 
1942
 
 
1943
    def __repr__(self):
 
1944
        return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
 
1945
 
 
1946
 
 
1947
######################################################################
 
1948
# results of operations
 
1949
 
 
1950
 
 
1951
class _Result(object):
 
1952
 
 
1953
    def _show_tag_conficts(self, to_file):
 
1954
        if not getattr(self, 'tag_conflicts', None):
 
1955
            return
 
1956
        to_file.write('Conflicting tags:\n')
 
1957
        for name, value1, value2 in self.tag_conflicts:
 
1958
            to_file.write('    %s\n' % (name, ))
 
1959
 
 
1960
 
 
1961
class PullResult(_Result):
 
1962
    """Result of a Branch.pull operation.
 
1963
 
 
1964
    :ivar old_revno: Revision number before pull.
 
1965
    :ivar new_revno: Revision number after pull.
 
1966
    :ivar old_revid: Tip revision id before pull.
 
1967
    :ivar new_revid: Tip revision id after pull.
 
1968
    :ivar source_branch: Source (local) branch object. (read locked)
 
1969
    :ivar master_branch: Master branch of the target, or the target if no
 
1970
        Master
 
1971
    :ivar local_branch: target branch if there is a Master, else None
 
1972
    :ivar target_branch: Target/destination branch object. (write locked)
 
1973
    :ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
 
1974
    :ivar tag_updates: A dict with new tags, see BasicTags.merge_to
 
1975
    """
 
1976
 
 
1977
    def report(self, to_file):
 
1978
        tag_conflicts = getattr(self, "tag_conflicts", None)
 
1979
        tag_updates = getattr(self, "tag_updates", None)
 
1980
        if not is_quiet():
 
1981
            if self.old_revid != self.new_revid:
 
1982
                to_file.write('Now on revision %d.\n' % self.new_revno)
 
1983
            if tag_updates:
 
1984
                to_file.write('%d tag(s) updated.\n' % len(tag_updates))
 
1985
            if self.old_revid == self.new_revid and not tag_updates:
 
1986
                if not tag_conflicts:
 
1987
                    to_file.write('No revisions or tags to pull.\n')
 
1988
                else:
 
1989
                    to_file.write('No revisions to pull.\n')
 
1990
        self._show_tag_conficts(to_file)
 
1991
 
 
1992
 
 
1993
class BranchPushResult(_Result):
 
1994
    """Result of a Branch.push operation.
 
1995
 
 
1996
    :ivar old_revno: Revision number (eg 10) of the target before push.
 
1997
    :ivar new_revno: Revision number (eg 12) of the target after push.
 
1998
    :ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
 
1999
        before the push.
 
2000
    :ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
 
2001
        after the push.
 
2002
    :ivar source_branch: Source branch object that the push was from. This is
 
2003
        read locked, and generally is a local (and thus low latency) branch.
 
2004
    :ivar master_branch: If target is a bound branch, the master branch of
 
2005
        target, or target itself. Always write locked.
 
2006
    :ivar target_branch: The direct Branch where data is being sent (write
 
2007
        locked).
 
2008
    :ivar local_branch: If the target is a bound branch this will be the
 
2009
        target, otherwise it will be None.
 
2010
    """
 
2011
 
 
2012
    def report(self, to_file):
 
2013
        # TODO: This function gets passed a to_file, but then
 
2014
        # ignores it and calls note() instead. This is also
 
2015
        # inconsistent with PullResult(), which writes to stdout.
 
2016
        # -- JRV20110901, bug #838853
 
2017
        tag_conflicts = getattr(self, "tag_conflicts", None)
 
2018
        tag_updates = getattr(self, "tag_updates", None)
 
2019
        if not is_quiet():
 
2020
            if self.old_revid != self.new_revid:
 
2021
                note(gettext('Pushed up to revision %d.') % self.new_revno)
 
2022
            if tag_updates:
 
2023
                note(ngettext('%d tag updated.', '%d tags updated.',
 
2024
                              len(tag_updates)) % len(tag_updates))
 
2025
            if self.old_revid == self.new_revid and not tag_updates:
 
2026
                if not tag_conflicts:
 
2027
                    note(gettext('No new revisions or tags to push.'))
 
2028
                else:
 
2029
                    note(gettext('No new revisions to push.'))
 
2030
        self._show_tag_conficts(to_file)
 
2031
 
 
2032
 
 
2033
class BranchCheckResult(object):
 
2034
    """Results of checking branch consistency.
 
2035
 
 
2036
    :see: Branch.check
 
2037
    """
 
2038
 
 
2039
    def __init__(self, branch):
 
2040
        self.branch = branch
 
2041
        self.errors = []
 
2042
 
 
2043
    def report_results(self, verbose):
 
2044
        """Report the check results via trace.note.
 
2045
 
 
2046
        :param verbose: Requests more detailed display of what was checked,
 
2047
            if any.
 
2048
        """
 
2049
        note(gettext('checked branch {0} format {1}').format(
 
2050
            self.branch.user_url, self.branch._format))
 
2051
        for error in self.errors:
 
2052
            note(gettext('found error:%s'), error)
 
2053
 
 
2054
 
 
2055
class InterBranch(InterObject):
 
2056
    """This class represents operations taking place between two branches.
 
2057
 
 
2058
    Its instances have methods like pull() and push() and contain
 
2059
    references to the source and target repositories these operations
 
2060
    can be carried out on.
 
2061
    """
 
2062
 
 
2063
    _optimisers = []
 
2064
    """The available optimised InterBranch types."""
 
2065
 
 
2066
    @classmethod
 
2067
    def _get_branch_formats_to_test(klass):
 
2068
        """Return an iterable of format tuples for testing.
 
2069
 
 
2070
        :return: An iterable of (from_format, to_format) to use when testing
 
2071
            this InterBranch class. Each InterBranch class should define this
 
2072
            method itself.
 
2073
        """
 
2074
        raise NotImplementedError(klass._get_branch_formats_to_test)
 
2075
 
 
2076
    def pull(self, overwrite=False, stop_revision=None,
 
2077
             possible_transports=None, local=False):
 
2078
        """Mirror source into target branch.
 
2079
 
 
2080
        The target branch is considered to be 'local', having low latency.
 
2081
 
 
2082
        :returns: PullResult instance
 
2083
        """
 
2084
        raise NotImplementedError(self.pull)
 
2085
 
 
2086
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2087
             _override_hook_source_branch=None):
 
2088
        """Mirror the source branch into the target branch.
 
2089
 
 
2090
        The source branch is considered to be 'local', having low latency.
 
2091
        """
 
2092
        raise NotImplementedError(self.push)
 
2093
 
 
2094
    def copy_content_into(self, revision_id=None):
 
2095
        """Copy the content of source into target
 
2096
 
 
2097
        revision_id: if not None, the revision history in the new branch will
 
2098
                     be truncated to end with revision_id.
 
2099
        """
 
2100
        raise NotImplementedError(self.copy_content_into)
 
2101
 
 
2102
    def fetch(self, stop_revision=None, limit=None):
 
2103
        """Fetch revisions.
 
2104
 
 
2105
        :param stop_revision: Last revision to fetch
 
2106
        :param limit: Optional rough limit of revisions to fetch
 
2107
        """
 
2108
        raise NotImplementedError(self.fetch)
 
2109
 
 
2110
 
 
2111
def _fix_overwrite_type(overwrite):
 
2112
    if isinstance(overwrite, bool):
 
2113
        if overwrite:
 
2114
            return ["history", "tags"]
 
2115
        else:
 
2116
            return []
 
2117
    return overwrite
 
2118
 
 
2119
 
 
2120
class GenericInterBranch(InterBranch):
 
2121
    """InterBranch implementation that uses public Branch functions."""
 
2122
 
 
2123
    @classmethod
 
2124
    def is_compatible(klass, source, target):
 
2125
        # GenericBranch uses the public API, so always compatible
 
2126
        return True
 
2127
 
 
2128
    @classmethod
 
2129
    def _get_branch_formats_to_test(klass):
 
2130
        return [(format_registry.get_default(), format_registry.get_default())]
 
2131
 
 
2132
    @classmethod
 
2133
    def unwrap_format(klass, format):
 
2134
        if isinstance(format, remote.RemoteBranchFormat):
 
2135
            format._ensure_real()
 
2136
            return format._custom_format
 
2137
        return format
 
2138
 
 
2139
    def copy_content_into(self, revision_id=None):
 
2140
        """Copy the content of source into target
 
2141
 
 
2142
        revision_id: if not None, the revision history in the new branch will
 
2143
                     be truncated to end with revision_id.
 
2144
        """
 
2145
        with self.source.lock_read(), self.target.lock_write():
 
2146
            self.source.update_references(self.target)
 
2147
            self.source._synchronize_history(self.target, revision_id)
 
2148
            try:
 
2149
                parent = self.source.get_parent()
 
2150
            except errors.InaccessibleParent as e:
 
2151
                mutter('parent was not accessible to copy: %s', str(e))
 
2152
            else:
 
2153
                if parent:
 
2154
                    self.target.set_parent(parent)
 
2155
            if self.source._push_should_merge_tags():
 
2156
                self.source.tags.merge_to(self.target.tags)
 
2157
 
 
2158
    def fetch(self, stop_revision=None, limit=None):
 
2159
        if self.target.base == self.source.base:
 
2160
            return (0, [])
 
2161
        with self.source.lock_read(), self.target.lock_write():
 
2162
            fetch_spec_factory = fetch.FetchSpecFactory()
 
2163
            fetch_spec_factory.source_branch = self.source
 
2164
            fetch_spec_factory.source_branch_stop_revision_id = stop_revision
 
2165
            fetch_spec_factory.source_repo = self.source.repository
 
2166
            fetch_spec_factory.target_repo = self.target.repository
 
2167
            fetch_spec_factory.target_repo_kind = (
 
2168
                fetch.TargetRepoKinds.PREEXISTING)
 
2169
            fetch_spec_factory.limit = limit
 
2170
            fetch_spec = fetch_spec_factory.make_fetch_spec()
 
2171
            return self.target.repository.fetch(
 
2172
                self.source.repository,
 
2173
                fetch_spec=fetch_spec)
 
2174
 
 
2175
    def _update_revisions(self, stop_revision=None, overwrite=False,
 
2176
                          graph=None):
 
2177
        with self.source.lock_read(), self.target.lock_write():
 
2178
            other_revno, other_last_revision = self.source.last_revision_info()
 
2179
            stop_revno = None  # unknown
 
2180
            if stop_revision is None:
 
2181
                stop_revision = other_last_revision
 
2182
                if _mod_revision.is_null(stop_revision):
 
2183
                    # if there are no commits, we're done.
 
2184
                    return
 
2185
                stop_revno = other_revno
 
2186
 
 
2187
            # what's the current last revision, before we fetch [and change it
 
2188
            # possibly]
 
2189
            last_rev = _mod_revision.ensure_null(self.target.last_revision())
 
2190
            # we fetch here so that we don't process data twice in the common
 
2191
            # case of having something to pull, and so that the check for
 
2192
            # already merged can operate on the just fetched graph, which will
 
2193
            # be cached in memory.
 
2194
            self.fetch(stop_revision=stop_revision)
 
2195
            # Check to see if one is an ancestor of the other
 
2196
            if not overwrite:
 
2197
                if graph is None:
 
2198
                    graph = self.target.repository.get_graph()
 
2199
                if self.target._check_if_descendant_or_diverged(
 
2200
                        stop_revision, last_rev, graph, self.source):
 
2201
                    # stop_revision is a descendant of last_rev, but we aren't
 
2202
                    # overwriting, so we're done.
 
2203
                    return
 
2204
            if stop_revno is None:
 
2205
                if graph is None:
 
2206
                    graph = self.target.repository.get_graph()
 
2207
                this_revno, this_last_revision = \
 
2208
                    self.target.last_revision_info()
 
2209
                stop_revno = graph.find_distance_to_null(
 
2210
                    stop_revision, [(other_last_revision, other_revno),
 
2211
                                    (this_last_revision, this_revno)])
 
2212
            self.target.set_last_revision_info(stop_revno, stop_revision)
 
2213
 
 
2214
    def pull(self, overwrite=False, stop_revision=None,
 
2215
             possible_transports=None, run_hooks=True,
 
2216
             _override_hook_target=None, local=False):
 
2217
        """Pull from source into self, updating my master if any.
 
2218
 
 
2219
        :param run_hooks: Private parameter - if false, this branch
 
2220
            is being called because it's the master of the primary branch,
 
2221
            so it should not run its hooks.
 
2222
        """
 
2223
        with self.target.lock_write():
 
2224
            bound_location = self.target.get_bound_location()
 
2225
            if local and not bound_location:
 
2226
                raise errors.LocalRequiresBoundBranch()
 
2227
            master_branch = None
 
2228
            source_is_master = False
 
2229
            if bound_location:
 
2230
                # bound_location comes from a config file, some care has to be
 
2231
                # taken to relate it to source.user_url
 
2232
                normalized = urlutils.normalize_url(bound_location)
 
2233
                try:
 
2234
                    relpath = self.source.user_transport.relpath(normalized)
 
2235
                    source_is_master = (relpath == '')
 
2236
                except (errors.PathNotChild, urlutils.InvalidURL):
 
2237
                    source_is_master = False
 
2238
            if not local and bound_location and not source_is_master:
 
2239
                # not pulling from master, so we need to update master.
 
2240
                master_branch = self.target.get_master_branch(
 
2241
                    possible_transports)
 
2242
                master_branch.lock_write()
 
2243
            try:
 
2244
                if master_branch:
 
2245
                    # pull from source into master.
 
2246
                    master_branch.pull(
 
2247
                        self.source, overwrite, stop_revision, run_hooks=False)
 
2248
                return self._pull(
 
2249
                    overwrite, stop_revision, _hook_master=master_branch,
 
2250
                    run_hooks=run_hooks,
 
2251
                    _override_hook_target=_override_hook_target,
 
2252
                    merge_tags_to_master=not source_is_master)
 
2253
            finally:
 
2254
                if master_branch:
 
2255
                    master_branch.unlock()
 
2256
 
 
2257
    def push(self, overwrite=False, stop_revision=None, lossy=False,
 
2258
             _override_hook_source_branch=None):
 
2259
        """See InterBranch.push.
 
2260
 
 
2261
        This is the basic concrete implementation of push()
 
2262
 
 
2263
        :param _override_hook_source_branch: If specified, run the hooks
 
2264
            passing this Branch as the source, rather than self.  This is for
 
2265
            use of RemoteBranch, where push is delegated to the underlying
 
2266
            vfs-based Branch.
 
2267
        """
 
2268
        if lossy:
 
2269
            raise errors.LossyPushToSameVCS(self.source, self.target)
 
2270
        # TODO: Public option to disable running hooks - should be trivial but
 
2271
        # needs tests.
 
2272
 
 
2273
        def _run_hooks():
 
2274
            if _override_hook_source_branch:
 
2275
                result.source_branch = _override_hook_source_branch
 
2276
            for hook in Branch.hooks['post_push']:
 
2277
                hook(result)
 
2278
 
 
2279
        with self.source.lock_read(), self.target.lock_write():
 
2280
            bound_location = self.target.get_bound_location()
 
2281
            if bound_location and self.target.base != bound_location:
 
2282
                # there is a master branch.
 
2283
                #
 
2284
                # XXX: Why the second check?  Is it even supported for a branch
 
2285
                # to be bound to itself? -- mbp 20070507
 
2286
                master_branch = self.target.get_master_branch()
 
2287
                with master_branch.lock_write():
 
2288
                    # push into the master from the source branch.
 
2289
                    master_inter = InterBranch.get(self.source, master_branch)
 
2290
                    master_inter._basic_push(overwrite, stop_revision)
 
2291
                    # and push into the target branch from the source. Note
 
2292
                    # that we push from the source branch again, because it's
 
2293
                    # considered the highest bandwidth repository.
 
2294
                    result = self._basic_push(overwrite, stop_revision)
 
2295
                    result.master_branch = master_branch
 
2296
                    result.local_branch = self.target
 
2297
                    _run_hooks()
 
2298
            else:
 
2299
                master_branch = None
 
2300
                # no master branch
 
2301
                result = self._basic_push(overwrite, stop_revision)
 
2302
                # TODO: Why set master_branch and local_branch if there's no
 
2303
                # binding?  Maybe cleaner to just leave them unset? -- mbp
 
2304
                # 20070504
 
2305
                result.master_branch = self.target
 
2306
                result.local_branch = None
 
2307
                _run_hooks()
 
2308
            return result
 
2309
 
 
2310
    def _basic_push(self, overwrite, stop_revision):
 
2311
        """Basic implementation of push without bound branches or hooks.
 
2312
 
 
2313
        Must be called with source read locked and target write locked.
 
2314
        """
 
2315
        result = BranchPushResult()
 
2316
        result.source_branch = self.source
 
2317
        result.target_branch = self.target
 
2318
        result.old_revno, result.old_revid = self.target.last_revision_info()
 
2319
        self.source.update_references(self.target)
 
2320
        overwrite = _fix_overwrite_type(overwrite)
 
2321
        if result.old_revid != stop_revision:
 
2322
            # We assume that during 'push' this repository is closer than
 
2323
            # the target.
 
2324
            graph = self.source.repository.get_graph(self.target.repository)
 
2325
            self._update_revisions(
 
2326
                stop_revision, overwrite=("history" in overwrite), graph=graph)
 
2327
        if self.source._push_should_merge_tags():
 
2328
            result.tag_updates, result.tag_conflicts = (
 
2329
                self.source.tags.merge_to(
 
2330
                    self.target.tags, "tags" in overwrite))
 
2331
        result.new_revno, result.new_revid = self.target.last_revision_info()
 
2332
        return result
 
2333
 
 
2334
    def _pull(self, overwrite=False, stop_revision=None,
 
2335
              possible_transports=None, _hook_master=None, run_hooks=True,
 
2336
              _override_hook_target=None, local=False,
 
2337
              merge_tags_to_master=True):
 
2338
        """See Branch.pull.
 
2339
 
 
2340
        This function is the core worker, used by GenericInterBranch.pull to
 
2341
        avoid duplication when pulling source->master and source->local.
 
2342
 
 
2343
        :param _hook_master: Private parameter - set the branch to
 
2344
            be supplied as the master to pull hooks.
 
2345
        :param run_hooks: Private parameter - if false, this branch
 
2346
            is being called because it's the master of the primary branch,
 
2347
            so it should not run its hooks.
 
2348
            is being called because it's the master of the primary branch,
 
2349
            so it should not run its hooks.
 
2350
        :param _override_hook_target: Private parameter - set the branch to be
 
2351
            supplied as the target_branch to pull hooks.
 
2352
        :param local: Only update the local branch, and not the bound branch.
 
2353
        """
 
2354
        # This type of branch can't be bound.
 
2355
        if local:
 
2356
            raise errors.LocalRequiresBoundBranch()
 
2357
        result = PullResult()
 
2358
        result.source_branch = self.source
 
2359
        if _override_hook_target is None:
 
2360
            result.target_branch = self.target
 
2361
        else:
 
2362
            result.target_branch = _override_hook_target
 
2363
        with self.source.lock_read():
 
2364
            # We assume that during 'pull' the target repository is closer than
 
2365
            # the source one.
 
2366
            self.source.update_references(self.target)
 
2367
            graph = self.target.repository.get_graph(self.source.repository)
 
2368
            # TODO: Branch formats should have a flag that indicates
 
2369
            # that revno's are expensive, and pull() should honor that flag.
 
2370
            # -- JRV20090506
 
2371
            result.old_revno, result.old_revid = \
 
2372
                self.target.last_revision_info()
 
2373
            overwrite = _fix_overwrite_type(overwrite)
 
2374
            self._update_revisions(
 
2375
                stop_revision, overwrite=("history" in overwrite), graph=graph)
 
2376
            # TODO: The old revid should be specified when merging tags,
 
2377
            # so a tags implementation that versions tags can only
 
2378
            # pull in the most recent changes. -- JRV20090506
 
2379
            result.tag_updates, result.tag_conflicts = (
 
2380
                self.source.tags.merge_to(
 
2381
                    self.target.tags, "tags" in overwrite,
 
2382
                    ignore_master=not merge_tags_to_master))
 
2383
            result.new_revno, result.new_revid = (
 
2384
                self.target.last_revision_info())
 
2385
            if _hook_master:
 
2386
                result.master_branch = _hook_master
 
2387
                result.local_branch = result.target_branch
 
2388
            else:
 
2389
                result.master_branch = result.target_branch
 
2390
                result.local_branch = None
 
2391
            if run_hooks:
 
2392
                for hook in Branch.hooks['post_pull']:
 
2393
                    hook(result)
 
2394
            return result
 
2395
 
 
2396
 
 
2397
InterBranch.register_optimiser(GenericInterBranch)