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,
31
revision as _mod_revision,
37
from breezy.bzr import (
41
from breezy.i18n import gettext, ngettext
48
from .decorators import (
51
from .hooks import Hooks
52
from .inter import InterObject
53
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._last_revision_info_cache = None
102
self._master_branch_cache = None
103
self._merge_sorted_revisions_cache = None
104
self._open_hook(possible_transports)
105
hooks = Branch.hooks['open']
109
def _open_hook(self, possible_transports):
110
"""Called by init to allow simpler extension of the base class."""
112
def _activate_fallback_location(self, url, possible_transports):
113
"""Activate the branch/repository from url as a fallback repository."""
114
for existing_fallback_repo in self.repository._fallback_repositories:
115
if existing_fallback_repo.user_url == url:
116
# This fallback is already configured. This probably only
117
# happens because ControlDir.sprout is a horrible mess. To
118
# avoid confusing _unstack we don't add this a second time.
119
mutter('duplicate activation of fallback %r on %r', url, self)
121
repo = self._get_fallback_repository(url, possible_transports)
122
if repo.has_same_location(self.repository):
123
raise errors.UnstackableLocationError(self.user_url, url)
124
self.repository.add_fallback_repository(repo)
126
def break_lock(self):
127
"""Break a lock if one is present from another instance.
129
Uses the ui factory to ask for confirmation if the lock may be from
132
This will probe the repository for its lock as well.
134
self.control_files.break_lock()
135
self.repository.break_lock()
136
master = self.get_master_branch()
137
if master is not None:
140
def _check_stackable_repo(self):
141
if not self.repository._format.supports_external_lookups:
142
raise errors.UnstackableRepositoryFormat(
143
self.repository._format, self.repository.base)
145
def _extend_partial_history(self, stop_index=None, stop_revision=None):
146
"""Extend the partial history to include a given index
148
If a stop_index is supplied, stop when that index has been reached.
149
If a stop_revision is supplied, stop when that revision is
150
encountered. Otherwise, stop when the beginning of history is
153
:param stop_index: The index which should be present. When it is
154
present, history extension will stop.
155
:param stop_revision: The revision id which should be present. When
156
it is encountered, history extension will stop.
158
if len(self._partial_revision_history_cache) == 0:
159
self._partial_revision_history_cache = [self.last_revision()]
160
repository._iter_for_revno(
161
self.repository, self._partial_revision_history_cache,
162
stop_index=stop_index, stop_revision=stop_revision)
163
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
164
self._partial_revision_history_cache.pop()
166
def _get_check_refs(self):
167
"""Get the references needed for check().
171
revid = self.last_revision()
172
return [('revision-existence', revid), ('lefthand-distance', revid)]
175
def open(base, _unsupported=False, possible_transports=None):
176
"""Open the branch rooted at base.
178
For instance, if the branch is at URL/.bzr/branch,
179
Branch.open(URL) -> a Branch instance.
181
control = controldir.ControlDir.open(base,
182
possible_transports=possible_transports, _unsupported=_unsupported)
183
return control.open_branch(unsupported=_unsupported,
184
possible_transports=possible_transports)
187
def open_from_transport(transport, name=None, _unsupported=False,
188
possible_transports=None):
189
"""Open the branch rooted at transport"""
190
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
191
return control.open_branch(name=name, unsupported=_unsupported,
192
possible_transports=possible_transports)
195
def open_containing(url, possible_transports=None):
196
"""Open an existing branch which contains url.
198
This probes for a branch at url, and searches upwards from there.
200
Basically we keep looking up until we find the control directory or
201
run into the root. If there isn't one, raises NotBranchError.
202
If there is one and it is either an unrecognised format or an unsupported
203
format, UnknownFormatError or UnsupportedFormatError are raised.
204
If there is one, it is returned, along with the unused portion of url.
206
control, relpath = controldir.ControlDir.open_containing(url,
208
branch = control.open_branch(possible_transports=possible_transports)
209
return (branch, relpath)
211
def _push_should_merge_tags(self):
212
"""Should _basic_push merge this branch's tags into the target?
214
The default implementation returns False if this branch has no tags,
215
and True the rest of the time. Subclasses may override this.
217
return self.supports_tags() and self.tags.get_tag_dict()
219
def get_config(self):
220
"""Get a breezy.config.BranchConfig for this Branch.
222
This can then be used to get and set configuration options for the
225
:return: A breezy.config.BranchConfig.
227
return _mod_config.BranchConfig(self)
229
def get_config_stack(self):
230
"""Get a breezy.config.BranchStack for this Branch.
232
This can then be used to get and set configuration options for the
235
:return: A breezy.config.BranchStack.
237
return _mod_config.BranchStack(self)
239
def store_uncommitted(self, creator):
240
"""Store uncommitted changes from a ShelfCreator.
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.
246
raise NotImplementedError(self.store_uncommitted)
248
def get_unshelver(self, tree):
249
"""Return a shelf.Unshelver for this branch and tree.
251
:param tree: The tree to use to construct the Unshelver.
252
:return: an Unshelver or None if no changes are stored.
254
raise NotImplementedError(self.get_unshelver)
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
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():
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
273
except errors.RecursiveBind as e:
275
except errors.BzrError as e:
276
# Silently fall back to local implicit nick if the master is
278
mutter("Could not connect to bound branch, "
279
"falling back to local nick.\n " + str(e))
280
return config.get_nickname()
282
def _set_nick(self, nick):
283
self.get_config().set_user_option('nickname', nick, warn_masked=True)
285
nick = property(_get_nick, _set_nick)
288
raise NotImplementedError(self.is_locked)
290
def _lefthand_history(self, revision_id, last_rev=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
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 and
309
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()
317
def lock_write(self, token=None):
318
"""Lock the branch for write operations.
320
:param token: A token to permit reacquiring a previously held and
322
:return: A BranchWriteLockResult.
324
raise NotImplementedError(self.lock_write)
327
"""Lock the branch for read operations.
329
:return: A breezy.lock.LogicalLockResult.
331
raise NotImplementedError(self.lock_read)
334
raise NotImplementedError(self.unlock)
336
def peek_lock_mode(self):
337
"""Return lock mode for the Branch: 'r', 'w' or None"""
338
raise NotImplementedError(self.peek_lock_mode)
340
def get_physical_lock_status(self):
341
raise NotImplementedError(self.get_physical_lock_status)
343
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
344
"""Return the revision_id for a dotted revno.
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
354
with self.lock_read():
355
rev_id = self._do_dotted_revno_to_revision_id(revno)
357
self._partial_revision_id_to_revno_cache[rev_id] = revno
360
def _do_dotted_revno_to_revision_id(self, revno):
361
"""Worker function for dotted_revno_to_revision_id.
363
Subclasses should override this if they wish to
364
provide a more efficient implementation.
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]
375
revno_str = '.'.join(map(str, revno))
376
raise errors.NoSuchRevision(self, revno_str)
378
def revision_id_to_dotted_revno(self, revision_id):
379
"""Given a revision id, return its dotted revno.
381
:return: a tuple like (1,) or (400,1,3).
383
with self.lock_read():
384
return self._do_revision_id_to_dotted_revno(revision_id)
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:
392
if self._revision_id_to_revno_cache:
393
result = self._revision_id_to_revno_cache.get(revision_id)
395
raise errors.NoSuchRevision(self, revision_id)
396
# Try the mainline as it's optimised
398
revno = self.revision_id_to_revno(revision_id)
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)
404
raise errors.NoSuchRevision(self, revision_id)
407
def get_revision_id_to_revno_map(self):
408
"""Return the revision_id => dotted revno map.
410
This will be regenerated on demand, but will be cached.
412
:return: A dictionary mapping revision_id => dotted revno.
413
This dictionary should not be modified by the caller.
415
with self.lock_read():
416
if self._revision_id_to_revno_cache is not None:
417
mapping = self._revision_id_to_revno_cache
419
mapping = self._gen_revno_map()
420
self._cache_revision_id_to_revno(mapping)
421
# TODO: jam 20070417 Since this is being cached, should we be returning
423
# I would rather not, and instead just declare that users should not
424
# modify the return value.
427
def _gen_revno_map(self):
428
"""Create a new mapping from revision ids to dotted revnos.
430
Dotted revnos are generated based on the current tip in the revision
432
This is the worker function for get_revision_id_to_revno_map, which
433
just caches the return value.
435
:return: A dictionary mapping revision_id => dotted revno.
437
revision_id_to_revno = dict((rev_id, revno)
438
for rev_id, depth, revno, end_of_merge
439
in self.iter_merge_sorted_revisions())
440
return revision_id_to_revno
442
def iter_merge_sorted_revisions(self, start_revision_id=None,
443
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
444
"""Walk the revisions for a branch in merge sorted order.
446
Merge sorted order is the output from a merge-aware,
447
topological sort, i.e. all parents come before their
448
children going forward; the opposite for reverse.
450
:param start_revision_id: the revision_id to begin walking from.
451
If None, the branch tip is used.
452
:param stop_revision_id: the revision_id to terminate the walk
453
after. If None, the rest of history is included.
454
:param stop_rule: if stop_revision_id is not None, the precise rule
455
to use for termination:
457
* 'exclude' - leave the stop revision out of the result (default)
458
* 'include' - the stop revision is the last item in the result
459
* 'with-merges' - include the stop revision and all of its
460
merged revisions in the result
461
* 'with-merges-without-common-ancestry' - filter out revisions
462
that are in both ancestries
463
:param direction: either 'reverse' or 'forward':
465
* reverse means return the start_revision_id first, i.e.
466
start at the most recent revision and go backwards in history
467
* forward returns tuples in the opposite order to reverse.
468
Note in particular that forward does *not* do any intelligent
469
ordering w.r.t. depth as some clients of this API may like.
470
(If required, that ought to be done at higher layers.)
472
:return: an iterator over (revision_id, depth, revno, end_of_merge)
475
* revision_id: the unique id of the revision
476
* depth: How many levels of merging deep this node has been
478
* revno_sequence: This field provides a sequence of
479
revision numbers for all revisions. The format is:
480
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
481
branch that the revno is on. From left to right the REVNO numbers
482
are the sequence numbers within that branch of the revision.
483
* end_of_merge: When True the next node (earlier in history) is
484
part of a different merge.
486
with self.lock_read():
487
# Note: depth and revno values are in the context of the branch so
488
# we need the full graph to get stable numbers, regardless of the
490
if self._merge_sorted_revisions_cache is None:
491
last_revision = self.last_revision()
492
known_graph = self.repository.get_known_graph_ancestry(
494
self._merge_sorted_revisions_cache = known_graph.merge_sort(
496
filtered = self._filter_merge_sorted_revisions(
497
self._merge_sorted_revisions_cache, start_revision_id,
498
stop_revision_id, stop_rule)
499
# Make sure we don't return revisions that are not part of the
500
# start_revision_id ancestry.
501
filtered = self._filter_start_non_ancestors(filtered)
502
if direction == 'reverse':
504
if direction == 'forward':
505
return reversed(list(filtered))
507
raise ValueError('invalid direction %r' % direction)
509
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
510
start_revision_id, stop_revision_id, stop_rule):
511
"""Iterate over an inclusive range of sorted revisions."""
512
rev_iter = iter(merge_sorted_revisions)
513
if start_revision_id is not None:
514
for node in rev_iter:
516
if rev_id != start_revision_id:
519
# The decision to include the start or not
520
# depends on the stop_rule if a stop is provided
521
# so pop this node back into the iterator
522
rev_iter = itertools.chain(iter([node]), rev_iter)
524
if stop_revision_id is None:
526
for node in rev_iter:
528
yield (rev_id, node.merge_depth, node.revno,
530
elif stop_rule == 'exclude':
531
for node in rev_iter:
533
if rev_id == stop_revision_id:
535
yield (rev_id, node.merge_depth, node.revno,
537
elif stop_rule == 'include':
538
for node in rev_iter:
540
yield (rev_id, node.merge_depth, node.revno,
542
if rev_id == stop_revision_id:
544
elif stop_rule == 'with-merges-without-common-ancestry':
545
# We want to exclude all revisions that are already part of the
546
# stop_revision_id ancestry.
547
graph = self.repository.get_graph()
548
ancestors = graph.find_unique_ancestors(start_revision_id,
550
for node in rev_iter:
552
if rev_id not in ancestors:
554
yield (rev_id, node.merge_depth, node.revno,
556
elif stop_rule == 'with-merges':
557
stop_rev = self.repository.get_revision(stop_revision_id)
558
if stop_rev.parent_ids:
559
left_parent = stop_rev.parent_ids[0]
561
left_parent = _mod_revision.NULL_REVISION
562
# left_parent is the actual revision we want to stop logging at,
563
# since we want to show the merged revisions after the stop_rev too
564
reached_stop_revision_id = False
565
revision_id_whitelist = []
566
for node in rev_iter:
568
if rev_id == left_parent:
569
# reached the left parent after the stop_revision
571
if (not reached_stop_revision_id or
572
rev_id in revision_id_whitelist):
573
yield (rev_id, node.merge_depth, node.revno,
575
if reached_stop_revision_id or rev_id == stop_revision_id:
576
# only do the merged revs of rev_id from now on
577
rev = self.repository.get_revision(rev_id)
579
reached_stop_revision_id = True
580
revision_id_whitelist.extend(rev.parent_ids)
582
raise ValueError('invalid stop_rule %r' % stop_rule)
584
def _filter_start_non_ancestors(self, rev_iter):
585
# If we started from a dotted revno, we want to consider it as a tip
586
# and don't want to yield revisions that are not part of its
587
# ancestry. Given the order guaranteed by the merge sort, we will see
588
# uninteresting descendants of the first parent of our tip before the
590
first = next(rev_iter)
591
(rev_id, merge_depth, revno, end_of_merge) = first
594
# We start at a mainline revision so by definition, all others
595
# revisions in rev_iter are ancestors
596
for node in rev_iter:
601
pmap = self.repository.get_parent_map([rev_id])
602
parents = pmap.get(rev_id, [])
604
whitelist.update(parents)
606
# If there is no parents, there is nothing of interest left
608
# FIXME: It's hard to test this scenario here as this code is never
609
# called in that case. -- vila 20100322
612
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
614
if rev_id in whitelist:
615
pmap = self.repository.get_parent_map([rev_id])
616
parents = pmap.get(rev_id, [])
617
whitelist.remove(rev_id)
618
whitelist.update(parents)
620
# We've reached the mainline, there is nothing left to
624
# A revision that is not part of the ancestry of our
627
yield (rev_id, merge_depth, revno, end_of_merge)
629
def leave_lock_in_place(self):
630
"""Tell this branch object not to release the physical lock when this
633
If lock_write doesn't return a token, then this method is not supported.
635
self.control_files.leave_in_place()
637
def dont_leave_lock_in_place(self):
638
"""Tell this branch object to release the physical lock when this
639
object is unlocked, even if it didn't originally acquire it.
641
If lock_write doesn't return a token, then this method is not supported.
643
self.control_files.dont_leave_in_place()
645
def bind(self, other):
646
"""Bind the local branch the other branch.
648
:param other: The branch to bind to
651
raise errors.UpgradeRequired(self.user_url)
653
def get_append_revisions_only(self):
654
"""Whether it is only possible to append revisions to the history.
656
if not self._format.supports_set_append_revisions_only():
658
return self.get_config_stack().get('append_revisions_only')
660
def set_append_revisions_only(self, enabled):
661
if not self._format.supports_set_append_revisions_only():
662
raise errors.UpgradeRequired(self.user_url)
663
self.get_config_stack().set('append_revisions_only', enabled)
665
def set_reference_info(self, tree_path, branch_location, file_id=None):
666
"""Set the branch location to use for a tree reference."""
667
raise errors.UnsupportedOperation(self.set_reference_info, self)
669
def get_reference_info(self, path):
670
"""Get the tree_path and branch_location for a tree reference."""
671
raise errors.UnsupportedOperation(self.get_reference_info, self)
673
def fetch(self, from_branch, last_revision=None, limit=None):
674
"""Copy revisions from from_branch into this branch.
676
:param from_branch: Where to copy from.
677
:param last_revision: What revision to stop at (None for at the end
679
:param limit: Optional rough limit of revisions to fetch
682
with self.lock_write():
683
return InterBranch.get(from_branch, self).fetch(
684
last_revision, limit=limit)
686
def get_bound_location(self):
687
"""Return the URL of the branch we are bound to.
689
Older format branches cannot bind, please be sure to use a metadir
694
def get_old_bound_location(self):
695
"""Return the URL of the branch we used to be bound to
697
raise errors.UpgradeRequired(self.user_url)
699
def get_commit_builder(self, parents, config_stack=None, timestamp=None,
700
timezone=None, committer=None, revprops=None,
701
revision_id=None, lossy=False):
702
"""Obtain a CommitBuilder for this branch.
704
:param parents: Revision ids of the parents of the new revision.
705
:param config: Optional configuration to use.
706
:param timestamp: Optional timestamp recorded for commit.
707
:param timezone: Optional timezone for timestamp.
708
:param committer: Optional committer to set for commit.
709
:param revprops: Optional dictionary of revision properties.
710
:param revision_id: Optional revision id.
711
:param lossy: Whether to discard data that can not be natively
712
represented, when pushing to a foreign VCS
715
if config_stack is None:
716
config_stack = self.get_config_stack()
718
return self.repository.get_commit_builder(self, parents, config_stack,
719
timestamp, timezone, committer, revprops, revision_id,
722
def get_master_branch(self, possible_transports=None):
723
"""Return the branch we are bound to.
725
:return: Either a Branch, or None
729
def get_stacked_on_url(self):
730
"""Get the URL this branch is stacked against.
732
:raises NotStacked: If the branch is not stacked.
733
:raises UnstackableBranchFormat: If the branch does not support
736
raise NotImplementedError(self.get_stacked_on_url)
738
def set_last_revision_info(self, revno, revision_id):
739
"""Set the last revision of this branch.
741
The caller is responsible for checking that the revno is correct
742
for this revision id.
744
It may be possible to set the branch last revision to an id not
745
present in the repository. However, branches can also be
746
configured to check constraints on history, in which case this may not
749
raise NotImplementedError(self.set_last_revision_info)
751
def generate_revision_history(self, revision_id, last_rev=None,
753
"""See Branch.generate_revision_history"""
754
with self.lock_write():
755
graph = self.repository.get_graph()
756
(last_revno, last_revid) = self.last_revision_info()
757
known_revision_ids = [
758
(last_revid, last_revno),
759
(_mod_revision.NULL_REVISION, 0),
761
if last_rev is not None:
762
if not graph.is_ancestor(last_rev, revision_id):
763
# our previous tip is not merged into stop_revision
764
raise errors.DivergedBranches(self, other_branch)
765
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
766
self.set_last_revision_info(revno, revision_id)
768
def set_parent(self, url):
769
"""See Branch.set_parent."""
770
# TODO: Maybe delete old location files?
771
# URLs should never be unicode, even on the local fs,
772
# FIXUP this and get_parent in a future branch format bump:
773
# read and rewrite the file. RBC 20060125
775
if isinstance(url, text_type):
777
url = url.encode('ascii')
778
except UnicodeEncodeError:
779
raise urlutils.InvalidURL(url,
780
"Urls must be 7-bit ascii, "
781
"use breezy.urlutils.escape")
782
url = urlutils.relative_url(self.base, url)
783
with self.lock_write():
784
self._set_parent_location(url)
786
def set_stacked_on_url(self, url):
787
"""Set the URL this branch is stacked against.
789
:raises UnstackableBranchFormat: If the branch does not support
791
:raises UnstackableRepositoryFormat: If the repository does not support
794
if not self._format.supports_stacking():
795
raise UnstackableBranchFormat(self._format, self.user_url)
796
with self.lock_write():
797
# XXX: Changing from one fallback repository to another does not check
798
# that all the data you need is present in the new fallback.
799
# Possibly it should.
800
self._check_stackable_repo()
803
old_url = self.get_stacked_on_url()
804
except (errors.NotStacked, UnstackableBranchFormat,
805
errors.UnstackableRepositoryFormat):
809
self._activate_fallback_location(url,
810
possible_transports=[self.controldir.root_transport])
811
# write this out after the repository is stacked to avoid setting a
812
# stacked config that doesn't work.
813
self._set_config_location('stacked_on_location', url)
816
"""Change a branch to be unstacked, copying data as needed.
818
Don't call this directly, use set_stacked_on_url(None).
820
with ui.ui_factory.nested_progress_bar() as pb:
821
pb.update(gettext("Unstacking"))
822
# The basic approach here is to fetch the tip of the branch,
823
# including all available ghosts, from the existing stacked
824
# repository into a new repository object without the fallbacks.
826
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
827
# correct for CHKMap repostiories
828
old_repository = self.repository
829
if len(old_repository._fallback_repositories) != 1:
830
raise AssertionError("can't cope with fallback repositories "
831
"of %r (fallbacks: %r)" % (old_repository,
832
old_repository._fallback_repositories))
833
# Open the new repository object.
834
# Repositories don't offer an interface to remove fallback
835
# repositories today; take the conceptually simpler option and just
836
# reopen it. We reopen it starting from the URL so that we
837
# get a separate connection for RemoteRepositories and can
838
# stream from one of them to the other. This does mean doing
839
# separate SSH connection setup, but unstacking is not a
840
# common operation so it's tolerable.
841
new_bzrdir = controldir.ControlDir.open(
842
self.controldir.root_transport.base)
843
new_repository = new_bzrdir.find_repository()
844
if new_repository._fallback_repositories:
845
raise AssertionError("didn't expect %r to have "
846
"fallback_repositories"
847
% (self.repository,))
848
# Replace self.repository with the new repository.
849
# Do our best to transfer the lock state (i.e. lock-tokens and
850
# lock count) of self.repository to the new repository.
851
lock_token = old_repository.lock_write().repository_token
852
self.repository = new_repository
853
if isinstance(self, remote.RemoteBranch):
854
# Remote branches can have a second reference to the old
855
# repository that need to be replaced.
856
if self._real_branch is not None:
857
self._real_branch.repository = new_repository
858
self.repository.lock_write(token=lock_token)
859
if lock_token is not None:
860
old_repository.leave_lock_in_place()
861
old_repository.unlock()
862
if lock_token is not None:
863
# XXX: self.repository.leave_lock_in_place() before this
864
# function will not be preserved. Fortunately that doesn't
865
# affect the current default format (2a), and would be a
866
# corner-case anyway.
867
# - Andrew Bennetts, 2010/06/30
868
self.repository.dont_leave_lock_in_place()
872
old_repository.unlock()
873
except errors.LockNotHeld:
876
if old_lock_count == 0:
877
raise AssertionError(
878
'old_repository should have been locked at least once.')
879
for i in range(old_lock_count-1):
880
self.repository.lock_write()
881
# Fetch from the old repository into the new.
882
with old_repository.lock_read():
883
# XXX: If you unstack a branch while it has a working tree
884
# with a pending merge, the pending-merged revisions will no
885
# longer be present. You can (probably) revert and remerge.
887
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
888
except errors.TagsNotSupported:
889
tags_to_fetch = set()
890
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
891
old_repository, required_ids=[self.last_revision()],
892
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
893
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
895
def _cache_revision_history(self, rev_history):
896
"""Set the cached revision history to rev_history.
898
The revision_history method will use this cache to avoid regenerating
899
the revision history.
901
This API is semi-public; it only for use by subclasses, all other code
902
should consider it to be private.
904
self._revision_history_cache = rev_history
906
def _cache_revision_id_to_revno(self, revision_id_to_revno):
907
"""Set the cached revision_id => revno map to revision_id_to_revno.
909
This API is semi-public; it only for use by subclasses, all other code
910
should consider it to be private.
912
self._revision_id_to_revno_cache = revision_id_to_revno
914
def _clear_cached_state(self):
915
"""Clear any cached data on this branch, e.g. cached revision history.
917
This means the next call to revision_history will need to call
918
_gen_revision_history.
920
This API is semi-public; it is only for use by subclasses, all other
921
code should consider it to be private.
923
self._revision_history_cache = None
924
self._revision_id_to_revno_cache = None
925
self._last_revision_info_cache = None
926
self._master_branch_cache = None
927
self._merge_sorted_revisions_cache = None
928
self._partial_revision_history_cache = []
929
self._partial_revision_id_to_revno_cache = {}
931
def _gen_revision_history(self):
932
"""Return sequence of revision hashes on to this branch.
934
Unlike revision_history, this method always regenerates or rereads the
935
revision history, i.e. it does not cache the result, so repeated calls
938
Concrete subclasses should override this instead of revision_history so
939
that subclasses do not need to deal with caching logic.
941
This API is semi-public; it only for use by subclasses, all other code
942
should consider it to be private.
944
raise NotImplementedError(self._gen_revision_history)
946
def _revision_history(self):
947
if 'evil' in debug.debug_flags:
948
mutter_callsite(3, "revision_history scales with history.")
949
if self._revision_history_cache is not None:
950
history = self._revision_history_cache
952
history = self._gen_revision_history()
953
self._cache_revision_history(history)
957
"""Return current revision number for this branch.
959
That is equivalent to the number of revisions committed to
962
return self.last_revision_info()[0]
965
"""Older format branches cannot bind or unbind."""
966
raise errors.UpgradeRequired(self.user_url)
968
def last_revision(self):
969
"""Return last revision id, or NULL_REVISION."""
970
return self.last_revision_info()[1]
972
def last_revision_info(self):
973
"""Return information about the last revision.
975
:return: A tuple (revno, revision_id).
977
with self.lock_read():
978
if self._last_revision_info_cache is None:
979
self._last_revision_info_cache = self._read_last_revision_info()
980
return self._last_revision_info_cache
982
def _read_last_revision_info(self):
983
raise NotImplementedError(self._read_last_revision_info)
985
def import_last_revision_info_and_tags(self, source, revno, revid,
987
"""Set the last revision info, importing from another repo if necessary.
989
This is used by the bound branch code to upload a revision to
990
the master branch first before updating the tip of the local branch.
991
Revisions referenced by source's tags are also transferred.
993
:param source: Source branch to optionally fetch from
994
:param revno: Revision number of the new tip
995
:param revid: Revision id of the new tip
996
:param lossy: Whether to discard metadata that can not be
998
:return: Tuple with the new revision number and revision id
999
(should only be different from the arguments when lossy=True)
1001
if not self.repository.has_same_location(source.repository):
1002
self.fetch(source, revid)
1003
self.set_last_revision_info(revno, revid)
1004
return (revno, revid)
1006
def revision_id_to_revno(self, revision_id):
1007
"""Given a revision id, return its revno"""
1008
if _mod_revision.is_null(revision_id):
1010
history = self._revision_history()
1012
return history.index(revision_id) + 1
1014
raise errors.NoSuchRevision(self, revision_id)
1016
def get_rev_id(self, revno, history=None):
1017
"""Find the revision id of the specified revno."""
1018
with self.lock_read():
1020
return _mod_revision.NULL_REVISION
1021
last_revno, last_revid = self.last_revision_info()
1022
if revno == last_revno:
1024
if revno <= 0 or revno > last_revno:
1025
raise errors.NoSuchRevision(self, revno)
1026
distance_from_last = last_revno - revno
1027
if len(self._partial_revision_history_cache) <= distance_from_last:
1028
self._extend_partial_history(distance_from_last)
1029
return self._partial_revision_history_cache[distance_from_last]
1031
def pull(self, source, overwrite=False, stop_revision=None,
1032
possible_transports=None, *args, **kwargs):
1033
"""Mirror source into this branch.
1035
This branch is considered to be 'local', having low latency.
1037
:returns: PullResult instance
1039
return InterBranch.get(source, self).pull(overwrite=overwrite,
1040
stop_revision=stop_revision,
1041
possible_transports=possible_transports, *args, **kwargs)
1043
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1045
"""Mirror this branch into target.
1047
This branch is considered to be 'local', having low latency.
1049
return InterBranch.get(self, target).push(overwrite, stop_revision,
1050
lossy, *args, **kwargs)
1052
def basis_tree(self):
1053
"""Return `Tree` object for last revision."""
1054
return self.repository.revision_tree(self.last_revision())
1056
def get_parent(self):
1057
"""Return the parent location of the branch.
1059
This is the default location for pull/missing. The usual
1060
pattern is that the user can override it by specifying a
1063
parent = self._get_parent_location()
1066
# This is an old-format absolute path to a local branch
1067
# turn it into a url
1068
if parent.startswith('/'):
1069
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1071
return urlutils.join(self.base[:-1], parent)
1072
except urlutils.InvalidURLJoin as e:
1073
raise errors.InaccessibleParent(parent, self.user_url)
1075
def _get_parent_location(self):
1076
raise NotImplementedError(self._get_parent_location)
1078
def _set_config_location(self, name, url, config=None,
1079
make_relative=False):
1081
config = self.get_config_stack()
1085
url = urlutils.relative_url(self.base, url)
1086
config.set(name, url)
1088
def _get_config_location(self, name, config=None):
1090
config = self.get_config_stack()
1091
location = config.get(name)
1096
def get_child_submit_format(self):
1097
"""Return the preferred format of submissions to this branch."""
1098
return self.get_config_stack().get('child_submit_format')
1100
def get_submit_branch(self):
1101
"""Return the submit location of the branch.
1103
This is the default location for bundle. The usual
1104
pattern is that the user can override it by specifying a
1107
return self.get_config_stack().get('submit_branch')
1109
def set_submit_branch(self, location):
1110
"""Return the submit location of the branch.
1112
This is the default location for bundle. The usual
1113
pattern is that the user can override it by specifying a
1116
self.get_config_stack().set('submit_branch', location)
1118
def get_public_branch(self):
1119
"""Return the public location of the branch.
1121
This is used by merge directives.
1123
return self._get_config_location('public_branch')
1125
def set_public_branch(self, location):
1126
"""Return the submit location of the branch.
1128
This is the default location for bundle. The usual
1129
pattern is that the user can override it by specifying a
1132
self._set_config_location('public_branch', location)
1134
def get_push_location(self):
1135
"""Return None or the location to push this branch to."""
1136
return self.get_config_stack().get('push_location')
1138
def set_push_location(self, location):
1139
"""Set a new push location for this branch."""
1140
raise NotImplementedError(self.set_push_location)
1142
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1143
"""Run the post_change_branch_tip hooks."""
1144
hooks = Branch.hooks['post_change_branch_tip']
1147
new_revno, new_revid = self.last_revision_info()
1148
params = ChangeBranchTipParams(
1149
self, old_revno, new_revno, old_revid, new_revid)
1153
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1154
"""Run the pre_change_branch_tip hooks."""
1155
hooks = Branch.hooks['pre_change_branch_tip']
1158
old_revno, old_revid = self.last_revision_info()
1159
params = ChangeBranchTipParams(
1160
self, old_revno, new_revno, old_revid, new_revid)
1165
"""Synchronise this branch with the master branch if any.
1167
:return: None or the last_revision pivoted out during the update.
1171
def check_revno(self, revno):
1173
Check whether a revno corresponds to any revision.
1174
Zero (the NULL revision) is considered valid.
1177
self.check_real_revno(revno)
1179
def check_real_revno(self, revno):
1181
Check whether a revno corresponds to a real revision.
1182
Zero (the NULL revision) is considered invalid
1184
if revno < 1 or revno > self.revno():
1185
raise errors.InvalidRevisionNumber(revno)
1187
def clone(self, to_controldir, revision_id=None, repository_policy=None):
1188
"""Clone this branch into to_controldir preserving all semantic values.
1190
Most API users will want 'create_clone_on_transport', which creates a
1191
new bzrdir and branch on the fly.
1193
revision_id: if not None, the revision history in the new branch will
1194
be truncated to end with revision_id.
1196
result = to_controldir.create_branch()
1197
with self.lock_read(), result.lock_write():
1198
if repository_policy is not None:
1199
repository_policy.configure_branch(result)
1200
self.copy_content_into(result, revision_id=revision_id)
1203
def sprout(self, to_controldir, revision_id=None, repository_policy=None,
1204
repository=None, lossy=False):
1205
"""Create a new line of development from the branch, into to_controldir.
1207
to_controldir controls the branch format.
1209
revision_id: if not None, the revision history in the new branch will
1210
be truncated to end with revision_id.
1212
if (repository_policy is not None and
1213
repository_policy.requires_stacking()):
1214
to_controldir._format.require_stacking(_skip_repo=True)
1215
result = to_controldir.create_branch(repository=repository)
1217
raise errors.LossyPushToSameVCS(self, result)
1218
with self.lock_read(), result.lock_write():
1219
if repository_policy is not None:
1220
repository_policy.configure_branch(result)
1221
self.copy_content_into(result, revision_id=revision_id)
1222
master_url = self.get_bound_location()
1223
if master_url is None:
1224
result.set_parent(self.user_url)
1226
result.set_parent(master_url)
1229
def _synchronize_history(self, destination, revision_id):
1230
"""Synchronize last revision and revision history between branches.
1232
This version is most efficient when the destination is also a
1233
BzrBranch6, but works for BzrBranch5, as long as the destination's
1234
repository contains all the lefthand ancestors of the intended
1235
last_revision. If not, set_last_revision_info will fail.
1237
:param destination: The branch to copy the history into
1238
:param revision_id: The revision-id to truncate history at. May
1239
be None to copy complete history.
1241
source_revno, source_revision_id = self.last_revision_info()
1242
if revision_id is None:
1243
revno, revision_id = source_revno, source_revision_id
1245
graph = self.repository.get_graph()
1247
revno = graph.find_distance_to_null(revision_id,
1248
[(source_revision_id, source_revno)])
1249
except errors.GhostRevisionsHaveNoRevno:
1250
# Default to 1, if we can't find anything else
1252
destination.set_last_revision_info(revno, revision_id)
1254
def copy_content_into(self, destination, revision_id=None):
1255
"""Copy the content of self into destination.
1257
revision_id: if not None, the revision history in the new branch will
1258
be truncated to end with revision_id.
1260
return InterBranch.get(self, destination).copy_content_into(
1261
revision_id=revision_id)
1263
def update_references(self, target):
1264
if not getattr(self._format, 'supports_reference_locations', False):
1266
reference_dict = self._get_all_reference_info()
1267
if len(reference_dict) == 0:
1269
old_base = self.base
1270
new_base = target.base
1271
target_reference_dict = target._get_all_reference_info()
1272
for tree_path, (branch_location, file_id) in viewitems(reference_dict):
1273
branch_location = urlutils.rebase_url(branch_location,
1275
target_reference_dict.setdefault(
1276
tree_path, (branch_location, file_id))
1277
target._set_all_reference_info(target_reference_dict)
1279
def check(self, refs):
1280
"""Check consistency of the branch.
1282
In particular this checks that revisions given in the revision-history
1283
do actually match up in the revision graph, and that they're all
1284
present in the repository.
1286
Callers will typically also want to check the repository.
1288
:param refs: Calculated refs for this branch as specified by
1289
branch._get_check_refs()
1290
:return: A BranchCheckResult.
1292
with self.lock_read():
1293
result = BranchCheckResult(self)
1294
last_revno, last_revision_id = self.last_revision_info()
1295
actual_revno = refs[('lefthand-distance', last_revision_id)]
1296
if actual_revno != last_revno:
1297
result.errors.append(errors.BzrCheckError(
1298
'revno does not match len(mainline) %s != %s' % (
1299
last_revno, actual_revno)))
1300
# TODO: We should probably also check that self.revision_history
1301
# matches the repository for older branch formats.
1302
# If looking for the code that cross-checks repository parents against
1303
# the Graph.iter_lefthand_ancestry output, that is now a repository
1307
def _get_checkout_format(self, lightweight=False):
1308
"""Return the most suitable metadir for a checkout of this branch.
1309
Weaves are used if this branch's repository uses weaves.
1311
format = self.repository.controldir.checkout_metadir()
1312
format.set_branch_format(self._format)
1315
def create_clone_on_transport(self, to_transport, revision_id=None,
1316
stacked_on=None, create_prefix=False, use_existing_dir=False,
1318
"""Create a clone of this branch and its bzrdir.
1320
:param to_transport: The transport to clone onto.
1321
:param revision_id: The revision id to use as tip in the new branch.
1322
If None the tip is obtained from this branch.
1323
:param stacked_on: An optional URL to stack the clone on.
1324
:param create_prefix: Create any missing directories leading up to
1326
:param use_existing_dir: Use an existing directory if one exists.
1328
# XXX: Fix the bzrdir API to allow getting the branch back from the
1329
# clone call. Or something. 20090224 RBC/spiv.
1330
# XXX: Should this perhaps clone colocated branches as well,
1331
# rather than just the default branch? 20100319 JRV
1332
if revision_id is None:
1333
revision_id = self.last_revision()
1334
dir_to = self.controldir.clone_on_transport(to_transport,
1335
revision_id=revision_id, stacked_on=stacked_on,
1336
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1338
return dir_to.open_branch()
1340
def create_checkout(self, to_location, revision_id=None,
1341
lightweight=False, accelerator_tree=None,
1343
"""Create a checkout of a branch.
1345
:param to_location: The url to produce the checkout at
1346
:param revision_id: The revision to check out
1347
:param lightweight: If True, produce a lightweight checkout, otherwise,
1348
produce a bound branch (heavyweight checkout)
1349
:param accelerator_tree: A tree which can be used for retrieving file
1350
contents more quickly than the revision tree, i.e. a workingtree.
1351
The revision tree will be used for cases where accelerator_tree's
1352
content is different.
1353
:param hardlink: If true, hard-link files from accelerator_tree,
1355
:return: The tree of the created checkout
1357
t = transport.get_transport(to_location)
1359
format = self._get_checkout_format(lightweight=lightweight)
1361
checkout = format.initialize_on_transport(t)
1362
except errors.AlreadyControlDirError:
1363
# It's fine if the control directory already exists,
1364
# as long as there is no existing branch and working tree.
1365
checkout = controldir.ControlDir.open_from_transport(t)
1367
checkout.open_branch()
1368
except errors.NotBranchError:
1371
raise errors.AlreadyControlDirError(t.base)
1372
if checkout.control_transport.base == self.controldir.control_transport.base:
1373
# When checking out to the same control directory,
1374
# always create a lightweight checkout
1378
from_branch = checkout.set_branch_reference(target_branch=self)
1380
policy = checkout.determine_repository_policy()
1381
repo = policy.acquire_repository()[0]
1382
checkout_branch = checkout.create_branch()
1383
checkout_branch.bind(self)
1384
# pull up to the specified revision_id to set the initial
1385
# branch tip correctly, and seed it with history.
1386
checkout_branch.pull(self, stop_revision=revision_id)
1388
tree = checkout.create_workingtree(revision_id,
1389
from_branch=from_branch,
1390
accelerator_tree=accelerator_tree,
1392
basis_tree = tree.basis_tree()
1393
with basis_tree.lock_read():
1394
for path, file_id in basis_tree.iter_references():
1395
reference_parent = self.reference_parent(path, file_id)
1396
reference_parent.create_checkout(tree.abspath(path),
1397
basis_tree.get_reference_revision(path, file_id),
1401
def reconcile(self, thorough=True):
1402
"""Make sure the data stored in this branch is consistent."""
1403
from breezy.reconcile import BranchReconciler
1404
with self.lock_write():
1405
reconciler = BranchReconciler(self, thorough=thorough)
1406
reconciler.reconcile()
1409
def reference_parent(self, path, file_id=None, possible_transports=None):
1410
"""Return the parent branch for a tree-reference file_id
1412
:param path: The path of the file_id in the tree
1413
:param file_id: Optional file_id of the tree reference
1414
:return: A branch associated with the file_id
1416
# FIXME should provide multiple branches, based on config
1417
return Branch.open(self.controldir.root_transport.clone(path).base,
1418
possible_transports=possible_transports)
1420
def supports_tags(self):
1421
return self._format.supports_tags()
1423
def automatic_tag_name(self, revision_id):
1424
"""Try to automatically find the tag name for a revision.
1426
:param revision_id: Revision id of the revision.
1427
:return: A tag name or None if no tag name could be determined.
1429
for hook in Branch.hooks['automatic_tag_name']:
1430
ret = hook(self, revision_id)
1435
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1437
"""Ensure that revision_b is a descendant of revision_a.
1439
This is a helper function for update_revisions.
1441
:raises: DivergedBranches if revision_b has diverged from revision_a.
1442
:returns: True if revision_b is a descendant of revision_a.
1444
relation = self._revision_relations(revision_a, revision_b, graph)
1445
if relation == 'b_descends_from_a':
1447
elif relation == 'diverged':
1448
raise errors.DivergedBranches(self, other_branch)
1449
elif relation == 'a_descends_from_b':
1452
raise AssertionError("invalid relation: %r" % (relation,))
1454
def _revision_relations(self, revision_a, revision_b, graph):
1455
"""Determine the relationship between two revisions.
1457
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1459
heads = graph.heads([revision_a, revision_b])
1460
if heads == {revision_b}:
1461
return 'b_descends_from_a'
1462
elif heads == {revision_a, revision_b}:
1463
# These branches have diverged
1465
elif heads == {revision_a}:
1466
return 'a_descends_from_b'
1468
raise AssertionError("invalid heads: %r" % (heads,))
1470
def heads_to_fetch(self):
1471
"""Return the heads that must and that should be fetched to copy this
1472
branch into another repo.
1474
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1475
set of heads that must be fetched. if_present_fetch is a set of
1476
heads that must be fetched if present, but no error is necessary if
1477
they are not present.
1479
# For bzr native formats must_fetch is just the tip, and
1480
# if_present_fetch are the tags.
1481
must_fetch = {self.last_revision()}
1482
if_present_fetch = set()
1483
if self.get_config_stack().get('branch.fetch_tags'):
1485
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1486
except errors.TagsNotSupported:
1488
must_fetch.discard(_mod_revision.NULL_REVISION)
1489
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1490
return must_fetch, if_present_fetch
1492
def create_memorytree(self):
1493
"""Create a memory tree for this branch.
1495
:return: An in-memory MutableTree instance
1497
return memorytree.MemoryTree.create_on_branch(self)
1500
class BranchFormat(controldir.ControlComponentFormat):
1501
"""An encapsulation of the initialization and open routines for a format.
1503
Formats provide three things:
1504
* An initialization routine,
1505
* a format description
1508
Formats are placed in an dict by their format string for reference
1509
during branch opening. It's not required that these be instances, they
1510
can be classes themselves with class methods - it simply depends on
1511
whether state is needed for a given format or not.
1513
Once a format is deprecated, just deprecate the initialize and open
1514
methods on the format class. Do not deprecate the object, as the
1515
object will be created every time regardless.
1518
def __eq__(self, other):
1519
return self.__class__ is other.__class__
1521
def __ne__(self, other):
1522
return not (self == other)
1524
def get_reference(self, controldir, name=None):
1525
"""Get the target reference of the branch in controldir.
1527
format probing must have been completed before calling
1528
this method - it is assumed that the format of the branch
1529
in controldir is correct.
1531
:param controldir: The controldir to get the branch data from.
1532
:param name: Name of the colocated branch to fetch
1533
:return: None if the branch is not a reference branch.
1538
def set_reference(self, controldir, name, to_branch):
1539
"""Set the target reference of the branch in controldir.
1541
format probing must have been completed before calling
1542
this method - it is assumed that the format of the branch
1543
in controldir is correct.
1545
:param controldir: The controldir to set the branch reference for.
1546
:param name: Name of colocated branch to set, None for default
1547
:param to_branch: branch that the checkout is to reference
1549
raise NotImplementedError(self.set_reference)
1551
def get_format_description(self):
1552
"""Return the short format description for this format."""
1553
raise NotImplementedError(self.get_format_description)
1555
def _run_post_branch_init_hooks(self, controldir, name, branch):
1556
hooks = Branch.hooks['post_branch_init']
1559
params = BranchInitHookParams(self, controldir, name, branch)
1563
def initialize(self, controldir, name=None, repository=None,
1564
append_revisions_only=None):
1565
"""Create a branch of this format in controldir.
1567
:param name: Name of the colocated branch to create.
1569
raise NotImplementedError(self.initialize)
1571
def is_supported(self):
1572
"""Is this format supported?
1574
Supported formats can be initialized and opened.
1575
Unsupported formats may not support initialization or committing or
1576
some other features depending on the reason for not being supported.
1580
def make_tags(self, branch):
1581
"""Create a tags object for branch.
1583
This method is on BranchFormat, because BranchFormats are reflected
1584
over the wire via network_name(), whereas full Branch instances require
1585
multiple VFS method calls to operate at all.
1587
The default implementation returns a disabled-tags instance.
1589
Note that it is normal for branch to be a RemoteBranch when using tags
1592
return _mod_tag.DisabledTags(branch)
1594
def network_name(self):
1595
"""A simple byte string uniquely identifying this format for RPC calls.
1597
MetaDir branch formats use their disk format string to identify the
1598
repository over the wire. All in one formats such as bzr < 0.8, and
1599
foreign formats like svn/git and hg should use some marker which is
1600
unique and immutable.
1602
raise NotImplementedError(self.network_name)
1604
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1605
found_repository=None, possible_transports=None):
1606
"""Return the branch object for controldir.
1608
:param controldir: A ControlDir that contains a branch.
1609
:param name: Name of colocated branch to open
1610
:param _found: a private parameter, do not use it. It is used to
1611
indicate if format probing has already be done.
1612
:param ignore_fallbacks: when set, no fallback branches will be opened
1613
(if there are any). Default is to open fallbacks.
1615
raise NotImplementedError(self.open)
1617
def supports_set_append_revisions_only(self):
1618
"""True if this format supports set_append_revisions_only."""
1621
def supports_stacking(self):
1622
"""True if this format records a stacked-on branch."""
1625
def supports_leaving_lock(self):
1626
"""True if this format supports leaving locks in place."""
1627
return False # by default
1630
return self.get_format_description().rstrip()
1632
def supports_tags(self):
1633
"""True if this format supports tags stored in the branch"""
1634
return False # by default
1636
def tags_are_versioned(self):
1637
"""Whether the tag container for this branch versions tags."""
1640
def supports_tags_referencing_ghosts(self):
1641
"""True if tags can reference ghost revisions."""
1644
def supports_store_uncommitted(self):
1645
"""True if uncommitted changes can be stored in this branch."""
1649
class BranchHooks(Hooks):
1650
"""A dictionary mapping hook name to a list of callables for branch hooks.
1652
e.g. ['post_push'] Is the list of items to be called when the
1653
push function is invoked.
1657
"""Create the default hooks.
1659
These are all empty initially, because by default nothing should get
1662
Hooks.__init__(self, "breezy.branch", "Branch.hooks")
1663
self.add_hook('open',
1664
"Called with the Branch object that has been opened after a "
1665
"branch is opened.", (1, 8))
1666
self.add_hook('post_push',
1667
"Called after a push operation completes. post_push is called "
1668
"with a breezy.branch.BranchPushResult object and only runs in the "
1669
"bzr client.", (0, 15))
1670
self.add_hook('post_pull',
1671
"Called after a pull operation completes. post_pull is called "
1672
"with a breezy.branch.PullResult object and only runs in the "
1673
"bzr client.", (0, 15))
1674
self.add_hook('pre_commit',
1675
"Called after a commit is calculated but before it is "
1676
"completed. pre_commit is called with (local, master, old_revno, "
1677
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1678
"). old_revid is NULL_REVISION for the first commit to a branch, "
1679
"tree_delta is a TreeDelta object describing changes from the "
1680
"basis revision. hooks MUST NOT modify this delta. "
1681
" future_tree is an in-memory tree obtained from "
1682
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1684
self.add_hook('post_commit',
1685
"Called in the bzr client after a commit has completed. "
1686
"post_commit is called with (local, master, old_revno, old_revid, "
1687
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1688
"commit to a branch.", (0, 15))
1689
self.add_hook('post_uncommit',
1690
"Called in the bzr client after an uncommit completes. "
1691
"post_uncommit is called with (local, master, old_revno, "
1692
"old_revid, new_revno, new_revid) where local is the local branch "
1693
"or None, master is the target branch, and an empty branch "
1694
"receives new_revno of 0, new_revid of None.", (0, 15))
1695
self.add_hook('pre_change_branch_tip',
1696
"Called in bzr client and server before a change to the tip of a "
1697
"branch is made. pre_change_branch_tip is called with a "
1698
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1699
"commit, uncommit will all trigger this hook.", (1, 6))
1700
self.add_hook('post_change_branch_tip',
1701
"Called in bzr client and server after a change to the tip of a "
1702
"branch is made. post_change_branch_tip is called with a "
1703
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1704
"commit, uncommit will all trigger this hook.", (1, 4))
1705
self.add_hook('transform_fallback_location',
1706
"Called when a stacked branch is activating its fallback "
1707
"locations. transform_fallback_location is called with (branch, "
1708
"url), and should return a new url. Returning the same url "
1709
"allows it to be used as-is, returning a different one can be "
1710
"used to cause the branch to stack on a closer copy of that "
1711
"fallback_location. Note that the branch cannot have history "
1712
"accessing methods called on it during this hook because the "
1713
"fallback locations have not been activated. When there are "
1714
"multiple hooks installed for transform_fallback_location, "
1715
"all are called with the url returned from the previous hook."
1716
"The order is however undefined.", (1, 9))
1717
self.add_hook('automatic_tag_name',
1718
"Called to determine an automatic tag name for a revision. "
1719
"automatic_tag_name is called with (branch, revision_id) and "
1720
"should return a tag name or None if no tag name could be "
1721
"determined. The first non-None tag name returned will be used.",
1723
self.add_hook('post_branch_init',
1724
"Called after new branch initialization completes. "
1725
"post_branch_init is called with a "
1726
"breezy.branch.BranchInitHookParams. "
1727
"Note that init, branch and checkout (both heavyweight and "
1728
"lightweight) will all trigger this hook.", (2, 2))
1729
self.add_hook('post_switch',
1730
"Called after a checkout switches branch. "
1731
"post_switch is called with a "
1732
"breezy.branch.SwitchHookParams.", (2, 2))
1736
# install the default hooks into the Branch class.
1737
Branch.hooks = BranchHooks()
1740
class ChangeBranchTipParams(object):
1741
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1743
There are 5 fields that hooks may wish to access:
1745
:ivar branch: the branch being changed
1746
:ivar old_revno: revision number before the change
1747
:ivar new_revno: revision number after the change
1748
:ivar old_revid: revision id before the change
1749
:ivar new_revid: revision id after the change
1751
The revid fields are strings. The revno fields are integers.
1754
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1755
"""Create a group of ChangeBranchTip parameters.
1757
:param branch: The branch being changed.
1758
:param old_revno: Revision number before the change.
1759
:param new_revno: Revision number after the change.
1760
:param old_revid: Tip revision id before the change.
1761
:param new_revid: Tip revision id after the change.
1763
self.branch = branch
1764
self.old_revno = old_revno
1765
self.new_revno = new_revno
1766
self.old_revid = old_revid
1767
self.new_revid = new_revid
1769
def __eq__(self, other):
1770
return self.__dict__ == other.__dict__
1773
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1774
self.__class__.__name__, self.branch,
1775
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1778
class BranchInitHookParams(object):
1779
"""Object holding parameters passed to `*_branch_init` hooks.
1781
There are 4 fields that hooks may wish to access:
1783
:ivar format: the branch format
1784
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1785
:ivar name: name of colocated branch, if any (or None)
1786
:ivar branch: the branch created
1788
Note that for lightweight checkouts, the bzrdir and format fields refer to
1789
the checkout, hence they are different from the corresponding fields in
1790
branch, which refer to the original branch.
1793
def __init__(self, format, controldir, name, branch):
1794
"""Create a group of BranchInitHook parameters.
1796
:param format: the branch format
1797
:param controldir: the ControlDir where the branch will be/has been
1799
:param name: name of colocated branch, if any (or None)
1800
:param branch: the branch created
1802
Note that for lightweight checkouts, the bzrdir and format fields refer
1803
to the checkout, hence they are different from the corresponding fields
1804
in branch, which refer to the original branch.
1806
self.format = format
1807
self.controldir = controldir
1809
self.branch = branch
1811
def __eq__(self, other):
1812
return self.__dict__ == other.__dict__
1815
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1818
class SwitchHookParams(object):
1819
"""Object holding parameters passed to `*_switch` hooks.
1821
There are 4 fields that hooks may wish to access:
1823
:ivar control_dir: ControlDir of the checkout to change
1824
:ivar to_branch: branch that the checkout is to reference
1825
:ivar force: skip the check for local commits in a heavy checkout
1826
:ivar revision_id: revision ID to switch to (or None)
1829
def __init__(self, control_dir, to_branch, force, revision_id):
1830
"""Create a group of SwitchHook parameters.
1832
:param control_dir: ControlDir of the checkout to change
1833
:param to_branch: branch that the checkout is to reference
1834
:param force: skip the check for local commits in a heavy checkout
1835
:param revision_id: revision ID to switch to (or None)
1837
self.control_dir = control_dir
1838
self.to_branch = to_branch
1840
self.revision_id = revision_id
1842
def __eq__(self, other):
1843
return self.__dict__ == other.__dict__
1846
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1847
self.control_dir, self.to_branch,
1851
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1852
"""Branch format registry."""
1854
def __init__(self, other_registry=None):
1855
super(BranchFormatRegistry, self).__init__(other_registry)
1856
self._default_format = None
1857
self._default_format_key = None
1859
def get_default(self):
1860
"""Return the current default format."""
1861
if (self._default_format_key is not None and
1862
self._default_format is None):
1863
self._default_format = self.get(self._default_format_key)
1864
return self._default_format
1866
def set_default(self, format):
1867
"""Set the default format."""
1868
self._default_format = format
1869
self._default_format_key = None
1871
def set_default_key(self, format_string):
1872
"""Set the default format by its format string."""
1873
self._default_format_key = format_string
1874
self._default_format = None
1877
network_format_registry = registry.FormatRegistry()
1878
"""Registry of formats indexed by their network name.
1880
The network name for a branch format is an identifier that can be used when
1881
referring to formats with smart server operations. See
1882
BranchFormat.network_name() for more detail.
1885
format_registry = BranchFormatRegistry(network_format_registry)
1888
# formats which have no format string are not discoverable
1889
# and not independently creatable, so are not registered.
1890
format_registry.register_lazy(
1891
b"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1893
format_registry.register_lazy(
1894
b"Bazaar Branch Format 6 (bzr 0.15)\n",
1895
"breezy.bzr.branch", "BzrBranchFormat6")
1896
format_registry.register_lazy(
1897
b"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1898
"breezy.bzr.branch", "BzrBranchFormat7")
1899
format_registry.register_lazy(
1900
b"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1901
"breezy.bzr.branch", "BzrBranchFormat8")
1902
format_registry.register_lazy(
1903
b"Bazaar-NG Branch Reference Format 1\n",
1904
"breezy.bzr.branch", "BranchReferenceFormat")
1906
format_registry.set_default_key(b"Bazaar Branch Format 7 (needs bzr 1.6)\n")
1909
class BranchWriteLockResult(LogicalLockResult):
1910
"""The result of write locking a branch.
1912
:ivar token: The token obtained from the underlying branch lock, or
1914
:ivar unlock: A callable which will unlock the lock.
1918
return "BranchWriteLockResult(%r, %r)" % (self.unlock, self.token)
1921
######################################################################
1922
# results of operations
1925
class _Result(object):
1927
def _show_tag_conficts(self, to_file):
1928
if not getattr(self, 'tag_conflicts', None):
1930
to_file.write('Conflicting tags:\n')
1931
for name, value1, value2 in self.tag_conflicts:
1932
to_file.write(' %s\n' % (name, ))
1935
class PullResult(_Result):
1936
"""Result of a Branch.pull operation.
1938
:ivar old_revno: Revision number before pull.
1939
:ivar new_revno: Revision number after pull.
1940
:ivar old_revid: Tip revision id before pull.
1941
:ivar new_revid: Tip revision id after pull.
1942
:ivar source_branch: Source (local) branch object. (read locked)
1943
:ivar master_branch: Master branch of the target, or the target if no
1945
:ivar local_branch: target branch if there is a Master, else None
1946
:ivar target_branch: Target/destination branch object. (write locked)
1947
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
1948
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
1951
def report(self, to_file):
1952
tag_conflicts = getattr(self, "tag_conflicts", None)
1953
tag_updates = getattr(self, "tag_updates", None)
1955
if self.old_revid != self.new_revid:
1956
to_file.write('Now on revision %d.\n' % self.new_revno)
1958
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
1959
if self.old_revid == self.new_revid and not tag_updates:
1960
if not tag_conflicts:
1961
to_file.write('No revisions or tags to pull.\n')
1963
to_file.write('No revisions to pull.\n')
1964
self._show_tag_conficts(to_file)
1967
class BranchPushResult(_Result):
1968
"""Result of a Branch.push operation.
1970
:ivar old_revno: Revision number (eg 10) of the target before push.
1971
:ivar new_revno: Revision number (eg 12) of the target after push.
1972
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
1974
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
1976
:ivar source_branch: Source branch object that the push was from. This is
1977
read locked, and generally is a local (and thus low latency) branch.
1978
:ivar master_branch: If target is a bound branch, the master branch of
1979
target, or target itself. Always write locked.
1980
:ivar target_branch: The direct Branch where data is being sent (write
1982
:ivar local_branch: If the target is a bound branch this will be the
1983
target, otherwise it will be None.
1986
def report(self, to_file):
1987
# TODO: This function gets passed a to_file, but then
1988
# ignores it and calls note() instead. This is also
1989
# inconsistent with PullResult(), which writes to stdout.
1990
# -- JRV20110901, bug #838853
1991
tag_conflicts = getattr(self, "tag_conflicts", None)
1992
tag_updates = getattr(self, "tag_updates", None)
1994
if self.old_revid != self.new_revid:
1995
note(gettext('Pushed up to revision %d.') % self.new_revno)
1997
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
1998
if self.old_revid == self.new_revid and not tag_updates:
1999
if not tag_conflicts:
2000
note(gettext('No new revisions or tags to push.'))
2002
note(gettext('No new revisions to push.'))
2003
self._show_tag_conficts(to_file)
2006
class BranchCheckResult(object):
2007
"""Results of checking branch consistency.
2012
def __init__(self, branch):
2013
self.branch = branch
2016
def report_results(self, verbose):
2017
"""Report the check results via trace.note.
2019
:param verbose: Requests more detailed display of what was checked,
2022
note(gettext('checked branch {0} format {1}').format(
2023
self.branch.user_url, self.branch._format))
2024
for error in self.errors:
2025
note(gettext('found error:%s'), error)
2028
class InterBranch(InterObject):
2029
"""This class represents operations taking place between two branches.
2031
Its instances have methods like pull() and push() and contain
2032
references to the source and target repositories these operations
2033
can be carried out on.
2037
"""The available optimised InterBranch types."""
2040
def _get_branch_formats_to_test(klass):
2041
"""Return an iterable of format tuples for testing.
2043
:return: An iterable of (from_format, to_format) to use when testing
2044
this InterBranch class. Each InterBranch class should define this
2047
raise NotImplementedError(klass._get_branch_formats_to_test)
2049
def pull(self, overwrite=False, stop_revision=None,
2050
possible_transports=None, local=False):
2051
"""Mirror source into target branch.
2053
The target branch is considered to be 'local', having low latency.
2055
:returns: PullResult instance
2057
raise NotImplementedError(self.pull)
2059
def push(self, overwrite=False, stop_revision=None, lossy=False,
2060
_override_hook_source_branch=None):
2061
"""Mirror the source branch into the target branch.
2063
The source branch is considered to be 'local', having low latency.
2065
raise NotImplementedError(self.push)
2067
def copy_content_into(self, revision_id=None):
2068
"""Copy the content of source into target
2070
revision_id: if not None, the revision history in the new branch will
2071
be truncated to end with revision_id.
2073
raise NotImplementedError(self.copy_content_into)
2075
def fetch(self, stop_revision=None, limit=None):
2078
:param stop_revision: Last revision to fetch
2079
:param limit: Optional rough limit of revisions to fetch
2081
raise NotImplementedError(self.fetch)
2084
def _fix_overwrite_type(overwrite):
2085
if isinstance(overwrite, bool):
2087
return ["history", "tags"]
2093
class GenericInterBranch(InterBranch):
2094
"""InterBranch implementation that uses public Branch functions."""
2097
def is_compatible(klass, source, target):
2098
# GenericBranch uses the public API, so always compatible
2102
def _get_branch_formats_to_test(klass):
2103
return [(format_registry.get_default(), format_registry.get_default())]
2106
def unwrap_format(klass, format):
2107
if isinstance(format, remote.RemoteBranchFormat):
2108
format._ensure_real()
2109
return format._custom_format
2112
def copy_content_into(self, revision_id=None):
2113
"""Copy the content of source into target
2115
revision_id: if not None, the revision history in the new branch will
2116
be truncated to end with revision_id.
2118
with self.source.lock_read(), self.target.lock_write():
2119
self.source.update_references(self.target)
2120
self.source._synchronize_history(self.target, revision_id)
2122
parent = self.source.get_parent()
2123
except errors.InaccessibleParent as e:
2124
mutter('parent was not accessible to copy: %s', e)
2127
self.target.set_parent(parent)
2128
if self.source._push_should_merge_tags():
2129
self.source.tags.merge_to(self.target.tags)
2131
def fetch(self, stop_revision=None, limit=None):
2132
if self.target.base == self.source.base:
2134
with self.source.lock_read(), self.target.lock_write():
2135
fetch_spec_factory = fetch.FetchSpecFactory()
2136
fetch_spec_factory.source_branch = self.source
2137
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
2138
fetch_spec_factory.source_repo = self.source.repository
2139
fetch_spec_factory.target_repo = self.target.repository
2140
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
2141
fetch_spec_factory.limit = limit
2142
fetch_spec = fetch_spec_factory.make_fetch_spec()
2143
return self.target.repository.fetch(
2144
self.source.repository,
2145
fetch_spec=fetch_spec)
2147
def _update_revisions(self, stop_revision=None, overwrite=False,
2149
with self.source.lock_read(), self.target.lock_write():
2150
other_revno, other_last_revision = self.source.last_revision_info()
2151
stop_revno = None # unknown
2152
if stop_revision is None:
2153
stop_revision = other_last_revision
2154
if _mod_revision.is_null(stop_revision):
2155
# if there are no commits, we're done.
2157
stop_revno = other_revno
2159
# what's the current last revision, before we fetch [and change it
2161
last_rev = _mod_revision.ensure_null(self.target.last_revision())
2162
# we fetch here so that we don't process data twice in the common
2163
# case of having something to pull, and so that the check for
2164
# already merged can operate on the just fetched graph, which will
2165
# be cached in memory.
2166
self.fetch(stop_revision=stop_revision)
2167
# Check to see if one is an ancestor of the other
2170
graph = self.target.repository.get_graph()
2171
if self.target._check_if_descendant_or_diverged(
2172
stop_revision, last_rev, graph, self.source):
2173
# stop_revision is a descendant of last_rev, but we aren't
2174
# overwriting, so we're done.
2176
if stop_revno is None:
2178
graph = self.target.repository.get_graph()
2179
this_revno, this_last_revision = \
2180
self.target.last_revision_info()
2181
stop_revno = graph.find_distance_to_null(stop_revision,
2182
[(other_last_revision, other_revno),
2183
(this_last_revision, this_revno)])
2184
self.target.set_last_revision_info(stop_revno, stop_revision)
2186
def pull(self, overwrite=False, stop_revision=None,
2187
possible_transports=None, run_hooks=True,
2188
_override_hook_target=None, local=False):
2189
"""Pull from source into self, updating my master if any.
2191
:param run_hooks: Private parameter - if false, this branch
2192
is being called because it's the master of the primary branch,
2193
so it should not run its hooks.
2195
with self.target.lock_write():
2196
bound_location = self.target.get_bound_location()
2197
if local and not bound_location:
2198
raise errors.LocalRequiresBoundBranch()
2199
master_branch = None
2200
source_is_master = False
2202
# bound_location comes from a config file, some care has to be
2203
# taken to relate it to source.user_url
2204
normalized = urlutils.normalize_url(bound_location)
2206
relpath = self.source.user_transport.relpath(normalized)
2207
source_is_master = (relpath == '')
2208
except (errors.PathNotChild, urlutils.InvalidURL):
2209
source_is_master = False
2210
if not local and bound_location and not source_is_master:
2211
# not pulling from master, so we need to update master.
2212
master_branch = self.target.get_master_branch(possible_transports)
2213
master_branch.lock_write()
2216
# pull from source into master.
2217
master_branch.pull(self.source, overwrite, stop_revision,
2219
return self._pull(overwrite,
2220
stop_revision, _hook_master=master_branch,
2221
run_hooks=run_hooks,
2222
_override_hook_target=_override_hook_target,
2223
merge_tags_to_master=not source_is_master)
2226
master_branch.unlock()
2228
def push(self, overwrite=False, stop_revision=None, lossy=False,
2229
_override_hook_source_branch=None):
2230
"""See InterBranch.push.
2232
This is the basic concrete implementation of push()
2234
:param _override_hook_source_branch: If specified, run the hooks
2235
passing this Branch as the source, rather than self. This is for
2236
use of RemoteBranch, where push is delegated to the underlying
2240
raise errors.LossyPushToSameVCS(self.source, self.target)
2241
# TODO: Public option to disable running hooks - should be trivial but
2244
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
2245
op.add_cleanup(self.source.lock_read().unlock)
2246
op.add_cleanup(self.target.lock_write().unlock)
2247
return op.run(overwrite, stop_revision,
2248
_override_hook_source_branch=_override_hook_source_branch)
2250
def _basic_push(self, overwrite, stop_revision):
2251
"""Basic implementation of push without bound branches or hooks.
2253
Must be called with source read locked and target write locked.
2255
result = BranchPushResult()
2256
result.source_branch = self.source
2257
result.target_branch = self.target
2258
result.old_revno, result.old_revid = self.target.last_revision_info()
2259
self.source.update_references(self.target)
2260
overwrite = _fix_overwrite_type(overwrite)
2261
if result.old_revid != stop_revision:
2262
# We assume that during 'push' this repository is closer than
2264
graph = self.source.repository.get_graph(self.target.repository)
2265
self._update_revisions(stop_revision,
2266
overwrite=("history" in overwrite),
2268
if self.source._push_should_merge_tags():
2269
result.tag_updates, result.tag_conflicts = (
2270
self.source.tags.merge_to(
2271
self.target.tags, "tags" in overwrite))
2272
result.new_revno, result.new_revid = self.target.last_revision_info()
2275
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
2276
_override_hook_source_branch=None):
2277
"""Push from source into target, and into target's master if any.
2280
if _override_hook_source_branch:
2281
result.source_branch = _override_hook_source_branch
2282
for hook in Branch.hooks['post_push']:
2285
bound_location = self.target.get_bound_location()
2286
if bound_location and self.target.base != bound_location:
2287
# there is a master branch.
2289
# XXX: Why the second check? Is it even supported for a branch to
2290
# be bound to itself? -- mbp 20070507
2291
master_branch = self.target.get_master_branch()
2292
master_branch.lock_write()
2293
operation.add_cleanup(master_branch.unlock)
2294
# push into the master from the source branch.
2295
master_inter = InterBranch.get(self.source, master_branch)
2296
master_inter._basic_push(overwrite, stop_revision)
2297
# and push into the target branch from the source. Note that
2298
# we push from the source branch again, because it's considered
2299
# the highest bandwidth repository.
2300
result = self._basic_push(overwrite, stop_revision)
2301
result.master_branch = master_branch
2302
result.local_branch = self.target
2304
master_branch = None
2306
result = self._basic_push(overwrite, stop_revision)
2307
# TODO: Why set master_branch and local_branch if there's no
2308
# binding? Maybe cleaner to just leave them unset? -- mbp
2310
result.master_branch = self.target
2311
result.local_branch = None
2315
def _pull(self, overwrite=False, stop_revision=None,
2316
possible_transports=None, _hook_master=None, run_hooks=True,
2317
_override_hook_target=None, local=False,
2318
merge_tags_to_master=True):
2321
This function is the core worker, used by GenericInterBranch.pull to
2322
avoid duplication when pulling source->master and source->local.
2324
:param _hook_master: Private parameter - set the branch to
2325
be supplied as the master to pull hooks.
2326
:param run_hooks: Private parameter - if false, this branch
2327
is being called because it's the master of the primary branch,
2328
so it should not run its hooks.
2329
is being called because it's the master of the primary branch,
2330
so it should not run its hooks.
2331
:param _override_hook_target: Private parameter - set the branch to be
2332
supplied as the target_branch to pull hooks.
2333
:param local: Only update the local branch, and not the bound branch.
2335
# This type of branch can't be bound.
2337
raise errors.LocalRequiresBoundBranch()
2338
result = PullResult()
2339
result.source_branch = self.source
2340
if _override_hook_target is None:
2341
result.target_branch = self.target
2343
result.target_branch = _override_hook_target
2344
with self.source.lock_read():
2345
# We assume that during 'pull' the target repository is closer than
2347
self.source.update_references(self.target)
2348
graph = self.target.repository.get_graph(self.source.repository)
2349
# TODO: Branch formats should have a flag that indicates
2350
# that revno's are expensive, and pull() should honor that flag.
2352
result.old_revno, result.old_revid = \
2353
self.target.last_revision_info()
2354
overwrite = _fix_overwrite_type(overwrite)
2355
self._update_revisions(stop_revision,
2356
overwrite=("history" in overwrite),
2358
# TODO: The old revid should be specified when merging tags,
2359
# so a tags implementation that versions tags can only
2360
# pull in the most recent changes. -- JRV20090506
2361
result.tag_updates, result.tag_conflicts = (
2362
self.source.tags.merge_to(self.target.tags,
2363
"tags" in overwrite,
2364
ignore_master=not merge_tags_to_master))
2365
result.new_revno, result.new_revid = self.target.last_revision_info()
2367
result.master_branch = _hook_master
2368
result.local_branch = result.target_branch
2370
result.master_branch = result.target_branch
2371
result.local_branch = None
2373
for hook in Branch.hooks['post_pull']:
2378
InterBranch.register_optimiser(GenericInterBranch)