1
# Copyright (C) 2005-2012 Canonical Ltd
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.
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.
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
17
from __future__ import absolute_import
21
from .lazy_import import lazy_import
22
lazy_import(globals(), """
26
config as _mod_config,
30
revision as _mod_revision,
36
from breezy.bzr import (
40
from breezy.i18n import gettext, ngettext
47
from .decorators import (
52
from .hooks import Hooks
53
from .inter import InterObject
54
from .lock import LogicalLockResult
59
from .trace import mutter, mutter_callsite, note, is_quiet
62
class UnstackableBranchFormat(errors.BzrError):
64
_fmt = ("The branch '%(url)s'(%(format)s) is not a stackable format. "
65
"You will need to upgrade the branch to permit branch stacking.")
67
def __init__(self, format, url):
68
errors.BzrError.__init__(self)
73
class Branch(controldir.ControlComponent):
74
"""Branch holding a history of revisions.
77
Base directory/url of the branch; using control_url and
78
control_transport is more standardized.
79
:ivar hooks: An instance of BranchHooks.
80
:ivar _master_branch_cache: cached result of get_master_branch, see
83
# this is really an instance variable - FIXME move it there
88
def control_transport(self):
89
return self._transport
92
def user_transport(self):
93
return self.controldir.user_transport
95
def __init__(self, possible_transports=None):
96
self.tags = self._format.make_tags(self)
97
self._revision_history_cache = None
98
self._revision_id_to_revno_cache = None
99
self._partial_revision_id_to_revno_cache = {}
100
self._partial_revision_history_cache = []
101
self._tags_bytes = None
102
self._last_revision_info_cache = None
103
self._master_branch_cache = None
104
self._merge_sorted_revisions_cache = None
105
self._open_hook(possible_transports)
106
hooks = Branch.hooks['open']
110
def _open_hook(self, possible_transports):
111
"""Called by init to allow simpler extension of the base class."""
113
def _activate_fallback_location(self, url, possible_transports):
114
"""Activate the branch/repository from url as a fallback repository."""
115
for existing_fallback_repo in self.repository._fallback_repositories:
116
if existing_fallback_repo.user_url == url:
117
# This fallback is already configured. This probably only
118
# happens because ControlDir.sprout is a horrible mess. To
119
# avoid confusing _unstack we don't add this a second time.
120
mutter('duplicate activation of fallback %r on %r', url, self)
122
repo = self._get_fallback_repository(url, possible_transports)
123
if repo.has_same_location(self.repository):
124
raise errors.UnstackableLocationError(self.user_url, url)
125
self.repository.add_fallback_repository(repo)
127
def break_lock(self):
128
"""Break a lock if one is present from another instance.
130
Uses the ui factory to ask for confirmation if the lock may be from
133
This will probe the repository for its lock as well.
135
self.control_files.break_lock()
136
self.repository.break_lock()
137
master = self.get_master_branch()
138
if master is not None:
141
def _check_stackable_repo(self):
142
if not self.repository._format.supports_external_lookups:
143
raise errors.UnstackableRepositoryFormat(
144
self.repository._format, self.repository.base)
146
def _extend_partial_history(self, stop_index=None, stop_revision=None):
147
"""Extend the partial history to include a given index
149
If a stop_index is supplied, stop when that index has been reached.
150
If a stop_revision is supplied, stop when that revision is
151
encountered. Otherwise, stop when the beginning of history is
154
:param stop_index: The index which should be present. When it is
155
present, history extension will stop.
156
:param stop_revision: The revision id which should be present. When
157
it is encountered, history extension will stop.
159
if len(self._partial_revision_history_cache) == 0:
160
self._partial_revision_history_cache = [self.last_revision()]
161
repository._iter_for_revno(
162
self.repository, self._partial_revision_history_cache,
163
stop_index=stop_index, stop_revision=stop_revision)
164
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
165
self._partial_revision_history_cache.pop()
167
def _get_check_refs(self):
168
"""Get the references needed for check().
172
revid = self.last_revision()
173
return [('revision-existence', revid), ('lefthand-distance', revid)]
176
def open(base, _unsupported=False, possible_transports=None):
177
"""Open the branch rooted at base.
179
For instance, if the branch is at URL/.bzr/branch,
180
Branch.open(URL) -> a Branch instance.
182
control = controldir.ControlDir.open(base,
183
possible_transports=possible_transports, _unsupported=_unsupported)
184
return control.open_branch(unsupported=_unsupported,
185
possible_transports=possible_transports)
188
def open_from_transport(transport, name=None, _unsupported=False,
189
possible_transports=None):
190
"""Open the branch rooted at transport"""
191
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
192
return control.open_branch(name=name, unsupported=_unsupported,
193
possible_transports=possible_transports)
196
def open_containing(url, possible_transports=None):
197
"""Open an existing branch which contains url.
199
This probes for a branch at url, and searches upwards from there.
201
Basically we keep looking up until we find the control directory or
202
run into the root. If there isn't one, raises NotBranchError.
203
If there is one and it is either an unrecognised format or an unsupported
204
format, UnknownFormatError or UnsupportedFormatError are raised.
205
If there is one, it is returned, along with the unused portion of url.
207
control, relpath = controldir.ControlDir.open_containing(url,
209
branch = control.open_branch(possible_transports=possible_transports)
210
return (branch, relpath)
212
def _push_should_merge_tags(self):
213
"""Should _basic_push merge this branch's tags into the target?
215
The default implementation returns False if this branch has no tags,
216
and True the rest of the time. Subclasses may override this.
218
return self.supports_tags() and self.tags.get_tag_dict()
220
def get_config(self):
221
"""Get a breezy.config.BranchConfig for this Branch.
223
This can then be used to get and set configuration options for the
226
:return: A breezy.config.BranchConfig.
228
return _mod_config.BranchConfig(self)
230
def get_config_stack(self):
231
"""Get a breezy.config.BranchStack for this Branch.
233
This can then be used to get and set configuration options for the
236
:return: A breezy.config.BranchStack.
238
return _mod_config.BranchStack(self)
240
def _get_config(self):
241
"""Get the concrete config for just the config in this branch.
243
This is not intended for client use; see Branch.get_config for the
248
:return: An object supporting get_option and set_option.
250
raise NotImplementedError(self._get_config)
252
def store_uncommitted(self, creator):
253
"""Store uncommitted changes from a ShelfCreator.
255
:param creator: The ShelfCreator containing uncommitted changes, or
256
None to delete any stored changes.
257
:raises: ChangesAlreadyStored if the branch already has changes.
259
raise NotImplementedError(self.store_uncommitted)
261
def get_unshelver(self, tree):
262
"""Return a shelf.Unshelver for this branch and tree.
264
:param tree: The tree to use to construct the Unshelver.
265
:return: an Unshelver or None if no changes are stored.
267
raise NotImplementedError(self.get_unshelver)
269
def _get_fallback_repository(self, url, possible_transports):
270
"""Get the repository we fallback to at url."""
271
url = urlutils.join(self.base, url)
272
a_branch = Branch.open(url, possible_transports=possible_transports)
273
return a_branch.repository
276
def _get_tags_bytes(self):
277
"""Get the bytes of a serialised tags dict.
279
Note that not all branches support tags, nor do all use the same tags
280
logic: this method is specific to BasicTags. Other tag implementations
281
may use the same method name and behave differently, safely, because
282
of the double-dispatch via
283
format.make_tags->tags_instance->get_tags_dict.
285
:return: The bytes of the tags file.
286
:seealso: Branch._set_tags_bytes.
288
if self._tags_bytes is None:
289
self._tags_bytes = self._transport.get_bytes('tags')
290
return self._tags_bytes
292
def _get_nick(self, local=False, possible_transports=None):
293
config = self.get_config()
294
# explicit overrides master, but don't look for master if local is True
295
if not local and not config.has_explicit_nickname():
297
master = self.get_master_branch(possible_transports)
298
if master and self.user_url == master.user_url:
299
raise errors.RecursiveBind(self.user_url)
300
if master is not None:
301
# return the master branch value
303
except errors.RecursiveBind as e:
305
except errors.BzrError as e:
306
# Silently fall back to local implicit nick if the master is
308
mutter("Could not connect to bound branch, "
309
"falling back to local nick.\n " + str(e))
310
return config.get_nickname()
312
def _set_nick(self, nick):
313
self.get_config().set_user_option('nickname', nick, warn_masked=True)
315
nick = property(_get_nick, _set_nick)
318
raise NotImplementedError(self.is_locked)
320
def _lefthand_history(self, revision_id, last_rev=None,
322
if 'evil' in debug.debug_flags:
323
mutter_callsite(4, "_lefthand_history scales with history.")
324
# stop_revision must be a descendant of last_revision
325
graph = self.repository.get_graph()
326
if last_rev is not None:
327
if not graph.is_ancestor(last_rev, revision_id):
328
# our previous tip is not merged into stop_revision
329
raise errors.DivergedBranches(self, other_branch)
330
# make a new revision history from the graph
331
parents_map = graph.get_parent_map([revision_id])
332
if revision_id not in parents_map:
333
raise errors.NoSuchRevision(self, revision_id)
334
current_rev_id = revision_id
336
check_not_reserved_id = _mod_revision.check_not_reserved_id
337
# Do not include ghosts or graph origin in revision_history
338
while (current_rev_id in parents_map and
339
len(parents_map[current_rev_id]) > 0):
340
check_not_reserved_id(current_rev_id)
341
new_history.append(current_rev_id)
342
current_rev_id = parents_map[current_rev_id][0]
343
parents_map = graph.get_parent_map([current_rev_id])
344
new_history.reverse()
347
def lock_write(self, token=None):
348
"""Lock the branch for write operations.
350
:param token: A token to permit reacquiring a previously held and
352
:return: A BranchWriteLockResult.
354
raise NotImplementedError(self.lock_write)
357
"""Lock the branch for read operations.
359
:return: A breezy.lock.LogicalLockResult.
361
raise NotImplementedError(self.lock_read)
364
raise NotImplementedError(self.unlock)
366
def peek_lock_mode(self):
367
"""Return lock mode for the Branch: 'r', 'w' or None"""
368
raise NotImplementedError(self.peek_lock_mode)
370
def get_physical_lock_status(self):
371
raise NotImplementedError(self.get_physical_lock_status)
374
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
375
"""Return the revision_id for a dotted revno.
377
:param revno: a tuple like (1,) or (1,1,2)
378
:param _cache_reverse: a private parameter enabling storage
379
of the reverse mapping in a top level cache. (This should
380
only be done in selective circumstances as we want to
381
avoid having the mapping cached multiple times.)
382
:return: the revision_id
383
:raises errors.NoSuchRevision: if the revno doesn't exist
385
rev_id = self._do_dotted_revno_to_revision_id(revno)
387
self._partial_revision_id_to_revno_cache[rev_id] = revno
390
def _do_dotted_revno_to_revision_id(self, revno):
391
"""Worker function for dotted_revno_to_revision_id.
393
Subclasses should override this if they wish to
394
provide a more efficient implementation.
397
return self.get_rev_id(revno[0])
398
revision_id_to_revno = self.get_revision_id_to_revno_map()
399
revision_ids = [revision_id for revision_id, this_revno
400
in viewitems(revision_id_to_revno)
401
if revno == this_revno]
402
if len(revision_ids) == 1:
403
return revision_ids[0]
405
revno_str = '.'.join(map(str, revno))
406
raise errors.NoSuchRevision(self, revno_str)
409
def revision_id_to_dotted_revno(self, revision_id):
410
"""Given a revision id, return its dotted revno.
412
:return: a tuple like (1,) or (400,1,3).
414
return self._do_revision_id_to_dotted_revno(revision_id)
416
def _do_revision_id_to_dotted_revno(self, revision_id):
417
"""Worker function for revision_id_to_revno."""
418
# Try the caches if they are loaded
419
result = self._partial_revision_id_to_revno_cache.get(revision_id)
420
if result is not None:
422
if self._revision_id_to_revno_cache:
423
result = self._revision_id_to_revno_cache.get(revision_id)
425
raise errors.NoSuchRevision(self, revision_id)
426
# Try the mainline as it's optimised
428
revno = self.revision_id_to_revno(revision_id)
430
except errors.NoSuchRevision:
431
# We need to load and use the full revno map after all
432
result = self.get_revision_id_to_revno_map().get(revision_id)
434
raise errors.NoSuchRevision(self, revision_id)
438
def get_revision_id_to_revno_map(self):
439
"""Return the revision_id => dotted revno map.
441
This will be regenerated on demand, but will be cached.
443
:return: A dictionary mapping revision_id => dotted revno.
444
This dictionary should not be modified by the caller.
446
if self._revision_id_to_revno_cache is not None:
447
mapping = self._revision_id_to_revno_cache
449
mapping = self._gen_revno_map()
450
self._cache_revision_id_to_revno(mapping)
451
# TODO: jam 20070417 Since this is being cached, should we be returning
453
# I would rather not, and instead just declare that users should not
454
# modify the return value.
457
def _gen_revno_map(self):
458
"""Create a new mapping from revision ids to dotted revnos.
460
Dotted revnos are generated based on the current tip in the revision
462
This is the worker function for get_revision_id_to_revno_map, which
463
just caches the return value.
465
:return: A dictionary mapping revision_id => dotted revno.
467
revision_id_to_revno = dict((rev_id, revno)
468
for rev_id, depth, revno, end_of_merge
469
in self.iter_merge_sorted_revisions())
470
return revision_id_to_revno
473
def iter_merge_sorted_revisions(self, start_revision_id=None,
474
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
475
"""Walk the revisions for a branch in merge sorted order.
477
Merge sorted order is the output from a merge-aware,
478
topological sort, i.e. all parents come before their
479
children going forward; the opposite for reverse.
481
:param start_revision_id: the revision_id to begin walking from.
482
If None, the branch tip is used.
483
:param stop_revision_id: the revision_id to terminate the walk
484
after. If None, the rest of history is included.
485
:param stop_rule: if stop_revision_id is not None, the precise rule
486
to use for termination:
488
* 'exclude' - leave the stop revision out of the result (default)
489
* 'include' - the stop revision is the last item in the result
490
* 'with-merges' - include the stop revision and all of its
491
merged revisions in the result
492
* 'with-merges-without-common-ancestry' - filter out revisions
493
that are in both ancestries
494
:param direction: either 'reverse' or 'forward':
496
* reverse means return the start_revision_id first, i.e.
497
start at the most recent revision and go backwards in history
498
* forward returns tuples in the opposite order to reverse.
499
Note in particular that forward does *not* do any intelligent
500
ordering w.r.t. depth as some clients of this API may like.
501
(If required, that ought to be done at higher layers.)
503
:return: an iterator over (revision_id, depth, revno, end_of_merge)
506
* revision_id: the unique id of the revision
507
* depth: How many levels of merging deep this node has been
509
* revno_sequence: This field provides a sequence of
510
revision numbers for all revisions. The format is:
511
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
512
branch that the revno is on. From left to right the REVNO numbers
513
are the sequence numbers within that branch of the revision.
514
* end_of_merge: When True the next node (earlier in history) is
515
part of a different merge.
517
# Note: depth and revno values are in the context of the branch so
518
# we need the full graph to get stable numbers, regardless of the
520
if self._merge_sorted_revisions_cache is None:
521
last_revision = self.last_revision()
522
known_graph = self.repository.get_known_graph_ancestry(
524
self._merge_sorted_revisions_cache = known_graph.merge_sort(
526
filtered = self._filter_merge_sorted_revisions(
527
self._merge_sorted_revisions_cache, start_revision_id,
528
stop_revision_id, stop_rule)
529
# Make sure we don't return revisions that are not part of the
530
# start_revision_id ancestry.
531
filtered = self._filter_start_non_ancestors(filtered)
532
if direction == 'reverse':
534
if direction == 'forward':
535
return reversed(list(filtered))
537
raise ValueError('invalid direction %r' % direction)
539
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
540
start_revision_id, stop_revision_id, stop_rule):
541
"""Iterate over an inclusive range of sorted revisions."""
542
rev_iter = iter(merge_sorted_revisions)
543
if start_revision_id is not None:
544
for node in rev_iter:
546
if rev_id != start_revision_id:
549
# The decision to include the start or not
550
# depends on the stop_rule if a stop is provided
551
# so pop this node back into the iterator
552
rev_iter = itertools.chain(iter([node]), rev_iter)
554
if stop_revision_id is None:
556
for node in rev_iter:
558
yield (rev_id, node.merge_depth, node.revno,
560
elif stop_rule == 'exclude':
561
for node in rev_iter:
563
if rev_id == stop_revision_id:
565
yield (rev_id, node.merge_depth, node.revno,
567
elif stop_rule == 'include':
568
for node in rev_iter:
570
yield (rev_id, node.merge_depth, node.revno,
572
if rev_id == stop_revision_id:
574
elif stop_rule == 'with-merges-without-common-ancestry':
575
# We want to exclude all revisions that are already part of the
576
# stop_revision_id ancestry.
577
graph = self.repository.get_graph()
578
ancestors = graph.find_unique_ancestors(start_revision_id,
580
for node in rev_iter:
582
if rev_id not in ancestors:
584
yield (rev_id, node.merge_depth, node.revno,
586
elif stop_rule == 'with-merges':
587
stop_rev = self.repository.get_revision(stop_revision_id)
588
if stop_rev.parent_ids:
589
left_parent = stop_rev.parent_ids[0]
591
left_parent = _mod_revision.NULL_REVISION
592
# left_parent is the actual revision we want to stop logging at,
593
# since we want to show the merged revisions after the stop_rev too
594
reached_stop_revision_id = False
595
revision_id_whitelist = []
596
for node in rev_iter:
598
if rev_id == left_parent:
599
# reached the left parent after the stop_revision
601
if (not reached_stop_revision_id or
602
rev_id in revision_id_whitelist):
603
yield (rev_id, node.merge_depth, node.revno,
605
if reached_stop_revision_id or rev_id == stop_revision_id:
606
# only do the merged revs of rev_id from now on
607
rev = self.repository.get_revision(rev_id)
609
reached_stop_revision_id = True
610
revision_id_whitelist.extend(rev.parent_ids)
612
raise ValueError('invalid stop_rule %r' % stop_rule)
614
def _filter_start_non_ancestors(self, rev_iter):
615
# If we started from a dotted revno, we want to consider it as a tip
616
# and don't want to yield revisions that are not part of its
617
# ancestry. Given the order guaranteed by the merge sort, we will see
618
# uninteresting descendants of the first parent of our tip before the
620
first = next(rev_iter)
621
(rev_id, merge_depth, revno, end_of_merge) = first
624
# We start at a mainline revision so by definition, all others
625
# revisions in rev_iter are ancestors
626
for node in rev_iter:
631
pmap = self.repository.get_parent_map([rev_id])
632
parents = pmap.get(rev_id, [])
634
whitelist.update(parents)
636
# If there is no parents, there is nothing of interest left
638
# FIXME: It's hard to test this scenario here as this code is never
639
# called in that case. -- vila 20100322
642
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
644
if rev_id in whitelist:
645
pmap = self.repository.get_parent_map([rev_id])
646
parents = pmap.get(rev_id, [])
647
whitelist.remove(rev_id)
648
whitelist.update(parents)
650
# We've reached the mainline, there is nothing left to
654
# A revision that is not part of the ancestry of our
657
yield (rev_id, merge_depth, revno, end_of_merge)
659
def leave_lock_in_place(self):
660
"""Tell this branch object not to release the physical lock when this
663
If lock_write doesn't return a token, then this method is not supported.
665
self.control_files.leave_in_place()
667
def dont_leave_lock_in_place(self):
668
"""Tell this branch object to release the physical lock when this
669
object is unlocked, even if it didn't originally acquire it.
671
If lock_write doesn't return a token, then this method is not supported.
673
self.control_files.dont_leave_in_place()
675
def bind(self, other):
676
"""Bind the local branch the other branch.
678
:param other: The branch to bind to
681
raise errors.UpgradeRequired(self.user_url)
683
def get_append_revisions_only(self):
684
"""Whether it is only possible to append revisions to the history.
686
if not self._format.supports_set_append_revisions_only():
688
return self.get_config_stack().get('append_revisions_only')
690
def set_append_revisions_only(self, enabled):
691
if not self._format.supports_set_append_revisions_only():
692
raise errors.UpgradeRequired(self.user_url)
693
self.get_config_stack().set('append_revisions_only', enabled)
695
def set_reference_info(self, file_id, tree_path, branch_location):
696
"""Set the branch location to use for a tree reference."""
697
raise errors.UnsupportedOperation(self.set_reference_info, self)
699
def get_reference_info(self, file_id):
700
"""Get the tree_path and branch_location for a tree reference."""
701
raise errors.UnsupportedOperation(self.get_reference_info, self)
704
def fetch(self, from_branch, last_revision=None, limit=None):
705
"""Copy revisions from from_branch into this branch.
707
:param from_branch: Where to copy from.
708
:param last_revision: What revision to stop at (None for at the end
710
:param limit: Optional rough limit of revisions to fetch
713
return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
715
def get_bound_location(self):
716
"""Return the URL of the branch we are bound to.
718
Older format branches cannot bind, please be sure to use a metadir
723
def get_old_bound_location(self):
724
"""Return the URL of the branch we used to be bound to
726
raise errors.UpgradeRequired(self.user_url)
728
def get_commit_builder(self, parents, config_stack=None, timestamp=None,
729
timezone=None, committer=None, revprops=None,
730
revision_id=None, lossy=False):
731
"""Obtain a CommitBuilder for this branch.
733
:param parents: Revision ids of the parents of the new revision.
734
:param config: Optional configuration to use.
735
:param timestamp: Optional timestamp recorded for commit.
736
:param timezone: Optional timezone for timestamp.
737
:param committer: Optional committer to set for commit.
738
:param revprops: Optional dictionary of revision properties.
739
:param revision_id: Optional revision id.
740
:param lossy: Whether to discard data that can not be natively
741
represented, when pushing to a foreign VCS
744
if config_stack is None:
745
config_stack = self.get_config_stack()
747
return self.repository.get_commit_builder(self, parents, config_stack,
748
timestamp, timezone, committer, revprops, revision_id,
751
def get_master_branch(self, possible_transports=None):
752
"""Return the branch we are bound to.
754
:return: Either a Branch, or None
758
def get_stacked_on_url(self):
759
"""Get the URL this branch is stacked against.
761
:raises NotStacked: If the branch is not stacked.
762
:raises UnstackableBranchFormat: If the branch does not support
765
raise NotImplementedError(self.get_stacked_on_url)
767
def print_file(self, file, revision_id):
768
"""Print `file` to stdout."""
769
raise NotImplementedError(self.print_file)
772
def set_last_revision_info(self, revno, revision_id):
773
"""Set the last revision of this branch.
775
The caller is responsible for checking that the revno is correct
776
for this revision id.
778
It may be possible to set the branch last revision to an id not
779
present in the repository. However, branches can also be
780
configured to check constraints on history, in which case this may not
783
raise NotImplementedError(self.set_last_revision_info)
786
def generate_revision_history(self, revision_id, last_rev=None,
788
"""See Branch.generate_revision_history"""
789
graph = self.repository.get_graph()
790
(last_revno, last_revid) = self.last_revision_info()
791
known_revision_ids = [
792
(last_revid, last_revno),
793
(_mod_revision.NULL_REVISION, 0),
795
if last_rev is not None:
796
if not graph.is_ancestor(last_rev, revision_id):
797
# our previous tip is not merged into stop_revision
798
raise errors.DivergedBranches(self, other_branch)
799
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
800
self.set_last_revision_info(revno, revision_id)
803
def set_parent(self, url):
804
"""See Branch.set_parent."""
805
# TODO: Maybe delete old location files?
806
# URLs should never be unicode, even on the local fs,
807
# FIXUP this and get_parent in a future branch format bump:
808
# read and rewrite the file. RBC 20060125
810
if isinstance(url, unicode):
812
url = url.encode('ascii')
813
except UnicodeEncodeError:
814
raise urlutils.InvalidURL(url,
815
"Urls must be 7-bit ascii, "
816
"use breezy.urlutils.escape")
817
url = urlutils.relative_url(self.base, url)
818
self._set_parent_location(url)
821
def set_stacked_on_url(self, url):
822
"""Set the URL this branch is stacked against.
824
:raises UnstackableBranchFormat: If the branch does not support
826
:raises UnstackableRepositoryFormat: If the repository does not support
829
if not self._format.supports_stacking():
830
raise UnstackableBranchFormat(self._format, self.user_url)
831
# XXX: Changing from one fallback repository to another does not check
832
# that all the data you need is present in the new fallback.
833
# Possibly it should.
834
self._check_stackable_repo()
837
old_url = self.get_stacked_on_url()
838
except (errors.NotStacked, UnstackableBranchFormat,
839
errors.UnstackableRepositoryFormat):
843
self._activate_fallback_location(url,
844
possible_transports=[self.controldir.root_transport])
845
# write this out after the repository is stacked to avoid setting a
846
# stacked config that doesn't work.
847
self._set_config_location('stacked_on_location', url)
850
"""Change a branch to be unstacked, copying data as needed.
852
Don't call this directly, use set_stacked_on_url(None).
854
pb = ui.ui_factory.nested_progress_bar()
856
pb.update(gettext("Unstacking"))
857
# The basic approach here is to fetch the tip of the branch,
858
# including all available ghosts, from the existing stacked
859
# repository into a new repository object without the fallbacks.
861
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
862
# correct for CHKMap repostiories
863
old_repository = self.repository
864
if len(old_repository._fallback_repositories) != 1:
865
raise AssertionError("can't cope with fallback repositories "
866
"of %r (fallbacks: %r)" % (old_repository,
867
old_repository._fallback_repositories))
868
# Open the new repository object.
869
# Repositories don't offer an interface to remove fallback
870
# repositories today; take the conceptually simpler option and just
871
# reopen it. We reopen it starting from the URL so that we
872
# get a separate connection for RemoteRepositories and can
873
# stream from one of them to the other. This does mean doing
874
# separate SSH connection setup, but unstacking is not a
875
# common operation so it's tolerable.
876
new_bzrdir = controldir.ControlDir.open(
877
self.controldir.root_transport.base)
878
new_repository = new_bzrdir.find_repository()
879
if new_repository._fallback_repositories:
880
raise AssertionError("didn't expect %r to have "
881
"fallback_repositories"
882
% (self.repository,))
883
# Replace self.repository with the new repository.
884
# Do our best to transfer the lock state (i.e. lock-tokens and
885
# lock count) of self.repository to the new repository.
886
lock_token = old_repository.lock_write().repository_token
887
self.repository = new_repository
888
if isinstance(self, remote.RemoteBranch):
889
# Remote branches can have a second reference to the old
890
# repository that need to be replaced.
891
if self._real_branch is not None:
892
self._real_branch.repository = new_repository
893
self.repository.lock_write(token=lock_token)
894
if lock_token is not None:
895
old_repository.leave_lock_in_place()
896
old_repository.unlock()
897
if lock_token is not None:
898
# XXX: self.repository.leave_lock_in_place() before this
899
# function will not be preserved. Fortunately that doesn't
900
# affect the current default format (2a), and would be a
901
# corner-case anyway.
902
# - Andrew Bennetts, 2010/06/30
903
self.repository.dont_leave_lock_in_place()
907
old_repository.unlock()
908
except errors.LockNotHeld:
911
if old_lock_count == 0:
912
raise AssertionError(
913
'old_repository should have been locked at least once.')
914
for i in range(old_lock_count-1):
915
self.repository.lock_write()
916
# Fetch from the old repository into the new.
917
old_repository.lock_read()
919
# XXX: If you unstack a branch while it has a working tree
920
# with a pending merge, the pending-merged revisions will no
921
# longer be present. You can (probably) revert and remerge.
923
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
924
except errors.TagsNotSupported:
925
tags_to_fetch = set()
926
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
927
old_repository, required_ids=[self.last_revision()],
928
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
929
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
931
old_repository.unlock()
935
def _set_tags_bytes(self, bytes):
936
"""Mirror method for _get_tags_bytes.
938
:seealso: Branch._get_tags_bytes.
940
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
941
op.add_cleanup(self.lock_write().unlock)
942
return op.run_simple(bytes)
944
def _set_tags_bytes_locked(self, bytes):
945
self._tags_bytes = bytes
946
return self._transport.put_bytes('tags', bytes)
948
def _cache_revision_history(self, rev_history):
949
"""Set the cached revision history to rev_history.
951
The revision_history method will use this cache to avoid regenerating
952
the revision history.
954
This API is semi-public; it only for use by subclasses, all other code
955
should consider it to be private.
957
self._revision_history_cache = rev_history
959
def _cache_revision_id_to_revno(self, revision_id_to_revno):
960
"""Set the cached revision_id => revno map to revision_id_to_revno.
962
This API is semi-public; it only for use by subclasses, all other code
963
should consider it to be private.
965
self._revision_id_to_revno_cache = revision_id_to_revno
967
def _clear_cached_state(self):
968
"""Clear any cached data on this branch, e.g. cached revision history.
970
This means the next call to revision_history will need to call
971
_gen_revision_history.
973
This API is semi-public; it is only for use by subclasses, all other
974
code should consider it to be private.
976
self._revision_history_cache = None
977
self._revision_id_to_revno_cache = None
978
self._last_revision_info_cache = None
979
self._master_branch_cache = None
980
self._merge_sorted_revisions_cache = None
981
self._partial_revision_history_cache = []
982
self._partial_revision_id_to_revno_cache = {}
983
self._tags_bytes = None
985
def _gen_revision_history(self):
986
"""Return sequence of revision hashes on to this branch.
988
Unlike revision_history, this method always regenerates or rereads the
989
revision history, i.e. it does not cache the result, so repeated calls
992
Concrete subclasses should override this instead of revision_history so
993
that subclasses do not need to deal with caching logic.
995
This API is semi-public; it only for use by subclasses, all other code
996
should consider it to be private.
998
raise NotImplementedError(self._gen_revision_history)
1000
def _revision_history(self):
1001
if 'evil' in debug.debug_flags:
1002
mutter_callsite(3, "revision_history scales with history.")
1003
if self._revision_history_cache is not None:
1004
history = self._revision_history_cache
1006
history = self._gen_revision_history()
1007
self._cache_revision_history(history)
1008
return list(history)
1011
"""Return current revision number for this branch.
1013
That is equivalent to the number of revisions committed to
1016
return self.last_revision_info()[0]
1019
"""Older format branches cannot bind or unbind."""
1020
raise errors.UpgradeRequired(self.user_url)
1022
def last_revision(self):
1023
"""Return last revision id, or NULL_REVISION."""
1024
return self.last_revision_info()[1]
1027
def last_revision_info(self):
1028
"""Return information about the last revision.
1030
:return: A tuple (revno, revision_id).
1032
if self._last_revision_info_cache is None:
1033
self._last_revision_info_cache = self._read_last_revision_info()
1034
return self._last_revision_info_cache
1036
def _read_last_revision_info(self):
1037
raise NotImplementedError(self._read_last_revision_info)
1039
def import_last_revision_info_and_tags(self, source, revno, revid,
1041
"""Set the last revision info, importing from another repo if necessary.
1043
This is used by the bound branch code to upload a revision to
1044
the master branch first before updating the tip of the local branch.
1045
Revisions referenced by source's tags are also transferred.
1047
:param source: Source branch to optionally fetch from
1048
:param revno: Revision number of the new tip
1049
:param revid: Revision id of the new tip
1050
:param lossy: Whether to discard metadata that can not be
1051
natively represented
1052
:return: Tuple with the new revision number and revision id
1053
(should only be different from the arguments when lossy=True)
1055
if not self.repository.has_same_location(source.repository):
1056
self.fetch(source, revid)
1057
self.set_last_revision_info(revno, revid)
1058
return (revno, revid)
1060
def revision_id_to_revno(self, revision_id):
1061
"""Given a revision id, return its revno"""
1062
if _mod_revision.is_null(revision_id):
1064
history = self._revision_history()
1066
return history.index(revision_id) + 1
1068
raise errors.NoSuchRevision(self, revision_id)
1071
def get_rev_id(self, revno, history=None):
1072
"""Find the revision id of the specified revno."""
1074
return _mod_revision.NULL_REVISION
1075
last_revno, last_revid = self.last_revision_info()
1076
if revno == last_revno:
1078
if revno <= 0 or revno > last_revno:
1079
raise errors.NoSuchRevision(self, revno)
1080
distance_from_last = last_revno - revno
1081
if len(self._partial_revision_history_cache) <= distance_from_last:
1082
self._extend_partial_history(distance_from_last)
1083
return self._partial_revision_history_cache[distance_from_last]
1085
def pull(self, source, overwrite=False, stop_revision=None,
1086
possible_transports=None, *args, **kwargs):
1087
"""Mirror source into this branch.
1089
This branch is considered to be 'local', having low latency.
1091
:returns: PullResult instance
1093
return InterBranch.get(source, self).pull(overwrite=overwrite,
1094
stop_revision=stop_revision,
1095
possible_transports=possible_transports, *args, **kwargs)
1097
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1099
"""Mirror this branch into target.
1101
This branch is considered to be 'local', having low latency.
1103
return InterBranch.get(self, target).push(overwrite, stop_revision,
1104
lossy, *args, **kwargs)
1106
def basis_tree(self):
1107
"""Return `Tree` object for last revision."""
1108
return self.repository.revision_tree(self.last_revision())
1110
def get_parent(self):
1111
"""Return the parent location of the branch.
1113
This is the default location for pull/missing. The usual
1114
pattern is that the user can override it by specifying a
1117
parent = self._get_parent_location()
1120
# This is an old-format absolute path to a local branch
1121
# turn it into a url
1122
if parent.startswith('/'):
1123
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1125
return urlutils.join(self.base[:-1], parent)
1126
except urlutils.InvalidURLJoin as e:
1127
raise errors.InaccessibleParent(parent, self.user_url)
1129
def _get_parent_location(self):
1130
raise NotImplementedError(self._get_parent_location)
1132
def _set_config_location(self, name, url, config=None,
1133
make_relative=False):
1135
config = self.get_config_stack()
1139
url = urlutils.relative_url(self.base, url)
1140
config.set(name, url)
1142
def _get_config_location(self, name, config=None):
1144
config = self.get_config_stack()
1145
location = config.get(name)
1150
def get_child_submit_format(self):
1151
"""Return the preferred format of submissions to this branch."""
1152
return self.get_config_stack().get('child_submit_format')
1154
def get_submit_branch(self):
1155
"""Return the submit location of the branch.
1157
This is the default location for bundle. The usual
1158
pattern is that the user can override it by specifying a
1161
return self.get_config_stack().get('submit_branch')
1163
def set_submit_branch(self, location):
1164
"""Return the submit location of the branch.
1166
This is the default location for bundle. The usual
1167
pattern is that the user can override it by specifying a
1170
self.get_config_stack().set('submit_branch', location)
1172
def get_public_branch(self):
1173
"""Return the public location of the branch.
1175
This is used by merge directives.
1177
return self._get_config_location('public_branch')
1179
def set_public_branch(self, location):
1180
"""Return the submit location of the branch.
1182
This is the default location for bundle. The usual
1183
pattern is that the user can override it by specifying a
1186
self._set_config_location('public_branch', location)
1188
def get_push_location(self):
1189
"""Return None or the location to push this branch to."""
1190
return self.get_config_stack().get('push_location')
1192
def set_push_location(self, location):
1193
"""Set a new push location for this branch."""
1194
raise NotImplementedError(self.set_push_location)
1196
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1197
"""Run the post_change_branch_tip hooks."""
1198
hooks = Branch.hooks['post_change_branch_tip']
1201
new_revno, new_revid = self.last_revision_info()
1202
params = ChangeBranchTipParams(
1203
self, old_revno, new_revno, old_revid, new_revid)
1207
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1208
"""Run the pre_change_branch_tip hooks."""
1209
hooks = Branch.hooks['pre_change_branch_tip']
1212
old_revno, old_revid = self.last_revision_info()
1213
params = ChangeBranchTipParams(
1214
self, old_revno, new_revno, old_revid, new_revid)
1220
"""Synchronise this branch with the master branch if any.
1222
:return: None or the last_revision pivoted out during the update.
1226
def check_revno(self, revno):
1228
Check whether a revno corresponds to any revision.
1229
Zero (the NULL revision) is considered valid.
1232
self.check_real_revno(revno)
1234
def check_real_revno(self, revno):
1236
Check whether a revno corresponds to a real revision.
1237
Zero (the NULL revision) is considered invalid
1239
if revno < 1 or revno > self.revno():
1240
raise errors.InvalidRevisionNumber(revno)
1243
def clone(self, to_controldir, revision_id=None, repository_policy=None):
1244
"""Clone this branch into to_controldir preserving all semantic values.
1246
Most API users will want 'create_clone_on_transport', which creates a
1247
new bzrdir and branch on the fly.
1249
revision_id: if not None, the revision history in the new branch will
1250
be truncated to end with revision_id.
1252
result = to_controldir.create_branch()
1255
if repository_policy is not None:
1256
repository_policy.configure_branch(result)
1257
self.copy_content_into(result, revision_id=revision_id)
1263
def sprout(self, to_controldir, revision_id=None, repository_policy=None,
1265
"""Create a new line of development from the branch, into to_controldir.
1267
to_controldir controls the branch format.
1269
revision_id: if not None, the revision history in the new branch will
1270
be truncated to end with revision_id.
1272
if (repository_policy is not None and
1273
repository_policy.requires_stacking()):
1274
to_controldir._format.require_stacking(_skip_repo=True)
1275
result = to_controldir.create_branch(repository=repository)
1278
if repository_policy is not None:
1279
repository_policy.configure_branch(result)
1280
self.copy_content_into(result, revision_id=revision_id)
1281
master_url = self.get_bound_location()
1282
if master_url is None:
1283
result.set_parent(self.controldir.root_transport.base)
1285
result.set_parent(master_url)
1290
def _synchronize_history(self, destination, revision_id):
1291
"""Synchronize last revision and revision history between branches.
1293
This version is most efficient when the destination is also a
1294
BzrBranch6, but works for BzrBranch5, as long as the destination's
1295
repository contains all the lefthand ancestors of the intended
1296
last_revision. If not, set_last_revision_info will fail.
1298
:param destination: The branch to copy the history into
1299
:param revision_id: The revision-id to truncate history at. May
1300
be None to copy complete history.
1302
source_revno, source_revision_id = self.last_revision_info()
1303
if revision_id is None:
1304
revno, revision_id = source_revno, source_revision_id
1306
graph = self.repository.get_graph()
1308
revno = graph.find_distance_to_null(revision_id,
1309
[(source_revision_id, source_revno)])
1310
except errors.GhostRevisionsHaveNoRevno:
1311
# Default to 1, if we can't find anything else
1313
destination.set_last_revision_info(revno, revision_id)
1315
def copy_content_into(self, destination, revision_id=None):
1316
"""Copy the content of self into destination.
1318
revision_id: if not None, the revision history in the new branch will
1319
be truncated to end with revision_id.
1321
return InterBranch.get(self, destination).copy_content_into(
1322
revision_id=revision_id)
1324
def update_references(self, target):
1325
if not getattr(self._format, 'supports_reference_locations', False):
1327
reference_dict = self._get_all_reference_info()
1328
if len(reference_dict) == 0:
1330
old_base = self.base
1331
new_base = target.base
1332
target_reference_dict = target._get_all_reference_info()
1333
for file_id, (tree_path, branch_location) in viewitems(reference_dict):
1334
branch_location = urlutils.rebase_url(branch_location,
1336
target_reference_dict.setdefault(
1337
file_id, (tree_path, branch_location))
1338
target._set_all_reference_info(target_reference_dict)
1341
def check(self, refs):
1342
"""Check consistency of the branch.
1344
In particular this checks that revisions given in the revision-history
1345
do actually match up in the revision graph, and that they're all
1346
present in the repository.
1348
Callers will typically also want to check the repository.
1350
:param refs: Calculated refs for this branch as specified by
1351
branch._get_check_refs()
1352
:return: A BranchCheckResult.
1354
result = BranchCheckResult(self)
1355
last_revno, last_revision_id = self.last_revision_info()
1356
actual_revno = refs[('lefthand-distance', last_revision_id)]
1357
if actual_revno != last_revno:
1358
result.errors.append(errors.BzrCheckError(
1359
'revno does not match len(mainline) %s != %s' % (
1360
last_revno, actual_revno)))
1361
# TODO: We should probably also check that self.revision_history
1362
# matches the repository for older branch formats.
1363
# If looking for the code that cross-checks repository parents against
1364
# the Graph.iter_lefthand_ancestry output, that is now a repository
1368
def _get_checkout_format(self, lightweight=False):
1369
"""Return the most suitable metadir for a checkout of this branch.
1370
Weaves are used if this branch's repository uses weaves.
1372
format = self.repository.controldir.checkout_metadir()
1373
format.set_branch_format(self._format)
1376
def create_clone_on_transport(self, to_transport, revision_id=None,
1377
stacked_on=None, create_prefix=False, use_existing_dir=False,
1379
"""Create a clone of this branch and its bzrdir.
1381
:param to_transport: The transport to clone onto.
1382
:param revision_id: The revision id to use as tip in the new branch.
1383
If None the tip is obtained from this branch.
1384
:param stacked_on: An optional URL to stack the clone on.
1385
:param create_prefix: Create any missing directories leading up to
1387
:param use_existing_dir: Use an existing directory if one exists.
1389
# XXX: Fix the bzrdir API to allow getting the branch back from the
1390
# clone call. Or something. 20090224 RBC/spiv.
1391
# XXX: Should this perhaps clone colocated branches as well,
1392
# rather than just the default branch? 20100319 JRV
1393
if revision_id is None:
1394
revision_id = self.last_revision()
1395
dir_to = self.controldir.clone_on_transport(to_transport,
1396
revision_id=revision_id, stacked_on=stacked_on,
1397
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1399
return dir_to.open_branch()
1401
def create_checkout(self, to_location, revision_id=None,
1402
lightweight=False, accelerator_tree=None,
1404
"""Create a checkout of a branch.
1406
:param to_location: The url to produce the checkout at
1407
:param revision_id: The revision to check out
1408
:param lightweight: If True, produce a lightweight checkout, otherwise,
1409
produce a bound branch (heavyweight checkout)
1410
:param accelerator_tree: A tree which can be used for retrieving file
1411
contents more quickly than the revision tree, i.e. a workingtree.
1412
The revision tree will be used for cases where accelerator_tree's
1413
content is different.
1414
:param hardlink: If true, hard-link files from accelerator_tree,
1416
:return: The tree of the created checkout
1418
t = transport.get_transport(to_location)
1420
format = self._get_checkout_format(lightweight=lightweight)
1422
checkout = format.initialize_on_transport(t)
1423
except errors.AlreadyControlDirError:
1424
# It's fine if the control directory already exists,
1425
# as long as there is no existing branch and working tree.
1426
checkout = controldir.ControlDir.open_from_transport(t)
1428
checkout.open_branch()
1429
except errors.NotBranchError:
1432
raise errors.AlreadyControlDirError(t.base)
1433
if checkout.control_transport.base == self.controldir.control_transport.base:
1434
# When checking out to the same control directory,
1435
# always create a lightweight checkout
1439
from_branch = checkout.set_branch_reference(target_branch=self)
1441
policy = checkout.determine_repository_policy()
1442
repo = policy.acquire_repository()[0]
1443
checkout_branch = checkout.create_branch()
1444
checkout_branch.bind(self)
1445
# pull up to the specified revision_id to set the initial
1446
# branch tip correctly, and seed it with history.
1447
checkout_branch.pull(self, stop_revision=revision_id)
1449
tree = checkout.create_workingtree(revision_id,
1450
from_branch=from_branch,
1451
accelerator_tree=accelerator_tree,
1453
basis_tree = tree.basis_tree()
1454
basis_tree.lock_read()
1456
for path, file_id in basis_tree.iter_references():
1457
reference_parent = self.reference_parent(file_id, path)
1458
reference_parent.create_checkout(tree.abspath(path),
1459
basis_tree.get_reference_revision(file_id, path),
1466
def reconcile(self, thorough=True):
1467
"""Make sure the data stored in this branch is consistent."""
1468
from breezy.reconcile import BranchReconciler
1469
reconciler = BranchReconciler(self, thorough=thorough)
1470
reconciler.reconcile()
1473
def reference_parent(self, file_id, path, possible_transports=None):
1474
"""Return the parent branch for a tree-reference file_id
1476
:param file_id: The file_id of the tree reference
1477
:param path: The path of the file_id in the tree
1478
:return: A branch associated with the file_id
1480
# FIXME should provide multiple branches, based on config
1481
return Branch.open(self.controldir.root_transport.clone(path).base,
1482
possible_transports=possible_transports)
1484
def supports_tags(self):
1485
return self._format.supports_tags()
1487
def automatic_tag_name(self, revision_id):
1488
"""Try to automatically find the tag name for a revision.
1490
:param revision_id: Revision id of the revision.
1491
:return: A tag name or None if no tag name could be determined.
1493
for hook in Branch.hooks['automatic_tag_name']:
1494
ret = hook(self, revision_id)
1499
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1501
"""Ensure that revision_b is a descendant of revision_a.
1503
This is a helper function for update_revisions.
1505
:raises: DivergedBranches if revision_b has diverged from revision_a.
1506
:returns: True if revision_b is a descendant of revision_a.
1508
relation = self._revision_relations(revision_a, revision_b, graph)
1509
if relation == 'b_descends_from_a':
1511
elif relation == 'diverged':
1512
raise errors.DivergedBranches(self, other_branch)
1513
elif relation == 'a_descends_from_b':
1516
raise AssertionError("invalid relation: %r" % (relation,))
1518
def _revision_relations(self, revision_a, revision_b, graph):
1519
"""Determine the relationship between two revisions.
1521
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1523
heads = graph.heads([revision_a, revision_b])
1524
if heads == {revision_b}:
1525
return 'b_descends_from_a'
1526
elif heads == {revision_a, revision_b}:
1527
# These branches have diverged
1529
elif heads == {revision_a}:
1530
return 'a_descends_from_b'
1532
raise AssertionError("invalid heads: %r" % (heads,))
1534
def heads_to_fetch(self):
1535
"""Return the heads that must and that should be fetched to copy this
1536
branch into another repo.
1538
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1539
set of heads that must be fetched. if_present_fetch is a set of
1540
heads that must be fetched if present, but no error is necessary if
1541
they are not present.
1543
# For bzr native formats must_fetch is just the tip, and
1544
# if_present_fetch are the tags.
1545
must_fetch = {self.last_revision()}
1546
if_present_fetch = set()
1547
if self.get_config_stack().get('branch.fetch_tags'):
1549
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1550
except errors.TagsNotSupported:
1552
must_fetch.discard(_mod_revision.NULL_REVISION)
1553
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1554
return must_fetch, if_present_fetch
1557
class BranchFormat(controldir.ControlComponentFormat):
1558
"""An encapsulation of the initialization and open routines for a format.
1560
Formats provide three things:
1561
* An initialization routine,
1562
* a format description
1565
Formats are placed in an dict by their format string for reference
1566
during branch opening. It's not required that these be instances, they
1567
can be classes themselves with class methods - it simply depends on
1568
whether state is needed for a given format or not.
1570
Once a format is deprecated, just deprecate the initialize and open
1571
methods on the format class. Do not deprecate the object, as the
1572
object will be created every time regardless.
1575
def __eq__(self, other):
1576
return self.__class__ is other.__class__
1578
def __ne__(self, other):
1579
return not (self == other)
1581
def get_reference(self, controldir, name=None):
1582
"""Get the target reference of the branch in controldir.
1584
format probing must have been completed before calling
1585
this method - it is assumed that the format of the branch
1586
in controldir is correct.
1588
:param controldir: The controldir to get the branch data from.
1589
:param name: Name of the colocated branch to fetch
1590
:return: None if the branch is not a reference branch.
1595
def set_reference(self, controldir, name, to_branch):
1596
"""Set the target reference of the branch in controldir.
1598
format probing must have been completed before calling
1599
this method - it is assumed that the format of the branch
1600
in controldir is correct.
1602
:param controldir: The controldir to set the branch reference for.
1603
:param name: Name of colocated branch to set, None for default
1604
:param to_branch: branch that the checkout is to reference
1606
raise NotImplementedError(self.set_reference)
1608
def get_format_description(self):
1609
"""Return the short format description for this format."""
1610
raise NotImplementedError(self.get_format_description)
1612
def _run_post_branch_init_hooks(self, controldir, name, branch):
1613
hooks = Branch.hooks['post_branch_init']
1616
params = BranchInitHookParams(self, controldir, name, branch)
1620
def initialize(self, controldir, name=None, repository=None,
1621
append_revisions_only=None):
1622
"""Create a branch of this format in controldir.
1624
:param name: Name of the colocated branch to create.
1626
raise NotImplementedError(self.initialize)
1628
def is_supported(self):
1629
"""Is this format supported?
1631
Supported formats can be initialized and opened.
1632
Unsupported formats may not support initialization or committing or
1633
some other features depending on the reason for not being supported.
1637
def make_tags(self, branch):
1638
"""Create a tags object for branch.
1640
This method is on BranchFormat, because BranchFormats are reflected
1641
over the wire via network_name(), whereas full Branch instances require
1642
multiple VFS method calls to operate at all.
1644
The default implementation returns a disabled-tags instance.
1646
Note that it is normal for branch to be a RemoteBranch when using tags
1649
return _mod_tag.DisabledTags(branch)
1651
def network_name(self):
1652
"""A simple byte string uniquely identifying this format for RPC calls.
1654
MetaDir branch formats use their disk format string to identify the
1655
repository over the wire. All in one formats such as bzr < 0.8, and
1656
foreign formats like svn/git and hg should use some marker which is
1657
unique and immutable.
1659
raise NotImplementedError(self.network_name)
1661
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1662
found_repository=None, possible_transports=None):
1663
"""Return the branch object for controldir.
1665
:param controldir: A ControlDir that contains a branch.
1666
:param name: Name of colocated branch to open
1667
:param _found: a private parameter, do not use it. It is used to
1668
indicate if format probing has already be done.
1669
:param ignore_fallbacks: when set, no fallback branches will be opened
1670
(if there are any). Default is to open fallbacks.
1672
raise NotImplementedError(self.open)
1674
def supports_set_append_revisions_only(self):
1675
"""True if this format supports set_append_revisions_only."""
1678
def supports_stacking(self):
1679
"""True if this format records a stacked-on branch."""
1682
def supports_leaving_lock(self):
1683
"""True if this format supports leaving locks in place."""
1684
return False # by default
1687
return self.get_format_description().rstrip()
1689
def supports_tags(self):
1690
"""True if this format supports tags stored in the branch"""
1691
return False # by default
1693
def tags_are_versioned(self):
1694
"""Whether the tag container for this branch versions tags."""
1697
def supports_tags_referencing_ghosts(self):
1698
"""True if tags can reference ghost revisions."""
1702
class BranchHooks(Hooks):
1703
"""A dictionary mapping hook name to a list of callables for branch hooks.
1705
e.g. ['post_push'] Is the list of items to be called when the
1706
push function is invoked.
1710
"""Create the default hooks.
1712
These are all empty initially, because by default nothing should get
1715
Hooks.__init__(self, "breezy.branch", "Branch.hooks")
1716
self.add_hook('open',
1717
"Called with the Branch object that has been opened after a "
1718
"branch is opened.", (1, 8))
1719
self.add_hook('post_push',
1720
"Called after a push operation completes. post_push is called "
1721
"with a breezy.branch.BranchPushResult object and only runs in the "
1722
"bzr client.", (0, 15))
1723
self.add_hook('post_pull',
1724
"Called after a pull operation completes. post_pull is called "
1725
"with a breezy.branch.PullResult object and only runs in the "
1726
"bzr client.", (0, 15))
1727
self.add_hook('pre_commit',
1728
"Called after a commit is calculated but before it is "
1729
"completed. pre_commit is called with (local, master, old_revno, "
1730
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1731
"). old_revid is NULL_REVISION for the first commit to a branch, "
1732
"tree_delta is a TreeDelta object describing changes from the "
1733
"basis revision. hooks MUST NOT modify this delta. "
1734
" future_tree is an in-memory tree obtained from "
1735
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1737
self.add_hook('post_commit',
1738
"Called in the bzr client after a commit has completed. "
1739
"post_commit is called with (local, master, old_revno, old_revid, "
1740
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1741
"commit to a branch.", (0, 15))
1742
self.add_hook('post_uncommit',
1743
"Called in the bzr client after an uncommit completes. "
1744
"post_uncommit is called with (local, master, old_revno, "
1745
"old_revid, new_revno, new_revid) where local is the local branch "
1746
"or None, master is the target branch, and an empty branch "
1747
"receives new_revno of 0, new_revid of None.", (0, 15))
1748
self.add_hook('pre_change_branch_tip',
1749
"Called in bzr client and server before a change to the tip of a "
1750
"branch is made. pre_change_branch_tip is called with a "
1751
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1752
"commit, uncommit will all trigger this hook.", (1, 6))
1753
self.add_hook('post_change_branch_tip',
1754
"Called in bzr client and server after a change to the tip of a "
1755
"branch is made. post_change_branch_tip is called with a "
1756
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1757
"commit, uncommit will all trigger this hook.", (1, 4))
1758
self.add_hook('transform_fallback_location',
1759
"Called when a stacked branch is activating its fallback "
1760
"locations. transform_fallback_location is called with (branch, "
1761
"url), and should return a new url. Returning the same url "
1762
"allows it to be used as-is, returning a different one can be "
1763
"used to cause the branch to stack on a closer copy of that "
1764
"fallback_location. Note that the branch cannot have history "
1765
"accessing methods called on it during this hook because the "
1766
"fallback locations have not been activated. When there are "
1767
"multiple hooks installed for transform_fallback_location, "
1768
"all are called with the url returned from the previous hook."
1769
"The order is however undefined.", (1, 9))
1770
self.add_hook('automatic_tag_name',
1771
"Called to determine an automatic tag name for a revision. "
1772
"automatic_tag_name is called with (branch, revision_id) and "
1773
"should return a tag name or None if no tag name could be "
1774
"determined. The first non-None tag name returned will be used.",
1776
self.add_hook('post_branch_init',
1777
"Called after new branch initialization completes. "
1778
"post_branch_init is called with a "
1779
"breezy.branch.BranchInitHookParams. "
1780
"Note that init, branch and checkout (both heavyweight and "
1781
"lightweight) will all trigger this hook.", (2, 2))
1782
self.add_hook('post_switch',
1783
"Called after a checkout switches branch. "
1784
"post_switch is called with a "
1785
"breezy.branch.SwitchHookParams.", (2, 2))
1789
# install the default hooks into the Branch class.
1790
Branch.hooks = BranchHooks()
1793
class ChangeBranchTipParams(object):
1794
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1796
There are 5 fields that hooks may wish to access:
1798
:ivar branch: the branch being changed
1799
:ivar old_revno: revision number before the change
1800
:ivar new_revno: revision number after the change
1801
:ivar old_revid: revision id before the change
1802
:ivar new_revid: revision id after the change
1804
The revid fields are strings. The revno fields are integers.
1807
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1808
"""Create a group of ChangeBranchTip parameters.
1810
:param branch: The branch being changed.
1811
:param old_revno: Revision number before the change.
1812
:param new_revno: Revision number after the change.
1813
:param old_revid: Tip revision id before the change.
1814
:param new_revid: Tip revision id after the change.
1816
self.branch = branch
1817
self.old_revno = old_revno
1818
self.new_revno = new_revno
1819
self.old_revid = old_revid
1820
self.new_revid = new_revid
1822
def __eq__(self, other):
1823
return self.__dict__ == other.__dict__
1826
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1827
self.__class__.__name__, self.branch,
1828
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1831
class BranchInitHookParams(object):
1832
"""Object holding parameters passed to `*_branch_init` hooks.
1834
There are 4 fields that hooks may wish to access:
1836
:ivar format: the branch format
1837
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1838
:ivar name: name of colocated branch, if any (or None)
1839
:ivar branch: the branch created
1841
Note that for lightweight checkouts, the bzrdir and format fields refer to
1842
the checkout, hence they are different from the corresponding fields in
1843
branch, which refer to the original branch.
1846
def __init__(self, format, controldir, name, branch):
1847
"""Create a group of BranchInitHook parameters.
1849
:param format: the branch format
1850
:param controldir: the ControlDir where the branch will be/has been
1852
:param name: name of colocated branch, if any (or None)
1853
:param branch: the branch created
1855
Note that for lightweight checkouts, the bzrdir and format fields refer
1856
to the checkout, hence they are different from the corresponding fields
1857
in branch, which refer to the original branch.
1859
self.format = format
1860
self.controldir = controldir
1862
self.branch = branch
1864
def __eq__(self, other):
1865
return self.__dict__ == other.__dict__
1868
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1871
class SwitchHookParams(object):
1872
"""Object holding parameters passed to `*_switch` hooks.
1874
There are 4 fields that hooks may wish to access:
1876
:ivar control_dir: ControlDir of the checkout to change
1877
:ivar to_branch: branch that the checkout is to reference
1878
:ivar force: skip the check for local commits in a heavy checkout
1879
:ivar revision_id: revision ID to switch to (or None)
1882
def __init__(self, control_dir, to_branch, force, revision_id):
1883
"""Create a group of SwitchHook parameters.
1885
:param control_dir: ControlDir of the checkout to change
1886
:param to_branch: branch that the checkout is to reference
1887
:param force: skip the check for local commits in a heavy checkout
1888
:param revision_id: revision ID to switch to (or None)
1890
self.control_dir = control_dir
1891
self.to_branch = to_branch
1893
self.revision_id = revision_id
1895
def __eq__(self, other):
1896
return self.__dict__ == other.__dict__
1899
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1900
self.control_dir, self.to_branch,
1904
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1905
"""Branch format registry."""
1907
def __init__(self, other_registry=None):
1908
super(BranchFormatRegistry, self).__init__(other_registry)
1909
self._default_format = None
1910
self._default_format_key = None
1912
def get_default(self):
1913
"""Return the current default format."""
1914
if (self._default_format_key is not None and
1915
self._default_format is None):
1916
self._default_format = self.get(self._default_format_key)
1917
return self._default_format
1919
def set_default(self, format):
1920
"""Set the default format."""
1921
self._default_format = format
1922
self._default_format_key = None
1924
def set_default_key(self, format_string):
1925
"""Set the default format by its format string."""
1926
self._default_format_key = format_string
1927
self._default_format = None
1930
network_format_registry = registry.FormatRegistry()
1931
"""Registry of formats indexed by their network name.
1933
The network name for a branch format is an identifier that can be used when
1934
referring to formats with smart server operations. See
1935
BranchFormat.network_name() for more detail.
1938
format_registry = BranchFormatRegistry(network_format_registry)
1941
# formats which have no format string are not discoverable
1942
# and not independently creatable, so are not registered.
1943
format_registry.register_lazy(
1944
"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1946
format_registry.register_lazy(
1947
"Bazaar Branch Format 6 (bzr 0.15)\n",
1948
"breezy.bzr.branch", "BzrBranchFormat6")
1949
format_registry.register_lazy(
1950
"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1951
"breezy.bzr.branch", "BzrBranchFormat7")
1952
format_registry.register_lazy(
1953
"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1954
"breezy.bzr.branch", "BzrBranchFormat8")
1955
format_registry.register_lazy(
1956
"Bazaar-NG Branch Reference Format 1\n",
1957
"breezy.bzr.branch", "BranchReferenceFormat")
1959
format_registry.set_default_key("Bazaar Branch Format 7 (needs bzr 1.6)\n")
1962
class BranchWriteLockResult(LogicalLockResult):
1963
"""The result of write locking a branch.
1965
:ivar branch_token: The token obtained from the underlying branch lock, or
1967
:ivar unlock: A callable which will unlock the lock.
1970
def __init__(self, unlock, branch_token):
1971
LogicalLockResult.__init__(self, unlock)
1972
self.branch_token = branch_token
1975
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
1979
######################################################################
1980
# results of operations
1983
class _Result(object):
1985
def _show_tag_conficts(self, to_file):
1986
if not getattr(self, 'tag_conflicts', None):
1988
to_file.write('Conflicting tags:\n')
1989
for name, value1, value2 in self.tag_conflicts:
1990
to_file.write(' %s\n' % (name, ))
1993
class PullResult(_Result):
1994
"""Result of a Branch.pull operation.
1996
:ivar old_revno: Revision number before pull.
1997
:ivar new_revno: Revision number after pull.
1998
:ivar old_revid: Tip revision id before pull.
1999
:ivar new_revid: Tip revision id after pull.
2000
:ivar source_branch: Source (local) branch object. (read locked)
2001
:ivar master_branch: Master branch of the target, or the target if no
2003
:ivar local_branch: target branch if there is a Master, else None
2004
:ivar target_branch: Target/destination branch object. (write locked)
2005
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2006
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
2009
def report(self, to_file):
2010
tag_conflicts = getattr(self, "tag_conflicts", None)
2011
tag_updates = getattr(self, "tag_updates", None)
2013
if self.old_revid != self.new_revid:
2014
to_file.write('Now on revision %d.\n' % self.new_revno)
2016
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
2017
if self.old_revid == self.new_revid and not tag_updates:
2018
if not tag_conflicts:
2019
to_file.write('No revisions or tags to pull.\n')
2021
to_file.write('No revisions to pull.\n')
2022
self._show_tag_conficts(to_file)
2025
class BranchPushResult(_Result):
2026
"""Result of a Branch.push operation.
2028
:ivar old_revno: Revision number (eg 10) of the target before push.
2029
:ivar new_revno: Revision number (eg 12) of the target after push.
2030
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
2032
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
2034
:ivar source_branch: Source branch object that the push was from. This is
2035
read locked, and generally is a local (and thus low latency) branch.
2036
:ivar master_branch: If target is a bound branch, the master branch of
2037
target, or target itself. Always write locked.
2038
:ivar target_branch: The direct Branch where data is being sent (write
2040
:ivar local_branch: If the target is a bound branch this will be the
2041
target, otherwise it will be None.
2044
def report(self, to_file):
2045
# TODO: This function gets passed a to_file, but then
2046
# ignores it and calls note() instead. This is also
2047
# inconsistent with PullResult(), which writes to stdout.
2048
# -- JRV20110901, bug #838853
2049
tag_conflicts = getattr(self, "tag_conflicts", None)
2050
tag_updates = getattr(self, "tag_updates", None)
2052
if self.old_revid != self.new_revid:
2053
note(gettext('Pushed up to revision %d.') % self.new_revno)
2055
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
2056
if self.old_revid == self.new_revid and not tag_updates:
2057
if not tag_conflicts:
2058
note(gettext('No new revisions or tags to push.'))
2060
note(gettext('No new revisions to push.'))
2061
self._show_tag_conficts(to_file)
2064
class BranchCheckResult(object):
2065
"""Results of checking branch consistency.
2070
def __init__(self, branch):
2071
self.branch = branch
2074
def report_results(self, verbose):
2075
"""Report the check results via trace.note.
2077
:param verbose: Requests more detailed display of what was checked,
2080
note(gettext('checked branch {0} format {1}').format(
2081
self.branch.user_url, self.branch._format))
2082
for error in self.errors:
2083
note(gettext('found error:%s'), error)
2086
class InterBranch(InterObject):
2087
"""This class represents operations taking place between two branches.
2089
Its instances have methods like pull() and push() and contain
2090
references to the source and target repositories these operations
2091
can be carried out on.
2095
"""The available optimised InterBranch types."""
2098
def _get_branch_formats_to_test(klass):
2099
"""Return an iterable of format tuples for testing.
2101
:return: An iterable of (from_format, to_format) to use when testing
2102
this InterBranch class. Each InterBranch class should define this
2105
raise NotImplementedError(klass._get_branch_formats_to_test)
2108
def pull(self, overwrite=False, stop_revision=None,
2109
possible_transports=None, local=False):
2110
"""Mirror source into target branch.
2112
The target branch is considered to be 'local', having low latency.
2114
:returns: PullResult instance
2116
raise NotImplementedError(self.pull)
2119
def push(self, overwrite=False, stop_revision=None, lossy=False,
2120
_override_hook_source_branch=None):
2121
"""Mirror the source branch into the target branch.
2123
The source branch is considered to be 'local', having low latency.
2125
raise NotImplementedError(self.push)
2128
def copy_content_into(self, revision_id=None):
2129
"""Copy the content of source into target
2131
revision_id: if not None, the revision history in the new branch will
2132
be truncated to end with revision_id.
2134
raise NotImplementedError(self.copy_content_into)
2137
def fetch(self, stop_revision=None, limit=None):
2140
:param stop_revision: Last revision to fetch
2141
:param limit: Optional rough limit of revisions to fetch
2143
raise NotImplementedError(self.fetch)
2146
def _fix_overwrite_type(overwrite):
2147
if isinstance(overwrite, bool):
2149
return ["history", "tags"]
2155
class GenericInterBranch(InterBranch):
2156
"""InterBranch implementation that uses public Branch functions."""
2159
def is_compatible(klass, source, target):
2160
# GenericBranch uses the public API, so always compatible
2164
def _get_branch_formats_to_test(klass):
2165
return [(format_registry.get_default(), format_registry.get_default())]
2168
def unwrap_format(klass, format):
2169
if isinstance(format, remote.RemoteBranchFormat):
2170
format._ensure_real()
2171
return format._custom_format
2175
def copy_content_into(self, revision_id=None):
2176
"""Copy the content of source into target
2178
revision_id: if not None, the revision history in the new branch will
2179
be truncated to end with revision_id.
2181
self.source.update_references(self.target)
2182
self.source._synchronize_history(self.target, revision_id)
2184
parent = self.source.get_parent()
2185
except errors.InaccessibleParent as e:
2186
mutter('parent was not accessible to copy: %s', e)
2189
self.target.set_parent(parent)
2190
if self.source._push_should_merge_tags():
2191
self.source.tags.merge_to(self.target.tags)
2194
def fetch(self, stop_revision=None, limit=None):
2195
if self.target.base == self.source.base:
2197
self.source.lock_read()
2199
fetch_spec_factory = fetch.FetchSpecFactory()
2200
fetch_spec_factory.source_branch = self.source
2201
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
2202
fetch_spec_factory.source_repo = self.source.repository
2203
fetch_spec_factory.target_repo = self.target.repository
2204
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
2205
fetch_spec_factory.limit = limit
2206
fetch_spec = fetch_spec_factory.make_fetch_spec()
2207
return self.target.repository.fetch(self.source.repository,
2208
fetch_spec=fetch_spec)
2210
self.source.unlock()
2213
def _update_revisions(self, stop_revision=None, overwrite=False,
2215
other_revno, other_last_revision = self.source.last_revision_info()
2216
stop_revno = None # unknown
2217
if stop_revision is None:
2218
stop_revision = other_last_revision
2219
if _mod_revision.is_null(stop_revision):
2220
# if there are no commits, we're done.
2222
stop_revno = other_revno
2224
# what's the current last revision, before we fetch [and change it
2226
last_rev = _mod_revision.ensure_null(self.target.last_revision())
2227
# we fetch here so that we don't process data twice in the common
2228
# case of having something to pull, and so that the check for
2229
# already merged can operate on the just fetched graph, which will
2230
# be cached in memory.
2231
self.fetch(stop_revision=stop_revision)
2232
# Check to see if one is an ancestor of the other
2235
graph = self.target.repository.get_graph()
2236
if self.target._check_if_descendant_or_diverged(
2237
stop_revision, last_rev, graph, self.source):
2238
# stop_revision is a descendant of last_rev, but we aren't
2239
# overwriting, so we're done.
2241
if stop_revno is None:
2243
graph = self.target.repository.get_graph()
2244
this_revno, this_last_revision = \
2245
self.target.last_revision_info()
2246
stop_revno = graph.find_distance_to_null(stop_revision,
2247
[(other_last_revision, other_revno),
2248
(this_last_revision, this_revno)])
2249
self.target.set_last_revision_info(stop_revno, stop_revision)
2252
def pull(self, overwrite=False, stop_revision=None,
2253
possible_transports=None, run_hooks=True,
2254
_override_hook_target=None, local=False):
2255
"""Pull from source into self, updating my master if any.
2257
:param run_hooks: Private parameter - if false, this branch
2258
is being called because it's the master of the primary branch,
2259
so it should not run its hooks.
2261
bound_location = self.target.get_bound_location()
2262
if local and not bound_location:
2263
raise errors.LocalRequiresBoundBranch()
2264
master_branch = None
2265
source_is_master = False
2267
# bound_location comes from a config file, some care has to be
2268
# taken to relate it to source.user_url
2269
normalized = urlutils.normalize_url(bound_location)
2271
relpath = self.source.user_transport.relpath(normalized)
2272
source_is_master = (relpath == '')
2273
except (errors.PathNotChild, urlutils.InvalidURL):
2274
source_is_master = False
2275
if not local and bound_location and not source_is_master:
2276
# not pulling from master, so we need to update master.
2277
master_branch = self.target.get_master_branch(possible_transports)
2278
master_branch.lock_write()
2281
# pull from source into master.
2282
master_branch.pull(self.source, overwrite, stop_revision,
2284
return self._pull(overwrite,
2285
stop_revision, _hook_master=master_branch,
2286
run_hooks=run_hooks,
2287
_override_hook_target=_override_hook_target,
2288
merge_tags_to_master=not source_is_master)
2291
master_branch.unlock()
2293
def push(self, overwrite=False, stop_revision=None, lossy=False,
2294
_override_hook_source_branch=None):
2295
"""See InterBranch.push.
2297
This is the basic concrete implementation of push()
2299
:param _override_hook_source_branch: If specified, run the hooks
2300
passing this Branch as the source, rather than self. This is for
2301
use of RemoteBranch, where push is delegated to the underlying
2305
raise errors.LossyPushToSameVCS(self.source, self.target)
2306
# TODO: Public option to disable running hooks - should be trivial but
2309
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
2310
op.add_cleanup(self.source.lock_read().unlock)
2311
op.add_cleanup(self.target.lock_write().unlock)
2312
return op.run(overwrite, stop_revision,
2313
_override_hook_source_branch=_override_hook_source_branch)
2315
def _basic_push(self, overwrite, stop_revision):
2316
"""Basic implementation of push without bound branches or hooks.
2318
Must be called with source read locked and target write locked.
2320
result = BranchPushResult()
2321
result.source_branch = self.source
2322
result.target_branch = self.target
2323
result.old_revno, result.old_revid = self.target.last_revision_info()
2324
self.source.update_references(self.target)
2325
overwrite = _fix_overwrite_type(overwrite)
2326
if result.old_revid != stop_revision:
2327
# We assume that during 'push' this repository is closer than
2329
graph = self.source.repository.get_graph(self.target.repository)
2330
self._update_revisions(stop_revision,
2331
overwrite=("history" in overwrite),
2333
if self.source._push_should_merge_tags():
2334
result.tag_updates, result.tag_conflicts = (
2335
self.source.tags.merge_to(
2336
self.target.tags, "tags" in overwrite))
2337
result.new_revno, result.new_revid = self.target.last_revision_info()
2340
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
2341
_override_hook_source_branch=None):
2342
"""Push from source into target, and into target's master if any.
2345
if _override_hook_source_branch:
2346
result.source_branch = _override_hook_source_branch
2347
for hook in Branch.hooks['post_push']:
2350
bound_location = self.target.get_bound_location()
2351
if bound_location and self.target.base != bound_location:
2352
# there is a master branch.
2354
# XXX: Why the second check? Is it even supported for a branch to
2355
# be bound to itself? -- mbp 20070507
2356
master_branch = self.target.get_master_branch()
2357
master_branch.lock_write()
2358
operation.add_cleanup(master_branch.unlock)
2359
# push into the master from the source branch.
2360
master_inter = InterBranch.get(self.source, master_branch)
2361
master_inter._basic_push(overwrite, stop_revision)
2362
# and push into the target branch from the source. Note that
2363
# we push from the source branch again, because it's considered
2364
# the highest bandwidth repository.
2365
result = self._basic_push(overwrite, stop_revision)
2366
result.master_branch = master_branch
2367
result.local_branch = self.target
2369
master_branch = None
2371
result = self._basic_push(overwrite, stop_revision)
2372
# TODO: Why set master_branch and local_branch if there's no
2373
# binding? Maybe cleaner to just leave them unset? -- mbp
2375
result.master_branch = self.target
2376
result.local_branch = None
2380
def _pull(self, overwrite=False, stop_revision=None,
2381
possible_transports=None, _hook_master=None, run_hooks=True,
2382
_override_hook_target=None, local=False,
2383
merge_tags_to_master=True):
2386
This function is the core worker, used by GenericInterBranch.pull to
2387
avoid duplication when pulling source->master and source->local.
2389
:param _hook_master: Private parameter - set the branch to
2390
be supplied as the master to pull hooks.
2391
:param run_hooks: Private parameter - if false, this branch
2392
is being called because it's the master of the primary branch,
2393
so it should not run its hooks.
2394
is being called because it's the master of the primary branch,
2395
so it should not run its hooks.
2396
:param _override_hook_target: Private parameter - set the branch to be
2397
supplied as the target_branch to pull hooks.
2398
:param local: Only update the local branch, and not the bound branch.
2400
# This type of branch can't be bound.
2402
raise errors.LocalRequiresBoundBranch()
2403
result = PullResult()
2404
result.source_branch = self.source
2405
if _override_hook_target is None:
2406
result.target_branch = self.target
2408
result.target_branch = _override_hook_target
2409
self.source.lock_read()
2411
# We assume that during 'pull' the target repository is closer than
2413
self.source.update_references(self.target)
2414
graph = self.target.repository.get_graph(self.source.repository)
2415
# TODO: Branch formats should have a flag that indicates
2416
# that revno's are expensive, and pull() should honor that flag.
2418
result.old_revno, result.old_revid = \
2419
self.target.last_revision_info()
2420
overwrite = _fix_overwrite_type(overwrite)
2421
self._update_revisions(stop_revision,
2422
overwrite=("history" in overwrite),
2424
# TODO: The old revid should be specified when merging tags,
2425
# so a tags implementation that versions tags can only
2426
# pull in the most recent changes. -- JRV20090506
2427
result.tag_updates, result.tag_conflicts = (
2428
self.source.tags.merge_to(self.target.tags,
2429
"tags" in overwrite,
2430
ignore_master=not merge_tags_to_master))
2431
result.new_revno, result.new_revid = self.target.last_revision_info()
2433
result.master_branch = _hook_master
2434
result.local_branch = result.target_branch
2436
result.master_branch = result.target_branch
2437
result.local_branch = None
2439
for hook in Branch.hooks['post_pull']:
2442
self.source.unlock()
2446
InterBranch.register_optimiser(GenericInterBranch)