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(), """
29
config as _mod_config,
38
revision as _mod_revision,
47
from breezy.i18n import gettext, ngettext
50
# Explicitly import breezy.bzrdir so that the BzrProber
51
# is guaranteed to be registered.
59
from .decorators import (
64
from .hooks import Hooks
65
from .inter import InterObject
66
from .lock import _RelockDebugMixin, LogicalLockResult
71
from .trace import mutter, mutter_callsite, note, is_quiet
74
class Branch(controldir.ControlComponent):
75
"""Branch holding a history of revisions.
78
Base directory/url of the branch; using control_url and
79
control_transport is more standardized.
80
:ivar hooks: An instance of BranchHooks.
81
:ivar _master_branch_cache: cached result of get_master_branch, see
84
# this is really an instance variable - FIXME move it there
89
def control_transport(self):
90
return self._transport
93
def user_transport(self):
94
return self.bzrdir.user_transport
96
def __init__(self, possible_transports=None):
97
self.tags = self._format.make_tags(self)
98
self._revision_history_cache = None
99
self._revision_id_to_revno_cache = None
100
self._partial_revision_id_to_revno_cache = {}
101
self._partial_revision_history_cache = []
102
self._tags_bytes = None
103
self._last_revision_info_cache = None
104
self._master_branch_cache = None
105
self._merge_sorted_revisions_cache = None
106
self._open_hook(possible_transports)
107
hooks = Branch.hooks['open']
111
def _open_hook(self, possible_transports):
112
"""Called by init to allow simpler extension of the base class."""
114
def _activate_fallback_location(self, url, possible_transports):
115
"""Activate the branch/repository from url as a fallback repository."""
116
for existing_fallback_repo in self.repository._fallback_repositories:
117
if existing_fallback_repo.user_url == url:
118
# This fallback is already configured. This probably only
119
# happens because ControlDir.sprout is a horrible mess. To avoid
120
# confusing _unstack we don't add this a second time.
121
mutter('duplicate activation of fallback %r on %r', url, self)
123
repo = self._get_fallback_repository(url, possible_transports)
124
if repo.has_same_location(self.repository):
125
raise errors.UnstackableLocationError(self.user_url, url)
126
self.repository.add_fallback_repository(repo)
128
def break_lock(self):
129
"""Break a lock if one is present from another instance.
131
Uses the ui factory to ask for confirmation if the lock may be from
134
This will probe the repository for its lock as well.
136
self.control_files.break_lock()
137
self.repository.break_lock()
138
master = self.get_master_branch()
139
if master is not None:
142
def _check_stackable_repo(self):
143
if not self.repository._format.supports_external_lookups:
144
raise errors.UnstackableRepositoryFormat(self.repository._format,
145
self.repository.base)
147
def _extend_partial_history(self, stop_index=None, stop_revision=None):
148
"""Extend the partial history to include a given index
150
If a stop_index is supplied, stop when that index has been reached.
151
If a stop_revision is supplied, stop when that revision is
152
encountered. Otherwise, stop when the beginning of history is
155
:param stop_index: The index which should be present. When it is
156
present, history extension will stop.
157
:param stop_revision: The revision id which should be present. When
158
it is encountered, history extension will stop.
160
if len(self._partial_revision_history_cache) == 0:
161
self._partial_revision_history_cache = [self.last_revision()]
162
repository._iter_for_revno(
163
self.repository, self._partial_revision_history_cache,
164
stop_index=stop_index, stop_revision=stop_revision)
165
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
166
self._partial_revision_history_cache.pop()
168
def _get_check_refs(self):
169
"""Get the references needed for check().
173
revid = self.last_revision()
174
return [('revision-existence', revid), ('lefthand-distance', revid)]
177
def open(base, _unsupported=False, possible_transports=None):
178
"""Open the branch rooted at base.
180
For instance, if the branch is at URL/.bzr/branch,
181
Branch.open(URL) -> a Branch instance.
183
control = controldir.ControlDir.open(base,
184
possible_transports=possible_transports, _unsupported=_unsupported)
185
return control.open_branch(unsupported=_unsupported,
186
possible_transports=possible_transports)
189
def open_from_transport(transport, name=None, _unsupported=False,
190
possible_transports=None):
191
"""Open the branch rooted at transport"""
192
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
193
return control.open_branch(name=name, unsupported=_unsupported,
194
possible_transports=possible_transports)
197
def open_containing(url, possible_transports=None):
198
"""Open an existing branch which contains url.
200
This probes for a branch at url, and searches upwards from there.
202
Basically we keep looking up until we find the control directory or
203
run into the root. If there isn't one, raises NotBranchError.
204
If there is one and it is either an unrecognised format or an unsupported
205
format, UnknownFormatError or UnsupportedFormatError are raised.
206
If there is one, it is returned, along with the unused portion of url.
208
control, relpath = controldir.ControlDir.open_containing(url,
210
branch = control.open_branch(possible_transports=possible_transports)
211
return (branch, relpath)
213
def _push_should_merge_tags(self):
214
"""Should _basic_push merge this branch's tags into the target?
216
The default implementation returns False if this branch has no tags,
217
and True the rest of the time. Subclasses may override this.
219
return self.supports_tags() and self.tags.get_tag_dict()
221
def get_config(self):
222
"""Get a breezy.config.BranchConfig for this Branch.
224
This can then be used to get and set configuration options for the
227
:return: A breezy.config.BranchConfig.
229
return _mod_config.BranchConfig(self)
231
def get_config_stack(self):
232
"""Get a breezy.config.BranchStack for this Branch.
234
This can then be used to get and set configuration options for the
237
:return: A breezy.config.BranchStack.
239
return _mod_config.BranchStack(self)
241
def _get_config(self):
242
"""Get the concrete config for just the config in this branch.
244
This is not intended for client use; see Branch.get_config for the
249
:return: An object supporting get_option and set_option.
251
raise NotImplementedError(self._get_config)
253
def store_uncommitted(self, creator):
254
"""Store uncommitted changes from a ShelfCreator.
256
:param creator: The ShelfCreator containing uncommitted changes, or
257
None to delete any stored changes.
258
:raises: ChangesAlreadyStored if the branch already has changes.
260
raise NotImplementedError(self.store_uncommitted)
262
def get_unshelver(self, tree):
263
"""Return a shelf.Unshelver for this branch and tree.
265
:param tree: The tree to use to construct the Unshelver.
266
:return: an Unshelver or None if no changes are stored.
268
raise NotImplementedError(self.get_unshelver)
270
def _get_fallback_repository(self, url, possible_transports):
271
"""Get the repository we fallback to at url."""
272
url = urlutils.join(self.base, url)
273
a_branch = Branch.open(url, possible_transports=possible_transports)
274
return a_branch.repository
277
def _get_tags_bytes(self):
278
"""Get the bytes of a serialised tags dict.
280
Note that not all branches support tags, nor do all use the same tags
281
logic: this method is specific to BasicTags. Other tag implementations
282
may use the same method name and behave differently, safely, because
283
of the double-dispatch via
284
format.make_tags->tags_instance->get_tags_dict.
286
:return: The bytes of the tags file.
287
:seealso: Branch._set_tags_bytes.
289
if self._tags_bytes is None:
290
self._tags_bytes = self._transport.get_bytes('tags')
291
return self._tags_bytes
293
def _get_nick(self, local=False, possible_transports=None):
294
config = self.get_config()
295
# explicit overrides master, but don't look for master if local is True
296
if not local and not config.has_explicit_nickname():
298
master = self.get_master_branch(possible_transports)
299
if master and self.user_url == master.user_url:
300
raise errors.RecursiveBind(self.user_url)
301
if master is not None:
302
# return the master branch value
304
except errors.RecursiveBind as e:
306
except errors.BzrError as e:
307
# Silently fall back to local implicit nick if the master is
309
mutter("Could not connect to bound branch, "
310
"falling back to local nick.\n " + str(e))
311
return config.get_nickname()
313
def _set_nick(self, nick):
314
self.get_config().set_user_option('nickname', nick, warn_masked=True)
316
nick = property(_get_nick, _set_nick)
319
raise NotImplementedError(self.is_locked)
321
def _lefthand_history(self, revision_id, last_rev=None,
323
if 'evil' in debug.debug_flags:
324
mutter_callsite(4, "_lefthand_history scales with history.")
325
# stop_revision must be a descendant of last_revision
326
graph = self.repository.get_graph()
327
if last_rev is not None:
328
if not graph.is_ancestor(last_rev, revision_id):
329
# our previous tip is not merged into stop_revision
330
raise errors.DivergedBranches(self, other_branch)
331
# make a new revision history from the graph
332
parents_map = graph.get_parent_map([revision_id])
333
if revision_id not in parents_map:
334
raise errors.NoSuchRevision(self, revision_id)
335
current_rev_id = revision_id
337
check_not_reserved_id = _mod_revision.check_not_reserved_id
338
# Do not include ghosts or graph origin in revision_history
339
while (current_rev_id in parents_map and
340
len(parents_map[current_rev_id]) > 0):
341
check_not_reserved_id(current_rev_id)
342
new_history.append(current_rev_id)
343
current_rev_id = parents_map[current_rev_id][0]
344
parents_map = graph.get_parent_map([current_rev_id])
345
new_history.reverse()
348
def lock_write(self, token=None):
349
"""Lock the branch for write operations.
351
:param token: A token to permit reacquiring a previously held and
353
:return: A BranchWriteLockResult.
355
raise NotImplementedError(self.lock_write)
358
"""Lock the branch for read operations.
360
:return: A breezy.lock.LogicalLockResult.
362
raise NotImplementedError(self.lock_read)
365
raise NotImplementedError(self.unlock)
367
def peek_lock_mode(self):
368
"""Return lock mode for the Branch: 'r', 'w' or None"""
369
raise NotImplementedError(self.peek_lock_mode)
371
def get_physical_lock_status(self):
372
raise NotImplementedError(self.get_physical_lock_status)
375
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
376
"""Return the revision_id for a dotted revno.
378
:param revno: a tuple like (1,) or (1,1,2)
379
:param _cache_reverse: a private parameter enabling storage
380
of the reverse mapping in a top level cache. (This should
381
only be done in selective circumstances as we want to
382
avoid having the mapping cached multiple times.)
383
:return: the revision_id
384
:raises errors.NoSuchRevision: if the revno doesn't exist
386
rev_id = self._do_dotted_revno_to_revision_id(revno)
388
self._partial_revision_id_to_revno_cache[rev_id] = revno
391
def _do_dotted_revno_to_revision_id(self, revno):
392
"""Worker function for dotted_revno_to_revision_id.
394
Subclasses should override this if they wish to
395
provide a more efficient implementation.
398
return self.get_rev_id(revno[0])
399
revision_id_to_revno = self.get_revision_id_to_revno_map()
400
revision_ids = [revision_id for revision_id, this_revno
401
in viewitems(revision_id_to_revno)
402
if revno == this_revno]
403
if len(revision_ids) == 1:
404
return revision_ids[0]
406
revno_str = '.'.join(map(str, revno))
407
raise errors.NoSuchRevision(self, revno_str)
410
def revision_id_to_dotted_revno(self, revision_id):
411
"""Given a revision id, return its dotted revno.
413
:return: a tuple like (1,) or (400,1,3).
415
return self._do_revision_id_to_dotted_revno(revision_id)
417
def _do_revision_id_to_dotted_revno(self, revision_id):
418
"""Worker function for revision_id_to_revno."""
419
# Try the caches if they are loaded
420
result = self._partial_revision_id_to_revno_cache.get(revision_id)
421
if result is not None:
423
if self._revision_id_to_revno_cache:
424
result = self._revision_id_to_revno_cache.get(revision_id)
426
raise errors.NoSuchRevision(self, revision_id)
427
# Try the mainline as it's optimised
429
revno = self.revision_id_to_revno(revision_id)
431
except errors.NoSuchRevision:
432
# We need to load and use the full revno map after all
433
result = self.get_revision_id_to_revno_map().get(revision_id)
435
raise errors.NoSuchRevision(self, revision_id)
439
def get_revision_id_to_revno_map(self):
440
"""Return the revision_id => dotted revno map.
442
This will be regenerated on demand, but will be cached.
444
:return: A dictionary mapping revision_id => dotted revno.
445
This dictionary should not be modified by the caller.
447
if self._revision_id_to_revno_cache is not None:
448
mapping = self._revision_id_to_revno_cache
450
mapping = self._gen_revno_map()
451
self._cache_revision_id_to_revno(mapping)
452
# TODO: jam 20070417 Since this is being cached, should we be returning
454
# I would rather not, and instead just declare that users should not
455
# modify the return value.
458
def _gen_revno_map(self):
459
"""Create a new mapping from revision ids to dotted revnos.
461
Dotted revnos are generated based on the current tip in the revision
463
This is the worker function for get_revision_id_to_revno_map, which
464
just caches the return value.
466
:return: A dictionary mapping revision_id => dotted revno.
468
revision_id_to_revno = dict((rev_id, revno)
469
for rev_id, depth, revno, end_of_merge
470
in self.iter_merge_sorted_revisions())
471
return revision_id_to_revno
474
def iter_merge_sorted_revisions(self, start_revision_id=None,
475
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
476
"""Walk the revisions for a branch in merge sorted order.
478
Merge sorted order is the output from a merge-aware,
479
topological sort, i.e. all parents come before their
480
children going forward; the opposite for reverse.
482
:param start_revision_id: the revision_id to begin walking from.
483
If None, the branch tip is used.
484
:param stop_revision_id: the revision_id to terminate the walk
485
after. If None, the rest of history is included.
486
:param stop_rule: if stop_revision_id is not None, the precise rule
487
to use for termination:
489
* 'exclude' - leave the stop revision out of the result (default)
490
* 'include' - the stop revision is the last item in the result
491
* 'with-merges' - include the stop revision and all of its
492
merged revisions in the result
493
* 'with-merges-without-common-ancestry' - filter out revisions
494
that are in both ancestries
495
:param direction: either 'reverse' or 'forward':
497
* reverse means return the start_revision_id first, i.e.
498
start at the most recent revision and go backwards in history
499
* forward returns tuples in the opposite order to reverse.
500
Note in particular that forward does *not* do any intelligent
501
ordering w.r.t. depth as some clients of this API may like.
502
(If required, that ought to be done at higher layers.)
504
:return: an iterator over (revision_id, depth, revno, end_of_merge)
507
* revision_id: the unique id of the revision
508
* depth: How many levels of merging deep this node has been
510
* revno_sequence: This field provides a sequence of
511
revision numbers for all revisions. The format is:
512
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
513
branch that the revno is on. From left to right the REVNO numbers
514
are the sequence numbers within that branch of the revision.
515
* end_of_merge: When True the next node (earlier in history) is
516
part of a different merge.
518
# Note: depth and revno values are in the context of the branch so
519
# we need the full graph to get stable numbers, regardless of the
521
if self._merge_sorted_revisions_cache is None:
522
last_revision = self.last_revision()
523
known_graph = self.repository.get_known_graph_ancestry(
525
self._merge_sorted_revisions_cache = known_graph.merge_sort(
527
filtered = self._filter_merge_sorted_revisions(
528
self._merge_sorted_revisions_cache, start_revision_id,
529
stop_revision_id, stop_rule)
530
# Make sure we don't return revisions that are not part of the
531
# start_revision_id ancestry.
532
filtered = self._filter_start_non_ancestors(filtered)
533
if direction == 'reverse':
535
if direction == 'forward':
536
return reversed(list(filtered))
538
raise ValueError('invalid direction %r' % direction)
540
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
541
start_revision_id, stop_revision_id, stop_rule):
542
"""Iterate over an inclusive range of sorted revisions."""
543
rev_iter = iter(merge_sorted_revisions)
544
if start_revision_id is not None:
545
for node in rev_iter:
547
if rev_id != start_revision_id:
550
# The decision to include the start or not
551
# depends on the stop_rule if a stop is provided
552
# so pop this node back into the iterator
553
rev_iter = itertools.chain(iter([node]), rev_iter)
555
if stop_revision_id is None:
557
for node in rev_iter:
559
yield (rev_id, node.merge_depth, node.revno,
561
elif stop_rule == 'exclude':
562
for node in rev_iter:
564
if rev_id == stop_revision_id:
566
yield (rev_id, node.merge_depth, node.revno,
568
elif stop_rule == 'include':
569
for node in rev_iter:
571
yield (rev_id, node.merge_depth, node.revno,
573
if rev_id == stop_revision_id:
575
elif stop_rule == 'with-merges-without-common-ancestry':
576
# We want to exclude all revisions that are already part of the
577
# stop_revision_id ancestry.
578
graph = self.repository.get_graph()
579
ancestors = graph.find_unique_ancestors(start_revision_id,
581
for node in rev_iter:
583
if rev_id not in ancestors:
585
yield (rev_id, node.merge_depth, node.revno,
587
elif stop_rule == 'with-merges':
588
stop_rev = self.repository.get_revision(stop_revision_id)
589
if stop_rev.parent_ids:
590
left_parent = stop_rev.parent_ids[0]
592
left_parent = _mod_revision.NULL_REVISION
593
# left_parent is the actual revision we want to stop logging at,
594
# since we want to show the merged revisions after the stop_rev too
595
reached_stop_revision_id = False
596
revision_id_whitelist = []
597
for node in rev_iter:
599
if rev_id == left_parent:
600
# reached the left parent after the stop_revision
602
if (not reached_stop_revision_id or
603
rev_id in revision_id_whitelist):
604
yield (rev_id, node.merge_depth, node.revno,
606
if reached_stop_revision_id or rev_id == stop_revision_id:
607
# only do the merged revs of rev_id from now on
608
rev = self.repository.get_revision(rev_id)
610
reached_stop_revision_id = True
611
revision_id_whitelist.extend(rev.parent_ids)
613
raise ValueError('invalid stop_rule %r' % stop_rule)
615
def _filter_start_non_ancestors(self, rev_iter):
616
# If we started from a dotted revno, we want to consider it as a tip
617
# and don't want to yield revisions that are not part of its
618
# ancestry. Given the order guaranteed by the merge sort, we will see
619
# uninteresting descendants of the first parent of our tip before the
621
first = next(rev_iter)
622
(rev_id, merge_depth, revno, end_of_merge) = first
625
# We start at a mainline revision so by definition, all others
626
# revisions in rev_iter are ancestors
627
for node in rev_iter:
632
pmap = self.repository.get_parent_map([rev_id])
633
parents = pmap.get(rev_id, [])
635
whitelist.update(parents)
637
# If there is no parents, there is nothing of interest left
639
# FIXME: It's hard to test this scenario here as this code is never
640
# called in that case. -- vila 20100322
643
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
645
if rev_id in whitelist:
646
pmap = self.repository.get_parent_map([rev_id])
647
parents = pmap.get(rev_id, [])
648
whitelist.remove(rev_id)
649
whitelist.update(parents)
651
# We've reached the mainline, there is nothing left to
655
# A revision that is not part of the ancestry of our
658
yield (rev_id, merge_depth, revno, end_of_merge)
660
def leave_lock_in_place(self):
661
"""Tell this branch object not to release the physical lock when this
664
If lock_write doesn't return a token, then this method is not supported.
666
self.control_files.leave_in_place()
668
def dont_leave_lock_in_place(self):
669
"""Tell this branch object to release the physical lock when this
670
object is unlocked, even if it didn't originally acquire it.
672
If lock_write doesn't return a token, then this method is not supported.
674
self.control_files.dont_leave_in_place()
676
def bind(self, other):
677
"""Bind the local branch the other branch.
679
:param other: The branch to bind to
682
raise errors.UpgradeRequired(self.user_url)
684
def get_append_revisions_only(self):
685
"""Whether it is only possible to append revisions to the history.
687
if not self._format.supports_set_append_revisions_only():
689
return self.get_config_stack().get('append_revisions_only')
691
def set_append_revisions_only(self, enabled):
692
if not self._format.supports_set_append_revisions_only():
693
raise errors.UpgradeRequired(self.user_url)
694
self.get_config_stack().set('append_revisions_only', enabled)
696
def set_reference_info(self, file_id, tree_path, branch_location):
697
"""Set the branch location to use for a tree reference."""
698
raise errors.UnsupportedOperation(self.set_reference_info, self)
700
def get_reference_info(self, file_id):
701
"""Get the tree_path and branch_location for a tree reference."""
702
raise errors.UnsupportedOperation(self.get_reference_info, self)
705
def fetch(self, from_branch, last_revision=None, limit=None):
706
"""Copy revisions from from_branch into this branch.
708
:param from_branch: Where to copy from.
709
:param last_revision: What revision to stop at (None for at the end
711
:param limit: Optional rough limit of revisions to fetch
714
return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
716
def get_bound_location(self):
717
"""Return the URL of the branch we are bound to.
719
Older format branches cannot bind, please be sure to use a metadir
724
def get_old_bound_location(self):
725
"""Return the URL of the branch we used to be bound to
727
raise errors.UpgradeRequired(self.user_url)
729
def get_commit_builder(self, parents, config_stack=None, timestamp=None,
730
timezone=None, committer=None, revprops=None,
731
revision_id=None, lossy=False):
732
"""Obtain a CommitBuilder for this branch.
734
:param parents: Revision ids of the parents of the new revision.
735
:param config: Optional configuration to use.
736
:param timestamp: Optional timestamp recorded for commit.
737
:param timezone: Optional timezone for timestamp.
738
:param committer: Optional committer to set for commit.
739
:param revprops: Optional dictionary of revision properties.
740
:param revision_id: Optional revision id.
741
:param lossy: Whether to discard data that can not be natively
742
represented, when pushing to a foreign VCS
745
if config_stack is None:
746
config_stack = self.get_config_stack()
748
return self.repository.get_commit_builder(self, parents, config_stack,
749
timestamp, timezone, committer, revprops, revision_id,
752
def get_master_branch(self, possible_transports=None):
753
"""Return the branch we are bound to.
755
:return: Either a Branch, or None
759
def get_stacked_on_url(self):
760
"""Get the URL this branch is stacked against.
762
:raises NotStacked: If the branch is not stacked.
763
:raises UnstackableBranchFormat: If the branch does not support
766
raise NotImplementedError(self.get_stacked_on_url)
768
def print_file(self, file, revision_id):
769
"""Print `file` to stdout."""
770
raise NotImplementedError(self.print_file)
773
def set_last_revision_info(self, revno, revision_id):
774
"""Set the last revision of this branch.
776
The caller is responsible for checking that the revno is correct
777
for this revision id.
779
It may be possible to set the branch last revision to an id not
780
present in the repository. However, branches can also be
781
configured to check constraints on history, in which case this may not
784
raise NotImplementedError(self.set_last_revision_info)
787
def generate_revision_history(self, revision_id, last_rev=None,
789
"""See Branch.generate_revision_history"""
790
graph = self.repository.get_graph()
791
(last_revno, last_revid) = self.last_revision_info()
792
known_revision_ids = [
793
(last_revid, last_revno),
794
(_mod_revision.NULL_REVISION, 0),
796
if last_rev is not None:
797
if not graph.is_ancestor(last_rev, revision_id):
798
# our previous tip is not merged into stop_revision
799
raise errors.DivergedBranches(self, other_branch)
800
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
801
self.set_last_revision_info(revno, revision_id)
804
def set_parent(self, url):
805
"""See Branch.set_parent."""
806
# TODO: Maybe delete old location files?
807
# URLs should never be unicode, even on the local fs,
808
# FIXUP this and get_parent in a future branch format bump:
809
# read and rewrite the file. RBC 20060125
811
if isinstance(url, unicode):
813
url = url.encode('ascii')
814
except UnicodeEncodeError:
815
raise errors.InvalidURL(url,
816
"Urls must be 7-bit ascii, "
817
"use breezy.urlutils.escape")
818
url = urlutils.relative_url(self.base, url)
819
self._set_parent_location(url)
822
def set_stacked_on_url(self, url):
823
"""Set the URL this branch is stacked against.
825
:raises UnstackableBranchFormat: If the branch does not support
827
:raises UnstackableRepositoryFormat: If the repository does not support
830
if not self._format.supports_stacking():
831
raise errors.UnstackableBranchFormat(self._format, self.user_url)
832
# XXX: Changing from one fallback repository to another does not check
833
# that all the data you need is present in the new fallback.
834
# Possibly it should.
835
self._check_stackable_repo()
838
old_url = self.get_stacked_on_url()
839
except (errors.NotStacked, errors.UnstackableBranchFormat,
840
errors.UnstackableRepositoryFormat):
844
self._activate_fallback_location(url,
845
possible_transports=[self.bzrdir.root_transport])
846
# write this out after the repository is stacked to avoid setting a
847
# stacked config that doesn't work.
848
self._set_config_location('stacked_on_location', url)
851
"""Change a branch to be unstacked, copying data as needed.
853
Don't call this directly, use set_stacked_on_url(None).
855
pb = ui.ui_factory.nested_progress_bar()
857
pb.update(gettext("Unstacking"))
858
# The basic approach here is to fetch the tip of the branch,
859
# including all available ghosts, from the existing stacked
860
# repository into a new repository object without the fallbacks.
862
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
863
# correct for CHKMap repostiories
864
old_repository = self.repository
865
if len(old_repository._fallback_repositories) != 1:
866
raise AssertionError("can't cope with fallback repositories "
867
"of %r (fallbacks: %r)" % (old_repository,
868
old_repository._fallback_repositories))
869
# Open the new repository object.
870
# Repositories don't offer an interface to remove fallback
871
# repositories today; take the conceptually simpler option and just
872
# reopen it. We reopen it starting from the URL so that we
873
# get a separate connection for RemoteRepositories and can
874
# stream from one of them to the other. This does mean doing
875
# separate SSH connection setup, but unstacking is not a
876
# common operation so it's tolerable.
877
new_bzrdir = controldir.ControlDir.open(
878
self.bzrdir.root_transport.base)
879
new_repository = new_bzrdir.find_repository()
880
if new_repository._fallback_repositories:
881
raise AssertionError("didn't expect %r to have "
882
"fallback_repositories"
883
% (self.repository,))
884
# Replace self.repository with the new repository.
885
# Do our best to transfer the lock state (i.e. lock-tokens and
886
# lock count) of self.repository to the new repository.
887
lock_token = old_repository.lock_write().repository_token
888
self.repository = new_repository
889
if isinstance(self, remote.RemoteBranch):
890
# Remote branches can have a second reference to the old
891
# repository that need to be replaced.
892
if self._real_branch is not None:
893
self._real_branch.repository = new_repository
894
self.repository.lock_write(token=lock_token)
895
if lock_token is not None:
896
old_repository.leave_lock_in_place()
897
old_repository.unlock()
898
if lock_token is not None:
899
# XXX: self.repository.leave_lock_in_place() before this
900
# function will not be preserved. Fortunately that doesn't
901
# affect the current default format (2a), and would be a
902
# corner-case anyway.
903
# - Andrew Bennetts, 2010/06/30
904
self.repository.dont_leave_lock_in_place()
908
old_repository.unlock()
909
except errors.LockNotHeld:
912
if old_lock_count == 0:
913
raise AssertionError(
914
'old_repository should have been locked at least once.')
915
for i in range(old_lock_count-1):
916
self.repository.lock_write()
917
# Fetch from the old repository into the new.
918
old_repository.lock_read()
920
# XXX: If you unstack a branch while it has a working tree
921
# with a pending merge, the pending-merged revisions will no
922
# longer be present. You can (probably) revert and remerge.
924
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
925
except errors.TagsNotSupported:
926
tags_to_fetch = set()
927
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
928
old_repository, required_ids=[self.last_revision()],
929
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
930
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
932
old_repository.unlock()
936
def _set_tags_bytes(self, bytes):
937
"""Mirror method for _get_tags_bytes.
939
:seealso: Branch._get_tags_bytes.
941
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
942
op.add_cleanup(self.lock_write().unlock)
943
return op.run_simple(bytes)
945
def _set_tags_bytes_locked(self, bytes):
946
self._tags_bytes = bytes
947
return self._transport.put_bytes('tags', bytes)
949
def _cache_revision_history(self, rev_history):
950
"""Set the cached revision history to rev_history.
952
The revision_history method will use this cache to avoid regenerating
953
the revision history.
955
This API is semi-public; it only for use by subclasses, all other code
956
should consider it to be private.
958
self._revision_history_cache = rev_history
960
def _cache_revision_id_to_revno(self, revision_id_to_revno):
961
"""Set the cached revision_id => revno map to revision_id_to_revno.
963
This API is semi-public; it only for use by subclasses, all other code
964
should consider it to be private.
966
self._revision_id_to_revno_cache = revision_id_to_revno
968
def _clear_cached_state(self):
969
"""Clear any cached data on this branch, e.g. cached revision history.
971
This means the next call to revision_history will need to call
972
_gen_revision_history.
974
This API is semi-public; it is only for use by subclasses, all other
975
code should consider it to be private.
977
self._revision_history_cache = None
978
self._revision_id_to_revno_cache = None
979
self._last_revision_info_cache = None
980
self._master_branch_cache = None
981
self._merge_sorted_revisions_cache = None
982
self._partial_revision_history_cache = []
983
self._partial_revision_id_to_revno_cache = {}
984
self._tags_bytes = None
986
def _gen_revision_history(self):
987
"""Return sequence of revision hashes on to this branch.
989
Unlike revision_history, this method always regenerates or rereads the
990
revision history, i.e. it does not cache the result, so repeated calls
993
Concrete subclasses should override this instead of revision_history so
994
that subclasses do not need to deal with caching logic.
996
This API is semi-public; it only for use by subclasses, all other code
997
should consider it to be private.
999
raise NotImplementedError(self._gen_revision_history)
1001
def _revision_history(self):
1002
if 'evil' in debug.debug_flags:
1003
mutter_callsite(3, "revision_history scales with history.")
1004
if self._revision_history_cache is not None:
1005
history = self._revision_history_cache
1007
history = self._gen_revision_history()
1008
self._cache_revision_history(history)
1009
return list(history)
1012
"""Return current revision number for this branch.
1014
That is equivalent to the number of revisions committed to
1017
return self.last_revision_info()[0]
1020
"""Older format branches cannot bind or unbind."""
1021
raise errors.UpgradeRequired(self.user_url)
1023
def last_revision(self):
1024
"""Return last revision id, or NULL_REVISION."""
1025
return self.last_revision_info()[1]
1028
def last_revision_info(self):
1029
"""Return information about the last revision.
1031
:return: A tuple (revno, revision_id).
1033
if self._last_revision_info_cache is None:
1034
self._last_revision_info_cache = self._read_last_revision_info()
1035
return self._last_revision_info_cache
1037
def _read_last_revision_info(self):
1038
raise NotImplementedError(self._read_last_revision_info)
1040
def import_last_revision_info_and_tags(self, source, revno, revid,
1042
"""Set the last revision info, importing from another repo if necessary.
1044
This is used by the bound branch code to upload a revision to
1045
the master branch first before updating the tip of the local branch.
1046
Revisions referenced by source's tags are also transferred.
1048
:param source: Source branch to optionally fetch from
1049
:param revno: Revision number of the new tip
1050
:param revid: Revision id of the new tip
1051
:param lossy: Whether to discard metadata that can not be
1052
natively represented
1053
:return: Tuple with the new revision number and revision id
1054
(should only be different from the arguments when lossy=True)
1056
if not self.repository.has_same_location(source.repository):
1057
self.fetch(source, revid)
1058
self.set_last_revision_info(revno, revid)
1059
return (revno, revid)
1061
def revision_id_to_revno(self, revision_id):
1062
"""Given a revision id, return its revno"""
1063
if _mod_revision.is_null(revision_id):
1065
history = self._revision_history()
1067
return history.index(revision_id) + 1
1069
raise errors.NoSuchRevision(self, revision_id)
1072
def get_rev_id(self, revno, history=None):
1073
"""Find the revision id of the specified revno."""
1075
return _mod_revision.NULL_REVISION
1076
last_revno, last_revid = self.last_revision_info()
1077
if revno == last_revno:
1079
if revno <= 0 or revno > last_revno:
1080
raise errors.NoSuchRevision(self, revno)
1081
distance_from_last = last_revno - revno
1082
if len(self._partial_revision_history_cache) <= distance_from_last:
1083
self._extend_partial_history(distance_from_last)
1084
return self._partial_revision_history_cache[distance_from_last]
1086
def pull(self, source, overwrite=False, stop_revision=None,
1087
possible_transports=None, *args, **kwargs):
1088
"""Mirror source into this branch.
1090
This branch is considered to be 'local', having low latency.
1092
:returns: PullResult instance
1094
return InterBranch.get(source, self).pull(overwrite=overwrite,
1095
stop_revision=stop_revision,
1096
possible_transports=possible_transports, *args, **kwargs)
1098
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1100
"""Mirror this branch into target.
1102
This branch is considered to be 'local', having low latency.
1104
return InterBranch.get(self, target).push(overwrite, stop_revision,
1105
lossy, *args, **kwargs)
1107
def basis_tree(self):
1108
"""Return `Tree` object for last revision."""
1109
return self.repository.revision_tree(self.last_revision())
1111
def get_parent(self):
1112
"""Return the parent location of the branch.
1114
This is the default location for pull/missing. The usual
1115
pattern is that the user can override it by specifying a
1118
parent = self._get_parent_location()
1121
# This is an old-format absolute path to a local branch
1122
# turn it into a url
1123
if parent.startswith('/'):
1124
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1126
return urlutils.join(self.base[:-1], parent)
1127
except errors.InvalidURLJoin as e:
1128
raise errors.InaccessibleParent(parent, self.user_url)
1130
def _get_parent_location(self):
1131
raise NotImplementedError(self._get_parent_location)
1133
def _set_config_location(self, name, url, config=None,
1134
make_relative=False):
1136
config = self.get_config_stack()
1140
url = urlutils.relative_url(self.base, url)
1141
config.set(name, url)
1143
def _get_config_location(self, name, config=None):
1145
config = self.get_config_stack()
1146
location = config.get(name)
1151
def get_child_submit_format(self):
1152
"""Return the preferred format of submissions to this branch."""
1153
return self.get_config_stack().get('child_submit_format')
1155
def get_submit_branch(self):
1156
"""Return the submit location of the branch.
1158
This is the default location for bundle. The usual
1159
pattern is that the user can override it by specifying a
1162
return self.get_config_stack().get('submit_branch')
1164
def set_submit_branch(self, location):
1165
"""Return the submit location of the branch.
1167
This is the default location for bundle. The usual
1168
pattern is that the user can override it by specifying a
1171
self.get_config_stack().set('submit_branch', location)
1173
def get_public_branch(self):
1174
"""Return the public location of the branch.
1176
This is used by merge directives.
1178
return self._get_config_location('public_branch')
1180
def set_public_branch(self, location):
1181
"""Return the submit location of the branch.
1183
This is the default location for bundle. The usual
1184
pattern is that the user can override it by specifying a
1187
self._set_config_location('public_branch', location)
1189
def get_push_location(self):
1190
"""Return None or the location to push this branch to."""
1191
return self.get_config_stack().get('push_location')
1193
def set_push_location(self, location):
1194
"""Set a new push location for this branch."""
1195
raise NotImplementedError(self.set_push_location)
1197
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1198
"""Run the post_change_branch_tip hooks."""
1199
hooks = Branch.hooks['post_change_branch_tip']
1202
new_revno, new_revid = self.last_revision_info()
1203
params = ChangeBranchTipParams(
1204
self, old_revno, new_revno, old_revid, new_revid)
1208
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1209
"""Run the pre_change_branch_tip hooks."""
1210
hooks = Branch.hooks['pre_change_branch_tip']
1213
old_revno, old_revid = self.last_revision_info()
1214
params = ChangeBranchTipParams(
1215
self, old_revno, new_revno, old_revid, new_revid)
1221
"""Synchronise this branch with the master branch if any.
1223
:return: None or the last_revision pivoted out during the update.
1227
def check_revno(self, revno):
1229
Check whether a revno corresponds to any revision.
1230
Zero (the NULL revision) is considered valid.
1233
self.check_real_revno(revno)
1235
def check_real_revno(self, revno):
1237
Check whether a revno corresponds to a real revision.
1238
Zero (the NULL revision) is considered invalid
1240
if revno < 1 or revno > self.revno():
1241
raise errors.InvalidRevisionNumber(revno)
1244
def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
1245
"""Clone this branch into to_bzrdir preserving all semantic values.
1247
Most API users will want 'create_clone_on_transport', which creates a
1248
new bzrdir and branch on the fly.
1250
revision_id: if not None, the revision history in the new branch will
1251
be truncated to end with revision_id.
1253
result = to_bzrdir.create_branch()
1256
if repository_policy is not None:
1257
repository_policy.configure_branch(result)
1258
self.copy_content_into(result, revision_id=revision_id)
1264
def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1266
"""Create a new line of development from the branch, into to_bzrdir.
1268
to_bzrdir controls the branch format.
1270
revision_id: if not None, the revision history in the new branch will
1271
be truncated to end with revision_id.
1273
if (repository_policy is not None and
1274
repository_policy.requires_stacking()):
1275
to_bzrdir._format.require_stacking(_skip_repo=True)
1276
result = to_bzrdir.create_branch(repository=repository)
1279
if repository_policy is not None:
1280
repository_policy.configure_branch(result)
1281
self.copy_content_into(result, revision_id=revision_id)
1282
master_url = self.get_bound_location()
1283
if master_url is None:
1284
result.set_parent(self.bzrdir.root_transport.base)
1286
result.set_parent(master_url)
1291
def _synchronize_history(self, destination, revision_id):
1292
"""Synchronize last revision and revision history between branches.
1294
This version is most efficient when the destination is also a
1295
BzrBranch6, but works for BzrBranch5, as long as the destination's
1296
repository contains all the lefthand ancestors of the intended
1297
last_revision. If not, set_last_revision_info will fail.
1299
:param destination: The branch to copy the history into
1300
:param revision_id: The revision-id to truncate history at. May
1301
be None to copy complete history.
1303
source_revno, source_revision_id = self.last_revision_info()
1304
if revision_id is None:
1305
revno, revision_id = source_revno, source_revision_id
1307
graph = self.repository.get_graph()
1309
revno = graph.find_distance_to_null(revision_id,
1310
[(source_revision_id, source_revno)])
1311
except errors.GhostRevisionsHaveNoRevno:
1312
# Default to 1, if we can't find anything else
1314
destination.set_last_revision_info(revno, revision_id)
1316
def copy_content_into(self, destination, revision_id=None):
1317
"""Copy the content of self into destination.
1319
revision_id: if not None, the revision history in the new branch will
1320
be truncated to end with revision_id.
1322
return InterBranch.get(self, destination).copy_content_into(
1323
revision_id=revision_id)
1325
def update_references(self, target):
1326
if not getattr(self._format, 'supports_reference_locations', False):
1328
reference_dict = self._get_all_reference_info()
1329
if len(reference_dict) == 0:
1331
old_base = self.base
1332
new_base = target.base
1333
target_reference_dict = target._get_all_reference_info()
1334
for file_id, (tree_path, branch_location) in viewitems(reference_dict):
1335
branch_location = urlutils.rebase_url(branch_location,
1337
target_reference_dict.setdefault(
1338
file_id, (tree_path, branch_location))
1339
target._set_all_reference_info(target_reference_dict)
1342
def check(self, refs):
1343
"""Check consistency of the branch.
1345
In particular this checks that revisions given in the revision-history
1346
do actually match up in the revision graph, and that they're all
1347
present in the repository.
1349
Callers will typically also want to check the repository.
1351
:param refs: Calculated refs for this branch as specified by
1352
branch._get_check_refs()
1353
:return: A BranchCheckResult.
1355
result = BranchCheckResult(self)
1356
last_revno, last_revision_id = self.last_revision_info()
1357
actual_revno = refs[('lefthand-distance', last_revision_id)]
1358
if actual_revno != last_revno:
1359
result.errors.append(errors.BzrCheckError(
1360
'revno does not match len(mainline) %s != %s' % (
1361
last_revno, actual_revno)))
1362
# TODO: We should probably also check that self.revision_history
1363
# matches the repository for older branch formats.
1364
# If looking for the code that cross-checks repository parents against
1365
# the Graph.iter_lefthand_ancestry output, that is now a repository
1369
def _get_checkout_format(self, lightweight=False):
1370
"""Return the most suitable metadir for a checkout of this branch.
1371
Weaves are used if this branch's repository uses weaves.
1373
format = self.repository.bzrdir.checkout_metadir()
1374
format.set_branch_format(self._format)
1377
def create_clone_on_transport(self, to_transport, revision_id=None,
1378
stacked_on=None, create_prefix=False, use_existing_dir=False,
1380
"""Create a clone of this branch and its bzrdir.
1382
:param to_transport: The transport to clone onto.
1383
:param revision_id: The revision id to use as tip in the new branch.
1384
If None the tip is obtained from this branch.
1385
:param stacked_on: An optional URL to stack the clone on.
1386
:param create_prefix: Create any missing directories leading up to
1388
:param use_existing_dir: Use an existing directory if one exists.
1390
# XXX: Fix the bzrdir API to allow getting the branch back from the
1391
# clone call. Or something. 20090224 RBC/spiv.
1392
# XXX: Should this perhaps clone colocated branches as well,
1393
# rather than just the default branch? 20100319 JRV
1394
if revision_id is None:
1395
revision_id = self.last_revision()
1396
dir_to = self.bzrdir.clone_on_transport(to_transport,
1397
revision_id=revision_id, stacked_on=stacked_on,
1398
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1400
return dir_to.open_branch()
1402
def create_checkout(self, to_location, revision_id=None,
1403
lightweight=False, accelerator_tree=None,
1405
"""Create a checkout of a branch.
1407
:param to_location: The url to produce the checkout at
1408
:param revision_id: The revision to check out
1409
:param lightweight: If True, produce a lightweight checkout, otherwise,
1410
produce a bound branch (heavyweight checkout)
1411
:param accelerator_tree: A tree which can be used for retrieving file
1412
contents more quickly than the revision tree, i.e. a workingtree.
1413
The revision tree will be used for cases where accelerator_tree's
1414
content is different.
1415
:param hardlink: If true, hard-link files from accelerator_tree,
1417
:return: The tree of the created checkout
1419
t = transport.get_transport(to_location)
1421
format = self._get_checkout_format(lightweight=lightweight)
1423
checkout = format.initialize_on_transport(t)
1424
except errors.AlreadyControlDirError:
1425
# It's fine if the control directory already exists,
1426
# as long as there is no existing branch and working tree.
1427
checkout = controldir.ControlDir.open_from_transport(t)
1429
checkout.open_branch()
1430
except errors.NotBranchError:
1433
raise errors.AlreadyControlDirError(t.base)
1434
if checkout.control_transport.base == self.bzrdir.control_transport.base:
1435
# When checking out to the same control directory,
1436
# always create a lightweight checkout
1440
from_branch = checkout.set_branch_reference(target_branch=self)
1442
policy = checkout.determine_repository_policy()
1443
repo = policy.acquire_repository()[0]
1444
checkout_branch = checkout.create_branch()
1445
checkout_branch.bind(self)
1446
# pull up to the specified revision_id to set the initial
1447
# branch tip correctly, and seed it with history.
1448
checkout_branch.pull(self, stop_revision=revision_id)
1450
tree = checkout.create_workingtree(revision_id,
1451
from_branch=from_branch,
1452
accelerator_tree=accelerator_tree,
1454
basis_tree = tree.basis_tree()
1455
basis_tree.lock_read()
1457
for path, file_id in basis_tree.iter_references():
1458
reference_parent = self.reference_parent(file_id, path)
1459
reference_parent.create_checkout(tree.abspath(path),
1460
basis_tree.get_reference_revision(file_id, path),
1467
def reconcile(self, thorough=True):
1468
"""Make sure the data stored in this branch is consistent."""
1469
from breezy.reconcile import BranchReconciler
1470
reconciler = BranchReconciler(self, thorough=thorough)
1471
reconciler.reconcile()
1474
def reference_parent(self, file_id, path, possible_transports=None):
1475
"""Return the parent branch for a tree-reference file_id
1477
:param file_id: The file_id of the tree reference
1478
:param path: The path of the file_id in the tree
1479
:return: A branch associated with the file_id
1481
# FIXME should provide multiple branches, based on config
1482
return Branch.open(self.bzrdir.root_transport.clone(path).base,
1483
possible_transports=possible_transports)
1485
def supports_tags(self):
1486
return self._format.supports_tags()
1488
def automatic_tag_name(self, revision_id):
1489
"""Try to automatically find the tag name for a revision.
1491
:param revision_id: Revision id of the revision.
1492
:return: A tag name or None if no tag name could be determined.
1494
for hook in Branch.hooks['automatic_tag_name']:
1495
ret = hook(self, revision_id)
1500
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1502
"""Ensure that revision_b is a descendant of revision_a.
1504
This is a helper function for update_revisions.
1506
:raises: DivergedBranches if revision_b has diverged from revision_a.
1507
:returns: True if revision_b is a descendant of revision_a.
1509
relation = self._revision_relations(revision_a, revision_b, graph)
1510
if relation == 'b_descends_from_a':
1512
elif relation == 'diverged':
1513
raise errors.DivergedBranches(self, other_branch)
1514
elif relation == 'a_descends_from_b':
1517
raise AssertionError("invalid relation: %r" % (relation,))
1519
def _revision_relations(self, revision_a, revision_b, graph):
1520
"""Determine the relationship between two revisions.
1522
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1524
heads = graph.heads([revision_a, revision_b])
1525
if heads == {revision_b}:
1526
return 'b_descends_from_a'
1527
elif heads == {revision_a, revision_b}:
1528
# These branches have diverged
1530
elif heads == {revision_a}:
1531
return 'a_descends_from_b'
1533
raise AssertionError("invalid heads: %r" % (heads,))
1535
def heads_to_fetch(self):
1536
"""Return the heads that must and that should be fetched to copy this
1537
branch into another repo.
1539
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1540
set of heads that must be fetched. if_present_fetch is a set of
1541
heads that must be fetched if present, but no error is necessary if
1542
they are not present.
1544
# For bzr native formats must_fetch is just the tip, and
1545
# if_present_fetch are the tags.
1546
must_fetch = {self.last_revision()}
1547
if_present_fetch = set()
1548
if self.get_config_stack().get('branch.fetch_tags'):
1550
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1551
except errors.TagsNotSupported:
1553
must_fetch.discard(_mod_revision.NULL_REVISION)
1554
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1555
return must_fetch, if_present_fetch
1558
class BranchFormat(controldir.ControlComponentFormat):
1559
"""An encapsulation of the initialization and open routines for a format.
1561
Formats provide three things:
1562
* An initialization routine,
1563
* a format description
1566
Formats are placed in an dict by their format string for reference
1567
during branch opening. It's not required that these be instances, they
1568
can be classes themselves with class methods - it simply depends on
1569
whether state is needed for a given format or not.
1571
Once a format is deprecated, just deprecate the initialize and open
1572
methods on the format class. Do not deprecate the object, as the
1573
object will be created every time regardless.
1576
def __eq__(self, other):
1577
return self.__class__ is other.__class__
1579
def __ne__(self, other):
1580
return not (self == other)
1582
def get_reference(self, controldir, name=None):
1583
"""Get the target reference of the branch in controldir.
1585
format probing must have been completed before calling
1586
this method - it is assumed that the format of the branch
1587
in controldir is correct.
1589
:param controldir: The controldir to get the branch data from.
1590
:param name: Name of the colocated branch to fetch
1591
:return: None if the branch is not a reference branch.
1596
def set_reference(self, controldir, name, to_branch):
1597
"""Set the target reference of the branch in controldir.
1599
format probing must have been completed before calling
1600
this method - it is assumed that the format of the branch
1601
in controldir is correct.
1603
:param controldir: The controldir to set the branch reference for.
1604
:param name: Name of colocated branch to set, None for default
1605
:param to_branch: branch that the checkout is to reference
1607
raise NotImplementedError(self.set_reference)
1609
def get_format_description(self):
1610
"""Return the short format description for this format."""
1611
raise NotImplementedError(self.get_format_description)
1613
def _run_post_branch_init_hooks(self, controldir, name, branch):
1614
hooks = Branch.hooks['post_branch_init']
1617
params = BranchInitHookParams(self, controldir, name, branch)
1621
def initialize(self, controldir, name=None, repository=None,
1622
append_revisions_only=None):
1623
"""Create a branch of this format in controldir.
1625
:param name: Name of the colocated branch to create.
1627
raise NotImplementedError(self.initialize)
1629
def is_supported(self):
1630
"""Is this format supported?
1632
Supported formats can be initialized and opened.
1633
Unsupported formats may not support initialization or committing or
1634
some other features depending on the reason for not being supported.
1638
def make_tags(self, branch):
1639
"""Create a tags object for branch.
1641
This method is on BranchFormat, because BranchFormats are reflected
1642
over the wire via network_name(), whereas full Branch instances require
1643
multiple VFS method calls to operate at all.
1645
The default implementation returns a disabled-tags instance.
1647
Note that it is normal for branch to be a RemoteBranch when using tags
1650
return _mod_tag.DisabledTags(branch)
1652
def network_name(self):
1653
"""A simple byte string uniquely identifying this format for RPC calls.
1655
MetaDir branch formats use their disk format string to identify the
1656
repository over the wire. All in one formats such as bzr < 0.8, and
1657
foreign formats like svn/git and hg should use some marker which is
1658
unique and immutable.
1660
raise NotImplementedError(self.network_name)
1662
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1663
found_repository=None, possible_transports=None):
1664
"""Return the branch object for controldir.
1666
:param controldir: A ControlDir that contains a branch.
1667
:param name: Name of colocated branch to open
1668
:param _found: a private parameter, do not use it. It is used to
1669
indicate if format probing has already be done.
1670
:param ignore_fallbacks: when set, no fallback branches will be opened
1671
(if there are any). Default is to open fallbacks.
1673
raise NotImplementedError(self.open)
1675
def supports_set_append_revisions_only(self):
1676
"""True if this format supports set_append_revisions_only."""
1679
def supports_stacking(self):
1680
"""True if this format records a stacked-on branch."""
1683
def supports_leaving_lock(self):
1684
"""True if this format supports leaving locks in place."""
1685
return False # by default
1688
return self.get_format_description().rstrip()
1690
def supports_tags(self):
1691
"""True if this format supports tags stored in the branch"""
1692
return False # by default
1694
def tags_are_versioned(self):
1695
"""Whether the tag container for this branch versions tags."""
1698
def supports_tags_referencing_ghosts(self):
1699
"""True if tags can reference ghost revisions."""
1703
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1704
"""A factory for a BranchFormat object, permitting simple lazy registration.
1706
While none of the built in BranchFormats are lazy registered yet,
1707
breezy.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1708
use it, and the bzr-loom plugin uses it as well (see
1709
breezy.plugins.loom.formats).
1712
def __init__(self, format_string, module_name, member_name):
1713
"""Create a MetaDirBranchFormatFactory.
1715
:param format_string: The format string the format has.
1716
:param module_name: Module to load the format class from.
1717
:param member_name: Attribute name within the module for the format class.
1719
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1720
self._format_string = format_string
1722
def get_format_string(self):
1723
"""See BranchFormat.get_format_string."""
1724
return self._format_string
1727
"""Used for network_format_registry support."""
1728
return self.get_obj()()
1731
class BranchHooks(Hooks):
1732
"""A dictionary mapping hook name to a list of callables for branch hooks.
1734
e.g. ['post_push'] Is the list of items to be called when the
1735
push function is invoked.
1739
"""Create the default hooks.
1741
These are all empty initially, because by default nothing should get
1744
Hooks.__init__(self, "breezy.branch", "Branch.hooks")
1745
self.add_hook('open',
1746
"Called with the Branch object that has been opened after a "
1747
"branch is opened.", (1, 8))
1748
self.add_hook('post_push',
1749
"Called after a push operation completes. post_push is called "
1750
"with a breezy.branch.BranchPushResult object and only runs in the "
1751
"bzr client.", (0, 15))
1752
self.add_hook('post_pull',
1753
"Called after a pull operation completes. post_pull is called "
1754
"with a breezy.branch.PullResult object and only runs in the "
1755
"bzr client.", (0, 15))
1756
self.add_hook('pre_commit',
1757
"Called after a commit is calculated but before it is "
1758
"completed. pre_commit is called with (local, master, old_revno, "
1759
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1760
"). old_revid is NULL_REVISION for the first commit to a branch, "
1761
"tree_delta is a TreeDelta object describing changes from the "
1762
"basis revision. hooks MUST NOT modify this delta. "
1763
" future_tree is an in-memory tree obtained from "
1764
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1766
self.add_hook('post_commit',
1767
"Called in the bzr client after a commit has completed. "
1768
"post_commit is called with (local, master, old_revno, old_revid, "
1769
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1770
"commit to a branch.", (0, 15))
1771
self.add_hook('post_uncommit',
1772
"Called in the bzr client after an uncommit completes. "
1773
"post_uncommit is called with (local, master, old_revno, "
1774
"old_revid, new_revno, new_revid) where local is the local branch "
1775
"or None, master is the target branch, and an empty branch "
1776
"receives new_revno of 0, new_revid of None.", (0, 15))
1777
self.add_hook('pre_change_branch_tip',
1778
"Called in bzr client and server before a change to the tip of a "
1779
"branch is made. pre_change_branch_tip is called with a "
1780
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1781
"commit, uncommit will all trigger this hook.", (1, 6))
1782
self.add_hook('post_change_branch_tip',
1783
"Called in bzr client and server after a change to the tip of a "
1784
"branch is made. post_change_branch_tip is called with a "
1785
"breezy.branch.ChangeBranchTipParams. Note that push, pull, "
1786
"commit, uncommit will all trigger this hook.", (1, 4))
1787
self.add_hook('transform_fallback_location',
1788
"Called when a stacked branch is activating its fallback "
1789
"locations. transform_fallback_location is called with (branch, "
1790
"url), and should return a new url. Returning the same url "
1791
"allows it to be used as-is, returning a different one can be "
1792
"used to cause the branch to stack on a closer copy of that "
1793
"fallback_location. Note that the branch cannot have history "
1794
"accessing methods called on it during this hook because the "
1795
"fallback locations have not been activated. When there are "
1796
"multiple hooks installed for transform_fallback_location, "
1797
"all are called with the url returned from the previous hook."
1798
"The order is however undefined.", (1, 9))
1799
self.add_hook('automatic_tag_name',
1800
"Called to determine an automatic tag name for a revision. "
1801
"automatic_tag_name is called with (branch, revision_id) and "
1802
"should return a tag name or None if no tag name could be "
1803
"determined. The first non-None tag name returned will be used.",
1805
self.add_hook('post_branch_init',
1806
"Called after new branch initialization completes. "
1807
"post_branch_init is called with a "
1808
"breezy.branch.BranchInitHookParams. "
1809
"Note that init, branch and checkout (both heavyweight and "
1810
"lightweight) will all trigger this hook.", (2, 2))
1811
self.add_hook('post_switch',
1812
"Called after a checkout switches branch. "
1813
"post_switch is called with a "
1814
"breezy.branch.SwitchHookParams.", (2, 2))
1818
# install the default hooks into the Branch class.
1819
Branch.hooks = BranchHooks()
1822
class ChangeBranchTipParams(object):
1823
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1825
There are 5 fields that hooks may wish to access:
1827
:ivar branch: the branch being changed
1828
:ivar old_revno: revision number before the change
1829
:ivar new_revno: revision number after the change
1830
:ivar old_revid: revision id before the change
1831
:ivar new_revid: revision id after the change
1833
The revid fields are strings. The revno fields are integers.
1836
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1837
"""Create a group of ChangeBranchTip parameters.
1839
:param branch: The branch being changed.
1840
:param old_revno: Revision number before the change.
1841
:param new_revno: Revision number after the change.
1842
:param old_revid: Tip revision id before the change.
1843
:param new_revid: Tip revision id after the change.
1845
self.branch = branch
1846
self.old_revno = old_revno
1847
self.new_revno = new_revno
1848
self.old_revid = old_revid
1849
self.new_revid = new_revid
1851
def __eq__(self, other):
1852
return self.__dict__ == other.__dict__
1855
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1856
self.__class__.__name__, self.branch,
1857
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1860
class BranchInitHookParams(object):
1861
"""Object holding parameters passed to `*_branch_init` hooks.
1863
There are 4 fields that hooks may wish to access:
1865
:ivar format: the branch format
1866
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1867
:ivar name: name of colocated branch, if any (or None)
1868
:ivar branch: the branch created
1870
Note that for lightweight checkouts, the bzrdir and format fields refer to
1871
the checkout, hence they are different from the corresponding fields in
1872
branch, which refer to the original branch.
1875
def __init__(self, format, controldir, name, branch):
1876
"""Create a group of BranchInitHook parameters.
1878
:param format: the branch format
1879
:param controldir: the ControlDir where the branch will be/has been
1881
:param name: name of colocated branch, if any (or None)
1882
:param branch: the branch created
1884
Note that for lightweight checkouts, the bzrdir and format fields refer
1885
to the checkout, hence they are different from the corresponding fields
1886
in branch, which refer to the original branch.
1888
self.format = format
1889
self.bzrdir = controldir
1891
self.branch = branch
1893
def __eq__(self, other):
1894
return self.__dict__ == other.__dict__
1897
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1900
class SwitchHookParams(object):
1901
"""Object holding parameters passed to `*_switch` hooks.
1903
There are 4 fields that hooks may wish to access:
1905
:ivar control_dir: ControlDir of the checkout to change
1906
:ivar to_branch: branch that the checkout is to reference
1907
:ivar force: skip the check for local commits in a heavy checkout
1908
:ivar revision_id: revision ID to switch to (or None)
1911
def __init__(self, control_dir, to_branch, force, revision_id):
1912
"""Create a group of SwitchHook parameters.
1914
:param control_dir: ControlDir of the checkout to change
1915
:param to_branch: branch that the checkout is to reference
1916
:param force: skip the check for local commits in a heavy checkout
1917
:param revision_id: revision ID to switch to (or None)
1919
self.control_dir = control_dir
1920
self.to_branch = to_branch
1922
self.revision_id = revision_id
1924
def __eq__(self, other):
1925
return self.__dict__ == other.__dict__
1928
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1929
self.control_dir, self.to_branch,
1933
class BranchFormatMetadir(bzrdir.BzrFormat, BranchFormat):
1934
"""Base class for branch formats that live in meta directories.
1938
BranchFormat.__init__(self)
1939
bzrdir.BzrFormat.__init__(self)
1942
def find_format(klass, controldir, name=None):
1943
"""Return the format for the branch object in controldir."""
1945
transport = controldir.get_branch_transport(None, name=name)
1946
except errors.NoSuchFile:
1947
raise errors.NotBranchError(path=name, bzrdir=controldir)
1949
format_string = transport.get_bytes("format")
1950
except errors.NoSuchFile:
1951
raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
1952
return klass._find_format(format_registry, 'branch', format_string)
1954
def _branch_class(self):
1955
"""What class to instantiate on open calls."""
1956
raise NotImplementedError(self._branch_class)
1958
def _get_initial_config(self, append_revisions_only=None):
1959
if append_revisions_only:
1960
return "append_revisions_only = True\n"
1962
# Avoid writing anything if append_revisions_only is disabled,
1963
# as that is the default.
1966
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1968
"""Initialize a branch in a control dir, with specified files
1970
:param a_bzrdir: The bzrdir to initialize the branch in
1971
:param utf8_files: The files to create as a list of
1972
(filename, content) tuples
1973
:param name: Name of colocated branch to create, if any
1974
:return: a branch in this format
1977
name = a_bzrdir._get_selected_branch()
1978
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1979
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1980
control_files = lockable_files.LockableFiles(branch_transport,
1981
'lock', lockdir.LockDir)
1982
control_files.create_lock()
1983
control_files.lock_write()
1985
utf8_files += [('format', self.as_string())]
1986
for (filename, content) in utf8_files:
1987
branch_transport.put_bytes(
1989
mode=a_bzrdir._get_file_mode())
1991
control_files.unlock()
1992
branch = self.open(a_bzrdir, name, _found=True,
1993
found_repository=repository)
1994
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1997
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1998
found_repository=None, possible_transports=None):
1999
"""See BranchFormat.open()."""
2001
name = a_bzrdir._get_selected_branch()
2003
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2004
if format.__class__ != self.__class__:
2005
raise AssertionError("wrong format %r found for %r" %
2007
transport = a_bzrdir.get_branch_transport(None, name=name)
2009
control_files = lockable_files.LockableFiles(transport, 'lock',
2011
if found_repository is None:
2012
found_repository = a_bzrdir.find_repository()
2013
return self._branch_class()(_format=self,
2014
_control_files=control_files,
2017
_repository=found_repository,
2018
ignore_fallbacks=ignore_fallbacks,
2019
possible_transports=possible_transports)
2020
except errors.NoSuchFile:
2021
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2024
def _matchingbzrdir(self):
2025
ret = bzrdir.BzrDirMetaFormat1()
2026
ret.set_branch_format(self)
2029
def supports_tags(self):
2032
def supports_leaving_lock(self):
2035
def check_support_status(self, allow_unsupported, recommend_upgrade=True,
2037
BranchFormat.check_support_status(self,
2038
allow_unsupported=allow_unsupported, recommend_upgrade=recommend_upgrade,
2040
bzrdir.BzrFormat.check_support_status(self, allow_unsupported=allow_unsupported,
2041
recommend_upgrade=recommend_upgrade, basedir=basedir)
2044
class BzrBranchFormat6(BranchFormatMetadir):
2045
"""Branch format with last-revision and tags.
2047
Unlike previous formats, this has no explicit revision history. Instead,
2048
this just stores the last-revision, and the left-hand history leading
2049
up to there is the history.
2051
This format was introduced in bzr 0.15
2052
and became the default in 0.91.
2055
def _branch_class(self):
2059
def get_format_string(cls):
2060
"""See BranchFormat.get_format_string()."""
2061
return "Bazaar Branch Format 6 (bzr 0.15)\n"
2063
def get_format_description(self):
2064
"""See BranchFormat.get_format_description()."""
2065
return "Branch format 6"
2067
def initialize(self, a_bzrdir, name=None, repository=None,
2068
append_revisions_only=None):
2069
"""Create a branch of this format in a_bzrdir."""
2070
utf8_files = [('last-revision', '0 null:\n'),
2072
self._get_initial_config(append_revisions_only)),
2075
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2077
def make_tags(self, branch):
2078
"""See breezy.branch.BranchFormat.make_tags()."""
2079
return _mod_tag.BasicTags(branch)
2081
def supports_set_append_revisions_only(self):
2085
class BzrBranchFormat8(BranchFormatMetadir):
2086
"""Metadir format supporting storing locations of subtree branches."""
2088
def _branch_class(self):
2092
def get_format_string(cls):
2093
"""See BranchFormat.get_format_string()."""
2094
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2096
def get_format_description(self):
2097
"""See BranchFormat.get_format_description()."""
2098
return "Branch format 8"
2100
def initialize(self, a_bzrdir, name=None, repository=None,
2101
append_revisions_only=None):
2102
"""Create a branch of this format in a_bzrdir."""
2103
utf8_files = [('last-revision', '0 null:\n'),
2105
self._get_initial_config(append_revisions_only)),
2109
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2111
def make_tags(self, branch):
2112
"""See breezy.branch.BranchFormat.make_tags()."""
2113
return _mod_tag.BasicTags(branch)
2115
def supports_set_append_revisions_only(self):
2118
def supports_stacking(self):
2121
supports_reference_locations = True
2124
class BzrBranchFormat7(BranchFormatMetadir):
2125
"""Branch format with last-revision, tags, and a stacked location pointer.
2127
The stacked location pointer is passed down to the repository and requires
2128
a repository format with supports_external_lookups = True.
2130
This format was introduced in bzr 1.6.
2133
def initialize(self, a_bzrdir, name=None, repository=None,
2134
append_revisions_only=None):
2135
"""Create a branch of this format in a_bzrdir."""
2136
utf8_files = [('last-revision', '0 null:\n'),
2138
self._get_initial_config(append_revisions_only)),
2141
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2143
def _branch_class(self):
2147
def get_format_string(cls):
2148
"""See BranchFormat.get_format_string()."""
2149
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2151
def get_format_description(self):
2152
"""See BranchFormat.get_format_description()."""
2153
return "Branch format 7"
2155
def supports_set_append_revisions_only(self):
2158
def supports_stacking(self):
2161
def make_tags(self, branch):
2162
"""See breezy.branch.BranchFormat.make_tags()."""
2163
return _mod_tag.BasicTags(branch)
2165
supports_reference_locations = False
2168
class BranchReferenceFormat(BranchFormatMetadir):
2169
"""Bzr branch reference format.
2171
Branch references are used in implementing checkouts, they
2172
act as an alias to the real branch which is at some other url.
2180
def get_format_string(cls):
2181
"""See BranchFormat.get_format_string()."""
2182
return "Bazaar-NG Branch Reference Format 1\n"
2184
def get_format_description(self):
2185
"""See BranchFormat.get_format_description()."""
2186
return "Checkout reference format 1"
2188
def get_reference(self, a_bzrdir, name=None):
2189
"""See BranchFormat.get_reference()."""
2190
transport = a_bzrdir.get_branch_transport(None, name=name)
2191
return transport.get_bytes('location')
2193
def set_reference(self, a_bzrdir, name, to_branch):
2194
"""See BranchFormat.set_reference()."""
2195
transport = a_bzrdir.get_branch_transport(None, name=name)
2196
location = transport.put_bytes('location', to_branch.base)
2198
def initialize(self, a_bzrdir, name=None, target_branch=None,
2199
repository=None, append_revisions_only=None):
2200
"""Create a branch of this format in a_bzrdir."""
2201
if target_branch is None:
2202
# this format does not implement branch itself, thus the implicit
2203
# creation contract must see it as uninitializable
2204
raise errors.UninitializableFormat(self)
2205
mutter('creating branch reference in %s', a_bzrdir.user_url)
2206
if a_bzrdir._format.fixed_components:
2207
raise errors.IncompatibleFormat(self, a_bzrdir._format)
2209
name = a_bzrdir._get_selected_branch()
2210
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2211
branch_transport.put_bytes('location',
2212
target_branch.user_url)
2213
branch_transport.put_bytes('format', self.as_string())
2214
branch = self.open(a_bzrdir, name, _found=True,
2215
possible_transports=[target_branch.bzrdir.root_transport])
2216
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2219
def _make_reference_clone_function(format, a_branch):
2220
"""Create a clone() routine for a branch dynamically."""
2221
def clone(to_bzrdir, revision_id=None,
2222
repository_policy=None):
2223
"""See Branch.clone()."""
2224
return format.initialize(to_bzrdir, target_branch=a_branch)
2225
# cannot obey revision_id limits when cloning a reference ...
2226
# FIXME RBC 20060210 either nuke revision_id for clone, or
2227
# emit some sort of warning/error to the caller ?!
2230
def open(self, a_bzrdir, name=None, _found=False, location=None,
2231
possible_transports=None, ignore_fallbacks=False,
2232
found_repository=None):
2233
"""Return the branch that the branch reference in a_bzrdir points at.
2235
:param a_bzrdir: A BzrDir that contains a branch.
2236
:param name: Name of colocated branch to open, if any
2237
:param _found: a private parameter, do not use it. It is used to
2238
indicate if format probing has already be done.
2239
:param ignore_fallbacks: when set, no fallback branches will be opened
2240
(if there are any). Default is to open fallbacks.
2241
:param location: The location of the referenced branch. If
2242
unspecified, this will be determined from the branch reference in
2244
:param possible_transports: An optional reusable transports list.
2247
name = a_bzrdir._get_selected_branch()
2249
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2250
if format.__class__ != self.__class__:
2251
raise AssertionError("wrong format %r found for %r" %
2253
if location is None:
2254
location = self.get_reference(a_bzrdir, name)
2255
real_bzrdir = controldir.ControlDir.open(
2256
location, possible_transports=possible_transports)
2257
result = real_bzrdir.open_branch(ignore_fallbacks=ignore_fallbacks,
2258
possible_transports=possible_transports)
2259
# this changes the behaviour of result.clone to create a new reference
2260
# rather than a copy of the content of the branch.
2261
# I did not use a proxy object because that needs much more extensive
2262
# testing, and we are only changing one behaviour at the moment.
2263
# If we decide to alter more behaviours - i.e. the implicit nickname
2264
# then this should be refactored to introduce a tested proxy branch
2265
# and a subclass of that for use in overriding clone() and ....
2267
result.clone = self._make_reference_clone_function(result)
2271
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2272
"""Branch format registry."""
2274
def __init__(self, other_registry=None):
2275
super(BranchFormatRegistry, self).__init__(other_registry)
2276
self._default_format = None
2278
def set_default(self, format):
2279
self._default_format = format
2281
def get_default(self):
2282
return self._default_format
2285
network_format_registry = registry.FormatRegistry()
2286
"""Registry of formats indexed by their network name.
2288
The network name for a branch format is an identifier that can be used when
2289
referring to formats with smart server operations. See
2290
BranchFormat.network_name() for more detail.
2293
format_registry = BranchFormatRegistry(network_format_registry)
2296
# formats which have no format string are not discoverable
2297
# and not independently creatable, so are not registered.
2298
__format6 = BzrBranchFormat6()
2299
__format7 = BzrBranchFormat7()
2300
__format8 = BzrBranchFormat8()
2301
format_registry.register_lazy(
2302
"Bazaar-NG branch format 5\n", "breezy.branchfmt.fullhistory", "BzrBranchFormat5")
2303
format_registry.register(BranchReferenceFormat())
2304
format_registry.register(__format6)
2305
format_registry.register(__format7)
2306
format_registry.register(__format8)
2307
format_registry.set_default(__format7)
2310
class BranchWriteLockResult(LogicalLockResult):
2311
"""The result of write locking a branch.
2313
:ivar branch_token: The token obtained from the underlying branch lock, or
2315
:ivar unlock: A callable which will unlock the lock.
2318
def __init__(self, unlock, branch_token):
2319
LogicalLockResult.__init__(self, unlock)
2320
self.branch_token = branch_token
2323
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2327
class BzrBranch(Branch, _RelockDebugMixin):
2328
"""A branch stored in the actual filesystem.
2330
Note that it's "local" in the context of the filesystem; it doesn't
2331
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2332
it's writable, and can be accessed via the normal filesystem API.
2334
:ivar _transport: Transport for file operations on this branch's
2335
control files, typically pointing to the .bzr/branch directory.
2336
:ivar repository: Repository for this branch.
2337
:ivar base: The url of the base directory for this branch; the one
2338
containing the .bzr directory.
2339
:ivar name: Optional colocated branch name as it exists in the control
2343
def __init__(self, _format=None,
2344
_control_files=None, a_bzrdir=None, name=None,
2345
_repository=None, ignore_fallbacks=False,
2346
possible_transports=None):
2347
"""Create new branch object at a particular location."""
2348
if a_bzrdir is None:
2349
raise ValueError('a_bzrdir must be supplied')
2351
raise ValueError('name must be supplied')
2352
self.bzrdir = a_bzrdir
2353
self._user_transport = self.bzrdir.transport.clone('..')
2355
self._user_transport.set_segment_parameter(
2356
"branch", urlutils.escape(name))
2357
self._base = self._user_transport.base
2359
self._format = _format
2360
if _control_files is None:
2361
raise ValueError('BzrBranch _control_files is None')
2362
self.control_files = _control_files
2363
self._transport = _control_files._transport
2364
self.repository = _repository
2365
self.conf_store = None
2366
Branch.__init__(self, possible_transports)
2369
return '%s(%s)' % (self.__class__.__name__, self.user_url)
2373
def _get_base(self):
2374
"""Returns the directory containing the control directory."""
2377
base = property(_get_base, doc="The URL for the root of this branch.")
2380
def user_transport(self):
2381
return self._user_transport
2383
def _get_config(self):
2384
return _mod_config.TransportConfig(self._transport, 'branch.conf')
2386
def _get_config_store(self):
2387
if self.conf_store is None:
2388
self.conf_store = _mod_config.BranchStore(self)
2389
return self.conf_store
2391
def _uncommitted_branch(self):
2392
"""Return the branch that may contain uncommitted changes."""
2393
master = self.get_master_branch()
2394
if master is not None:
2399
def store_uncommitted(self, creator):
2400
"""Store uncommitted changes from a ShelfCreator.
2402
:param creator: The ShelfCreator containing uncommitted changes, or
2403
None to delete any stored changes.
2404
:raises: ChangesAlreadyStored if the branch already has changes.
2406
branch = self._uncommitted_branch()
2408
branch._transport.delete('stored-transform')
2410
if branch._transport.has('stored-transform'):
2411
raise errors.ChangesAlreadyStored
2412
transform = BytesIO()
2413
creator.write_shelf(transform)
2415
branch._transport.put_file('stored-transform', transform)
2417
def get_unshelver(self, tree):
2418
"""Return a shelf.Unshelver for this branch and tree.
2420
:param tree: The tree to use to construct the Unshelver.
2421
:return: an Unshelver or None if no changes are stored.
2423
branch = self._uncommitted_branch()
2425
transform = branch._transport.get('stored-transform')
2426
except errors.NoSuchFile:
2428
return shelf.Unshelver.from_tree_and_shelf(tree, transform)
2430
def is_locked(self):
2431
return self.control_files.is_locked()
2433
def lock_write(self, token=None):
2434
"""Lock the branch for write operations.
2436
:param token: A token to permit reacquiring a previously held and
2438
:return: A BranchWriteLockResult.
2440
if not self.is_locked():
2441
self._note_lock('w')
2442
self.repository._warn_if_deprecated(self)
2443
self.repository.lock_write()
2448
return BranchWriteLockResult(self.unlock,
2449
self.control_files.lock_write(token=token))
2452
self.repository.unlock()
2455
def lock_read(self):
2456
"""Lock the branch for read operations.
2458
:return: A breezy.lock.LogicalLockResult.
2460
if not self.is_locked():
2461
self._note_lock('r')
2462
self.repository._warn_if_deprecated(self)
2463
self.repository.lock_read()
2468
self.control_files.lock_read()
2469
return LogicalLockResult(self.unlock)
2472
self.repository.unlock()
2475
@only_raises(errors.LockNotHeld, errors.LockBroken)
2477
if self.control_files._lock_count == 1 and self.conf_store is not None:
2478
self.conf_store.save_changes()
2480
self.control_files.unlock()
2482
if not self.control_files.is_locked():
2483
self.repository.unlock()
2484
# we just released the lock
2485
self._clear_cached_state()
2487
def peek_lock_mode(self):
2488
if self.control_files._lock_count == 0:
2491
return self.control_files._lock_mode
2493
def get_physical_lock_status(self):
2494
return self.control_files.get_physical_lock_status()
2497
def print_file(self, file, revision_id):
2498
"""See Branch.print_file."""
2499
return self.repository.print_file(file, revision_id)
2502
def set_last_revision_info(self, revno, revision_id):
2503
if not revision_id or not isinstance(revision_id, basestring):
2504
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2505
revision_id = _mod_revision.ensure_null(revision_id)
2506
old_revno, old_revid = self.last_revision_info()
2507
if self.get_append_revisions_only():
2508
self._check_history_violation(revision_id)
2509
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2510
self._write_last_revision_info(revno, revision_id)
2511
self._clear_cached_state()
2512
self._last_revision_info_cache = revno, revision_id
2513
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2515
def basis_tree(self):
2516
"""See Branch.basis_tree."""
2517
return self.repository.revision_tree(self.last_revision())
2519
def _get_parent_location(self):
2520
_locs = ['parent', 'pull', 'x-pull']
2523
return self._transport.get_bytes(l).strip('\n')
2524
except errors.NoSuchFile:
2528
def get_stacked_on_url(self):
2529
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2531
def set_push_location(self, location):
2532
"""See Branch.set_push_location."""
2533
self.get_config().set_user_option(
2534
'push_location', location,
2535
store=_mod_config.STORE_LOCATION_NORECURSE)
2537
def _set_parent_location(self, url):
2539
self._transport.delete('parent')
2541
self._transport.put_bytes('parent', url + '\n',
2542
mode=self.bzrdir._get_file_mode())
2546
"""If bound, unbind"""
2547
return self.set_bound_location(None)
2550
def bind(self, other):
2551
"""Bind this branch to the branch other.
2553
This does not push or pull data between the branches, though it does
2554
check for divergence to raise an error when the branches are not
2555
either the same, or one a prefix of the other. That behaviour may not
2556
be useful, so that check may be removed in future.
2558
:param other: The branch to bind to
2561
# TODO: jam 20051230 Consider checking if the target is bound
2562
# It is debatable whether you should be able to bind to
2563
# a branch which is itself bound.
2564
# Committing is obviously forbidden,
2565
# but binding itself may not be.
2566
# Since we *have* to check at commit time, we don't
2567
# *need* to check here
2569
# we want to raise diverged if:
2570
# last_rev is not in the other_last_rev history, AND
2571
# other_last_rev is not in our history, and do it without pulling
2573
self.set_bound_location(other.base)
2575
def get_bound_location(self):
2577
return self._transport.get_bytes('bound')[:-1]
2578
except errors.NoSuchFile:
2582
def get_master_branch(self, possible_transports=None):
2583
"""Return the branch we are bound to.
2585
:return: Either a Branch, or None
2587
if self._master_branch_cache is None:
2588
self._master_branch_cache = self._get_master_branch(
2589
possible_transports)
2590
return self._master_branch_cache
2592
def _get_master_branch(self, possible_transports):
2593
bound_loc = self.get_bound_location()
2597
return Branch.open(bound_loc,
2598
possible_transports=possible_transports)
2599
except (errors.NotBranchError, errors.ConnectionError) as e:
2600
raise errors.BoundBranchConnectionFailure(
2604
def set_bound_location(self, location):
2605
"""Set the target where this branch is bound to.
2607
:param location: URL to the target branch
2609
self._master_branch_cache = None
2611
self._transport.put_bytes('bound', location+'\n',
2612
mode=self.bzrdir._get_file_mode())
2615
self._transport.delete('bound')
2616
except errors.NoSuchFile:
2621
def update(self, possible_transports=None):
2622
"""Synchronise this branch with the master branch if any.
2624
:return: None or the last_revision that was pivoted out during the
2627
master = self.get_master_branch(possible_transports)
2628
if master is not None:
2629
old_tip = _mod_revision.ensure_null(self.last_revision())
2630
self.pull(master, overwrite=True)
2631
if self.repository.get_graph().is_ancestor(old_tip,
2632
_mod_revision.ensure_null(self.last_revision())):
2637
def _read_last_revision_info(self):
2638
revision_string = self._transport.get_bytes('last-revision')
2639
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2640
revision_id = cache_utf8.get_cached_utf8(revision_id)
2642
return revno, revision_id
2644
def _write_last_revision_info(self, revno, revision_id):
2645
"""Simply write out the revision id, with no checks.
2647
Use set_last_revision_info to perform this safely.
2649
Does not update the revision_history cache.
2651
revision_id = _mod_revision.ensure_null(revision_id)
2652
out_string = '%d %s\n' % (revno, revision_id)
2653
self._transport.put_bytes('last-revision', out_string,
2654
mode=self.bzrdir._get_file_mode())
2657
def update_feature_flags(self, updated_flags):
2658
"""Update the feature flags for this branch.
2660
:param updated_flags: Dictionary mapping feature names to necessities
2661
A necessity can be None to indicate the feature should be removed
2663
self._format._update_feature_flags(updated_flags)
2664
self.control_transport.put_bytes('format', self._format.as_string())
2667
class BzrBranch8(BzrBranch):
2668
"""A branch that stores tree-reference locations."""
2670
def _open_hook(self, possible_transports=None):
2671
if self._ignore_fallbacks:
2673
if possible_transports is None:
2674
possible_transports = [self.bzrdir.root_transport]
2676
url = self.get_stacked_on_url()
2677
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2678
errors.UnstackableBranchFormat):
2681
for hook in Branch.hooks['transform_fallback_location']:
2682
url = hook(self, url)
2684
hook_name = Branch.hooks.get_hook_name(hook)
2685
raise AssertionError(
2686
"'transform_fallback_location' hook %s returned "
2687
"None, not a URL." % hook_name)
2688
self._activate_fallback_location(url,
2689
possible_transports=possible_transports)
2691
def __init__(self, *args, **kwargs):
2692
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2693
super(BzrBranch8, self).__init__(*args, **kwargs)
2694
self._last_revision_info_cache = None
2695
self._reference_info = None
2697
def _clear_cached_state(self):
2698
super(BzrBranch8, self)._clear_cached_state()
2699
self._last_revision_info_cache = None
2700
self._reference_info = None
2702
def _check_history_violation(self, revision_id):
2703
current_revid = self.last_revision()
2704
last_revision = _mod_revision.ensure_null(current_revid)
2705
if _mod_revision.is_null(last_revision):
2707
graph = self.repository.get_graph()
2708
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2709
if lh_ancestor == current_revid:
2711
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2713
def _gen_revision_history(self):
2714
"""Generate the revision history from last revision
2716
last_revno, last_revision = self.last_revision_info()
2717
self._extend_partial_history(stop_index=last_revno-1)
2718
return list(reversed(self._partial_revision_history_cache))
2721
def _set_parent_location(self, url):
2722
"""Set the parent branch"""
2723
self._set_config_location('parent_location', url, make_relative=True)
2726
def _get_parent_location(self):
2727
"""Set the parent branch"""
2728
return self._get_config_location('parent_location')
2731
def _set_all_reference_info(self, info_dict):
2732
"""Replace all reference info stored in a branch.
2734
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2737
writer = rio.RioWriter(s)
2738
for key, (tree_path, branch_location) in viewitems(info_dict):
2739
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2740
branch_location=branch_location)
2741
writer.write_stanza(stanza)
2742
self._transport.put_bytes('references', s.getvalue())
2743
self._reference_info = info_dict
2746
def _get_all_reference_info(self):
2747
"""Return all the reference info stored in a branch.
2749
:return: A dict of {file_id: (tree_path, branch_location)}
2751
if self._reference_info is not None:
2752
return self._reference_info
2753
rio_file = self._transport.get('references')
2755
stanzas = rio.read_stanzas(rio_file)
2756
info_dict = dict((s['file_id'], (s['tree_path'],
2757
s['branch_location'])) for s in stanzas)
2760
self._reference_info = info_dict
2763
def set_reference_info(self, file_id, tree_path, branch_location):
2764
"""Set the branch location to use for a tree reference.
2766
:param file_id: The file-id of the tree reference.
2767
:param tree_path: The path of the tree reference in the tree.
2768
:param branch_location: The location of the branch to retrieve tree
2771
info_dict = self._get_all_reference_info()
2772
info_dict[file_id] = (tree_path, branch_location)
2773
if None in (tree_path, branch_location):
2774
if tree_path is not None:
2775
raise ValueError('tree_path must be None when branch_location'
2777
if branch_location is not None:
2778
raise ValueError('branch_location must be None when tree_path'
2780
del info_dict[file_id]
2781
self._set_all_reference_info(info_dict)
2783
def get_reference_info(self, file_id):
2784
"""Get the tree_path and branch_location for a tree reference.
2786
:return: a tuple of (tree_path, branch_location)
2788
return self._get_all_reference_info().get(file_id, (None, None))
2790
def reference_parent(self, file_id, path, possible_transports=None):
2791
"""Return the parent branch for a tree-reference file_id.
2793
:param file_id: The file_id of the tree reference
2794
:param path: The path of the file_id in the tree
2795
:return: A branch associated with the file_id
2797
branch_location = self.get_reference_info(file_id)[1]
2798
if branch_location is None:
2799
return Branch.reference_parent(self, file_id, path,
2800
possible_transports)
2801
branch_location = urlutils.join(self.user_url, branch_location)
2802
return Branch.open(branch_location,
2803
possible_transports=possible_transports)
2805
def set_push_location(self, location):
2806
"""See Branch.set_push_location."""
2807
self._set_config_location('push_location', location)
2809
def set_bound_location(self, location):
2810
"""See Branch.set_push_location."""
2811
self._master_branch_cache = None
2813
conf = self.get_config_stack()
2814
if location is None:
2815
if not conf.get('bound'):
2818
conf.set('bound', 'False')
2821
self._set_config_location('bound_location', location,
2823
conf.set('bound', 'True')
2826
def _get_bound_location(self, bound):
2827
"""Return the bound location in the config file.
2829
Return None if the bound parameter does not match"""
2830
conf = self.get_config_stack()
2831
if conf.get('bound') != bound:
2833
return self._get_config_location('bound_location', config=conf)
2835
def get_bound_location(self):
2836
"""See Branch.get_bound_location."""
2837
return self._get_bound_location(True)
2839
def get_old_bound_location(self):
2840
"""See Branch.get_old_bound_location"""
2841
return self._get_bound_location(False)
2843
def get_stacked_on_url(self):
2844
# you can always ask for the URL; but you might not be able to use it
2845
# if the repo can't support stacking.
2846
## self._check_stackable_repo()
2847
# stacked_on_location is only ever defined in branch.conf, so don't
2848
# waste effort reading the whole stack of config files.
2849
conf = _mod_config.BranchOnlyStack(self)
2850
stacked_url = self._get_config_location('stacked_on_location',
2852
if stacked_url is None:
2853
raise errors.NotStacked(self)
2854
return stacked_url.encode('utf-8')
2857
def get_rev_id(self, revno, history=None):
2858
"""Find the revision id of the specified revno."""
2860
return _mod_revision.NULL_REVISION
2862
last_revno, last_revision_id = self.last_revision_info()
2863
if revno <= 0 or revno > last_revno:
2864
raise errors.NoSuchRevision(self, revno)
2866
if history is not None:
2867
return history[revno - 1]
2869
index = last_revno - revno
2870
if len(self._partial_revision_history_cache) <= index:
2871
self._extend_partial_history(stop_index=index)
2872
if len(self._partial_revision_history_cache) > index:
2873
return self._partial_revision_history_cache[index]
2875
raise errors.NoSuchRevision(self, revno)
2878
def revision_id_to_revno(self, revision_id):
2879
"""Given a revision id, return its revno"""
2880
if _mod_revision.is_null(revision_id):
2883
index = self._partial_revision_history_cache.index(revision_id)
2886
self._extend_partial_history(stop_revision=revision_id)
2887
except errors.RevisionNotPresent as e:
2888
raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
2889
index = len(self._partial_revision_history_cache) - 1
2891
raise errors.NoSuchRevision(self, revision_id)
2892
if self._partial_revision_history_cache[index] != revision_id:
2893
raise errors.NoSuchRevision(self, revision_id)
2894
return self.revno() - index
2897
class BzrBranch7(BzrBranch8):
2898
"""A branch with support for a fallback repository."""
2900
def set_reference_info(self, file_id, tree_path, branch_location):
2901
Branch.set_reference_info(self, file_id, tree_path, branch_location)
2903
def get_reference_info(self, file_id):
2904
Branch.get_reference_info(self, file_id)
2906
def reference_parent(self, file_id, path, possible_transports=None):
2907
return Branch.reference_parent(self, file_id, path,
2908
possible_transports)
2911
class BzrBranch6(BzrBranch7):
2912
"""See BzrBranchFormat6 for the capabilities of this branch.
2914
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2918
def get_stacked_on_url(self):
2919
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2922
######################################################################
2923
# results of operations
2926
class _Result(object):
2928
def _show_tag_conficts(self, to_file):
2929
if not getattr(self, 'tag_conflicts', None):
2931
to_file.write('Conflicting tags:\n')
2932
for name, value1, value2 in self.tag_conflicts:
2933
to_file.write(' %s\n' % (name, ))
2936
class PullResult(_Result):
2937
"""Result of a Branch.pull operation.
2939
:ivar old_revno: Revision number before pull.
2940
:ivar new_revno: Revision number after pull.
2941
:ivar old_revid: Tip revision id before pull.
2942
:ivar new_revid: Tip revision id after pull.
2943
:ivar source_branch: Source (local) branch object. (read locked)
2944
:ivar master_branch: Master branch of the target, or the target if no
2946
:ivar local_branch: target branch if there is a Master, else None
2947
:ivar target_branch: Target/destination branch object. (write locked)
2948
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2949
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
2952
def report(self, to_file):
2953
tag_conflicts = getattr(self, "tag_conflicts", None)
2954
tag_updates = getattr(self, "tag_updates", None)
2956
if self.old_revid != self.new_revid:
2957
to_file.write('Now on revision %d.\n' % self.new_revno)
2959
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
2960
if self.old_revid == self.new_revid and not tag_updates:
2961
if not tag_conflicts:
2962
to_file.write('No revisions or tags to pull.\n')
2964
to_file.write('No revisions to pull.\n')
2965
self._show_tag_conficts(to_file)
2968
class BranchPushResult(_Result):
2969
"""Result of a Branch.push operation.
2971
:ivar old_revno: Revision number (eg 10) of the target before push.
2972
:ivar new_revno: Revision number (eg 12) of the target after push.
2973
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
2975
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
2977
:ivar source_branch: Source branch object that the push was from. This is
2978
read locked, and generally is a local (and thus low latency) branch.
2979
:ivar master_branch: If target is a bound branch, the master branch of
2980
target, or target itself. Always write locked.
2981
:ivar target_branch: The direct Branch where data is being sent (write
2983
:ivar local_branch: If the target is a bound branch this will be the
2984
target, otherwise it will be None.
2987
def report(self, to_file):
2988
# TODO: This function gets passed a to_file, but then
2989
# ignores it and calls note() instead. This is also
2990
# inconsistent with PullResult(), which writes to stdout.
2991
# -- JRV20110901, bug #838853
2992
tag_conflicts = getattr(self, "tag_conflicts", None)
2993
tag_updates = getattr(self, "tag_updates", None)
2995
if self.old_revid != self.new_revid:
2996
note(gettext('Pushed up to revision %d.') % self.new_revno)
2998
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
2999
if self.old_revid == self.new_revid and not tag_updates:
3000
if not tag_conflicts:
3001
note(gettext('No new revisions or tags to push.'))
3003
note(gettext('No new revisions to push.'))
3004
self._show_tag_conficts(to_file)
3007
class BranchCheckResult(object):
3008
"""Results of checking branch consistency.
3013
def __init__(self, branch):
3014
self.branch = branch
3017
def report_results(self, verbose):
3018
"""Report the check results via trace.note.
3020
:param verbose: Requests more detailed display of what was checked,
3023
note(gettext('checked branch {0} format {1}').format(
3024
self.branch.user_url, self.branch._format))
3025
for error in self.errors:
3026
note(gettext('found error:%s'), error)
3029
class Converter5to6(object):
3030
"""Perform an in-place upgrade of format 5 to format 6"""
3032
def convert(self, branch):
3033
# Data for 5 and 6 can peacefully coexist.
3034
format = BzrBranchFormat6()
3035
new_branch = format.open(branch.bzrdir, _found=True)
3037
# Copy source data into target
3038
new_branch._write_last_revision_info(*branch.last_revision_info())
3039
new_branch.lock_write()
3041
new_branch.set_parent(branch.get_parent())
3042
new_branch.set_bound_location(branch.get_bound_location())
3043
new_branch.set_push_location(branch.get_push_location())
3047
# New branch has no tags by default
3048
new_branch.tags._set_tag_dict({})
3050
# Copying done; now update target format
3051
new_branch._transport.put_bytes('format',
3053
mode=new_branch.bzrdir._get_file_mode())
3055
# Clean up old files
3056
new_branch._transport.delete('revision-history')
3060
branch.set_parent(None)
3061
except errors.NoSuchFile:
3063
branch.set_bound_location(None)
3068
class Converter6to7(object):
3069
"""Perform an in-place upgrade of format 6 to format 7"""
3071
def convert(self, branch):
3072
format = BzrBranchFormat7()
3073
branch._set_config_location('stacked_on_location', '')
3074
# update target format
3075
branch._transport.put_bytes('format', format.as_string())
3078
class Converter7to8(object):
3079
"""Perform an in-place upgrade of format 7 to format 8"""
3081
def convert(self, branch):
3082
format = BzrBranchFormat8()
3083
branch._transport.put_bytes('references', '')
3084
# update target format
3085
branch._transport.put_bytes('format', format.as_string())
3088
class InterBranch(InterObject):
3089
"""This class represents operations taking place between two branches.
3091
Its instances have methods like pull() and push() and contain
3092
references to the source and target repositories these operations
3093
can be carried out on.
3097
"""The available optimised InterBranch types."""
3100
def _get_branch_formats_to_test(klass):
3101
"""Return an iterable of format tuples for testing.
3103
:return: An iterable of (from_format, to_format) to use when testing
3104
this InterBranch class. Each InterBranch class should define this
3107
raise NotImplementedError(klass._get_branch_formats_to_test)
3110
def pull(self, overwrite=False, stop_revision=None,
3111
possible_transports=None, local=False):
3112
"""Mirror source into target branch.
3114
The target branch is considered to be 'local', having low latency.
3116
:returns: PullResult instance
3118
raise NotImplementedError(self.pull)
3121
def push(self, overwrite=False, stop_revision=None, lossy=False,
3122
_override_hook_source_branch=None):
3123
"""Mirror the source branch into the target branch.
3125
The source branch is considered to be 'local', having low latency.
3127
raise NotImplementedError(self.push)
3130
def copy_content_into(self, revision_id=None):
3131
"""Copy the content of source into target
3133
revision_id: if not None, the revision history in the new branch will
3134
be truncated to end with revision_id.
3136
raise NotImplementedError(self.copy_content_into)
3139
def fetch(self, stop_revision=None, limit=None):
3142
:param stop_revision: Last revision to fetch
3143
:param limit: Optional rough limit of revisions to fetch
3145
raise NotImplementedError(self.fetch)
3148
def _fix_overwrite_type(overwrite):
3149
if isinstance(overwrite, bool):
3151
return ["history", "tags"]
3157
class GenericInterBranch(InterBranch):
3158
"""InterBranch implementation that uses public Branch functions."""
3161
def is_compatible(klass, source, target):
3162
# GenericBranch uses the public API, so always compatible
3166
def _get_branch_formats_to_test(klass):
3167
return [(format_registry.get_default(), format_registry.get_default())]
3170
def unwrap_format(klass, format):
3171
if isinstance(format, remote.RemoteBranchFormat):
3172
format._ensure_real()
3173
return format._custom_format
3177
def copy_content_into(self, revision_id=None):
3178
"""Copy the content of source into target
3180
revision_id: if not None, the revision history in the new branch will
3181
be truncated to end with revision_id.
3183
self.source.update_references(self.target)
3184
self.source._synchronize_history(self.target, revision_id)
3186
parent = self.source.get_parent()
3187
except errors.InaccessibleParent as e:
3188
mutter('parent was not accessible to copy: %s', e)
3191
self.target.set_parent(parent)
3192
if self.source._push_should_merge_tags():
3193
self.source.tags.merge_to(self.target.tags)
3196
def fetch(self, stop_revision=None, limit=None):
3197
if self.target.base == self.source.base:
3199
self.source.lock_read()
3201
fetch_spec_factory = fetch.FetchSpecFactory()
3202
fetch_spec_factory.source_branch = self.source
3203
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3204
fetch_spec_factory.source_repo = self.source.repository
3205
fetch_spec_factory.target_repo = self.target.repository
3206
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3207
fetch_spec_factory.limit = limit
3208
fetch_spec = fetch_spec_factory.make_fetch_spec()
3209
return self.target.repository.fetch(self.source.repository,
3210
fetch_spec=fetch_spec)
3212
self.source.unlock()
3215
def _update_revisions(self, stop_revision=None, overwrite=False,
3217
other_revno, other_last_revision = self.source.last_revision_info()
3218
stop_revno = None # unknown
3219
if stop_revision is None:
3220
stop_revision = other_last_revision
3221
if _mod_revision.is_null(stop_revision):
3222
# if there are no commits, we're done.
3224
stop_revno = other_revno
3226
# what's the current last revision, before we fetch [and change it
3228
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3229
# we fetch here so that we don't process data twice in the common
3230
# case of having something to pull, and so that the check for
3231
# already merged can operate on the just fetched graph, which will
3232
# be cached in memory.
3233
self.fetch(stop_revision=stop_revision)
3234
# Check to see if one is an ancestor of the other
3237
graph = self.target.repository.get_graph()
3238
if self.target._check_if_descendant_or_diverged(
3239
stop_revision, last_rev, graph, self.source):
3240
# stop_revision is a descendant of last_rev, but we aren't
3241
# overwriting, so we're done.
3243
if stop_revno is None:
3245
graph = self.target.repository.get_graph()
3246
this_revno, this_last_revision = \
3247
self.target.last_revision_info()
3248
stop_revno = graph.find_distance_to_null(stop_revision,
3249
[(other_last_revision, other_revno),
3250
(this_last_revision, this_revno)])
3251
self.target.set_last_revision_info(stop_revno, stop_revision)
3254
def pull(self, overwrite=False, stop_revision=None,
3255
possible_transports=None, run_hooks=True,
3256
_override_hook_target=None, local=False):
3257
"""Pull from source into self, updating my master if any.
3259
:param run_hooks: Private parameter - if false, this branch
3260
is being called because it's the master of the primary branch,
3261
so it should not run its hooks.
3263
bound_location = self.target.get_bound_location()
3264
if local and not bound_location:
3265
raise errors.LocalRequiresBoundBranch()
3266
master_branch = None
3267
source_is_master = False
3269
# bound_location comes from a config file, some care has to be
3270
# taken to relate it to source.user_url
3271
normalized = urlutils.normalize_url(bound_location)
3273
relpath = self.source.user_transport.relpath(normalized)
3274
source_is_master = (relpath == '')
3275
except (errors.PathNotChild, errors.InvalidURL):
3276
source_is_master = False
3277
if not local and bound_location and not source_is_master:
3278
# not pulling from master, so we need to update master.
3279
master_branch = self.target.get_master_branch(possible_transports)
3280
master_branch.lock_write()
3283
# pull from source into master.
3284
master_branch.pull(self.source, overwrite, stop_revision,
3286
return self._pull(overwrite,
3287
stop_revision, _hook_master=master_branch,
3288
run_hooks=run_hooks,
3289
_override_hook_target=_override_hook_target,
3290
merge_tags_to_master=not source_is_master)
3293
master_branch.unlock()
3295
def push(self, overwrite=False, stop_revision=None, lossy=False,
3296
_override_hook_source_branch=None):
3297
"""See InterBranch.push.
3299
This is the basic concrete implementation of push()
3301
:param _override_hook_source_branch: If specified, run the hooks
3302
passing this Branch as the source, rather than self. This is for
3303
use of RemoteBranch, where push is delegated to the underlying
3307
raise errors.LossyPushToSameVCS(self.source, self.target)
3308
# TODO: Public option to disable running hooks - should be trivial but
3311
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3312
op.add_cleanup(self.source.lock_read().unlock)
3313
op.add_cleanup(self.target.lock_write().unlock)
3314
return op.run(overwrite, stop_revision,
3315
_override_hook_source_branch=_override_hook_source_branch)
3317
def _basic_push(self, overwrite, stop_revision):
3318
"""Basic implementation of push without bound branches or hooks.
3320
Must be called with source read locked and target write locked.
3322
result = BranchPushResult()
3323
result.source_branch = self.source
3324
result.target_branch = self.target
3325
result.old_revno, result.old_revid = self.target.last_revision_info()
3326
self.source.update_references(self.target)
3327
overwrite = _fix_overwrite_type(overwrite)
3328
if result.old_revid != stop_revision:
3329
# We assume that during 'push' this repository is closer than
3331
graph = self.source.repository.get_graph(self.target.repository)
3332
self._update_revisions(stop_revision,
3333
overwrite=("history" in overwrite),
3335
if self.source._push_should_merge_tags():
3336
result.tag_updates, result.tag_conflicts = (
3337
self.source.tags.merge_to(
3338
self.target.tags, "tags" in overwrite))
3339
result.new_revno, result.new_revid = self.target.last_revision_info()
3342
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3343
_override_hook_source_branch=None):
3344
"""Push from source into target, and into target's master if any.
3347
if _override_hook_source_branch:
3348
result.source_branch = _override_hook_source_branch
3349
for hook in Branch.hooks['post_push']:
3352
bound_location = self.target.get_bound_location()
3353
if bound_location and self.target.base != bound_location:
3354
# there is a master branch.
3356
# XXX: Why the second check? Is it even supported for a branch to
3357
# be bound to itself? -- mbp 20070507
3358
master_branch = self.target.get_master_branch()
3359
master_branch.lock_write()
3360
operation.add_cleanup(master_branch.unlock)
3361
# push into the master from the source branch.
3362
master_inter = InterBranch.get(self.source, master_branch)
3363
master_inter._basic_push(overwrite, stop_revision)
3364
# and push into the target branch from the source. Note that
3365
# we push from the source branch again, because it's considered
3366
# the highest bandwidth repository.
3367
result = self._basic_push(overwrite, stop_revision)
3368
result.master_branch = master_branch
3369
result.local_branch = self.target
3371
master_branch = None
3373
result = self._basic_push(overwrite, stop_revision)
3374
# TODO: Why set master_branch and local_branch if there's no
3375
# binding? Maybe cleaner to just leave them unset? -- mbp
3377
result.master_branch = self.target
3378
result.local_branch = None
3382
def _pull(self, overwrite=False, stop_revision=None,
3383
possible_transports=None, _hook_master=None, run_hooks=True,
3384
_override_hook_target=None, local=False,
3385
merge_tags_to_master=True):
3388
This function is the core worker, used by GenericInterBranch.pull to
3389
avoid duplication when pulling source->master and source->local.
3391
:param _hook_master: Private parameter - set the branch to
3392
be supplied as the master to pull hooks.
3393
:param run_hooks: Private parameter - if false, this branch
3394
is being called because it's the master of the primary branch,
3395
so it should not run its hooks.
3396
is being called because it's the master of the primary branch,
3397
so it should not run its hooks.
3398
:param _override_hook_target: Private parameter - set the branch to be
3399
supplied as the target_branch to pull hooks.
3400
:param local: Only update the local branch, and not the bound branch.
3402
# This type of branch can't be bound.
3404
raise errors.LocalRequiresBoundBranch()
3405
result = PullResult()
3406
result.source_branch = self.source
3407
if _override_hook_target is None:
3408
result.target_branch = self.target
3410
result.target_branch = _override_hook_target
3411
self.source.lock_read()
3413
# We assume that during 'pull' the target repository is closer than
3415
self.source.update_references(self.target)
3416
graph = self.target.repository.get_graph(self.source.repository)
3417
# TODO: Branch formats should have a flag that indicates
3418
# that revno's are expensive, and pull() should honor that flag.
3420
result.old_revno, result.old_revid = \
3421
self.target.last_revision_info()
3422
overwrite = _fix_overwrite_type(overwrite)
3423
self._update_revisions(stop_revision,
3424
overwrite=("history" in overwrite),
3426
# TODO: The old revid should be specified when merging tags,
3427
# so a tags implementation that versions tags can only
3428
# pull in the most recent changes. -- JRV20090506
3429
result.tag_updates, result.tag_conflicts = (
3430
self.source.tags.merge_to(self.target.tags,
3431
"tags" in overwrite,
3432
ignore_master=not merge_tags_to_master))
3433
result.new_revno, result.new_revid = self.target.last_revision_info()
3435
result.master_branch = _hook_master
3436
result.local_branch = result.target_branch
3438
result.master_branch = result.target_branch
3439
result.local_branch = None
3441
for hook in Branch.hooks['post_pull']:
3444
self.source.unlock()
3448
InterBranch.register_optimiser(GenericInterBranch)