145
191
possible_transports)
146
192
return control.open_branch(), relpath
194
def _push_should_merge_tags(self):
195
"""Should _basic_push merge this branch's tags into the target?
197
The default implementation returns False if this branch has no tags,
198
and True the rest of the time. Subclasses may override this.
200
return self.supports_tags() and self.tags.get_tag_dict()
148
202
def get_config(self):
149
203
return BranchConfig(self)
152
return self.get_config().get_nickname()
205
def _get_config(self):
206
"""Get the concrete config for just the config in this branch.
208
This is not intended for client use; see Branch.get_config for the
213
:return: An object supporting get_option and set_option.
215
raise NotImplementedError(self._get_config)
217
def _get_fallback_repository(self, url):
218
"""Get the repository we fallback to at url."""
219
url = urlutils.join(self.base, url)
220
a_branch = Branch.open(url,
221
possible_transports=[self.bzrdir.root_transport])
222
return a_branch.repository
224
def _get_tags_bytes(self):
225
"""Get the bytes of a serialised tags dict.
227
Note that not all branches support tags, nor do all use the same tags
228
logic: this method is specific to BasicTags. Other tag implementations
229
may use the same method name and behave differently, safely, because
230
of the double-dispatch via
231
format.make_tags->tags_instance->get_tags_dict.
233
:return: The bytes of the tags file.
234
:seealso: Branch._set_tags_bytes.
236
return self._transport.get_bytes('tags')
238
def _get_nick(self, local=False, possible_transports=None):
239
config = self.get_config()
240
# explicit overrides master, but don't look for master if local is True
241
if not local and not config.has_explicit_nickname():
243
master = self.get_master_branch(possible_transports)
244
if master is not None:
245
# return the master branch value
247
except errors.BzrError, e:
248
# Silently fall back to local implicit nick if the master is
250
mutter("Could not connect to bound branch, "
251
"falling back to local nick.\n " + str(e))
252
return config.get_nickname()
154
254
def _set_nick(self, nick):
155
255
self.get_config().set_user_option('nickname', nick, warn_masked=True)
176
303
raise NotImplementedError(self.get_physical_lock_status)
306
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
307
"""Return the revision_id for a dotted revno.
309
:param revno: a tuple like (1,) or (1,1,2)
310
:param _cache_reverse: a private parameter enabling storage
311
of the reverse mapping in a top level cache. (This should
312
only be done in selective circumstances as we want to
313
avoid having the mapping cached multiple times.)
314
:return: the revision_id
315
:raises errors.NoSuchRevision: if the revno doesn't exist
317
rev_id = self._do_dotted_revno_to_revision_id(revno)
319
self._partial_revision_id_to_revno_cache[rev_id] = revno
322
def _do_dotted_revno_to_revision_id(self, revno):
323
"""Worker function for dotted_revno_to_revision_id.
325
Subclasses should override this if they wish to
326
provide a more efficient implementation.
329
return self.get_rev_id(revno[0])
330
revision_id_to_revno = self.get_revision_id_to_revno_map()
331
revision_ids = [revision_id for revision_id, this_revno
332
in revision_id_to_revno.iteritems()
333
if revno == this_revno]
334
if len(revision_ids) == 1:
335
return revision_ids[0]
337
revno_str = '.'.join(map(str, revno))
338
raise errors.NoSuchRevision(self, revno_str)
341
def revision_id_to_dotted_revno(self, revision_id):
342
"""Given a revision id, return its dotted revno.
344
:return: a tuple like (1,) or (400,1,3).
346
return self._do_revision_id_to_dotted_revno(revision_id)
348
def _do_revision_id_to_dotted_revno(self, revision_id):
349
"""Worker function for revision_id_to_revno."""
350
# Try the caches if they are loaded
351
result = self._partial_revision_id_to_revno_cache.get(revision_id)
352
if result is not None:
354
if self._revision_id_to_revno_cache:
355
result = self._revision_id_to_revno_cache.get(revision_id)
357
raise errors.NoSuchRevision(self, revision_id)
358
# Try the mainline as it's optimised
360
revno = self.revision_id_to_revno(revision_id)
362
except errors.NoSuchRevision:
363
# We need to load and use the full revno map after all
364
result = self.get_revision_id_to_revno_map().get(revision_id)
366
raise errors.NoSuchRevision(self, revision_id)
179
370
def get_revision_id_to_revno_map(self):
180
371
"""Return the revision_id => dotted revno map.
206
397
:return: A dictionary mapping revision_id => dotted revno.
208
last_revision = self.last_revision()
209
revision_graph = repository._old_get_graph(self.repository,
211
merge_sorted_revisions = tsort.merge_sort(
216
399
revision_id_to_revno = dict((rev_id, revno)
217
for seq_num, rev_id, depth, revno, end_of_merge
218
in merge_sorted_revisions)
400
for rev_id, depth, revno, end_of_merge
401
in self.iter_merge_sorted_revisions())
219
402
return revision_id_to_revno
405
def iter_merge_sorted_revisions(self, start_revision_id=None,
406
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
407
"""Walk the revisions for a branch in merge sorted order.
409
Merge sorted order is the output from a merge-aware,
410
topological sort, i.e. all parents come before their
411
children going forward; the opposite for reverse.
413
:param start_revision_id: the revision_id to begin walking from.
414
If None, the branch tip is used.
415
:param stop_revision_id: the revision_id to terminate the walk
416
after. If None, the rest of history is included.
417
:param stop_rule: if stop_revision_id is not None, the precise rule
418
to use for termination:
419
* 'exclude' - leave the stop revision out of the result (default)
420
* 'include' - the stop revision is the last item in the result
421
* 'with-merges' - include the stop revision and all of its
422
merged revisions in the result
423
:param direction: either 'reverse' or 'forward':
424
* reverse means return the start_revision_id first, i.e.
425
start at the most recent revision and go backwards in history
426
* forward returns tuples in the opposite order to reverse.
427
Note in particular that forward does *not* do any intelligent
428
ordering w.r.t. depth as some clients of this API may like.
429
(If required, that ought to be done at higher layers.)
431
:return: an iterator over (revision_id, depth, revno, end_of_merge)
434
* revision_id: the unique id of the revision
435
* depth: How many levels of merging deep this node has been
437
* revno_sequence: This field provides a sequence of
438
revision numbers for all revisions. The format is:
439
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
440
branch that the revno is on. From left to right the REVNO numbers
441
are the sequence numbers within that branch of the revision.
442
* end_of_merge: When True the next node (earlier in history) is
443
part of a different merge.
445
# Note: depth and revno values are in the context of the branch so
446
# we need the full graph to get stable numbers, regardless of the
448
if self._merge_sorted_revisions_cache is None:
449
last_revision = self.last_revision()
450
known_graph = self.repository.get_known_graph_ancestry(
452
self._merge_sorted_revisions_cache = known_graph.merge_sort(
454
filtered = self._filter_merge_sorted_revisions(
455
self._merge_sorted_revisions_cache, start_revision_id,
456
stop_revision_id, stop_rule)
457
# Make sure we don't return revisions that are not part of the
458
# start_revision_id ancestry.
459
filtered = self._filter_non_ancestors(filtered)
460
if direction == 'reverse':
462
if direction == 'forward':
463
return reversed(list(filtered))
465
raise ValueError('invalid direction %r' % direction)
467
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
468
start_revision_id, stop_revision_id, stop_rule):
469
"""Iterate over an inclusive range of sorted revisions."""
470
rev_iter = iter(merge_sorted_revisions)
471
if start_revision_id is not None:
472
for node in rev_iter:
473
rev_id = node.key[-1]
474
if rev_id != start_revision_id:
477
# The decision to include the start or not
478
# depends on the stop_rule if a stop is provided
479
# so pop this node back into the iterator
480
rev_iter = chain(iter([node]), rev_iter)
482
if stop_revision_id is None:
484
for node in rev_iter:
485
rev_id = node.key[-1]
486
yield (rev_id, node.merge_depth, node.revno,
488
elif stop_rule == 'exclude':
489
for node in rev_iter:
490
rev_id = node.key[-1]
491
if rev_id == stop_revision_id:
493
yield (rev_id, node.merge_depth, node.revno,
495
elif stop_rule == 'include':
496
for node in rev_iter:
497
rev_id = node.key[-1]
498
yield (rev_id, node.merge_depth, node.revno,
500
if rev_id == stop_revision_id:
502
elif stop_rule == 'with-merges':
503
stop_rev = self.repository.get_revision(stop_revision_id)
504
if stop_rev.parent_ids:
505
left_parent = stop_rev.parent_ids[0]
507
left_parent = _mod_revision.NULL_REVISION
508
# left_parent is the actual revision we want to stop logging at,
509
# since we want to show the merged revisions after the stop_rev too
510
reached_stop_revision_id = False
511
revision_id_whitelist = []
512
for node in rev_iter:
513
rev_id = node.key[-1]
514
if rev_id == left_parent:
515
# reached the left parent after the stop_revision
517
if (not reached_stop_revision_id or
518
rev_id in revision_id_whitelist):
519
yield (rev_id, node.merge_depth, node.revno,
521
if reached_stop_revision_id or rev_id == stop_revision_id:
522
# only do the merged revs of rev_id from now on
523
rev = self.repository.get_revision(rev_id)
525
reached_stop_revision_id = True
526
revision_id_whitelist.extend(rev.parent_ids)
528
raise ValueError('invalid stop_rule %r' % stop_rule)
530
def _filter_non_ancestors(self, rev_iter):
531
# If we started from a dotted revno, we want to consider it as a tip
532
# and don't want to yield revisions that are not part of its
533
# ancestry. Given the order guaranteed by the merge sort, we will see
534
# uninteresting descendants of the first parent of our tip before the
536
first = rev_iter.next()
537
(rev_id, merge_depth, revno, end_of_merge) = first
540
# We start at a mainline revision so by definition, all others
541
# revisions in rev_iter are ancestors
542
for node in rev_iter:
547
pmap = self.repository.get_parent_map([rev_id])
548
parents = pmap.get(rev_id, [])
550
whitelist.update(parents)
552
# If there is no parents, there is nothing of interest left
554
# FIXME: It's hard to test this scenario here as this code is never
555
# called in that case. -- vila 20100322
558
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
560
if rev_id in whitelist:
561
pmap = self.repository.get_parent_map([rev_id])
562
parents = pmap.get(rev_id, [])
563
whitelist.remove(rev_id)
564
whitelist.update(parents)
566
# We've reached the mainline, there is nothing left to
570
# A revision that is not part of the ancestry of our
573
yield (rev_id, merge_depth, revno, end_of_merge)
221
575
def leave_lock_in_place(self):
222
576
"""Tell this branch object not to release the physical lock when this
223
577
object is unlocked.
225
579
If lock_write doesn't return a token, then this method is not supported.
227
581
self.control_files.leave_in_place()
351
735
:raises UnstackableRepositoryFormat: If the repository does not support
354
raise NotImplementedError(self.set_stacked_on_url)
738
if not self._format.supports_stacking():
739
raise errors.UnstackableBranchFormat(self._format, self.base)
740
# XXX: Changing from one fallback repository to another does not check
741
# that all the data you need is present in the new fallback.
742
# Possibly it should.
743
self._check_stackable_repo()
746
old_url = self.get_stacked_on_url()
747
except (errors.NotStacked, errors.UnstackableBranchFormat,
748
errors.UnstackableRepositoryFormat):
752
self._activate_fallback_location(url)
753
# write this out after the repository is stacked to avoid setting a
754
# stacked config that doesn't work.
755
self._set_config_location('stacked_on_location', url)
758
"""Change a branch to be unstacked, copying data as needed.
760
Don't call this directly, use set_stacked_on_url(None).
762
pb = ui.ui_factory.nested_progress_bar()
764
pb.update("Unstacking")
765
# The basic approach here is to fetch the tip of the branch,
766
# including all available ghosts, from the existing stacked
767
# repository into a new repository object without the fallbacks.
769
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
770
# correct for CHKMap repostiories
771
old_repository = self.repository
772
if len(old_repository._fallback_repositories) != 1:
773
raise AssertionError("can't cope with fallback repositories "
774
"of %r" % (self.repository,))
775
# unlock it, including unlocking the fallback
776
old_repository.unlock()
777
old_repository.lock_read()
779
# Repositories don't offer an interface to remove fallback
780
# repositories today; take the conceptually simpler option and just
781
# reopen it. We reopen it starting from the URL so that we
782
# get a separate connection for RemoteRepositories and can
783
# stream from one of them to the other. This does mean doing
784
# separate SSH connection setup, but unstacking is not a
785
# common operation so it's tolerable.
786
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
787
new_repository = new_bzrdir.find_repository()
788
self.repository = new_repository
789
if self.repository._fallback_repositories:
790
raise AssertionError("didn't expect %r to have "
791
"fallback_repositories"
792
% (self.repository,))
793
# this is not paired with an unlock because it's just restoring
794
# the previous state; the lock's released when set_stacked_on_url
796
self.repository.lock_write()
797
# XXX: If you unstack a branch while it has a working tree
798
# with a pending merge, the pending-merged revisions will no
799
# longer be present. You can (probably) revert and remerge.
801
# XXX: This only fetches up to the tip of the repository; it
802
# doesn't bring across any tags. That's fairly consistent
803
# with how branch works, but perhaps not ideal.
804
self.repository.fetch(old_repository,
805
revision_id=self.last_revision(),
808
old_repository.unlock()
812
def _set_tags_bytes(self, bytes):
813
"""Mirror method for _get_tags_bytes.
815
:seealso: Branch._get_tags_bytes.
817
return _run_with_write_locked_target(self, self._transport.put_bytes,
356
820
def _cache_revision_history(self, rev_history):
357
821
"""Set the cached revision history to rev_history.
490
953
information. This can be None.
495
other_revno, other_last_revision = other.last_revision_info()
496
stop_revno = None # unknown
497
if stop_revision is None:
498
stop_revision = other_last_revision
499
if _mod_revision.is_null(stop_revision):
500
# if there are no commits, we're done.
502
stop_revno = other_revno
504
# what's the current last revision, before we fetch [and change it
506
last_rev = _mod_revision.ensure_null(self.last_revision())
507
# we fetch here so that we don't process data twice in the common
508
# case of having something to pull, and so that the check for
509
# already merged can operate on the just fetched graph, which will
510
# be cached in memory.
511
self.fetch(other, stop_revision)
512
# Check to see if one is an ancestor of the other
515
graph = self.repository.get_graph()
516
if self._check_if_descendant_or_diverged(
517
stop_revision, last_rev, graph, other):
518
# stop_revision is a descendant of last_rev, but we aren't
519
# overwriting, so we're done.
521
if stop_revno is None:
523
graph = self.repository.get_graph()
524
this_revno, this_last_revision = self.last_revision_info()
525
stop_revno = graph.find_distance_to_null(stop_revision,
526
[(other_last_revision, other_revno),
527
(this_last_revision, this_revno)])
528
self.set_last_revision_info(stop_revno, stop_revision)
956
return InterBranch.get(other, self).update_revisions(stop_revision,
959
def import_last_revision_info(self, source_repo, revno, revid):
960
"""Set the last revision info, importing from another repo if necessary.
962
This is used by the bound branch code to upload a revision to
963
the master branch first before updating the tip of the local branch.
965
:param source_repo: Source repository to optionally fetch from
966
:param revno: Revision number of the new tip
967
:param revid: Revision id of the new tip
969
if not self.repository.has_same_location(source_repo):
970
self.repository.fetch(source_repo, revision_id=revid)
971
self.set_last_revision_info(revno, revid)
532
973
def revision_id_to_revno(self, revision_id):
533
974
"""Given a revision id, return its revno"""
539
980
except ValueError:
540
981
raise errors.NoSuchRevision(self, revision_id)
542
984
def get_rev_id(self, revno, history=None):
543
985
"""Find the revision id of the specified revno."""
545
987
return _mod_revision.NULL_REVISION
547
history = self.revision_history()
548
if revno <= 0 or revno > len(history):
988
last_revno, last_revid = self.last_revision_info()
989
if revno == last_revno:
991
if revno <= 0 or revno > last_revno:
549
992
raise errors.NoSuchRevision(self, revno)
550
return history[revno - 1]
993
distance_from_last = last_revno - revno
994
if len(self._partial_revision_history_cache) <= distance_from_last:
995
self._extend_partial_history(distance_from_last)
996
return self._partial_revision_history_cache[distance_from_last]
552
999
def pull(self, source, overwrite=False, stop_revision=None,
553
possible_transports=None, _override_hook_target=None):
1000
possible_transports=None, *args, **kwargs):
554
1001
"""Mirror source into this branch.
556
1003
This branch is considered to be 'local', having low latency.
558
1005
:returns: PullResult instance
560
raise NotImplementedError(self.pull)
1007
return InterBranch.get(source, self).pull(overwrite=overwrite,
1008
stop_revision=stop_revision,
1009
possible_transports=possible_transports, *args, **kwargs)
562
def push(self, target, overwrite=False, stop_revision=None):
1011
def push(self, target, overwrite=False, stop_revision=None, *args,
563
1013
"""Mirror this branch into target.
565
1015
This branch is considered to be 'local', having low latency.
567
raise NotImplementedError(self.push)
1017
return InterBranch.get(self, target).push(overwrite, stop_revision,
1020
def lossy_push(self, target, stop_revision=None):
1021
"""Push deltas into another branch.
1023
:note: This does not, like push, retain the revision ids from
1024
the source branch and will, rather than adding bzr-specific
1025
metadata, push only those semantics of the revision that can be
1026
natively represented by this branch' VCS.
1028
:param target: Target branch
1029
:param stop_revision: Revision to push, defaults to last revision.
1030
:return: BranchPushResult with an extra member revidmap:
1031
A dictionary mapping revision ids from the target branch
1032
to new revision ids in the target branch, for each
1033
revision that was pushed.
1035
inter = InterBranch.get(self, target)
1036
lossy_push = getattr(inter, "lossy_push", None)
1037
if lossy_push is None:
1038
raise errors.LossyPushToSameVCS(self, target)
1039
return lossy_push(stop_revision)
569
1041
def basis_tree(self):
570
1042
"""Return `Tree` object for last revision."""
688
1205
revision_id: if not None, the revision history in the new branch will
689
1206
be truncated to end with revision_id.
1208
if (repository_policy is not None and
1209
repository_policy.requires_stacking()):
1210
to_bzrdir._format.require_stacking(_skip_repo=True)
691
1211
result = to_bzrdir.create_branch()
692
self.copy_content_into(result, revision_id=revision_id)
693
result.set_parent(self.bzrdir.root_transport.base)
1214
if repository_policy is not None:
1215
repository_policy.configure_branch(result)
1216
self.copy_content_into(result, revision_id=revision_id)
1217
result.set_parent(self.bzrdir.root_transport.base)
696
1222
def _synchronize_history(self, destination, revision_id):
697
1223
"""Synchronize last revision and revision history between branches.
699
1225
This version is most efficient when the destination is also a
700
BzrBranch5, but works for BzrBranch6 as long as the revision
701
history is the true lefthand parent history, and all of the revisions
702
are in the destination's repository. If not, set_revision_history
1226
BzrBranch6, but works for BzrBranch5, as long as the destination's
1227
repository contains all the lefthand ancestors of the intended
1228
last_revision. If not, set_last_revision_info will fail.
705
1230
:param destination: The branch to copy the history into
706
1231
:param revision_id: The revision-id to truncate history at. May
707
1232
be None to copy complete history.
709
if revision_id == _mod_revision.NULL_REVISION:
1234
source_revno, source_revision_id = self.last_revision_info()
1235
if revision_id is None:
1236
revno, revision_id = source_revno, source_revision_id
712
new_history = self.revision_history()
713
if revision_id is not None and new_history != []:
1238
graph = self.repository.get_graph()
715
new_history = new_history[:new_history.index(revision_id) + 1]
717
rev = self.repository.get_revision(revision_id)
718
new_history = rev.get_history(self.repository)[1:]
719
destination.set_revision_history(new_history)
1240
revno = graph.find_distance_to_null(revision_id,
1241
[(source_revision_id, source_revno)])
1242
except errors.GhostRevisionsHaveNoRevno:
1243
# Default to 1, if we can't find anything else
1245
destination.set_last_revision_info(revno, revision_id)
721
1247
@needs_read_lock
722
1248
def copy_content_into(self, destination, revision_id=None):
735
1262
destination.set_parent(parent)
736
self.tags.merge_to(destination.tags)
1263
if self._push_should_merge_tags():
1264
self.tags.merge_to(destination.tags)
1266
def update_references(self, target):
1267
if not getattr(self._format, 'supports_reference_locations', False):
1269
reference_dict = self._get_all_reference_info()
1270
if len(reference_dict) == 0:
1272
old_base = self.base
1273
new_base = target.base
1274
target_reference_dict = target._get_all_reference_info()
1275
for file_id, (tree_path, branch_location) in (
1276
reference_dict.items()):
1277
branch_location = urlutils.rebase_url(branch_location,
1279
target_reference_dict.setdefault(
1280
file_id, (tree_path, branch_location))
1281
target._set_all_reference_info(target_reference_dict)
738
1283
@needs_read_lock
1284
def check(self, refs):
740
1285
"""Check consistency of the branch.
742
1287
In particular this checks that revisions given in the revision-history
743
do actually match up in the revision graph, and that they're all
1288
do actually match up in the revision graph, and that they're all
744
1289
present in the repository.
746
1291
Callers will typically also want to check the repository.
1293
:param refs: Calculated refs for this branch as specified by
1294
branch._get_check_refs()
748
1295
:return: A BranchCheckResult.
750
mainline_parent_id = None
1297
result = BranchCheckResult(self)
751
1298
last_revno, last_revision_id = self.last_revision_info()
752
real_rev_history = list(self.repository.iter_reverse_revision_history(
754
real_rev_history.reverse()
755
if len(real_rev_history) != last_revno:
756
raise errors.BzrCheckError('revno does not match len(mainline)'
757
' %s != %s' % (last_revno, len(real_rev_history)))
758
# TODO: We should probably also check that real_rev_history actually
759
# matches self.revision_history()
760
for revision_id in real_rev_history:
762
revision = self.repository.get_revision(revision_id)
763
except errors.NoSuchRevision, e:
764
raise errors.BzrCheckError("mainline revision {%s} not in repository"
766
# In general the first entry on the revision history has no parents.
767
# But it's not illegal for it to have parents listed; this can happen
768
# in imports from Arch when the parents weren't reachable.
769
if mainline_parent_id is not None:
770
if mainline_parent_id not in revision.parent_ids:
771
raise errors.BzrCheckError("previous revision {%s} not listed among "
773
% (mainline_parent_id, revision_id))
774
mainline_parent_id = revision_id
775
return BranchCheckResult(self)
1299
actual_revno = refs[('lefthand-distance', last_revision_id)]
1300
if actual_revno != last_revno:
1301
result.errors.append(errors.BzrCheckError(
1302
'revno does not match len(mainline) %s != %s' % (
1303
last_revno, actual_revno)))
1304
# TODO: We should probably also check that self.revision_history
1305
# matches the repository for older branch formats.
1306
# If looking for the code that cross-checks repository parents against
1307
# the iter_reverse_revision_history output, that is now a repository
777
1311
def _get_checkout_format(self):
778
1312
"""Return the most suitable metadir for a checkout of this branch.
1003
1582
filename, content,
1004
1583
mode=a_bzrdir._get_file_mode())
1006
control_files.unlock()
1007
return self.open(a_bzrdir, _found=True)
1586
control_files.unlock()
1587
return self.open(a_bzrdir, name, _found=True)
1009
def initialize(self, a_bzrdir):
1010
"""Create a branch of this format in a_bzrdir."""
1589
def initialize(self, a_bzrdir, name=None):
1590
"""Create a branch of this format in a_bzrdir.
1592
:param name: Name of the colocated branch to create.
1011
1594
raise NotImplementedError(self.initialize)
1013
1596
def is_supported(self):
1014
1597
"""Is this format supported?
1016
1599
Supported formats can be initialized and opened.
1017
Unsupported formats may not support initialization or committing or
1600
Unsupported formats may not support initialization or committing or
1018
1601
some other features depending on the reason for not being supported.
1022
def open(self, a_bzrdir, _found=False):
1605
def make_tags(self, branch):
1606
"""Create a tags object for branch.
1608
This method is on BranchFormat, because BranchFormats are reflected
1609
over the wire via network_name(), whereas full Branch instances require
1610
multiple VFS method calls to operate at all.
1612
The default implementation returns a disabled-tags instance.
1614
Note that it is normal for branch to be a RemoteBranch when using tags
1617
return DisabledTags(branch)
1619
def network_name(self):
1620
"""A simple byte string uniquely identifying this format for RPC calls.
1622
MetaDir branch formats use their disk format string to identify the
1623
repository over the wire. All in one formats such as bzr < 0.8, and
1624
foreign formats like svn/git and hg should use some marker which is
1625
unique and immutable.
1627
raise NotImplementedError(self.network_name)
1629
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1023
1630
"""Return the branch object for a_bzrdir
1025
_found is a private parameter, do not use it. It is used to indicate
1026
if format probing has already be done.
1632
:param a_bzrdir: A BzrDir that contains a branch.
1633
:param name: Name of colocated branch to open
1634
:param _found: a private parameter, do not use it. It is used to
1635
indicate if format probing has already be done.
1636
:param ignore_fallbacks: when set, no fallback branches will be opened
1637
(if there are any). Default is to open fallbacks.
1028
1639
raise NotImplementedError(self.open)
1031
1642
def register_format(klass, format):
1643
"""Register a metadir format."""
1032
1644
klass._formats[format.get_format_string()] = format
1645
# Metadir formats have a network name of their format string, and get
1646
# registered as class factories.
1647
network_format_registry.register(format.get_format_string(), format.__class__)
1035
1650
def set_default_format(klass, format):
1036
1651
klass._default_format = format
1653
def supports_set_append_revisions_only(self):
1654
"""True if this format supports set_append_revisions_only."""
1038
1657
def supports_stacking(self):
1039
1658
"""True if this format records a stacked-on branch."""
1067
1686
Hooks.__init__(self)
1068
# Introduced in 0.15:
1069
# invoked whenever the revision history has been set
1070
# with set_revision_history. The api signature is
1071
# (branch, revision_history), and the branch will
1074
# Invoked after a branch is opened. The api signature is (branch).
1076
# invoked after a push operation completes.
1077
# the api signature is
1079
# containing the members
1080
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1081
# where local is the local target branch or None, master is the target
1082
# master branch, and the rest should be self explanatory. The source
1083
# is read locked and the target branches write locked. Source will
1084
# be the local low-latency branch.
1085
self['post_push'] = []
1086
# invoked after a pull operation completes.
1087
# the api signature is
1089
# containing the members
1090
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1091
# where local is the local branch or None, master is the target
1092
# master branch, and the rest should be self explanatory. The source
1093
# is read locked and the target branches write locked. The local
1094
# branch is the low-latency branch.
1095
self['post_pull'] = []
1096
# invoked before a commit operation takes place.
1097
# the api signature is
1098
# (local, master, old_revno, old_revid, future_revno, future_revid,
1099
# tree_delta, future_tree).
1100
# old_revid is NULL_REVISION for the first commit to a branch
1101
# tree_delta is a TreeDelta object describing changes from the basis
1102
# revision, hooks MUST NOT modify this delta
1103
# future_tree is an in-memory tree obtained from
1104
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1105
self['pre_commit'] = []
1106
# invoked after a commit operation completes.
1107
# the api signature is
1108
# (local, master, old_revno, old_revid, new_revno, new_revid)
1109
# old_revid is NULL_REVISION for the first commit to a branch.
1110
self['post_commit'] = []
1111
# invoked after a uncommit operation completes.
1112
# the api signature is
1113
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1114
# local is the local branch or None, master is the target branch,
1115
# and an empty branch recieves new_revno of 0, new_revid of None.
1116
self['post_uncommit'] = []
1118
# Invoked before the tip of a branch changes.
1119
# the api signature is
1120
# (params) where params is a ChangeBranchTipParams with the members
1121
# (branch, old_revno, new_revno, old_revid, new_revid)
1122
self['pre_change_branch_tip'] = []
1124
# Invoked after the tip of a branch changes.
1125
# the api signature is
1126
# (params) where params is a ChangeBranchTipParams with the members
1127
# (branch, old_revno, new_revno, old_revid, new_revid)
1128
self['post_change_branch_tip'] = []
1687
self.create_hook(HookPoint('set_rh',
1688
"Invoked whenever the revision history has been set via "
1689
"set_revision_history. The api signature is (branch, "
1690
"revision_history), and the branch will be write-locked. "
1691
"The set_rh hook can be expensive for bzr to trigger, a better "
1692
"hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1693
self.create_hook(HookPoint('open',
1694
"Called with the Branch object that has been opened after a "
1695
"branch is opened.", (1, 8), None))
1696
self.create_hook(HookPoint('post_push',
1697
"Called after a push operation completes. post_push is called "
1698
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1699
"bzr client.", (0, 15), None))
1700
self.create_hook(HookPoint('post_pull',
1701
"Called after a pull operation completes. post_pull is called "
1702
"with a bzrlib.branch.PullResult object and only runs in the "
1703
"bzr client.", (0, 15), None))
1704
self.create_hook(HookPoint('pre_commit',
1705
"Called after a commit is calculated but before it is is "
1706
"completed. pre_commit is called with (local, master, old_revno, "
1707
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1708
"). old_revid is NULL_REVISION for the first commit to a branch, "
1709
"tree_delta is a TreeDelta object describing changes from the "
1710
"basis revision. hooks MUST NOT modify this delta. "
1711
" future_tree is an in-memory tree obtained from "
1712
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1713
"tree.", (0,91), None))
1714
self.create_hook(HookPoint('post_commit',
1715
"Called in the bzr client after a commit has completed. "
1716
"post_commit is called with (local, master, old_revno, old_revid, "
1717
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1718
"commit to a branch.", (0, 15), None))
1719
self.create_hook(HookPoint('post_uncommit',
1720
"Called in the bzr client after an uncommit completes. "
1721
"post_uncommit is called with (local, master, old_revno, "
1722
"old_revid, new_revno, new_revid) where local is the local branch "
1723
"or None, master is the target branch, and an empty branch "
1724
"receives new_revno of 0, new_revid of None.", (0, 15), None))
1725
self.create_hook(HookPoint('pre_change_branch_tip',
1726
"Called in bzr client and server before a change to the tip of a "
1727
"branch is made. pre_change_branch_tip is called with a "
1728
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1729
"commit, uncommit will all trigger this hook.", (1, 6), None))
1730
self.create_hook(HookPoint('post_change_branch_tip',
1731
"Called in bzr client and server after a change to the tip of a "
1732
"branch is made. post_change_branch_tip is called with a "
1733
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1734
"commit, uncommit will all trigger this hook.", (1, 4), None))
1735
self.create_hook(HookPoint('transform_fallback_location',
1736
"Called when a stacked branch is activating its fallback "
1737
"locations. transform_fallback_location is called with (branch, "
1738
"url), and should return a new url. Returning the same url "
1739
"allows it to be used as-is, returning a different one can be "
1740
"used to cause the branch to stack on a closer copy of that "
1741
"fallback_location. Note that the branch cannot have history "
1742
"accessing methods called on it during this hook because the "
1743
"fallback locations have not been activated. When there are "
1744
"multiple hooks installed for transform_fallback_location, "
1745
"all are called with the url returned from the previous hook."
1746
"The order is however undefined.", (1, 9), None))
1747
self.create_hook(HookPoint('automatic_tag_name',
1748
"Called to determine an automatic tag name for a revision."
1749
"automatic_tag_name is called with (branch, revision_id) and "
1750
"should return a tag name or None if no tag name could be "
1751
"determined. The first non-None tag name returned will be used.",
1131
1756
# install the default hooks into the Branch class.
1306
1938
"""See BranchFormat.get_format_description()."""
1307
1939
return "Branch format 6"
1309
def initialize(self, a_bzrdir):
1310
"""Create a branch of this format in a_bzrdir."""
1311
utf8_files = [('last-revision', '0 null:\n'),
1312
('branch.conf', ''),
1315
return self._initialize_helper(a_bzrdir, utf8_files)
1318
class BzrBranchFormat7(BranchFormatMetadir):
1941
def initialize(self, a_bzrdir, name=None):
1942
"""Create a branch of this format in a_bzrdir."""
1943
utf8_files = [('last-revision', '0 null:\n'),
1944
('branch.conf', ''),
1947
return self._initialize_helper(a_bzrdir, utf8_files, name)
1949
def make_tags(self, branch):
1950
"""See bzrlib.branch.BranchFormat.make_tags()."""
1951
return BasicTags(branch)
1953
def supports_set_append_revisions_only(self):
1957
class BzrBranchFormat8(BranchFormatMetadir):
1958
"""Metadir format supporting storing locations of subtree branches."""
1960
def _branch_class(self):
1963
def get_format_string(self):
1964
"""See BranchFormat.get_format_string()."""
1965
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
1967
def get_format_description(self):
1968
"""See BranchFormat.get_format_description()."""
1969
return "Branch format 8"
1971
def initialize(self, a_bzrdir, name=None):
1972
"""Create a branch of this format in a_bzrdir."""
1973
utf8_files = [('last-revision', '0 null:\n'),
1974
('branch.conf', ''),
1978
return self._initialize_helper(a_bzrdir, utf8_files, name)
1981
super(BzrBranchFormat8, self).__init__()
1982
self._matchingbzrdir.repository_format = \
1983
RepositoryFormatKnitPack5RichRoot()
1985
def make_tags(self, branch):
1986
"""See bzrlib.branch.BranchFormat.make_tags()."""
1987
return BasicTags(branch)
1989
def supports_set_append_revisions_only(self):
1992
def supports_stacking(self):
1995
supports_reference_locations = True
1998
class BzrBranchFormat7(BzrBranchFormat8):
1319
1999
"""Branch format with last-revision, tags, and a stacked location pointer.
1321
2001
The stacked location pointer is passed down to the repository and requires
1374
2051
def get_reference(self, a_bzrdir):
1375
2052
"""See BranchFormat.get_reference()."""
1376
2053
transport = a_bzrdir.get_branch_transport(None)
1377
return transport.get('location').read()
2054
return transport.get_bytes('location')
1379
2056
def set_reference(self, a_bzrdir, to_branch):
1380
2057
"""See BranchFormat.set_reference()."""
1381
2058
transport = a_bzrdir.get_branch_transport(None)
1382
2059
location = transport.put_bytes('location', to_branch.base)
1384
def initialize(self, a_bzrdir, target_branch=None):
2061
def initialize(self, a_bzrdir, name=None, target_branch=None):
1385
2062
"""Create a branch of this format in a_bzrdir."""
1386
2063
if target_branch is None:
1387
2064
# this format does not implement branch itself, thus the implicit
1388
2065
# creation contract must see it as uninitializable
1389
2066
raise errors.UninitializableFormat(self)
1390
2067
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1391
branch_transport = a_bzrdir.get_branch_transport(self)
2068
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1392
2069
branch_transport.put_bytes('location',
1393
2070
target_branch.bzrdir.root_transport.base)
1394
2071
branch_transport.put_bytes('format', self.get_format_string())
1395
2072
return self.open(
1396
a_bzrdir, _found=True,
2073
a_bzrdir, name, _found=True,
1397
2074
possible_transports=[target_branch.bzrdir.root_transport])
1399
2076
def __init__(self):
1400
2077
super(BranchReferenceFormat, self).__init__()
1401
2078
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2079
self._matchingbzrdir.set_branch_format(self)
1403
2081
def _make_reference_clone_function(format, a_branch):
1404
2082
"""Create a clone() routine for a branch dynamically."""
1405
def clone(to_bzrdir, revision_id=None):
2083
def clone(to_bzrdir, revision_id=None,
2084
repository_policy=None):
1406
2085
"""See Branch.clone()."""
1407
return format.initialize(to_bzrdir, a_branch)
2086
return format.initialize(to_bzrdir, target_branch=a_branch)
1408
2087
# cannot obey revision_id limits when cloning a reference ...
1409
2088
# FIXME RBC 20060210 either nuke revision_id for clone, or
1410
2089
# emit some sort of warning/error to the caller ?!
1413
def open(self, a_bzrdir, _found=False, location=None,
1414
possible_transports=None):
2092
def open(self, a_bzrdir, name=None, _found=False, location=None,
2093
possible_transports=None, ignore_fallbacks=False):
1415
2094
"""Return the branch that the branch reference in a_bzrdir points at.
1417
_found is a private parameter, do not use it. It is used to indicate
1418
if format probing has already be done.
2096
:param a_bzrdir: A BzrDir that contains a branch.
2097
:param name: Name of colocated branch to open, if any
2098
:param _found: a private parameter, do not use it. It is used to
2099
indicate if format probing has already be done.
2100
:param ignore_fallbacks: when set, no fallback branches will be opened
2101
(if there are any). Default is to open fallbacks.
2102
:param location: The location of the referenced branch. If
2103
unspecified, this will be determined from the branch reference in
2105
:param possible_transports: An optional reusable transports list.
1421
format = BranchFormat.find_format(a_bzrdir)
2108
format = BranchFormat.find_format(a_bzrdir, name=name)
1422
2109
if format.__class__ != self.__class__:
1423
2110
raise AssertionError("wrong format %r found for %r" %
1424
2111
(format, self))
2130
network_format_registry = registry.FormatRegistry()
2131
"""Registry of formats indexed by their network name.
2133
The network name for a branch format is an identifier that can be used when
2134
referring to formats with smart server operations. See
2135
BranchFormat.network_name() for more detail.
1442
2139
# formats which have no format string are not discoverable
1443
2140
# and not independently creatable, so are not registered.
1444
2141
__format5 = BzrBranchFormat5()
1445
2142
__format6 = BzrBranchFormat6()
1446
2143
__format7 = BzrBranchFormat7()
2144
__format8 = BzrBranchFormat8()
1447
2145
BranchFormat.register_format(__format5)
1448
2146
BranchFormat.register_format(BranchReferenceFormat())
1449
2147
BranchFormat.register_format(__format6)
1450
2148
BranchFormat.register_format(__format7)
1451
BranchFormat.set_default_format(__format6)
2149
BranchFormat.register_format(__format8)
2150
BranchFormat.set_default_format(__format7)
1452
2151
_legacy_formats = [BzrBranchFormat4(),
1455
class BzrBranch(Branch):
2153
network_format_registry.register(
2154
_legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2157
class BzrBranch(Branch, _RelockDebugMixin):
1456
2158
"""A branch stored in the actual filesystem.
1458
2160
Note that it's "local" in the context of the filesystem; it doesn't
1459
2161
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1460
2162
it's writable, and can be accessed via the normal filesystem API.
1462
:ivar _transport: Transport for file operations on this branch's
2164
:ivar _transport: Transport for file operations on this branch's
1463
2165
control files, typically pointing to the .bzr/branch directory.
1464
2166
:ivar repository: Repository for this branch.
1465
:ivar base: The url of the base directory for this branch; the one
2167
:ivar base: The url of the base directory for this branch; the one
1466
2168
containing the .bzr directory.
2169
:ivar name: Optional colocated branch name as it exists in the control
1469
2173
def __init__(self, _format=None,
1470
_control_files=None, a_bzrdir=None, _repository=None):
2174
_control_files=None, a_bzrdir=None, name=None,
2175
_repository=None, ignore_fallbacks=False):
1471
2176
"""Create new branch object at a particular location."""
1472
2177
if a_bzrdir is None:
1473
2178
raise ValueError('a_bzrdir must be supplied')
1475
2180
self.bzrdir = a_bzrdir
1476
2181
self._base = self.bzrdir.transport.clone('..').base
1477
2183
# XXX: We should be able to just do
1478
2184
# self.base = self.bzrdir.root_transport.base
1479
2185
# but this does not quite work yet -- mbp 20080522
1574
2309
if Branch.hooks['post_change_branch_tip']:
1575
2310
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1577
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1578
"""Run the pre_change_branch_tip hooks."""
1579
hooks = Branch.hooks['pre_change_branch_tip']
2312
def _synchronize_history(self, destination, revision_id):
2313
"""Synchronize last revision and revision history between branches.
2315
This version is most efficient when the destination is also a
2316
BzrBranch5, but works for BzrBranch6 as long as the revision
2317
history is the true lefthand parent history, and all of the revisions
2318
are in the destination's repository. If not, set_revision_history
2321
:param destination: The branch to copy the history into
2322
:param revision_id: The revision-id to truncate history at. May
2323
be None to copy complete history.
2325
if not isinstance(destination._format, BzrBranchFormat5):
2326
super(BzrBranch, self)._synchronize_history(
2327
destination, revision_id)
1582
old_revno, old_revid = self.last_revision_info()
1583
params = ChangeBranchTipParams(
1584
self, old_revno, new_revno, old_revid, new_revid)
2329
if revision_id == _mod_revision.NULL_REVISION:
2332
new_history = self.revision_history()
2333
if revision_id is not None and new_history != []:
1588
except errors.TipChangeRejected:
1591
exc_info = sys.exc_info()
1592
hook_name = Branch.hooks.get_hook_name(hook)
1593
raise errors.HookFailed(
1594
'pre_change_branch_tip', hook_name, exc_info)
1596
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1597
"""Run the post_change_branch_tip hooks."""
1598
hooks = Branch.hooks['post_change_branch_tip']
1601
new_revno, new_revid = self.last_revision_info()
1602
params = ChangeBranchTipParams(
1603
self, old_revno, new_revno, old_revid, new_revid)
2335
new_history = new_history[:new_history.index(revision_id) + 1]
2337
rev = self.repository.get_revision(revision_id)
2338
new_history = rev.get_history(self.repository)[1:]
2339
destination.set_revision_history(new_history)
1607
2341
@needs_write_lock
1608
2342
def set_last_revision_info(self, revno, revision_id):
1609
2343
"""Set the last revision of this branch.
1733
def push(self, target, overwrite=False, stop_revision=None,
1734
_override_hook_source_branch=None):
1737
This is the basic concrete implementation of push()
1739
:param _override_hook_source_branch: If specified, run
1740
the hooks passing this Branch as the source, rather than self.
1741
This is for use of RemoteBranch, where push is delegated to the
1742
underlying vfs-based Branch.
1744
# TODO: Public option to disable running hooks - should be trivial but
1748
result = self._push_with_bound_branches(target, overwrite,
1750
_override_hook_source_branch=_override_hook_source_branch)
1755
def _push_with_bound_branches(self, target, overwrite,
1757
_override_hook_source_branch=None):
1758
"""Push from self into target, and into target's master if any.
1760
This is on the base BzrBranch class even though it doesn't support
1761
bound branches because the *target* might be bound.
1764
if _override_hook_source_branch:
1765
result.source_branch = _override_hook_source_branch
1766
for hook in Branch.hooks['post_push']:
1769
bound_location = target.get_bound_location()
1770
if bound_location and target.base != bound_location:
1771
# there is a master branch.
1773
# XXX: Why the second check? Is it even supported for a branch to
1774
# be bound to itself? -- mbp 20070507
1775
master_branch = target.get_master_branch()
1776
master_branch.lock_write()
1778
# push into the master from this branch.
1779
self._basic_push(master_branch, overwrite, stop_revision)
1780
# and push into the target branch from this. Note that we push from
1781
# this branch again, because its considered the highest bandwidth
1783
result = self._basic_push(target, overwrite, stop_revision)
1784
result.master_branch = master_branch
1785
result.local_branch = target
1789
master_branch.unlock()
1792
result = self._basic_push(target, overwrite, stop_revision)
1793
# TODO: Why set master_branch and local_branch if there's no
1794
# binding? Maybe cleaner to just leave them unset? -- mbp
1796
result.master_branch = target
1797
result.local_branch = None
1801
2396
def _basic_push(self, target, overwrite, stop_revision):
1802
2397
"""Basic implementation of push without bound branches or hooks.
1804
Must be called with self read locked and target write locked.
2399
Must be called with source read locked and target write locked.
1806
result = PushResult()
2401
result = BranchPushResult()
1807
2402
result.source_branch = self
1808
2403
result.target_branch = target
1809
2404
result.old_revno, result.old_revid = target.last_revision_info()
2405
self.update_references(target)
1810
2406
if result.old_revid != self.last_revision():
1811
2407
# We assume that during 'push' this repository is closer than
1813
2409
graph = self.repository.get_graph(target.repository)
1814
target.update_revisions(self, stop_revision, overwrite=overwrite,
2410
target.update_revisions(self, stop_revision,
2411
overwrite=overwrite, graph=graph)
1816
2412
if self._push_should_merge_tags():
1817
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2413
result.tag_conflicts = self.tags.merge_to(target.tags,
1818
2415
result.new_revno, result.new_revid = target.last_revision_info()
1821
def _push_should_merge_tags(self):
1822
"""Should _basic_push merge this branch's tags into the target?
1824
The default implementation returns False if this branch has no tags,
1825
and True the rest of the time. Subclasses may override this.
1827
return self.tags.supports_tags() and self.tags.get_tag_dict()
1829
def get_parent(self):
1830
"""See Branch.get_parent."""
1831
parent = self._get_parent_location()
1834
# This is an old-format absolute path to a local branch
1835
# turn it into a url
1836
if parent.startswith('/'):
1837
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1839
return urlutils.join(self.base[:-1], parent)
1840
except errors.InvalidURLJoin, e:
1841
raise errors.InaccessibleParent(parent, self.base)
1843
2418
def get_stacked_on_url(self):
1844
2419
raise errors.UnstackableBranchFormat(self._format, self.base)
2008
class BzrBranch7(BzrBranch5):
2009
"""A branch with support for a fallback repository."""
2011
def _get_fallback_repository(self, url):
2012
"""Get the repository we fallback to at url."""
2013
url = urlutils.join(self.base, url)
2014
return bzrdir.BzrDir.open(url).open_branch().repository
2016
def _activate_fallback_location(self, url):
2017
"""Activate the branch/repository from url as a fallback repository."""
2018
self.repository.add_fallback_repository(
2019
self._get_fallback_repository(url))
2533
class BzrBranch8(BzrBranch5):
2534
"""A branch that stores tree-reference locations."""
2021
2536
def _open_hook(self):
2537
if self._ignore_fallbacks:
2023
2540
url = self.get_stacked_on_url()
2024
2541
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2025
2542
errors.UnstackableBranchFormat):
2545
for hook in Branch.hooks['transform_fallback_location']:
2546
url = hook(self, url)
2548
hook_name = Branch.hooks.get_hook_name(hook)
2549
raise AssertionError(
2550
"'transform_fallback_location' hook %s returned "
2551
"None, not a URL." % hook_name)
2028
2552
self._activate_fallback_location(url)
2030
def _check_stackable_repo(self):
2031
if not self.repository._format.supports_external_lookups:
2032
raise errors.UnstackableRepositoryFormat(self.repository._format,
2033
self.repository.base)
2035
2554
def __init__(self, *args, **kwargs):
2036
super(BzrBranch7, self).__init__(*args, **kwargs)
2555
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2556
super(BzrBranch8, self).__init__(*args, **kwargs)
2037
2557
self._last_revision_info_cache = None
2038
self._partial_revision_history_cache = []
2558
self._reference_info = None
2040
2560
def _clear_cached_state(self):
2041
super(BzrBranch7, self)._clear_cached_state()
2561
super(BzrBranch8, self)._clear_cached_state()
2042
2562
self._last_revision_info_cache = None
2043
self._partial_revision_history_cache = []
2563
self._reference_info = None
2045
2565
def _last_revision_info(self):
2046
2566
revision_string = self._transport.get_bytes('last-revision')
2144
2647
"""Set the parent branch"""
2145
2648
return self._get_config_location('parent_location')
2651
def _set_all_reference_info(self, info_dict):
2652
"""Replace all reference info stored in a branch.
2654
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2657
writer = rio.RioWriter(s)
2658
for key, (tree_path, branch_location) in info_dict.iteritems():
2659
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2660
branch_location=branch_location)
2661
writer.write_stanza(stanza)
2662
self._transport.put_bytes('references', s.getvalue())
2663
self._reference_info = info_dict
2666
def _get_all_reference_info(self):
2667
"""Return all the reference info stored in a branch.
2669
:return: A dict of {file_id: (tree_path, branch_location)}
2671
if self._reference_info is not None:
2672
return self._reference_info
2673
rio_file = self._transport.get('references')
2675
stanzas = rio.read_stanzas(rio_file)
2676
info_dict = dict((s['file_id'], (s['tree_path'],
2677
s['branch_location'])) for s in stanzas)
2680
self._reference_info = info_dict
2683
def set_reference_info(self, file_id, tree_path, branch_location):
2684
"""Set the branch location to use for a tree reference.
2686
:param file_id: The file-id of the tree reference.
2687
:param tree_path: The path of the tree reference in the tree.
2688
:param branch_location: The location of the branch to retrieve tree
2691
info_dict = self._get_all_reference_info()
2692
info_dict[file_id] = (tree_path, branch_location)
2693
if None in (tree_path, branch_location):
2694
if tree_path is not None:
2695
raise ValueError('tree_path must be None when branch_location'
2697
if branch_location is not None:
2698
raise ValueError('branch_location must be None when tree_path'
2700
del info_dict[file_id]
2701
self._set_all_reference_info(info_dict)
2703
def get_reference_info(self, file_id):
2704
"""Get the tree_path and branch_location for a tree reference.
2706
:return: a tuple of (tree_path, branch_location)
2708
return self._get_all_reference_info().get(file_id, (None, None))
2710
def reference_parent(self, file_id, path, possible_transports=None):
2711
"""Return the parent branch for a tree-reference file_id.
2713
:param file_id: The file_id of the tree reference
2714
:param path: The path of the file_id in the tree
2715
:return: A branch associated with the file_id
2717
branch_location = self.get_reference_info(file_id)[1]
2718
if branch_location is None:
2719
return Branch.reference_parent(self, file_id, path,
2720
possible_transports)
2721
branch_location = urlutils.join(self.base, branch_location)
2722
return Branch.open(branch_location,
2723
possible_transports=possible_transports)
2147
2725
def set_push_location(self, location):
2148
2726
"""See Branch.set_push_location."""
2149
2727
self._set_config_location('push_location', location)
2191
2769
raise errors.NotStacked(self)
2192
2770
return stacked_url
2194
def set_append_revisions_only(self, enabled):
2199
self.get_config().set_user_option('append_revisions_only', value,
2202
def set_stacked_on_url(self, url):
2203
self._check_stackable_repo()
2206
old_url = self.get_stacked_on_url()
2207
except (errors.NotStacked, errors.UnstackableBranchFormat,
2208
errors.UnstackableRepositoryFormat):
2211
# repositories don't offer an interface to remove fallback
2212
# repositories today; take the conceptually simpler option and just
2214
self.repository = self.bzrdir.find_repository()
2215
# for every revision reference the branch has, ensure it is pulled
2217
source_repository = self._get_fallback_repository(old_url)
2218
for revision_id in chain([self.last_revision()],
2219
self.tags.get_reverse_tag_dict()):
2220
self.repository.fetch(source_repository, revision_id,
2223
self._activate_fallback_location(url)
2224
# write this out after the repository is stacked to avoid setting a
2225
# stacked config that doesn't work.
2226
self._set_config_location('stacked_on_location', url)
2228
2772
def _get_append_revisions_only(self):
2229
2773
value = self.get_config().get_user_option('append_revisions_only')
2230
2774
return value == 'True'
2232
def _synchronize_history(self, destination, revision_id):
2233
"""Synchronize last revision and revision history between branches.
2235
This version is most efficient when the destination is also a
2236
BzrBranch6, but works for BzrBranch5, as long as the destination's
2237
repository contains all the lefthand ancestors of the intended
2238
last_revision. If not, set_last_revision_info will fail.
2240
:param destination: The branch to copy the history into
2241
:param revision_id: The revision-id to truncate history at. May
2242
be None to copy complete history.
2244
source_revno, source_revision_id = self.last_revision_info()
2245
if revision_id is None:
2246
revno, revision_id = source_revno, source_revision_id
2247
elif source_revision_id == revision_id:
2248
# we know the revno without needing to walk all of history
2249
revno = source_revno
2251
# To figure out the revno for a random revision, we need to build
2252
# the revision history, and count its length.
2253
# We don't care about the order, just how long it is.
2254
# Alternatively, we could start at the current location, and count
2255
# backwards. But there is no guarantee that we will find it since
2256
# it may be a merged revision.
2257
revno = len(list(self.repository.iter_reverse_revision_history(
2259
destination.set_last_revision_info(revno, revision_id)
2261
def _make_tags(self):
2262
return BasicTags(self)
2264
2776
@needs_write_lock
2265
2777
def generate_revision_history(self, revision_id, last_rev=None,
2266
2778
other_branch=None):
2445
2977
branch._set_config_location('stacked_on_location', '')
2446
2978
# update target format
2447
2979
branch._transport.put_bytes('format', format.get_format_string())
2982
class Converter7to8(object):
2983
"""Perform an in-place upgrade of format 6 to format 7"""
2985
def convert(self, branch):
2986
format = BzrBranchFormat8()
2987
branch._transport.put_bytes('references', '')
2988
# update target format
2989
branch._transport.put_bytes('format', format.get_format_string())
2992
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2993
"""Run ``callable(*args, **kwargs)``, write-locking target for the
2996
_run_with_write_locked_target will attempt to release the lock it acquires.
2998
If an exception is raised by callable, then that exception *will* be
2999
propagated, even if the unlock attempt raises its own error. Thus
3000
_run_with_write_locked_target should be preferred to simply doing::
3004
return callable(*args, **kwargs)
3009
# This is very similar to bzrlib.decorators.needs_write_lock. Perhaps they
3010
# should share code?
3013
result = callable(*args, **kwargs)
3015
exc_info = sys.exc_info()
3019
raise exc_info[0], exc_info[1], exc_info[2]
3025
class InterBranch(InterObject):
3026
"""This class represents operations taking place between two branches.
3028
Its instances have methods like pull() and push() and contain
3029
references to the source and target repositories these operations
3030
can be carried out on.
3034
"""The available optimised InterBranch types."""
3037
def _get_branch_formats_to_test():
3038
"""Return a tuple with the Branch formats to use when testing."""
3039
raise NotImplementedError(InterBranch._get_branch_formats_to_test)
3041
def pull(self, overwrite=False, stop_revision=None,
3042
possible_transports=None, local=False):
3043
"""Mirror source into target branch.
3045
The target branch is considered to be 'local', having low latency.
3047
:returns: PullResult instance
3049
raise NotImplementedError(self.pull)
3051
def update_revisions(self, stop_revision=None, overwrite=False,
3053
"""Pull in new perfect-fit revisions.
3055
:param stop_revision: Updated until the given revision
3056
:param overwrite: Always set the branch pointer, rather than checking
3057
to see if it is a proper descendant.
3058
:param graph: A Graph object that can be used to query history
3059
information. This can be None.
3062
raise NotImplementedError(self.update_revisions)
3064
def push(self, overwrite=False, stop_revision=None,
3065
_override_hook_source_branch=None):
3066
"""Mirror the source branch into the target branch.
3068
The source branch is considered to be 'local', having low latency.
3070
raise NotImplementedError(self.push)
3073
class GenericInterBranch(InterBranch):
3074
"""InterBranch implementation that uses public Branch functions.
3078
def _get_branch_formats_to_test():
3079
return BranchFormat._default_format, BranchFormat._default_format
3081
def update_revisions(self, stop_revision=None, overwrite=False,
3083
"""See InterBranch.update_revisions()."""
3084
self.source.lock_read()
3086
other_revno, other_last_revision = self.source.last_revision_info()
3087
stop_revno = None # unknown
3088
if stop_revision is None:
3089
stop_revision = other_last_revision
3090
if _mod_revision.is_null(stop_revision):
3091
# if there are no commits, we're done.
3093
stop_revno = other_revno
3095
# what's the current last revision, before we fetch [and change it
3097
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3098
# we fetch here so that we don't process data twice in the common
3099
# case of having something to pull, and so that the check for
3100
# already merged can operate on the just fetched graph, which will
3101
# be cached in memory.
3102
self.target.fetch(self.source, stop_revision)
3103
# Check to see if one is an ancestor of the other
3106
graph = self.target.repository.get_graph()
3107
if self.target._check_if_descendant_or_diverged(
3108
stop_revision, last_rev, graph, self.source):
3109
# stop_revision is a descendant of last_rev, but we aren't
3110
# overwriting, so we're done.
3112
if stop_revno is None:
3114
graph = self.target.repository.get_graph()
3115
this_revno, this_last_revision = \
3116
self.target.last_revision_info()
3117
stop_revno = graph.find_distance_to_null(stop_revision,
3118
[(other_last_revision, other_revno),
3119
(this_last_revision, this_revno)])
3120
self.target.set_last_revision_info(stop_revno, stop_revision)
3122
self.source.unlock()
3124
def pull(self, overwrite=False, stop_revision=None,
3125
possible_transports=None, _hook_master=None, run_hooks=True,
3126
_override_hook_target=None, local=False):
3129
:param _hook_master: Private parameter - set the branch to
3130
be supplied as the master to pull hooks.
3131
:param run_hooks: Private parameter - if false, this branch
3132
is being called because it's the master of the primary branch,
3133
so it should not run its hooks.
3134
:param _override_hook_target: Private parameter - set the branch to be
3135
supplied as the target_branch to pull hooks.
3136
:param local: Only update the local branch, and not the bound branch.
3138
# This type of branch can't be bound.
3140
raise errors.LocalRequiresBoundBranch()
3141
result = PullResult()
3142
result.source_branch = self.source
3143
if _override_hook_target is None:
3144
result.target_branch = self.target
3146
result.target_branch = _override_hook_target
3147
self.source.lock_read()
3149
# We assume that during 'pull' the target repository is closer than
3151
self.source.update_references(self.target)
3152
graph = self.target.repository.get_graph(self.source.repository)
3153
# TODO: Branch formats should have a flag that indicates
3154
# that revno's are expensive, and pull() should honor that flag.
3156
result.old_revno, result.old_revid = \
3157
self.target.last_revision_info()
3158
self.target.update_revisions(self.source, stop_revision,
3159
overwrite=overwrite, graph=graph)
3160
# TODO: The old revid should be specified when merging tags,
3161
# so a tags implementation that versions tags can only
3162
# pull in the most recent changes. -- JRV20090506
3163
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3165
result.new_revno, result.new_revid = self.target.last_revision_info()
3167
result.master_branch = _hook_master
3168
result.local_branch = result.target_branch
3170
result.master_branch = result.target_branch
3171
result.local_branch = None
3173
for hook in Branch.hooks['post_pull']:
3176
self.source.unlock()
3179
def push(self, overwrite=False, stop_revision=None,
3180
_override_hook_source_branch=None):
3181
"""See InterBranch.push.
3183
This is the basic concrete implementation of push()
3185
:param _override_hook_source_branch: If specified, run
3186
the hooks passing this Branch as the source, rather than self.
3187
This is for use of RemoteBranch, where push is delegated to the
3188
underlying vfs-based Branch.
3190
# TODO: Public option to disable running hooks - should be trivial but
3192
self.source.lock_read()
3194
return _run_with_write_locked_target(
3195
self.target, self._push_with_bound_branches, overwrite,
3197
_override_hook_source_branch=_override_hook_source_branch)
3199
self.source.unlock()
3201
def _push_with_bound_branches(self, overwrite, stop_revision,
3202
_override_hook_source_branch=None):
3203
"""Push from source into target, and into target's master if any.
3206
if _override_hook_source_branch:
3207
result.source_branch = _override_hook_source_branch
3208
for hook in Branch.hooks['post_push']:
3211
bound_location = self.target.get_bound_location()
3212
if bound_location and self.target.base != bound_location:
3213
# there is a master branch.
3215
# XXX: Why the second check? Is it even supported for a branch to
3216
# be bound to itself? -- mbp 20070507
3217
master_branch = self.target.get_master_branch()
3218
master_branch.lock_write()
3220
# push into the master from the source branch.
3221
self.source._basic_push(master_branch, overwrite, stop_revision)
3222
# and push into the target branch from the source. Note that we
3223
# push from the source branch again, because its considered the
3224
# highest bandwidth repository.
3225
result = self.source._basic_push(self.target, overwrite,
3227
result.master_branch = master_branch
3228
result.local_branch = self.target
3232
master_branch.unlock()
3235
result = self.source._basic_push(self.target, overwrite,
3237
# TODO: Why set master_branch and local_branch if there's no
3238
# binding? Maybe cleaner to just leave them unset? -- mbp
3240
result.master_branch = self.target
3241
result.local_branch = None
3246
def is_compatible(self, source, target):
3247
# GenericBranch uses the public API, so always compatible
3251
class InterToBranch5(GenericInterBranch):
3254
def _get_branch_formats_to_test():
3255
return BranchFormat._default_format, BzrBranchFormat5()
3257
def pull(self, overwrite=False, stop_revision=None,
3258
possible_transports=None, run_hooks=True,
3259
_override_hook_target=None, local=False):
3260
"""Pull from source into self, updating my master if any.
3262
:param run_hooks: Private parameter - if false, this branch
3263
is being called because it's the master of the primary branch,
3264
so it should not run its hooks.
3266
bound_location = self.target.get_bound_location()
3267
if local and not bound_location:
3268
raise errors.LocalRequiresBoundBranch()
3269
master_branch = None
3270
if not local and bound_location and self.source.base != bound_location:
3271
# not pulling from master, so we need to update master.
3272
master_branch = self.target.get_master_branch(possible_transports)
3273
master_branch.lock_write()
3276
# pull from source into master.
3277
master_branch.pull(self.source, overwrite, stop_revision,
3279
return super(InterToBranch5, self).pull(overwrite,
3280
stop_revision, _hook_master=master_branch,
3281
run_hooks=run_hooks,
3282
_override_hook_target=_override_hook_target)
3285
master_branch.unlock()
3288
InterBranch.register_optimiser(GenericInterBranch)
3289
InterBranch.register_optimiser(InterToBranch5)