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 Branch(controldir.ControlComponent):
63
"""Branch holding a history of revisions.
66
Base directory/url of the branch; using control_url and
67
control_transport is more standardized.
68
:ivar hooks: An instance of BranchHooks.
69
:ivar _master_branch_cache: cached result of get_master_branch, see
72
# this is really an instance variable - FIXME move it there
77
def control_transport(self):
78
return self._transport
81
def user_transport(self):
82
return self.controldir.user_transport
84
def __init__(self, possible_transports=None):
85
self.tags = self._format.make_tags(self)
86
self._revision_history_cache = None
87
self._revision_id_to_revno_cache = None
88
self._partial_revision_id_to_revno_cache = {}
89
self._partial_revision_history_cache = []
90
self._tags_bytes = None
91
self._last_revision_info_cache = None
92
self._master_branch_cache = None
93
self._merge_sorted_revisions_cache = None
94
self._open_hook(possible_transports)
95
hooks = Branch.hooks['open']
99
def _open_hook(self, possible_transports):
100
"""Called by init to allow simpler extension of the base class."""
102
def _activate_fallback_location(self, url, possible_transports):
103
"""Activate the branch/repository from url as a fallback repository."""
104
for existing_fallback_repo in self.repository._fallback_repositories:
105
if existing_fallback_repo.user_url == url:
106
# This fallback is already configured. This probably only
107
# happens because ControlDir.sprout is a horrible mess. To
108
# avoid confusing _unstack we don't add this a second time.
109
mutter('duplicate activation of fallback %r on %r', url, self)
111
repo = self._get_fallback_repository(url, possible_transports)
112
if repo.has_same_location(self.repository):
113
raise errors.UnstackableLocationError(self.user_url, url)
114
self.repository.add_fallback_repository(repo)
116
def break_lock(self):
117
"""Break a lock if one is present from another instance.
119
Uses the ui factory to ask for confirmation if the lock may be from
122
This will probe the repository for its lock as well.
124
self.control_files.break_lock()
125
self.repository.break_lock()
126
master = self.get_master_branch()
127
if master is not None:
130
def _check_stackable_repo(self):
131
if not self.repository._format.supports_external_lookups:
132
raise errors.UnstackableRepositoryFormat(
133
self.repository._format, self.repository.base)
135
def _extend_partial_history(self, stop_index=None, stop_revision=None):
136
"""Extend the partial history to include a given index
138
If a stop_index is supplied, stop when that index has been reached.
139
If a stop_revision is supplied, stop when that revision is
140
encountered. Otherwise, stop when the beginning of history is
143
:param stop_index: The index which should be present. When it is
144
present, history extension will stop.
145
:param stop_revision: The revision id which should be present. When
146
it is encountered, history extension will stop.
148
if len(self._partial_revision_history_cache) == 0:
149
self._partial_revision_history_cache = [self.last_revision()]
150
repository._iter_for_revno(
151
self.repository, self._partial_revision_history_cache,
152
stop_index=stop_index, stop_revision=stop_revision)
153
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
154
self._partial_revision_history_cache.pop()
156
def _get_check_refs(self):
157
"""Get the references needed for check().
161
revid = self.last_revision()
162
return [('revision-existence', revid), ('lefthand-distance', revid)]
165
def open(base, _unsupported=False, possible_transports=None):
166
"""Open the branch rooted at base.
168
For instance, if the branch is at URL/.bzr/branch,
169
Branch.open(URL) -> a Branch instance.
171
control = controldir.ControlDir.open(base,
172
possible_transports=possible_transports, _unsupported=_unsupported)
173
return control.open_branch(unsupported=_unsupported,
174
possible_transports=possible_transports)
177
def open_from_transport(transport, name=None, _unsupported=False,
178
possible_transports=None):
179
"""Open the branch rooted at transport"""
180
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
181
return control.open_branch(name=name, unsupported=_unsupported,
182
possible_transports=possible_transports)
185
def open_containing(url, possible_transports=None):
186
"""Open an existing branch which contains url.
188
This probes for a branch at url, and searches upwards from there.
190
Basically we keep looking up until we find the control directory or
191
run into the root. If there isn't one, raises NotBranchError.
192
If there is one and it is either an unrecognised format or an unsupported
193
format, UnknownFormatError or UnsupportedFormatError are raised.
194
If there is one, it is returned, along with the unused portion of url.
196
control, relpath = controldir.ControlDir.open_containing(url,
198
branch = control.open_branch(possible_transports=possible_transports)
199
return (branch, relpath)
201
def _push_should_merge_tags(self):
202
"""Should _basic_push merge this branch's tags into the target?
204
The default implementation returns False if this branch has no tags,
205
and True the rest of the time. Subclasses may override this.
207
return self.supports_tags() and self.tags.get_tag_dict()
209
def get_config(self):
210
"""Get a breezy.config.BranchConfig for this Branch.
212
This can then be used to get and set configuration options for the
215
:return: A breezy.config.BranchConfig.
217
return _mod_config.BranchConfig(self)
219
def get_config_stack(self):
220
"""Get a breezy.config.BranchStack for this Branch.
222
This can then be used to get and set configuration options for the
225
:return: A breezy.config.BranchStack.
227
return _mod_config.BranchStack(self)
229
def _get_config(self):
230
"""Get the concrete config for just the config in this branch.
232
This is not intended for client use; see Branch.get_config for the
237
:return: An object supporting get_option and set_option.
239
raise NotImplementedError(self._get_config)
241
def store_uncommitted(self, creator):
242
"""Store uncommitted changes from a ShelfCreator.
244
:param creator: The ShelfCreator containing uncommitted changes, or
245
None to delete any stored changes.
246
:raises: ChangesAlreadyStored if the branch already has changes.
248
raise NotImplementedError(self.store_uncommitted)
250
def get_unshelver(self, tree):
251
"""Return a shelf.Unshelver for this branch and tree.
253
:param tree: The tree to use to construct the Unshelver.
254
:return: an Unshelver or None if no changes are stored.
256
raise NotImplementedError(self.get_unshelver)
258
def _get_fallback_repository(self, url, possible_transports):
259
"""Get the repository we fallback to at url."""
260
url = urlutils.join(self.base, url)
261
a_branch = Branch.open(url, possible_transports=possible_transports)
262
return a_branch.repository
265
def _get_tags_bytes(self):
266
"""Get the bytes of a serialised tags dict.
268
Note that not all branches support tags, nor do all use the same tags
269
logic: this method is specific to BasicTags. Other tag implementations
270
may use the same method name and behave differently, safely, because
271
of the double-dispatch via
272
format.make_tags->tags_instance->get_tags_dict.
274
:return: The bytes of the tags file.
275
:seealso: Branch._set_tags_bytes.
277
if self._tags_bytes is None:
278
self._tags_bytes = self._transport.get_bytes('tags')
279
return self._tags_bytes
281
def _get_nick(self, local=False, possible_transports=None):
282
config = self.get_config()
283
# explicit overrides master, but don't look for master if local is True
284
if not local and not config.has_explicit_nickname():
286
master = self.get_master_branch(possible_transports)
287
if master and self.user_url == master.user_url:
288
raise errors.RecursiveBind(self.user_url)
289
if master is not None:
290
# return the master branch value
292
except errors.RecursiveBind as e:
294
except errors.BzrError as e:
295
# Silently fall back to local implicit nick if the master is
297
mutter("Could not connect to bound branch, "
298
"falling back to local nick.\n " + str(e))
299
return config.get_nickname()
301
def _set_nick(self, nick):
302
self.get_config().set_user_option('nickname', nick, warn_masked=True)
304
nick = property(_get_nick, _set_nick)
307
raise NotImplementedError(self.is_locked)
309
def _lefthand_history(self, revision_id, last_rev=None,
311
if 'evil' in debug.debug_flags:
312
mutter_callsite(4, "_lefthand_history scales with history.")
313
# stop_revision must be a descendant of last_revision
314
graph = self.repository.get_graph()
315
if last_rev is not None:
316
if not graph.is_ancestor(last_rev, revision_id):
317
# our previous tip is not merged into stop_revision
318
raise errors.DivergedBranches(self, other_branch)
319
# make a new revision history from the graph
320
parents_map = graph.get_parent_map([revision_id])
321
if revision_id not in parents_map:
322
raise errors.NoSuchRevision(self, revision_id)
323
current_rev_id = revision_id
325
check_not_reserved_id = _mod_revision.check_not_reserved_id
326
# Do not include ghosts or graph origin in revision_history
327
while (current_rev_id in parents_map and
328
len(parents_map[current_rev_id]) > 0):
329
check_not_reserved_id(current_rev_id)
330
new_history.append(current_rev_id)
331
current_rev_id = parents_map[current_rev_id][0]
332
parents_map = graph.get_parent_map([current_rev_id])
333
new_history.reverse()
336
def lock_write(self, token=None):
337
"""Lock the branch for write operations.
339
:param token: A token to permit reacquiring a previously held and
341
:return: A BranchWriteLockResult.
343
raise NotImplementedError(self.lock_write)
346
"""Lock the branch for read operations.
348
:return: A breezy.lock.LogicalLockResult.
350
raise NotImplementedError(self.lock_read)
353
raise NotImplementedError(self.unlock)
355
def peek_lock_mode(self):
356
"""Return lock mode for the Branch: 'r', 'w' or None"""
357
raise NotImplementedError(self.peek_lock_mode)
359
def get_physical_lock_status(self):
360
raise NotImplementedError(self.get_physical_lock_status)
363
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
364
"""Return the revision_id for a dotted revno.
366
:param revno: a tuple like (1,) or (1,1,2)
367
:param _cache_reverse: a private parameter enabling storage
368
of the reverse mapping in a top level cache. (This should
369
only be done in selective circumstances as we want to
370
avoid having the mapping cached multiple times.)
371
:return: the revision_id
372
:raises errors.NoSuchRevision: if the revno doesn't exist
374
rev_id = self._do_dotted_revno_to_revision_id(revno)
376
self._partial_revision_id_to_revno_cache[rev_id] = revno
379
def _do_dotted_revno_to_revision_id(self, revno):
380
"""Worker function for dotted_revno_to_revision_id.
382
Subclasses should override this if they wish to
383
provide a more efficient implementation.
386
return self.get_rev_id(revno[0])
387
revision_id_to_revno = self.get_revision_id_to_revno_map()
388
revision_ids = [revision_id for revision_id, this_revno
389
in viewitems(revision_id_to_revno)
390
if revno == this_revno]
391
if len(revision_ids) == 1:
392
return revision_ids[0]
394
revno_str = '.'.join(map(str, revno))
395
raise errors.NoSuchRevision(self, revno_str)
398
def revision_id_to_dotted_revno(self, revision_id):
399
"""Given a revision id, return its dotted revno.
401
:return: a tuple like (1,) or (400,1,3).
403
return self._do_revision_id_to_dotted_revno(revision_id)
405
def _do_revision_id_to_dotted_revno(self, revision_id):
406
"""Worker function for revision_id_to_revno."""
407
# Try the caches if they are loaded
408
result = self._partial_revision_id_to_revno_cache.get(revision_id)
409
if result is not None:
411
if self._revision_id_to_revno_cache:
412
result = self._revision_id_to_revno_cache.get(revision_id)
414
raise errors.NoSuchRevision(self, revision_id)
415
# Try the mainline as it's optimised
417
revno = self.revision_id_to_revno(revision_id)
419
except errors.NoSuchRevision:
420
# We need to load and use the full revno map after all
421
result = self.get_revision_id_to_revno_map().get(revision_id)
423
raise errors.NoSuchRevision(self, revision_id)
427
def get_revision_id_to_revno_map(self):
428
"""Return the revision_id => dotted revno map.
430
This will be regenerated on demand, but will be cached.
432
:return: A dictionary mapping revision_id => dotted revno.
433
This dictionary should not be modified by the caller.
435
if self._revision_id_to_revno_cache is not None:
436
mapping = self._revision_id_to_revno_cache
438
mapping = self._gen_revno_map()
439
self._cache_revision_id_to_revno(mapping)
440
# TODO: jam 20070417 Since this is being cached, should we be returning
442
# I would rather not, and instead just declare that users should not
443
# modify the return value.
446
def _gen_revno_map(self):
447
"""Create a new mapping from revision ids to dotted revnos.
449
Dotted revnos are generated based on the current tip in the revision
451
This is the worker function for get_revision_id_to_revno_map, which
452
just caches the return value.
454
:return: A dictionary mapping revision_id => dotted revno.
456
revision_id_to_revno = dict((rev_id, revno)
457
for rev_id, depth, revno, end_of_merge
458
in self.iter_merge_sorted_revisions())
459
return revision_id_to_revno
462
def iter_merge_sorted_revisions(self, start_revision_id=None,
463
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
464
"""Walk the revisions for a branch in merge sorted order.
466
Merge sorted order is the output from a merge-aware,
467
topological sort, i.e. all parents come before their
468
children going forward; the opposite for reverse.
470
:param start_revision_id: the revision_id to begin walking from.
471
If None, the branch tip is used.
472
:param stop_revision_id: the revision_id to terminate the walk
473
after. If None, the rest of history is included.
474
:param stop_rule: if stop_revision_id is not None, the precise rule
475
to use for termination:
477
* 'exclude' - leave the stop revision out of the result (default)
478
* 'include' - the stop revision is the last item in the result
479
* 'with-merges' - include the stop revision and all of its
480
merged revisions in the result
481
* 'with-merges-without-common-ancestry' - filter out revisions
482
that are in both ancestries
483
:param direction: either 'reverse' or 'forward':
485
* reverse means return the start_revision_id first, i.e.
486
start at the most recent revision and go backwards in history
487
* forward returns tuples in the opposite order to reverse.
488
Note in particular that forward does *not* do any intelligent
489
ordering w.r.t. depth as some clients of this API may like.
490
(If required, that ought to be done at higher layers.)
492
:return: an iterator over (revision_id, depth, revno, end_of_merge)
495
* revision_id: the unique id of the revision
496
* depth: How many levels of merging deep this node has been
498
* revno_sequence: This field provides a sequence of
499
revision numbers for all revisions. The format is:
500
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
501
branch that the revno is on. From left to right the REVNO numbers
502
are the sequence numbers within that branch of the revision.
503
* end_of_merge: When True the next node (earlier in history) is
504
part of a different merge.
506
# Note: depth and revno values are in the context of the branch so
507
# we need the full graph to get stable numbers, regardless of the
509
if self._merge_sorted_revisions_cache is None:
510
last_revision = self.last_revision()
511
known_graph = self.repository.get_known_graph_ancestry(
513
self._merge_sorted_revisions_cache = known_graph.merge_sort(
515
filtered = self._filter_merge_sorted_revisions(
516
self._merge_sorted_revisions_cache, start_revision_id,
517
stop_revision_id, stop_rule)
518
# Make sure we don't return revisions that are not part of the
519
# start_revision_id ancestry.
520
filtered = self._filter_start_non_ancestors(filtered)
521
if direction == 'reverse':
523
if direction == 'forward':
524
return reversed(list(filtered))
526
raise ValueError('invalid direction %r' % direction)
528
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
529
start_revision_id, stop_revision_id, stop_rule):
530
"""Iterate over an inclusive range of sorted revisions."""
531
rev_iter = iter(merge_sorted_revisions)
532
if start_revision_id is not None:
533
for node in rev_iter:
535
if rev_id != start_revision_id:
538
# The decision to include the start or not
539
# depends on the stop_rule if a stop is provided
540
# so pop this node back into the iterator
541
rev_iter = itertools.chain(iter([node]), rev_iter)
543
if stop_revision_id is None:
545
for node in rev_iter:
547
yield (rev_id, node.merge_depth, node.revno,
549
elif stop_rule == 'exclude':
550
for node in rev_iter:
552
if rev_id == stop_revision_id:
554
yield (rev_id, node.merge_depth, node.revno,
556
elif stop_rule == 'include':
557
for node in rev_iter:
559
yield (rev_id, node.merge_depth, node.revno,
561
if rev_id == stop_revision_id:
563
elif stop_rule == 'with-merges-without-common-ancestry':
564
# We want to exclude all revisions that are already part of the
565
# stop_revision_id ancestry.
566
graph = self.repository.get_graph()
567
ancestors = graph.find_unique_ancestors(start_revision_id,
569
for node in rev_iter:
571
if rev_id not in ancestors:
573
yield (rev_id, node.merge_depth, node.revno,
575
elif stop_rule == 'with-merges':
576
stop_rev = self.repository.get_revision(stop_revision_id)
577
if stop_rev.parent_ids:
578
left_parent = stop_rev.parent_ids[0]
580
left_parent = _mod_revision.NULL_REVISION
581
# left_parent is the actual revision we want to stop logging at,
582
# since we want to show the merged revisions after the stop_rev too
583
reached_stop_revision_id = False
584
revision_id_whitelist = []
585
for node in rev_iter:
587
if rev_id == left_parent:
588
# reached the left parent after the stop_revision
590
if (not reached_stop_revision_id or
591
rev_id in revision_id_whitelist):
592
yield (rev_id, node.merge_depth, node.revno,
594
if reached_stop_revision_id or rev_id == stop_revision_id:
595
# only do the merged revs of rev_id from now on
596
rev = self.repository.get_revision(rev_id)
598
reached_stop_revision_id = True
599
revision_id_whitelist.extend(rev.parent_ids)
601
raise ValueError('invalid stop_rule %r' % stop_rule)
603
def _filter_start_non_ancestors(self, rev_iter):
604
# If we started from a dotted revno, we want to consider it as a tip
605
# and don't want to yield revisions that are not part of its
606
# ancestry. Given the order guaranteed by the merge sort, we will see
607
# uninteresting descendants of the first parent of our tip before the
609
first = next(rev_iter)
610
(rev_id, merge_depth, revno, end_of_merge) = first
613
# We start at a mainline revision so by definition, all others
614
# revisions in rev_iter are ancestors
615
for node in rev_iter:
620
pmap = self.repository.get_parent_map([rev_id])
621
parents = pmap.get(rev_id, [])
623
whitelist.update(parents)
625
# If there is no parents, there is nothing of interest left
627
# FIXME: It's hard to test this scenario here as this code is never
628
# called in that case. -- vila 20100322
631
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
633
if rev_id in whitelist:
634
pmap = self.repository.get_parent_map([rev_id])
635
parents = pmap.get(rev_id, [])
636
whitelist.remove(rev_id)
637
whitelist.update(parents)
639
# We've reached the mainline, there is nothing left to
643
# A revision that is not part of the ancestry of our
646
yield (rev_id, merge_depth, revno, end_of_merge)
648
def leave_lock_in_place(self):
649
"""Tell this branch object not to release the physical lock when this
652
If lock_write doesn't return a token, then this method is not supported.
654
self.control_files.leave_in_place()
656
def dont_leave_lock_in_place(self):
657
"""Tell this branch object to release the physical lock when this
658
object is unlocked, even if it didn't originally acquire it.
660
If lock_write doesn't return a token, then this method is not supported.
662
self.control_files.dont_leave_in_place()
664
def bind(self, other):
665
"""Bind the local branch the other branch.
667
:param other: The branch to bind to
670
raise errors.UpgradeRequired(self.user_url)
672
def get_append_revisions_only(self):
673
"""Whether it is only possible to append revisions to the history.
675
if not self._format.supports_set_append_revisions_only():
677
return self.get_config_stack().get('append_revisions_only')
679
def set_append_revisions_only(self, enabled):
680
if not self._format.supports_set_append_revisions_only():
681
raise errors.UpgradeRequired(self.user_url)
682
self.get_config_stack().set('append_revisions_only', enabled)
684
def set_reference_info(self, file_id, tree_path, branch_location):
685
"""Set the branch location to use for a tree reference."""
686
raise errors.UnsupportedOperation(self.set_reference_info, self)
688
def get_reference_info(self, file_id):
689
"""Get the tree_path and branch_location for a tree reference."""
690
raise errors.UnsupportedOperation(self.get_reference_info, self)
693
def fetch(self, from_branch, last_revision=None, limit=None):
694
"""Copy revisions from from_branch into this branch.
696
:param from_branch: Where to copy from.
697
:param last_revision: What revision to stop at (None for at the end
699
:param limit: Optional rough limit of revisions to fetch
702
return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
704
def get_bound_location(self):
705
"""Return the URL of the branch we are bound to.
707
Older format branches cannot bind, please be sure to use a metadir
712
def get_old_bound_location(self):
713
"""Return the URL of the branch we used to be bound to
715
raise errors.UpgradeRequired(self.user_url)
717
def get_commit_builder(self, parents, config_stack=None, timestamp=None,
718
timezone=None, committer=None, revprops=None,
719
revision_id=None, lossy=False):
720
"""Obtain a CommitBuilder for this branch.
722
:param parents: Revision ids of the parents of the new revision.
723
:param config: Optional configuration to use.
724
:param timestamp: Optional timestamp recorded for commit.
725
:param timezone: Optional timezone for timestamp.
726
:param committer: Optional committer to set for commit.
727
:param revprops: Optional dictionary of revision properties.
728
:param revision_id: Optional revision id.
729
:param lossy: Whether to discard data that can not be natively
730
represented, when pushing to a foreign VCS
733
if config_stack is None:
734
config_stack = self.get_config_stack()
736
return self.repository.get_commit_builder(self, parents, config_stack,
737
timestamp, timezone, committer, revprops, revision_id,
740
def get_master_branch(self, possible_transports=None):
741
"""Return the branch we are bound to.
743
:return: Either a Branch, or None
747
def get_stacked_on_url(self):
748
"""Get the URL this branch is stacked against.
750
:raises NotStacked: If the branch is not stacked.
751
:raises UnstackableBranchFormat: If the branch does not support
754
raise NotImplementedError(self.get_stacked_on_url)
756
def print_file(self, file, revision_id):
757
"""Print `file` to stdout."""
758
raise NotImplementedError(self.print_file)
761
def set_last_revision_info(self, revno, revision_id):
762
"""Set the last revision of this branch.
764
The caller is responsible for checking that the revno is correct
765
for this revision id.
767
It may be possible to set the branch last revision to an id not
768
present in the repository. However, branches can also be
769
configured to check constraints on history, in which case this may not
772
raise NotImplementedError(self.set_last_revision_info)
775
def generate_revision_history(self, revision_id, last_rev=None,
777
"""See Branch.generate_revision_history"""
778
graph = self.repository.get_graph()
779
(last_revno, last_revid) = self.last_revision_info()
780
known_revision_ids = [
781
(last_revid, last_revno),
782
(_mod_revision.NULL_REVISION, 0),
784
if last_rev is not None:
785
if not graph.is_ancestor(last_rev, revision_id):
786
# our previous tip is not merged into stop_revision
787
raise errors.DivergedBranches(self, other_branch)
788
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
789
self.set_last_revision_info(revno, revision_id)
792
def set_parent(self, url):
793
"""See Branch.set_parent."""
794
# TODO: Maybe delete old location files?
795
# URLs should never be unicode, even on the local fs,
796
# FIXUP this and get_parent in a future branch format bump:
797
# read and rewrite the file. RBC 20060125
799
if isinstance(url, unicode):
801
url = url.encode('ascii')
802
except UnicodeEncodeError:
803
raise errors.InvalidURL(url,
804
"Urls must be 7-bit ascii, "
805
"use breezy.urlutils.escape")
806
url = urlutils.relative_url(self.base, url)
807
self._set_parent_location(url)
810
def set_stacked_on_url(self, url):
811
"""Set the URL this branch is stacked against.
813
:raises UnstackableBranchFormat: If the branch does not support
815
:raises UnstackableRepositoryFormat: If the repository does not support
818
if not self._format.supports_stacking():
819
raise errors.UnstackableBranchFormat(self._format, self.user_url)
820
# XXX: Changing from one fallback repository to another does not check
821
# that all the data you need is present in the new fallback.
822
# Possibly it should.
823
self._check_stackable_repo()
826
old_url = self.get_stacked_on_url()
827
except (errors.NotStacked, errors.UnstackableBranchFormat,
828
errors.UnstackableRepositoryFormat):
832
self._activate_fallback_location(url,
833
possible_transports=[self.controldir.root_transport])
834
# write this out after the repository is stacked to avoid setting a
835
# stacked config that doesn't work.
836
self._set_config_location('stacked_on_location', url)
839
"""Change a branch to be unstacked, copying data as needed.
841
Don't call this directly, use set_stacked_on_url(None).
843
pb = ui.ui_factory.nested_progress_bar()
845
pb.update(gettext("Unstacking"))
846
# The basic approach here is to fetch the tip of the branch,
847
# including all available ghosts, from the existing stacked
848
# repository into a new repository object without the fallbacks.
850
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
851
# correct for CHKMap repostiories
852
old_repository = self.repository
853
if len(old_repository._fallback_repositories) != 1:
854
raise AssertionError("can't cope with fallback repositories "
855
"of %r (fallbacks: %r)" % (old_repository,
856
old_repository._fallback_repositories))
857
# Open the new repository object.
858
# Repositories don't offer an interface to remove fallback
859
# repositories today; take the conceptually simpler option and just
860
# reopen it. We reopen it starting from the URL so that we
861
# get a separate connection for RemoteRepositories and can
862
# stream from one of them to the other. This does mean doing
863
# separate SSH connection setup, but unstacking is not a
864
# common operation so it's tolerable.
865
new_bzrdir = controldir.ControlDir.open(
866
self.controldir.root_transport.base)
867
new_repository = new_bzrdir.find_repository()
868
if new_repository._fallback_repositories:
869
raise AssertionError("didn't expect %r to have "
870
"fallback_repositories"
871
% (self.repository,))
872
# Replace self.repository with the new repository.
873
# Do our best to transfer the lock state (i.e. lock-tokens and
874
# lock count) of self.repository to the new repository.
875
lock_token = old_repository.lock_write().repository_token
876
self.repository = new_repository
877
if isinstance(self, remote.RemoteBranch):
878
# Remote branches can have a second reference to the old
879
# repository that need to be replaced.
880
if self._real_branch is not None:
881
self._real_branch.repository = new_repository
882
self.repository.lock_write(token=lock_token)
883
if lock_token is not None:
884
old_repository.leave_lock_in_place()
885
old_repository.unlock()
886
if lock_token is not None:
887
# XXX: self.repository.leave_lock_in_place() before this
888
# function will not be preserved. Fortunately that doesn't
889
# affect the current default format (2a), and would be a
890
# corner-case anyway.
891
# - Andrew Bennetts, 2010/06/30
892
self.repository.dont_leave_lock_in_place()
896
old_repository.unlock()
897
except errors.LockNotHeld:
900
if old_lock_count == 0:
901
raise AssertionError(
902
'old_repository should have been locked at least once.')
903
for i in range(old_lock_count-1):
904
self.repository.lock_write()
905
# Fetch from the old repository into the new.
906
old_repository.lock_read()
908
# XXX: If you unstack a branch while it has a working tree
909
# with a pending merge, the pending-merged revisions will no
910
# longer be present. You can (probably) revert and remerge.
912
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
913
except errors.TagsNotSupported:
914
tags_to_fetch = set()
915
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
916
old_repository, required_ids=[self.last_revision()],
917
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
918
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
920
old_repository.unlock()
924
def _set_tags_bytes(self, bytes):
925
"""Mirror method for _get_tags_bytes.
927
:seealso: Branch._get_tags_bytes.
929
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
930
op.add_cleanup(self.lock_write().unlock)
931
return op.run_simple(bytes)
933
def _set_tags_bytes_locked(self, bytes):
934
self._tags_bytes = bytes
935
return self._transport.put_bytes('tags', bytes)
937
def _cache_revision_history(self, rev_history):
938
"""Set the cached revision history to rev_history.
940
The revision_history method will use this cache to avoid regenerating
941
the revision history.
943
This API is semi-public; it only for use by subclasses, all other code
944
should consider it to be private.
946
self._revision_history_cache = rev_history
948
def _cache_revision_id_to_revno(self, revision_id_to_revno):
949
"""Set the cached revision_id => revno map to revision_id_to_revno.
951
This API is semi-public; it only for use by subclasses, all other code
952
should consider it to be private.
954
self._revision_id_to_revno_cache = revision_id_to_revno
956
def _clear_cached_state(self):
957
"""Clear any cached data on this branch, e.g. cached revision history.
959
This means the next call to revision_history will need to call
960
_gen_revision_history.
962
This API is semi-public; it is only for use by subclasses, all other
963
code should consider it to be private.
965
self._revision_history_cache = None
966
self._revision_id_to_revno_cache = None
967
self._last_revision_info_cache = None
968
self._master_branch_cache = None
969
self._merge_sorted_revisions_cache = None
970
self._partial_revision_history_cache = []
971
self._partial_revision_id_to_revno_cache = {}
972
self._tags_bytes = None
974
def _gen_revision_history(self):
975
"""Return sequence of revision hashes on to this branch.
977
Unlike revision_history, this method always regenerates or rereads the
978
revision history, i.e. it does not cache the result, so repeated calls
981
Concrete subclasses should override this instead of revision_history so
982
that subclasses do not need to deal with caching logic.
984
This API is semi-public; it only for use by subclasses, all other code
985
should consider it to be private.
987
raise NotImplementedError(self._gen_revision_history)
989
def _revision_history(self):
990
if 'evil' in debug.debug_flags:
991
mutter_callsite(3, "revision_history scales with history.")
992
if self._revision_history_cache is not None:
993
history = self._revision_history_cache
995
history = self._gen_revision_history()
996
self._cache_revision_history(history)
1000
"""Return current revision number for this branch.
1002
That is equivalent to the number of revisions committed to
1005
return self.last_revision_info()[0]
1008
"""Older format branches cannot bind or unbind."""
1009
raise errors.UpgradeRequired(self.user_url)
1011
def last_revision(self):
1012
"""Return last revision id, or NULL_REVISION."""
1013
return self.last_revision_info()[1]
1016
def last_revision_info(self):
1017
"""Return information about the last revision.
1019
:return: A tuple (revno, revision_id).
1021
if self._last_revision_info_cache is None:
1022
self._last_revision_info_cache = self._read_last_revision_info()
1023
return self._last_revision_info_cache
1025
def _read_last_revision_info(self):
1026
raise NotImplementedError(self._read_last_revision_info)
1028
def import_last_revision_info_and_tags(self, source, revno, revid,
1030
"""Set the last revision info, importing from another repo if necessary.
1032
This is used by the bound branch code to upload a revision to
1033
the master branch first before updating the tip of the local branch.
1034
Revisions referenced by source's tags are also transferred.
1036
:param source: Source branch to optionally fetch from
1037
:param revno: Revision number of the new tip
1038
:param revid: Revision id of the new tip
1039
:param lossy: Whether to discard metadata that can not be
1040
natively represented
1041
:return: Tuple with the new revision number and revision id
1042
(should only be different from the arguments when lossy=True)
1044
if not self.repository.has_same_location(source.repository):
1045
self.fetch(source, revid)
1046
self.set_last_revision_info(revno, revid)
1047
return (revno, revid)
1049
def revision_id_to_revno(self, revision_id):
1050
"""Given a revision id, return its revno"""
1051
if _mod_revision.is_null(revision_id):
1053
history = self._revision_history()
1055
return history.index(revision_id) + 1
1057
raise errors.NoSuchRevision(self, revision_id)
1060
def get_rev_id(self, revno, history=None):
1061
"""Find the revision id of the specified revno."""
1063
return _mod_revision.NULL_REVISION
1064
last_revno, last_revid = self.last_revision_info()
1065
if revno == last_revno:
1067
if revno <= 0 or revno > last_revno:
1068
raise errors.NoSuchRevision(self, revno)
1069
distance_from_last = last_revno - revno
1070
if len(self._partial_revision_history_cache) <= distance_from_last:
1071
self._extend_partial_history(distance_from_last)
1072
return self._partial_revision_history_cache[distance_from_last]
1074
def pull(self, source, overwrite=False, stop_revision=None,
1075
possible_transports=None, *args, **kwargs):
1076
"""Mirror source into this branch.
1078
This branch is considered to be 'local', having low latency.
1080
:returns: PullResult instance
1082
return InterBranch.get(source, self).pull(overwrite=overwrite,
1083
stop_revision=stop_revision,
1084
possible_transports=possible_transports, *args, **kwargs)
1086
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1088
"""Mirror this branch into target.
1090
This branch is considered to be 'local', having low latency.
1092
return InterBranch.get(self, target).push(overwrite, stop_revision,
1093
lossy, *args, **kwargs)
1095
def basis_tree(self):
1096
"""Return `Tree` object for last revision."""
1097
return self.repository.revision_tree(self.last_revision())
1099
def get_parent(self):
1100
"""Return the parent location of the branch.
1102
This is the default location for pull/missing. The usual
1103
pattern is that the user can override it by specifying a
1106
parent = self._get_parent_location()
1109
# This is an old-format absolute path to a local branch
1110
# turn it into a url
1111
if parent.startswith('/'):
1112
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1114
return urlutils.join(self.base[:-1], parent)
1115
except errors.InvalidURLJoin as e:
1116
raise errors.InaccessibleParent(parent, self.user_url)
1118
def _get_parent_location(self):
1119
raise NotImplementedError(self._get_parent_location)
1121
def _set_config_location(self, name, url, config=None,
1122
make_relative=False):
1124
config = self.get_config_stack()
1128
url = urlutils.relative_url(self.base, url)
1129
config.set(name, url)
1131
def _get_config_location(self, name, config=None):
1133
config = self.get_config_stack()
1134
location = config.get(name)
1139
def get_child_submit_format(self):
1140
"""Return the preferred format of submissions to this branch."""
1141
return self.get_config_stack().get('child_submit_format')
1143
def get_submit_branch(self):
1144
"""Return the submit location of the branch.
1146
This is the default location for bundle. The usual
1147
pattern is that the user can override it by specifying a
1150
return self.get_config_stack().get('submit_branch')
1152
def set_submit_branch(self, location):
1153
"""Return the submit location of the branch.
1155
This is the default location for bundle. The usual
1156
pattern is that the user can override it by specifying a
1159
self.get_config_stack().set('submit_branch', location)
1161
def get_public_branch(self):
1162
"""Return the public location of the branch.
1164
This is used by merge directives.
1166
return self._get_config_location('public_branch')
1168
def set_public_branch(self, location):
1169
"""Return the submit location of the branch.
1171
This is the default location for bundle. The usual
1172
pattern is that the user can override it by specifying a
1175
self._set_config_location('public_branch', location)
1177
def get_push_location(self):
1178
"""Return None or the location to push this branch to."""
1179
return self.get_config_stack().get('push_location')
1181
def set_push_location(self, location):
1182
"""Set a new push location for this branch."""
1183
raise NotImplementedError(self.set_push_location)
1185
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1186
"""Run the post_change_branch_tip hooks."""
1187
hooks = Branch.hooks['post_change_branch_tip']
1190
new_revno, new_revid = self.last_revision_info()
1191
params = ChangeBranchTipParams(
1192
self, old_revno, new_revno, old_revid, new_revid)
1196
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1197
"""Run the pre_change_branch_tip hooks."""
1198
hooks = Branch.hooks['pre_change_branch_tip']
1201
old_revno, old_revid = self.last_revision_info()
1202
params = ChangeBranchTipParams(
1203
self, old_revno, new_revno, old_revid, new_revid)
1209
"""Synchronise this branch with the master branch if any.
1211
:return: None or the last_revision pivoted out during the update.
1215
def check_revno(self, revno):
1217
Check whether a revno corresponds to any revision.
1218
Zero (the NULL revision) is considered valid.
1221
self.check_real_revno(revno)
1223
def check_real_revno(self, revno):
1225
Check whether a revno corresponds to a real revision.
1226
Zero (the NULL revision) is considered invalid
1228
if revno < 1 or revno > self.revno():
1229
raise errors.InvalidRevisionNumber(revno)
1232
def clone(self, to_controldir, revision_id=None, repository_policy=None):
1233
"""Clone this branch into to_controldir preserving all semantic values.
1235
Most API users will want 'create_clone_on_transport', which creates a
1236
new bzrdir and branch on the fly.
1238
revision_id: if not None, the revision history in the new branch will
1239
be truncated to end with revision_id.
1241
result = to_controldir.create_branch()
1244
if repository_policy is not None:
1245
repository_policy.configure_branch(result)
1246
self.copy_content_into(result, revision_id=revision_id)
1252
def sprout(self, to_controldir, revision_id=None, repository_policy=None,
1254
"""Create a new line of development from the branch, into to_controldir.
1256
to_controldir controls the branch format.
1258
revision_id: if not None, the revision history in the new branch will
1259
be truncated to end with revision_id.
1261
if (repository_policy is not None and
1262
repository_policy.requires_stacking()):
1263
to_controldir._format.require_stacking(_skip_repo=True)
1264
result = to_controldir.create_branch(repository=repository)
1267
if repository_policy is not None:
1268
repository_policy.configure_branch(result)
1269
self.copy_content_into(result, revision_id=revision_id)
1270
master_url = self.get_bound_location()
1271
if master_url is None:
1272
result.set_parent(self.controldir.root_transport.base)
1274
result.set_parent(master_url)
1279
def _synchronize_history(self, destination, revision_id):
1280
"""Synchronize last revision and revision history between branches.
1282
This version is most efficient when the destination is also a
1283
BzrBranch6, but works for BzrBranch5, as long as the destination's
1284
repository contains all the lefthand ancestors of the intended
1285
last_revision. If not, set_last_revision_info will fail.
1287
:param destination: The branch to copy the history into
1288
:param revision_id: The revision-id to truncate history at. May
1289
be None to copy complete history.
1291
source_revno, source_revision_id = self.last_revision_info()
1292
if revision_id is None:
1293
revno, revision_id = source_revno, source_revision_id
1295
graph = self.repository.get_graph()
1297
revno = graph.find_distance_to_null(revision_id,
1298
[(source_revision_id, source_revno)])
1299
except errors.GhostRevisionsHaveNoRevno:
1300
# Default to 1, if we can't find anything else
1302
destination.set_last_revision_info(revno, revision_id)
1304
def copy_content_into(self, destination, revision_id=None):
1305
"""Copy the content of self into destination.
1307
revision_id: if not None, the revision history in the new branch will
1308
be truncated to end with revision_id.
1310
return InterBranch.get(self, destination).copy_content_into(
1311
revision_id=revision_id)
1313
def update_references(self, target):
1314
if not getattr(self._format, 'supports_reference_locations', False):
1316
reference_dict = self._get_all_reference_info()
1317
if len(reference_dict) == 0:
1319
old_base = self.base
1320
new_base = target.base
1321
target_reference_dict = target._get_all_reference_info()
1322
for file_id, (tree_path, branch_location) in viewitems(reference_dict):
1323
branch_location = urlutils.rebase_url(branch_location,
1325
target_reference_dict.setdefault(
1326
file_id, (tree_path, branch_location))
1327
target._set_all_reference_info(target_reference_dict)
1330
def check(self, refs):
1331
"""Check consistency of the branch.
1333
In particular this checks that revisions given in the revision-history
1334
do actually match up in the revision graph, and that they're all
1335
present in the repository.
1337
Callers will typically also want to check the repository.
1339
:param refs: Calculated refs for this branch as specified by
1340
branch._get_check_refs()
1341
:return: A BranchCheckResult.
1343
result = BranchCheckResult(self)
1344
last_revno, last_revision_id = self.last_revision_info()
1345
actual_revno = refs[('lefthand-distance', last_revision_id)]
1346
if actual_revno != last_revno:
1347
result.errors.append(errors.BzrCheckError(
1348
'revno does not match len(mainline) %s != %s' % (
1349
last_revno, actual_revno)))
1350
# TODO: We should probably also check that self.revision_history
1351
# matches the repository for older branch formats.
1352
# If looking for the code that cross-checks repository parents against
1353
# the Graph.iter_lefthand_ancestry output, that is now a repository
1357
def _get_checkout_format(self, lightweight=False):
1358
"""Return the most suitable metadir for a checkout of this branch.
1359
Weaves are used if this branch's repository uses weaves.
1361
format = self.repository.controldir.checkout_metadir()
1362
format.set_branch_format(self._format)
1365
def create_clone_on_transport(self, to_transport, revision_id=None,
1366
stacked_on=None, create_prefix=False, use_existing_dir=False,
1368
"""Create a clone of this branch and its bzrdir.
1370
:param to_transport: The transport to clone onto.
1371
:param revision_id: The revision id to use as tip in the new branch.
1372
If None the tip is obtained from this branch.
1373
:param stacked_on: An optional URL to stack the clone on.
1374
:param create_prefix: Create any missing directories leading up to
1376
:param use_existing_dir: Use an existing directory if one exists.
1378
# XXX: Fix the bzrdir API to allow getting the branch back from the
1379
# clone call. Or something. 20090224 RBC/spiv.
1380
# XXX: Should this perhaps clone colocated branches as well,
1381
# rather than just the default branch? 20100319 JRV
1382
if revision_id is None:
1383
revision_id = self.last_revision()
1384
dir_to = self.controldir.clone_on_transport(to_transport,
1385
revision_id=revision_id, stacked_on=stacked_on,
1386
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1388
return dir_to.open_branch()
1390
def create_checkout(self, to_location, revision_id=None,
1391
lightweight=False, accelerator_tree=None,
1393
"""Create a checkout of a branch.
1395
:param to_location: The url to produce the checkout at
1396
:param revision_id: The revision to check out
1397
:param lightweight: If True, produce a lightweight checkout, otherwise,
1398
produce a bound branch (heavyweight checkout)
1399
:param accelerator_tree: A tree which can be used for retrieving file
1400
contents more quickly than the revision tree, i.e. a workingtree.
1401
The revision tree will be used for cases where accelerator_tree's
1402
content is different.
1403
:param hardlink: If true, hard-link files from accelerator_tree,
1405
:return: The tree of the created checkout
1407
t = transport.get_transport(to_location)
1409
format = self._get_checkout_format(lightweight=lightweight)
1411
checkout = format.initialize_on_transport(t)
1412
except errors.AlreadyControlDirError:
1413
# It's fine if the control directory already exists,
1414
# as long as there is no existing branch and working tree.
1415
checkout = controldir.ControlDir.open_from_transport(t)
1417
checkout.open_branch()
1418
except errors.NotBranchError:
1421
raise errors.AlreadyControlDirError(t.base)
1422
if checkout.control_transport.base == self.controldir.control_transport.base:
1423
# When checking out to the same control directory,
1424
# always create a lightweight checkout
1428
from_branch = checkout.set_branch_reference(target_branch=self)
1430
policy = checkout.determine_repository_policy()
1431
repo = policy.acquire_repository()[0]
1432
checkout_branch = checkout.create_branch()
1433
checkout_branch.bind(self)
1434
# pull up to the specified revision_id to set the initial
1435
# branch tip correctly, and seed it with history.
1436
checkout_branch.pull(self, stop_revision=revision_id)
1438
tree = checkout.create_workingtree(revision_id,
1439
from_branch=from_branch,
1440
accelerator_tree=accelerator_tree,
1442
basis_tree = tree.basis_tree()
1443
basis_tree.lock_read()
1445
for path, file_id in basis_tree.iter_references():
1446
reference_parent = self.reference_parent(file_id, path)
1447
reference_parent.create_checkout(tree.abspath(path),
1448
basis_tree.get_reference_revision(file_id, path),
1455
def reconcile(self, thorough=True):
1456
"""Make sure the data stored in this branch is consistent."""
1457
from breezy.reconcile import BranchReconciler
1458
reconciler = BranchReconciler(self, thorough=thorough)
1459
reconciler.reconcile()
1462
def reference_parent(self, file_id, path, possible_transports=None):
1463
"""Return the parent branch for a tree-reference file_id
1465
:param file_id: The file_id of the tree reference
1466
:param path: The path of the file_id in the tree
1467
:return: A branch associated with the file_id
1469
# FIXME should provide multiple branches, based on config
1470
return Branch.open(self.controldir.root_transport.clone(path).base,
1471
possible_transports=possible_transports)
1473
def supports_tags(self):
1474
return self._format.supports_tags()
1476
def automatic_tag_name(self, revision_id):
1477
"""Try to automatically find the tag name for a revision.
1479
:param revision_id: Revision id of the revision.
1480
:return: A tag name or None if no tag name could be determined.
1482
for hook in Branch.hooks['automatic_tag_name']:
1483
ret = hook(self, revision_id)
1488
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1490
"""Ensure that revision_b is a descendant of revision_a.
1492
This is a helper function for update_revisions.
1494
:raises: DivergedBranches if revision_b has diverged from revision_a.
1495
:returns: True if revision_b is a descendant of revision_a.
1497
relation = self._revision_relations(revision_a, revision_b, graph)
1498
if relation == 'b_descends_from_a':
1500
elif relation == 'diverged':
1501
raise errors.DivergedBranches(self, other_branch)
1502
elif relation == 'a_descends_from_b':
1505
raise AssertionError("invalid relation: %r" % (relation,))
1507
def _revision_relations(self, revision_a, revision_b, graph):
1508
"""Determine the relationship between two revisions.
1510
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1512
heads = graph.heads([revision_a, revision_b])
1513
if heads == {revision_b}:
1514
return 'b_descends_from_a'
1515
elif heads == {revision_a, revision_b}:
1516
# These branches have diverged
1518
elif heads == {revision_a}:
1519
return 'a_descends_from_b'
1521
raise AssertionError("invalid heads: %r" % (heads,))
1523
def heads_to_fetch(self):
1524
"""Return the heads that must and that should be fetched to copy this
1525
branch into another repo.
1527
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1528
set of heads that must be fetched. if_present_fetch is a set of
1529
heads that must be fetched if present, but no error is necessary if
1530
they are not present.
1532
# For bzr native formats must_fetch is just the tip, and
1533
# if_present_fetch are the tags.
1534
must_fetch = {self.last_revision()}
1535
if_present_fetch = set()
1536
if self.get_config_stack().get('branch.fetch_tags'):
1538
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1539
except errors.TagsNotSupported:
1541
must_fetch.discard(_mod_revision.NULL_REVISION)
1542
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1543
return must_fetch, if_present_fetch
1546
class BranchFormat(controldir.ControlComponentFormat):
1547
"""An encapsulation of the initialization and open routines for a format.
1549
Formats provide three things:
1550
* An initialization routine,
1551
* a format description
1554
Formats are placed in an dict by their format string for reference
1555
during branch opening. It's not required that these be instances, they
1556
can be classes themselves with class methods - it simply depends on
1557
whether state is needed for a given format or not.
1559
Once a format is deprecated, just deprecate the initialize and open
1560
methods on the format class. Do not deprecate the object, as the
1561
object will be created every time regardless.
1564
def __eq__(self, other):
1565
return self.__class__ is other.__class__
1567
def __ne__(self, other):
1568
return not (self == other)
1570
def get_reference(self, controldir, name=None):
1571
"""Get the target reference of the branch in controldir.
1573
format probing must have been completed before calling
1574
this method - it is assumed that the format of the branch
1575
in controldir is correct.
1577
:param controldir: The controldir to get the branch data from.
1578
:param name: Name of the colocated branch to fetch
1579
:return: None if the branch is not a reference branch.
1584
def set_reference(self, controldir, name, to_branch):
1585
"""Set the target reference of the branch in controldir.
1587
format probing must have been completed before calling
1588
this method - it is assumed that the format of the branch
1589
in controldir is correct.
1591
:param controldir: The controldir to set the branch reference for.
1592
:param name: Name of colocated branch to set, None for default
1593
:param to_branch: branch that the checkout is to reference
1595
raise NotImplementedError(self.set_reference)
1597
def get_format_description(self):
1598
"""Return the short format description for this format."""
1599
raise NotImplementedError(self.get_format_description)
1601
def _run_post_branch_init_hooks(self, controldir, name, branch):
1602
hooks = Branch.hooks['post_branch_init']
1605
params = BranchInitHookParams(self, controldir, name, branch)
1609
def initialize(self, controldir, name=None, repository=None,
1610
append_revisions_only=None):
1611
"""Create a branch of this format in controldir.
1613
:param name: Name of the colocated branch to create.
1615
raise NotImplementedError(self.initialize)
1617
def is_supported(self):
1618
"""Is this format supported?
1620
Supported formats can be initialized and opened.
1621
Unsupported formats may not support initialization or committing or
1622
some other features depending on the reason for not being supported.
1626
def make_tags(self, branch):
1627
"""Create a tags object for branch.
1629
This method is on BranchFormat, because BranchFormats are reflected
1630
over the wire via network_name(), whereas full Branch instances require
1631
multiple VFS method calls to operate at all.
1633
The default implementation returns a disabled-tags instance.
1635
Note that it is normal for branch to be a RemoteBranch when using tags
1638
return _mod_tag.DisabledTags(branch)
1640
def network_name(self):
1641
"""A simple byte string uniquely identifying this format for RPC calls.
1643
MetaDir branch formats use their disk format string to identify the
1644
repository over the wire. All in one formats such as bzr < 0.8, and
1645
foreign formats like svn/git and hg should use some marker which is
1646
unique and immutable.
1648
raise NotImplementedError(self.network_name)
1650
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1651
found_repository=None, possible_transports=None):
1652
"""Return the branch object for controldir.
1654
:param controldir: A ControlDir that contains a branch.
1655
:param name: Name of colocated branch to open
1656
:param _found: a private parameter, do not use it. It is used to
1657
indicate if format probing has already be done.
1658
:param ignore_fallbacks: when set, no fallback branches will be opened
1659
(if there are any). Default is to open fallbacks.
1661
raise NotImplementedError(self.open)
1663
def supports_set_append_revisions_only(self):
1664
"""True if this format supports set_append_revisions_only."""
1667
def supports_stacking(self):
1668
"""True if this format records a stacked-on branch."""
1671
def supports_leaving_lock(self):
1672
"""True if this format supports leaving locks in place."""
1673
return False # by default
1676
return self.get_format_description().rstrip()
1678
def supports_tags(self):
1679
"""True if this format supports tags stored in the branch"""
1680
return False # by default
1682
def tags_are_versioned(self):
1683
"""Whether the tag container for this branch versions tags."""
1686
def supports_tags_referencing_ghosts(self):
1687
"""True if tags can reference ghost revisions."""
1691
class BranchHooks(Hooks):
1692
"""A dictionary mapping hook name to a list of callables for branch hooks.
1694
e.g. ['post_push'] Is the list of items to be called when the
1695
push function is invoked.
1699
"""Create the default hooks.
1701
These are all empty initially, because by default nothing should get
1704
Hooks.__init__(self, "breezy.branch", "Branch.hooks")
1705
self.add_hook('open',
1706
"Called with the Branch object that has been opened after a "
1707
"branch is opened.", (1, 8))
1708
self.add_hook('post_push',
1709
"Called after a push operation completes. post_push is called "
1710
"with a breezy.branch.BranchPushResult object and only runs in the "
1711
"bzr client.", (0, 15))
1712
self.add_hook('post_pull',
1713
"Called after a pull operation completes. post_pull is called "
1714
"with a breezy.branch.PullResult object and only runs in the "
1715
"bzr client.", (0, 15))
1716
self.add_hook('pre_commit',
1717
"Called after a commit is calculated but before it is "
1718
"completed. pre_commit is called with (local, master, old_revno, "
1719
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1720
"). old_revid is NULL_REVISION for the first commit to a branch, "
1721
"tree_delta is a TreeDelta object describing changes from the "
1722
"basis revision. hooks MUST NOT modify this delta. "
1723
" future_tree is an in-memory tree obtained from "
1724
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1726
self.add_hook('post_commit',
1727
"Called in the bzr client after a commit has completed. "
1728
"post_commit is called with (local, master, old_revno, old_revid, "
1729
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1730
"commit to a branch.", (0, 15))
1731
self.add_hook('post_uncommit',
1732
"Called in the bzr client after an uncommit completes. "
1733
"post_uncommit is called with (local, master, old_revno, "
1734
"old_revid, new_revno, new_revid) where local is the local branch "
1735
"or None, master is the target branch, and an empty branch "
1736
"receives new_revno of 0, new_revid of None.", (0, 15))
1737
self.add_hook('pre_change_branch_tip',
1738
"Called in bzr client and server before a change to the tip of a "
1739
"branch is made. pre_change_branch_tip is called with a "
1740
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1741
"commit, uncommit will all trigger this hook.", (1, 6))
1742
self.add_hook('post_change_branch_tip',
1743
"Called in bzr client and server after a change to the tip of a "
1744
"branch is made. post_change_branch_tip is called with a "
1745
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1746
"commit, uncommit will all trigger this hook.", (1, 4))
1747
self.add_hook('transform_fallback_location',
1748
"Called when a stacked branch is activating its fallback "
1749
"locations. transform_fallback_location is called with (branch, "
1750
"url), and should return a new url. Returning the same url "
1751
"allows it to be used as-is, returning a different one can be "
1752
"used to cause the branch to stack on a closer copy of that "
1753
"fallback_location. Note that the branch cannot have history "
1754
"accessing methods called on it during this hook because the "
1755
"fallback locations have not been activated. When there are "
1756
"multiple hooks installed for transform_fallback_location, "
1757
"all are called with the url returned from the previous hook."
1758
"The order is however undefined.", (1, 9))
1759
self.add_hook('automatic_tag_name',
1760
"Called to determine an automatic tag name for a revision. "
1761
"automatic_tag_name is called with (branch, revision_id) and "
1762
"should return a tag name or None if no tag name could be "
1763
"determined. The first non-None tag name returned will be used.",
1765
self.add_hook('post_branch_init',
1766
"Called after new branch initialization completes. "
1767
"post_branch_init is called with a "
1768
"breezy.branch.BranchInitHookParams. "
1769
"Note that init, branch and checkout (both heavyweight and "
1770
"lightweight) will all trigger this hook.", (2, 2))
1771
self.add_hook('post_switch',
1772
"Called after a checkout switches branch. "
1773
"post_switch is called with a "
1774
"breezy.branch.SwitchHookParams.", (2, 2))
1778
# install the default hooks into the Branch class.
1779
Branch.hooks = BranchHooks()
1782
class ChangeBranchTipParams(object):
1783
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1785
There are 5 fields that hooks may wish to access:
1787
:ivar branch: the branch being changed
1788
:ivar old_revno: revision number before the change
1789
:ivar new_revno: revision number after the change
1790
:ivar old_revid: revision id before the change
1791
:ivar new_revid: revision id after the change
1793
The revid fields are strings. The revno fields are integers.
1796
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1797
"""Create a group of ChangeBranchTip parameters.
1799
:param branch: The branch being changed.
1800
:param old_revno: Revision number before the change.
1801
:param new_revno: Revision number after the change.
1802
:param old_revid: Tip revision id before the change.
1803
:param new_revid: Tip revision id after the change.
1805
self.branch = branch
1806
self.old_revno = old_revno
1807
self.new_revno = new_revno
1808
self.old_revid = old_revid
1809
self.new_revid = new_revid
1811
def __eq__(self, other):
1812
return self.__dict__ == other.__dict__
1815
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1816
self.__class__.__name__, self.branch,
1817
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1820
class BranchInitHookParams(object):
1821
"""Object holding parameters passed to `*_branch_init` hooks.
1823
There are 4 fields that hooks may wish to access:
1825
:ivar format: the branch format
1826
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1827
:ivar name: name of colocated branch, if any (or None)
1828
:ivar branch: the branch created
1830
Note that for lightweight checkouts, the bzrdir and format fields refer to
1831
the checkout, hence they are different from the corresponding fields in
1832
branch, which refer to the original branch.
1835
def __init__(self, format, controldir, name, branch):
1836
"""Create a group of BranchInitHook parameters.
1838
:param format: the branch format
1839
:param controldir: the ControlDir where the branch will be/has been
1841
:param name: name of colocated branch, if any (or None)
1842
:param branch: the branch created
1844
Note that for lightweight checkouts, the bzrdir and format fields refer
1845
to the checkout, hence they are different from the corresponding fields
1846
in branch, which refer to the original branch.
1848
self.format = format
1849
self.controldir = controldir
1851
self.branch = branch
1853
def __eq__(self, other):
1854
return self.__dict__ == other.__dict__
1857
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1860
class SwitchHookParams(object):
1861
"""Object holding parameters passed to `*_switch` hooks.
1863
There are 4 fields that hooks may wish to access:
1865
:ivar control_dir: ControlDir of the checkout to change
1866
:ivar to_branch: branch that the checkout is to reference
1867
:ivar force: skip the check for local commits in a heavy checkout
1868
:ivar revision_id: revision ID to switch to (or None)
1871
def __init__(self, control_dir, to_branch, force, revision_id):
1872
"""Create a group of SwitchHook parameters.
1874
:param control_dir: ControlDir of the checkout to change
1875
:param to_branch: branch that the checkout is to reference
1876
:param force: skip the check for local commits in a heavy checkout
1877
:param revision_id: revision ID to switch to (or None)
1879
self.control_dir = control_dir
1880
self.to_branch = to_branch
1882
self.revision_id = revision_id
1884
def __eq__(self, other):
1885
return self.__dict__ == other.__dict__
1888
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1889
self.control_dir, self.to_branch,
1893
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
1894
"""Branch format registry."""
1896
def __init__(self, other_registry=None):
1897
super(BranchFormatRegistry, self).__init__(other_registry)
1898
self._default_format = None
1899
self._default_format_key = None
1901
def get_default(self):
1902
"""Return the current default format."""
1903
if (self._default_format_key is not None and
1904
self._default_format is None):
1905
self._default_format = self.get(self._default_format_key)
1906
return self._default_format
1908
def set_default(self, format):
1909
"""Set the default format."""
1910
self._default_format = format
1911
self._default_format_key = None
1913
def set_default_key(self, format_string):
1914
"""Set the default format by its format string."""
1915
self._default_format_key = format_string
1916
self._default_format = None
1919
network_format_registry = registry.FormatRegistry()
1920
"""Registry of formats indexed by their network name.
1922
The network name for a branch format is an identifier that can be used when
1923
referring to formats with smart server operations. See
1924
BranchFormat.network_name() for more detail.
1927
format_registry = BranchFormatRegistry(network_format_registry)
1930
# formats which have no format string are not discoverable
1931
# and not independently creatable, so are not registered.
1932
format_registry.register_lazy(
1933
"Bazaar-NG branch format 5\n", "breezy.bzr.fullhistory",
1935
format_registry.register_lazy(
1936
"Bazaar Branch Format 6 (bzr 0.15)\n",
1937
"breezy.bzr.branch", "BzrBranchFormat6")
1938
format_registry.register_lazy(
1939
"Bazaar Branch Format 7 (needs bzr 1.6)\n",
1940
"breezy.bzr.branch", "BzrBranchFormat7")
1941
format_registry.register_lazy(
1942
"Bazaar Branch Format 8 (needs bzr 1.15)\n",
1943
"breezy.bzr.branch", "BzrBranchFormat8")
1944
format_registry.register_lazy(
1945
"Bazaar-NG Branch Reference Format 1\n",
1946
"breezy.bzr.branch", "BranchReferenceFormat")
1948
format_registry.set_default_key("Bazaar Branch Format 7 (needs bzr 1.6)\n")
1951
class BranchWriteLockResult(LogicalLockResult):
1952
"""The result of write locking a branch.
1954
:ivar branch_token: The token obtained from the underlying branch lock, or
1956
:ivar unlock: A callable which will unlock the lock.
1959
def __init__(self, unlock, branch_token):
1960
LogicalLockResult.__init__(self, unlock)
1961
self.branch_token = branch_token
1964
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
1968
######################################################################
1969
# results of operations
1972
class _Result(object):
1974
def _show_tag_conficts(self, to_file):
1975
if not getattr(self, 'tag_conflicts', None):
1977
to_file.write('Conflicting tags:\n')
1978
for name, value1, value2 in self.tag_conflicts:
1979
to_file.write(' %s\n' % (name, ))
1982
class PullResult(_Result):
1983
"""Result of a Branch.pull operation.
1985
:ivar old_revno: Revision number before pull.
1986
:ivar new_revno: Revision number after pull.
1987
:ivar old_revid: Tip revision id before pull.
1988
:ivar new_revid: Tip revision id after pull.
1989
:ivar source_branch: Source (local) branch object. (read locked)
1990
:ivar master_branch: Master branch of the target, or the target if no
1992
:ivar local_branch: target branch if there is a Master, else None
1993
:ivar target_branch: Target/destination branch object. (write locked)
1994
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
1995
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
1998
def report(self, to_file):
1999
tag_conflicts = getattr(self, "tag_conflicts", None)
2000
tag_updates = getattr(self, "tag_updates", None)
2002
if self.old_revid != self.new_revid:
2003
to_file.write('Now on revision %d.\n' % self.new_revno)
2005
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
2006
if self.old_revid == self.new_revid and not tag_updates:
2007
if not tag_conflicts:
2008
to_file.write('No revisions or tags to pull.\n')
2010
to_file.write('No revisions to pull.\n')
2011
self._show_tag_conficts(to_file)
2014
class BranchPushResult(_Result):
2015
"""Result of a Branch.push operation.
2017
:ivar old_revno: Revision number (eg 10) of the target before push.
2018
:ivar new_revno: Revision number (eg 12) of the target after push.
2019
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
2021
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
2023
:ivar source_branch: Source branch object that the push was from. This is
2024
read locked, and generally is a local (and thus low latency) branch.
2025
:ivar master_branch: If target is a bound branch, the master branch of
2026
target, or target itself. Always write locked.
2027
:ivar target_branch: The direct Branch where data is being sent (write
2029
:ivar local_branch: If the target is a bound branch this will be the
2030
target, otherwise it will be None.
2033
def report(self, to_file):
2034
# TODO: This function gets passed a to_file, but then
2035
# ignores it and calls note() instead. This is also
2036
# inconsistent with PullResult(), which writes to stdout.
2037
# -- JRV20110901, bug #838853
2038
tag_conflicts = getattr(self, "tag_conflicts", None)
2039
tag_updates = getattr(self, "tag_updates", None)
2041
if self.old_revid != self.new_revid:
2042
note(gettext('Pushed up to revision %d.') % self.new_revno)
2044
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
2045
if self.old_revid == self.new_revid and not tag_updates:
2046
if not tag_conflicts:
2047
note(gettext('No new revisions or tags to push.'))
2049
note(gettext('No new revisions to push.'))
2050
self._show_tag_conficts(to_file)
2053
class BranchCheckResult(object):
2054
"""Results of checking branch consistency.
2059
def __init__(self, branch):
2060
self.branch = branch
2063
def report_results(self, verbose):
2064
"""Report the check results via trace.note.
2066
:param verbose: Requests more detailed display of what was checked,
2069
note(gettext('checked branch {0} format {1}').format(
2070
self.branch.user_url, self.branch._format))
2071
for error in self.errors:
2072
note(gettext('found error:%s'), error)
2075
class InterBranch(InterObject):
2076
"""This class represents operations taking place between two branches.
2078
Its instances have methods like pull() and push() and contain
2079
references to the source and target repositories these operations
2080
can be carried out on.
2084
"""The available optimised InterBranch types."""
2087
def _get_branch_formats_to_test(klass):
2088
"""Return an iterable of format tuples for testing.
2090
:return: An iterable of (from_format, to_format) to use when testing
2091
this InterBranch class. Each InterBranch class should define this
2094
raise NotImplementedError(klass._get_branch_formats_to_test)
2097
def pull(self, overwrite=False, stop_revision=None,
2098
possible_transports=None, local=False):
2099
"""Mirror source into target branch.
2101
The target branch is considered to be 'local', having low latency.
2103
:returns: PullResult instance
2105
raise NotImplementedError(self.pull)
2108
def push(self, overwrite=False, stop_revision=None, lossy=False,
2109
_override_hook_source_branch=None):
2110
"""Mirror the source branch into the target branch.
2112
The source branch is considered to be 'local', having low latency.
2114
raise NotImplementedError(self.push)
2117
def copy_content_into(self, revision_id=None):
2118
"""Copy the content of source into target
2120
revision_id: if not None, the revision history in the new branch will
2121
be truncated to end with revision_id.
2123
raise NotImplementedError(self.copy_content_into)
2126
def fetch(self, stop_revision=None, limit=None):
2129
:param stop_revision: Last revision to fetch
2130
:param limit: Optional rough limit of revisions to fetch
2132
raise NotImplementedError(self.fetch)
2135
def _fix_overwrite_type(overwrite):
2136
if isinstance(overwrite, bool):
2138
return ["history", "tags"]
2144
class GenericInterBranch(InterBranch):
2145
"""InterBranch implementation that uses public Branch functions."""
2148
def is_compatible(klass, source, target):
2149
# GenericBranch uses the public API, so always compatible
2153
def _get_branch_formats_to_test(klass):
2154
return [(format_registry.get_default(), format_registry.get_default())]
2157
def unwrap_format(klass, format):
2158
if isinstance(format, remote.RemoteBranchFormat):
2159
format._ensure_real()
2160
return format._custom_format
2164
def copy_content_into(self, revision_id=None):
2165
"""Copy the content of source into target
2167
revision_id: if not None, the revision history in the new branch will
2168
be truncated to end with revision_id.
2170
self.source.update_references(self.target)
2171
self.source._synchronize_history(self.target, revision_id)
2173
parent = self.source.get_parent()
2174
except errors.InaccessibleParent as e:
2175
mutter('parent was not accessible to copy: %s', e)
2178
self.target.set_parent(parent)
2179
if self.source._push_should_merge_tags():
2180
self.source.tags.merge_to(self.target.tags)
2183
def fetch(self, stop_revision=None, limit=None):
2184
if self.target.base == self.source.base:
2186
self.source.lock_read()
2188
fetch_spec_factory = fetch.FetchSpecFactory()
2189
fetch_spec_factory.source_branch = self.source
2190
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
2191
fetch_spec_factory.source_repo = self.source.repository
2192
fetch_spec_factory.target_repo = self.target.repository
2193
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
2194
fetch_spec_factory.limit = limit
2195
fetch_spec = fetch_spec_factory.make_fetch_spec()
2196
return self.target.repository.fetch(self.source.repository,
2197
fetch_spec=fetch_spec)
2199
self.source.unlock()
2202
def _update_revisions(self, stop_revision=None, overwrite=False,
2204
other_revno, other_last_revision = self.source.last_revision_info()
2205
stop_revno = None # unknown
2206
if stop_revision is None:
2207
stop_revision = other_last_revision
2208
if _mod_revision.is_null(stop_revision):
2209
# if there are no commits, we're done.
2211
stop_revno = other_revno
2213
# what's the current last revision, before we fetch [and change it
2215
last_rev = _mod_revision.ensure_null(self.target.last_revision())
2216
# we fetch here so that we don't process data twice in the common
2217
# case of having something to pull, and so that the check for
2218
# already merged can operate on the just fetched graph, which will
2219
# be cached in memory.
2220
self.fetch(stop_revision=stop_revision)
2221
# Check to see if one is an ancestor of the other
2224
graph = self.target.repository.get_graph()
2225
if self.target._check_if_descendant_or_diverged(
2226
stop_revision, last_rev, graph, self.source):
2227
# stop_revision is a descendant of last_rev, but we aren't
2228
# overwriting, so we're done.
2230
if stop_revno is None:
2232
graph = self.target.repository.get_graph()
2233
this_revno, this_last_revision = \
2234
self.target.last_revision_info()
2235
stop_revno = graph.find_distance_to_null(stop_revision,
2236
[(other_last_revision, other_revno),
2237
(this_last_revision, this_revno)])
2238
self.target.set_last_revision_info(stop_revno, stop_revision)
2241
def pull(self, overwrite=False, stop_revision=None,
2242
possible_transports=None, run_hooks=True,
2243
_override_hook_target=None, local=False):
2244
"""Pull from source into self, updating my master if any.
2246
:param run_hooks: Private parameter - if false, this branch
2247
is being called because it's the master of the primary branch,
2248
so it should not run its hooks.
2250
bound_location = self.target.get_bound_location()
2251
if local and not bound_location:
2252
raise errors.LocalRequiresBoundBranch()
2253
master_branch = None
2254
source_is_master = False
2256
# bound_location comes from a config file, some care has to be
2257
# taken to relate it to source.user_url
2258
normalized = urlutils.normalize_url(bound_location)
2260
relpath = self.source.user_transport.relpath(normalized)
2261
source_is_master = (relpath == '')
2262
except (errors.PathNotChild, errors.InvalidURL):
2263
source_is_master = False
2264
if not local and bound_location and not source_is_master:
2265
# not pulling from master, so we need to update master.
2266
master_branch = self.target.get_master_branch(possible_transports)
2267
master_branch.lock_write()
2270
# pull from source into master.
2271
master_branch.pull(self.source, overwrite, stop_revision,
2273
return self._pull(overwrite,
2274
stop_revision, _hook_master=master_branch,
2275
run_hooks=run_hooks,
2276
_override_hook_target=_override_hook_target,
2277
merge_tags_to_master=not source_is_master)
2280
master_branch.unlock()
2282
def push(self, overwrite=False, stop_revision=None, lossy=False,
2283
_override_hook_source_branch=None):
2284
"""See InterBranch.push.
2286
This is the basic concrete implementation of push()
2288
:param _override_hook_source_branch: If specified, run the hooks
2289
passing this Branch as the source, rather than self. This is for
2290
use of RemoteBranch, where push is delegated to the underlying
2294
raise errors.LossyPushToSameVCS(self.source, self.target)
2295
# TODO: Public option to disable running hooks - should be trivial but
2298
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
2299
op.add_cleanup(self.source.lock_read().unlock)
2300
op.add_cleanup(self.target.lock_write().unlock)
2301
return op.run(overwrite, stop_revision,
2302
_override_hook_source_branch=_override_hook_source_branch)
2304
def _basic_push(self, overwrite, stop_revision):
2305
"""Basic implementation of push without bound branches or hooks.
2307
Must be called with source read locked and target write locked.
2309
result = BranchPushResult()
2310
result.source_branch = self.source
2311
result.target_branch = self.target
2312
result.old_revno, result.old_revid = self.target.last_revision_info()
2313
self.source.update_references(self.target)
2314
overwrite = _fix_overwrite_type(overwrite)
2315
if result.old_revid != stop_revision:
2316
# We assume that during 'push' this repository is closer than
2318
graph = self.source.repository.get_graph(self.target.repository)
2319
self._update_revisions(stop_revision,
2320
overwrite=("history" in overwrite),
2322
if self.source._push_should_merge_tags():
2323
result.tag_updates, result.tag_conflicts = (
2324
self.source.tags.merge_to(
2325
self.target.tags, "tags" in overwrite))
2326
result.new_revno, result.new_revid = self.target.last_revision_info()
2329
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
2330
_override_hook_source_branch=None):
2331
"""Push from source into target, and into target's master if any.
2334
if _override_hook_source_branch:
2335
result.source_branch = _override_hook_source_branch
2336
for hook in Branch.hooks['post_push']:
2339
bound_location = self.target.get_bound_location()
2340
if bound_location and self.target.base != bound_location:
2341
# there is a master branch.
2343
# XXX: Why the second check? Is it even supported for a branch to
2344
# be bound to itself? -- mbp 20070507
2345
master_branch = self.target.get_master_branch()
2346
master_branch.lock_write()
2347
operation.add_cleanup(master_branch.unlock)
2348
# push into the master from the source branch.
2349
master_inter = InterBranch.get(self.source, master_branch)
2350
master_inter._basic_push(overwrite, stop_revision)
2351
# and push into the target branch from the source. Note that
2352
# we push from the source branch again, because it's considered
2353
# the highest bandwidth repository.
2354
result = self._basic_push(overwrite, stop_revision)
2355
result.master_branch = master_branch
2356
result.local_branch = self.target
2358
master_branch = None
2360
result = self._basic_push(overwrite, stop_revision)
2361
# TODO: Why set master_branch and local_branch if there's no
2362
# binding? Maybe cleaner to just leave them unset? -- mbp
2364
result.master_branch = self.target
2365
result.local_branch = None
2369
def _pull(self, overwrite=False, stop_revision=None,
2370
possible_transports=None, _hook_master=None, run_hooks=True,
2371
_override_hook_target=None, local=False,
2372
merge_tags_to_master=True):
2375
This function is the core worker, used by GenericInterBranch.pull to
2376
avoid duplication when pulling source->master and source->local.
2378
:param _hook_master: Private parameter - set the branch to
2379
be supplied as the master to pull hooks.
2380
:param run_hooks: Private parameter - if false, this branch
2381
is being called because it's the master of the primary branch,
2382
so it should not run its hooks.
2383
is being called because it's the master of the primary branch,
2384
so it should not run its hooks.
2385
:param _override_hook_target: Private parameter - set the branch to be
2386
supplied as the target_branch to pull hooks.
2387
:param local: Only update the local branch, and not the bound branch.
2389
# This type of branch can't be bound.
2391
raise errors.LocalRequiresBoundBranch()
2392
result = PullResult()
2393
result.source_branch = self.source
2394
if _override_hook_target is None:
2395
result.target_branch = self.target
2397
result.target_branch = _override_hook_target
2398
self.source.lock_read()
2400
# We assume that during 'pull' the target repository is closer than
2402
self.source.update_references(self.target)
2403
graph = self.target.repository.get_graph(self.source.repository)
2404
# TODO: Branch formats should have a flag that indicates
2405
# that revno's are expensive, and pull() should honor that flag.
2407
result.old_revno, result.old_revid = \
2408
self.target.last_revision_info()
2409
overwrite = _fix_overwrite_type(overwrite)
2410
self._update_revisions(stop_revision,
2411
overwrite=("history" in overwrite),
2413
# TODO: The old revid should be specified when merging tags,
2414
# so a tags implementation that versions tags can only
2415
# pull in the most recent changes. -- JRV20090506
2416
result.tag_updates, result.tag_conflicts = (
2417
self.source.tags.merge_to(self.target.tags,
2418
"tags" in overwrite,
2419
ignore_master=not merge_tags_to_master))
2420
result.new_revno, result.new_revid = self.target.last_revision_info()
2422
result.master_branch = _hook_master
2423
result.local_branch = result.target_branch
2425
result.master_branch = result.target_branch
2426
result.local_branch = None
2428
for hook in Branch.hooks['post_pull']:
2431
self.source.unlock()
2435
InterBranch.register_optimiser(GenericInterBranch)