142
205
possible_transports)
143
206
return control.open_branch(), relpath
208
def _push_should_merge_tags(self):
209
"""Should _basic_push merge this branch's tags into the target?
211
The default implementation returns False if this branch has no tags,
212
and True the rest of the time. Subclasses may override this.
214
return self.supports_tags() and self.tags.get_tag_dict()
145
216
def get_config(self):
217
"""Get a bzrlib.config.BranchConfig for this Branch.
219
This can then be used to get and set configuration options for the
222
:return: A bzrlib.config.BranchConfig.
146
224
return BranchConfig(self)
149
return self.get_config().get_nickname()
226
def _get_config(self):
227
"""Get the concrete config for just the config in this branch.
229
This is not intended for client use; see Branch.get_config for the
234
:return: An object supporting get_option and set_option.
236
raise NotImplementedError(self._get_config)
238
def _get_fallback_repository(self, url):
239
"""Get the repository we fallback to at url."""
240
url = urlutils.join(self.base, url)
241
a_branch = Branch.open(url,
242
possible_transports=[self.bzrdir.root_transport])
243
return a_branch.repository
246
def _get_tags_bytes(self):
247
"""Get the bytes of a serialised tags dict.
249
Note that not all branches support tags, nor do all use the same tags
250
logic: this method is specific to BasicTags. Other tag implementations
251
may use the same method name and behave differently, safely, because
252
of the double-dispatch via
253
format.make_tags->tags_instance->get_tags_dict.
255
:return: The bytes of the tags file.
256
:seealso: Branch._set_tags_bytes.
258
if self._tags_bytes is None:
259
self._tags_bytes = self._transport.get_bytes('tags')
260
return self._tags_bytes
262
def _get_nick(self, local=False, possible_transports=None):
263
config = self.get_config()
264
# explicit overrides master, but don't look for master if local is True
265
if not local and not config.has_explicit_nickname():
267
master = self.get_master_branch(possible_transports)
268
if master and self.user_url == master.user_url:
269
raise errors.RecursiveBind(self.user_url)
270
if master is not None:
271
# return the master branch value
273
except errors.RecursiveBind, e:
275
except errors.BzrError, e:
276
# Silently fall back to local implicit nick if the master is
278
mutter("Could not connect to bound branch, "
279
"falling back to local nick.\n " + str(e))
280
return config.get_nickname()
151
282
def _set_nick(self, nick):
152
283
self.get_config().set_user_option('nickname', nick, warn_masked=True)
203
435
:return: A dictionary mapping revision_id => dotted revno.
205
last_revision = self.last_revision()
206
revision_graph = repository._old_get_graph(self.repository,
208
merge_sorted_revisions = tsort.merge_sort(
213
437
revision_id_to_revno = dict((rev_id, revno)
214
for seq_num, rev_id, depth, revno, end_of_merge
215
in merge_sorted_revisions)
438
for rev_id, depth, revno, end_of_merge
439
in self.iter_merge_sorted_revisions())
216
440
return revision_id_to_revno
443
def iter_merge_sorted_revisions(self, start_revision_id=None,
444
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
445
"""Walk the revisions for a branch in merge sorted order.
447
Merge sorted order is the output from a merge-aware,
448
topological sort, i.e. all parents come before their
449
children going forward; the opposite for reverse.
451
:param start_revision_id: the revision_id to begin walking from.
452
If None, the branch tip is used.
453
:param stop_revision_id: the revision_id to terminate the walk
454
after. If None, the rest of history is included.
455
:param stop_rule: if stop_revision_id is not None, the precise rule
456
to use for termination:
458
* 'exclude' - leave the stop revision out of the result (default)
459
* 'include' - the stop revision is the last item in the result
460
* 'with-merges' - include the stop revision and all of its
461
merged revisions in the result
462
* 'with-merges-without-common-ancestry' - filter out revisions
463
that are in both ancestries
464
:param direction: either 'reverse' or 'forward':
466
* reverse means return the start_revision_id first, i.e.
467
start at the most recent revision and go backwards in history
468
* forward returns tuples in the opposite order to reverse.
469
Note in particular that forward does *not* do any intelligent
470
ordering w.r.t. depth as some clients of this API may like.
471
(If required, that ought to be done at higher layers.)
473
:return: an iterator over (revision_id, depth, revno, end_of_merge)
476
* revision_id: the unique id of the revision
477
* depth: How many levels of merging deep this node has been
479
* revno_sequence: This field provides a sequence of
480
revision numbers for all revisions. The format is:
481
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
482
branch that the revno is on. From left to right the REVNO numbers
483
are the sequence numbers within that branch of the revision.
484
* end_of_merge: When True the next node (earlier in history) is
485
part of a different merge.
487
# Note: depth and revno values are in the context of the branch so
488
# we need the full graph to get stable numbers, regardless of the
490
if self._merge_sorted_revisions_cache is None:
491
last_revision = self.last_revision()
492
known_graph = self.repository.get_known_graph_ancestry(
494
self._merge_sorted_revisions_cache = known_graph.merge_sort(
496
filtered = self._filter_merge_sorted_revisions(
497
self._merge_sorted_revisions_cache, start_revision_id,
498
stop_revision_id, stop_rule)
499
# Make sure we don't return revisions that are not part of the
500
# start_revision_id ancestry.
501
filtered = self._filter_start_non_ancestors(filtered)
502
if direction == 'reverse':
504
if direction == 'forward':
505
return reversed(list(filtered))
507
raise ValueError('invalid direction %r' % direction)
509
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
510
start_revision_id, stop_revision_id, stop_rule):
511
"""Iterate over an inclusive range of sorted revisions."""
512
rev_iter = iter(merge_sorted_revisions)
513
if start_revision_id is not None:
514
for node in rev_iter:
515
rev_id = node.key[-1]
516
if rev_id != start_revision_id:
519
# The decision to include the start or not
520
# depends on the stop_rule if a stop is provided
521
# so pop this node back into the iterator
522
rev_iter = chain(iter([node]), rev_iter)
524
if stop_revision_id is None:
526
for node in rev_iter:
527
rev_id = node.key[-1]
528
yield (rev_id, node.merge_depth, node.revno,
530
elif stop_rule == 'exclude':
531
for node in rev_iter:
532
rev_id = node.key[-1]
533
if rev_id == stop_revision_id:
535
yield (rev_id, node.merge_depth, node.revno,
537
elif stop_rule == 'include':
538
for node in rev_iter:
539
rev_id = node.key[-1]
540
yield (rev_id, node.merge_depth, node.revno,
542
if rev_id == stop_revision_id:
544
elif stop_rule == 'with-merges-without-common-ancestry':
545
# We want to exclude all revisions that are already part of the
546
# stop_revision_id ancestry.
547
graph = self.repository.get_graph()
548
ancestors = graph.find_unique_ancestors(start_revision_id,
550
for node in rev_iter:
551
rev_id = node.key[-1]
552
if rev_id not in ancestors:
554
yield (rev_id, node.merge_depth, node.revno,
556
elif stop_rule == 'with-merges':
557
stop_rev = self.repository.get_revision(stop_revision_id)
558
if stop_rev.parent_ids:
559
left_parent = stop_rev.parent_ids[0]
561
left_parent = _mod_revision.NULL_REVISION
562
# left_parent is the actual revision we want to stop logging at,
563
# since we want to show the merged revisions after the stop_rev too
564
reached_stop_revision_id = False
565
revision_id_whitelist = []
566
for node in rev_iter:
567
rev_id = node.key[-1]
568
if rev_id == left_parent:
569
# reached the left parent after the stop_revision
571
if (not reached_stop_revision_id or
572
rev_id in revision_id_whitelist):
573
yield (rev_id, node.merge_depth, node.revno,
575
if reached_stop_revision_id or rev_id == stop_revision_id:
576
# only do the merged revs of rev_id from now on
577
rev = self.repository.get_revision(rev_id)
579
reached_stop_revision_id = True
580
revision_id_whitelist.extend(rev.parent_ids)
582
raise ValueError('invalid stop_rule %r' % stop_rule)
584
def _filter_start_non_ancestors(self, rev_iter):
585
# If we started from a dotted revno, we want to consider it as a tip
586
# and don't want to yield revisions that are not part of its
587
# ancestry. Given the order guaranteed by the merge sort, we will see
588
# uninteresting descendants of the first parent of our tip before the
590
first = rev_iter.next()
591
(rev_id, merge_depth, revno, end_of_merge) = first
594
# We start at a mainline revision so by definition, all others
595
# revisions in rev_iter are ancestors
596
for node in rev_iter:
601
pmap = self.repository.get_parent_map([rev_id])
602
parents = pmap.get(rev_id, [])
604
whitelist.update(parents)
606
# If there is no parents, there is nothing of interest left
608
# FIXME: It's hard to test this scenario here as this code is never
609
# called in that case. -- vila 20100322
612
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
614
if rev_id in whitelist:
615
pmap = self.repository.get_parent_map([rev_id])
616
parents = pmap.get(rev_id, [])
617
whitelist.remove(rev_id)
618
whitelist.update(parents)
620
# We've reached the mainline, there is nothing left to
624
# A revision that is not part of the ancestry of our
627
yield (rev_id, merge_depth, revno, end_of_merge)
218
629
def leave_lock_in_place(self):
219
630
"""Tell this branch object not to release the physical lock when this
220
631
object is unlocked.
222
633
If lock_write doesn't return a token, then this method is not supported.
224
635
self.control_files.leave_in_place()
337
747
"""Print `file` to stdout."""
338
748
raise NotImplementedError(self.print_file)
750
@deprecated_method(deprecated_in((2, 4, 0)))
340
751
def set_revision_history(self, rev_history):
341
raise NotImplementedError(self.set_revision_history)
752
"""See Branch.set_revision_history."""
753
self._set_revision_history(rev_history)
756
def _set_revision_history(self, rev_history):
757
if len(rev_history) == 0:
758
revid = _mod_revision.NULL_REVISION
760
revid = rev_history[-1]
761
if rev_history != self._lefthand_history(revid):
762
raise errors.NotLefthandHistory(rev_history)
763
self.set_last_revision_info(len(rev_history), revid)
764
self._cache_revision_history(rev_history)
765
for hook in Branch.hooks['set_rh']:
766
hook(self, rev_history)
769
def set_last_revision_info(self, revno, revision_id):
770
"""Set the last revision of this branch.
772
The caller is responsible for checking that the revno is correct
773
for this revision id.
775
It may be possible to set the branch last revision to an id not
776
present in the repository. However, branches can also be
777
configured to check constraints on history, in which case this may not
780
raise NotImplementedError(self.set_last_revision_info)
783
def generate_revision_history(self, revision_id, last_rev=None,
785
"""See Branch.generate_revision_history"""
786
graph = self.repository.get_graph()
787
known_revision_ids = [
788
self.last_revision_info(),
789
(_mod_revision.NULL_REVISION, 0),
791
if last_rev is not None:
792
if not graph.is_ancestor(last_rev, revision_id):
793
# our previous tip is not merged into stop_revision
794
raise errors.DivergedBranches(self, other_branch)
795
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
796
self.set_last_revision_info(revno, revision_id)
799
def set_parent(self, url):
800
"""See Branch.set_parent."""
801
# TODO: Maybe delete old location files?
802
# URLs should never be unicode, even on the local fs,
803
# FIXUP this and get_parent in a future branch format bump:
804
# read and rewrite the file. RBC 20060125
806
if isinstance(url, unicode):
808
url = url.encode('ascii')
809
except UnicodeEncodeError:
810
raise errors.InvalidURL(url,
811
"Urls must be 7-bit ascii, "
812
"use bzrlib.urlutils.escape")
813
url = urlutils.relative_url(self.base, url)
814
self._set_parent_location(url)
343
817
def set_stacked_on_url(self, url):
344
818
"""Set the URL this branch is stacked against.
348
822
:raises UnstackableRepositoryFormat: If the repository does not support
351
raise NotImplementedError(self.set_stacked_on_url)
825
if not self._format.supports_stacking():
826
raise errors.UnstackableBranchFormat(self._format, self.user_url)
827
# XXX: Changing from one fallback repository to another does not check
828
# that all the data you need is present in the new fallback.
829
# Possibly it should.
830
self._check_stackable_repo()
833
old_url = self.get_stacked_on_url()
834
except (errors.NotStacked, errors.UnstackableBranchFormat,
835
errors.UnstackableRepositoryFormat):
839
self._activate_fallback_location(url)
840
# write this out after the repository is stacked to avoid setting a
841
# stacked config that doesn't work.
842
self._set_config_location('stacked_on_location', url)
845
"""Change a branch to be unstacked, copying data as needed.
847
Don't call this directly, use set_stacked_on_url(None).
849
pb = ui.ui_factory.nested_progress_bar()
851
pb.update("Unstacking")
852
# The basic approach here is to fetch the tip of the branch,
853
# including all available ghosts, from the existing stacked
854
# repository into a new repository object without the fallbacks.
856
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
857
# correct for CHKMap repostiories
858
old_repository = self.repository
859
if len(old_repository._fallback_repositories) != 1:
860
raise AssertionError("can't cope with fallback repositories "
861
"of %r (fallbacks: %r)" % (old_repository,
862
old_repository._fallback_repositories))
863
# Open the new repository object.
864
# Repositories don't offer an interface to remove fallback
865
# repositories today; take the conceptually simpler option and just
866
# reopen it. We reopen it starting from the URL so that we
867
# get a separate connection for RemoteRepositories and can
868
# stream from one of them to the other. This does mean doing
869
# separate SSH connection setup, but unstacking is not a
870
# common operation so it's tolerable.
871
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
872
new_repository = new_bzrdir.find_repository()
873
if new_repository._fallback_repositories:
874
raise AssertionError("didn't expect %r to have "
875
"fallback_repositories"
876
% (self.repository,))
877
# Replace self.repository with the new repository.
878
# Do our best to transfer the lock state (i.e. lock-tokens and
879
# lock count) of self.repository to the new repository.
880
lock_token = old_repository.lock_write().repository_token
881
self.repository = new_repository
882
if isinstance(self, remote.RemoteBranch):
883
# Remote branches can have a second reference to the old
884
# repository that need to be replaced.
885
if self._real_branch is not None:
886
self._real_branch.repository = new_repository
887
self.repository.lock_write(token=lock_token)
888
if lock_token is not None:
889
old_repository.leave_lock_in_place()
890
old_repository.unlock()
891
if lock_token is not None:
892
# XXX: self.repository.leave_lock_in_place() before this
893
# function will not be preserved. Fortunately that doesn't
894
# affect the current default format (2a), and would be a
895
# corner-case anyway.
896
# - Andrew Bennetts, 2010/06/30
897
self.repository.dont_leave_lock_in_place()
901
old_repository.unlock()
902
except errors.LockNotHeld:
905
if old_lock_count == 0:
906
raise AssertionError(
907
'old_repository should have been locked at least once.')
908
for i in range(old_lock_count-1):
909
self.repository.lock_write()
910
# Fetch from the old repository into the new.
911
old_repository.lock_read()
913
# XXX: If you unstack a branch while it has a working tree
914
# with a pending merge, the pending-merged revisions will no
915
# longer be present. You can (probably) revert and remerge.
917
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
918
except errors.TagsNotSupported:
919
tags_to_fetch = set()
920
fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
921
old_repository, required_ids=[self.last_revision()],
922
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
923
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
925
old_repository.unlock()
929
def _set_tags_bytes(self, bytes):
930
"""Mirror method for _get_tags_bytes.
932
:seealso: Branch._get_tags_bytes.
934
return _run_with_write_locked_target(self, self._set_tags_bytes_locked,
937
def _set_tags_bytes_locked(self, bytes):
938
self._tags_bytes = bytes
939
return self._transport.put_bytes('tags', bytes)
353
941
def _cache_revision_history(self, rev_history):
354
942
"""Set the cached revision history to rev_history.
440
1029
:return: A tuple (revno, revision_id).
442
1031
if self._last_revision_info_cache is None:
443
self._last_revision_info_cache = self._last_revision_info()
1032
self._last_revision_info_cache = self._read_last_revision_info()
444
1033
return self._last_revision_info_cache
446
def _last_revision_info(self):
447
rh = self.revision_history()
450
return (revno, rh[-1])
452
return (0, _mod_revision.NULL_REVISION)
454
@deprecated_method(deprecated_in((1, 6, 0)))
455
def missing_revisions(self, other, stop_revision=None):
456
"""Return a list of new revisions that would perfectly fit.
458
If self and other have not diverged, return a list of the revisions
459
present in other, but missing from self.
461
self_history = self.revision_history()
462
self_len = len(self_history)
463
other_history = other.revision_history()
464
other_len = len(other_history)
465
common_index = min(self_len, other_len) -1
466
if common_index >= 0 and \
467
self_history[common_index] != other_history[common_index]:
468
raise errors.DivergedBranches(self, other)
470
if stop_revision is None:
471
stop_revision = other_len
473
if stop_revision > other_len:
474
raise errors.NoSuchRevision(self, stop_revision)
475
return other_history[self_len:stop_revision]
478
def update_revisions(self, other, stop_revision=None, overwrite=False,
480
"""Pull in new perfect-fit revisions.
482
:param other: Another Branch to pull from
483
:param stop_revision: Updated until the given revision
484
:param overwrite: Always set the branch pointer, rather than checking
485
to see if it is a proper descendant.
486
:param graph: A Graph object that can be used to query history
487
information. This can be None.
492
other_revno, other_last_revision = other.last_revision_info()
493
stop_revno = None # unknown
494
if stop_revision is None:
495
stop_revision = other_last_revision
496
if _mod_revision.is_null(stop_revision):
497
# if there are no commits, we're done.
499
stop_revno = other_revno
501
# what's the current last revision, before we fetch [and change it
503
last_rev = _mod_revision.ensure_null(self.last_revision())
504
# we fetch here so that we don't process data twice in the common
505
# case of having something to pull, and so that the check for
506
# already merged can operate on the just fetched graph, which will
507
# be cached in memory.
508
self.fetch(other, stop_revision)
509
# Check to see if one is an ancestor of the other
512
graph = self.repository.get_graph()
513
if self._check_if_descendant_or_diverged(
514
stop_revision, last_rev, graph, other):
515
# stop_revision is a descendant of last_rev, but we aren't
516
# overwriting, so we're done.
518
if stop_revno is None:
520
graph = self.repository.get_graph()
521
this_revno, this_last_revision = self.last_revision_info()
522
stop_revno = graph.find_distance_to_null(stop_revision,
523
[(other_last_revision, other_revno),
524
(this_last_revision, this_revno)])
525
self.set_last_revision_info(stop_revno, stop_revision)
1035
def _read_last_revision_info(self):
1036
raise NotImplementedError(self._read_last_revision_info)
1038
@deprecated_method(deprecated_in((2, 4, 0)))
1039
def import_last_revision_info(self, source_repo, revno, revid):
1040
"""Set the last revision info, importing from another repo if necessary.
1042
:param source_repo: Source repository to optionally fetch from
1043
:param revno: Revision number of the new tip
1044
:param revid: Revision id of the new tip
1046
if not self.repository.has_same_location(source_repo):
1047
self.repository.fetch(source_repo, revision_id=revid)
1048
self.set_last_revision_info(revno, revid)
1050
def import_last_revision_info_and_tags(self, source, revno, revid,
1052
"""Set the last revision info, importing from another repo if necessary.
1054
This is used by the bound branch code to upload a revision to
1055
the master branch first before updating the tip of the local branch.
1056
Revisions referenced by source's tags are also transferred.
1058
:param source: Source branch to optionally fetch from
1059
:param revno: Revision number of the new tip
1060
:param revid: Revision id of the new tip
1061
:param lossy: Whether to discard metadata that can not be
1062
natively represented
1063
:return: Tuple with the new revision number and revision id
1064
(should only be different from the arguments when lossy=True)
1066
if not self.repository.has_same_location(source.repository):
1067
self.fetch(source, revid)
1068
self.set_last_revision_info(revno, revid)
1069
return (revno, revid)
529
1071
def revision_id_to_revno(self, revision_id):
530
1072
"""Given a revision id, return its revno"""
685
1282
revision_id: if not None, the revision history in the new branch will
686
1283
be truncated to end with revision_id.
688
result = to_bzrdir.create_branch()
689
self.copy_content_into(result, revision_id=revision_id)
690
result.set_parent(self.bzrdir.root_transport.base)
1285
if (repository_policy is not None and
1286
repository_policy.requires_stacking()):
1287
to_bzrdir._format.require_stacking(_skip_repo=True)
1288
result = to_bzrdir.create_branch(repository=repository)
1291
if repository_policy is not None:
1292
repository_policy.configure_branch(result)
1293
self.copy_content_into(result, revision_id=revision_id)
1294
master_branch = self.get_master_branch()
1295
if master_branch is None:
1296
result.set_parent(self.bzrdir.root_transport.base)
1298
result.set_parent(master_branch.bzrdir.root_transport.base)
693
1303
def _synchronize_history(self, destination, revision_id):
694
1304
"""Synchronize last revision and revision history between branches.
696
1306
This version is most efficient when the destination is also a
697
BzrBranch5, but works for BzrBranch6 as long as the revision
698
history is the true lefthand parent history, and all of the revisions
699
are in the destination's repository. If not, set_revision_history
1307
BzrBranch6, but works for BzrBranch5, as long as the destination's
1308
repository contains all the lefthand ancestors of the intended
1309
last_revision. If not, set_last_revision_info will fail.
702
1311
:param destination: The branch to copy the history into
703
1312
:param revision_id: The revision-id to truncate history at. May
704
1313
be None to copy complete history.
706
if revision_id == _mod_revision.NULL_REVISION:
1315
source_revno, source_revision_id = self.last_revision_info()
1316
if revision_id is None:
1317
revno, revision_id = source_revno, source_revision_id
709
new_history = self.revision_history()
710
if revision_id is not None and new_history != []:
1319
graph = self.repository.get_graph()
712
new_history = new_history[:new_history.index(revision_id) + 1]
714
rev = self.repository.get_revision(revision_id)
715
new_history = rev.get_history(self.repository)[1:]
716
destination.set_revision_history(new_history)
1321
revno = graph.find_distance_to_null(revision_id,
1322
[(source_revision_id, source_revno)])
1323
except errors.GhostRevisionsHaveNoRevno:
1324
# Default to 1, if we can't find anything else
1326
destination.set_last_revision_info(revno, revision_id)
719
1328
def copy_content_into(self, destination, revision_id=None):
720
1329
"""Copy the content of self into destination.
722
1331
revision_id: if not None, the revision history in the new branch will
723
1332
be truncated to end with revision_id.
725
self._synchronize_history(destination, revision_id)
727
parent = self.get_parent()
728
except errors.InaccessibleParent, e:
729
mutter('parent was not accessible to copy: %s', e)
732
destination.set_parent(parent)
733
self.tags.merge_to(destination.tags)
1334
return InterBranch.get(self, destination).copy_content_into(
1335
revision_id=revision_id)
1337
def update_references(self, target):
1338
if not getattr(self._format, 'supports_reference_locations', False):
1340
reference_dict = self._get_all_reference_info()
1341
if len(reference_dict) == 0:
1343
old_base = self.base
1344
new_base = target.base
1345
target_reference_dict = target._get_all_reference_info()
1346
for file_id, (tree_path, branch_location) in (
1347
reference_dict.items()):
1348
branch_location = urlutils.rebase_url(branch_location,
1350
target_reference_dict.setdefault(
1351
file_id, (tree_path, branch_location))
1352
target._set_all_reference_info(target_reference_dict)
735
1354
@needs_read_lock
1355
def check(self, refs):
737
1356
"""Check consistency of the branch.
739
1358
In particular this checks that revisions given in the revision-history
740
do actually match up in the revision graph, and that they're all
1359
do actually match up in the revision graph, and that they're all
741
1360
present in the repository.
743
1362
Callers will typically also want to check the repository.
1364
:param refs: Calculated refs for this branch as specified by
1365
branch._get_check_refs()
745
1366
:return: A BranchCheckResult.
747
mainline_parent_id = None
1368
result = BranchCheckResult(self)
748
1369
last_revno, last_revision_id = self.last_revision_info()
749
real_rev_history = list(self.repository.iter_reverse_revision_history(
751
real_rev_history.reverse()
752
if len(real_rev_history) != last_revno:
753
raise errors.BzrCheckError('revno does not match len(mainline)'
754
' %s != %s' % (last_revno, len(real_rev_history)))
755
# TODO: We should probably also check that real_rev_history actually
756
# matches self.revision_history()
757
for revision_id in real_rev_history:
759
revision = self.repository.get_revision(revision_id)
760
except errors.NoSuchRevision, e:
761
raise errors.BzrCheckError("mainline revision {%s} not in repository"
763
# In general the first entry on the revision history has no parents.
764
# But it's not illegal for it to have parents listed; this can happen
765
# in imports from Arch when the parents weren't reachable.
766
if mainline_parent_id is not None:
767
if mainline_parent_id not in revision.parent_ids:
768
raise errors.BzrCheckError("previous revision {%s} not listed among "
770
% (mainline_parent_id, revision_id))
771
mainline_parent_id = revision_id
772
return BranchCheckResult(self)
1370
actual_revno = refs[('lefthand-distance', last_revision_id)]
1371
if actual_revno != last_revno:
1372
result.errors.append(errors.BzrCheckError(
1373
'revno does not match len(mainline) %s != %s' % (
1374
last_revno, actual_revno)))
1375
# TODO: We should probably also check that self.revision_history
1376
# matches the repository for older branch formats.
1377
# If looking for the code that cross-checks repository parents against
1378
# the iter_reverse_revision_history output, that is now a repository
774
1382
def _get_checkout_format(self):
775
1383
"""Return the most suitable metadir for a checkout of this branch.
776
1384
Weaves are used if this branch's repository uses weaves.
778
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
779
from bzrlib.repofmt import weaverepo
780
format = bzrdir.BzrDirMetaFormat1()
781
format.repository_format = weaverepo.RepositoryFormat7()
783
format = self.repository.bzrdir.checkout_metadir()
784
format.set_branch_format(self._format)
1386
format = self.repository.bzrdir.checkout_metadir()
1387
format.set_branch_format(self._format)
1390
def create_clone_on_transport(self, to_transport, revision_id=None,
1391
stacked_on=None, create_prefix=False, use_existing_dir=False,
1393
"""Create a clone of this branch and its bzrdir.
1395
:param to_transport: The transport to clone onto.
1396
:param revision_id: The revision id to use as tip in the new branch.
1397
If None the tip is obtained from this branch.
1398
:param stacked_on: An optional URL to stack the clone on.
1399
:param create_prefix: Create any missing directories leading up to
1401
:param use_existing_dir: Use an existing directory if one exists.
1403
# XXX: Fix the bzrdir API to allow getting the branch back from the
1404
# clone call. Or something. 20090224 RBC/spiv.
1405
# XXX: Should this perhaps clone colocated branches as well,
1406
# rather than just the default branch? 20100319 JRV
1407
if revision_id is None:
1408
revision_id = self.last_revision()
1409
dir_to = self.bzrdir.clone_on_transport(to_transport,
1410
revision_id=revision_id, stacked_on=stacked_on,
1411
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1413
return dir_to.open_branch()
787
1415
def create_checkout(self, to_location, revision_id=None,
788
1416
lightweight=False, accelerator_tree=None,
789
1417
hardlink=False):
790
1418
"""Create a checkout of a branch.
792
1420
:param to_location: The url to produce the checkout at
793
1421
:param revision_id: The revision to check out
794
1422
:param lightweight: If True, produce a lightweight checkout, otherwise,
795
produce a bound branch (heavyweight checkout)
1423
produce a bound branch (heavyweight checkout)
796
1424
:param accelerator_tree: A tree which can be used for retrieving file
797
1425
contents more quickly than the revision tree, i.e. a workingtree.
798
1426
The revision tree will be used for cases where accelerator_tree's
969
1641
"""Return the short format description for this format."""
970
1642
raise NotImplementedError(self.get_format_description)
972
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
974
"""Initialize a branch in a bzrdir, with specified files
1644
def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1645
hooks = Branch.hooks['post_branch_init']
1648
params = BranchInitHookParams(self, a_bzrdir, name, branch)
976
:param a_bzrdir: The bzrdir to initialize the branch in
977
:param utf8_files: The files to create as a list of
978
(filename, content) tuples
979
:param set_format: If True, set the format with
980
self.get_format_string. (BzrBranch4 has its format set
982
:return: a branch in this format
1652
def initialize(self, a_bzrdir, name=None, repository=None):
1653
"""Create a branch of this format in a_bzrdir.
1655
:param name: Name of the colocated branch to create.
984
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
985
branch_transport = a_bzrdir.get_branch_transport(self)
987
'metadir': ('lock', lockdir.LockDir),
988
'branch4': ('branch-lock', lockable_files.TransportLock),
990
lock_name, lock_class = lock_map[lock_type]
991
control_files = lockable_files.LockableFiles(branch_transport,
992
lock_name, lock_class)
993
control_files.create_lock()
994
control_files.lock_write()
996
utf8_files += [('format', self.get_format_string())]
998
for (filename, content) in utf8_files:
999
branch_transport.put_bytes(
1001
mode=a_bzrdir._get_file_mode())
1003
control_files.unlock()
1004
return self.open(a_bzrdir, _found=True)
1006
def initialize(self, a_bzrdir):
1007
"""Create a branch of this format in a_bzrdir."""
1008
1657
raise NotImplementedError(self.initialize)
1010
1659
def is_supported(self):
1011
1660
"""Is this format supported?
1013
1662
Supported formats can be initialized and opened.
1014
Unsupported formats may not support initialization or committing or
1663
Unsupported formats may not support initialization or committing or
1015
1664
some other features depending on the reason for not being supported.
1019
def open(self, a_bzrdir, _found=False):
1668
def make_tags(self, branch):
1669
"""Create a tags object for branch.
1671
This method is on BranchFormat, because BranchFormats are reflected
1672
over the wire via network_name(), whereas full Branch instances require
1673
multiple VFS method calls to operate at all.
1675
The default implementation returns a disabled-tags instance.
1677
Note that it is normal for branch to be a RemoteBranch when using tags
1680
return DisabledTags(branch)
1682
def network_name(self):
1683
"""A simple byte string uniquely identifying this format for RPC calls.
1685
MetaDir branch formats use their disk format string to identify the
1686
repository over the wire. All in one formats such as bzr < 0.8, and
1687
foreign formats like svn/git and hg should use some marker which is
1688
unique and immutable.
1690
raise NotImplementedError(self.network_name)
1692
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1693
found_repository=None):
1020
1694
"""Return the branch object for a_bzrdir
1022
_found is a private parameter, do not use it. It is used to indicate
1023
if format probing has already be done.
1696
:param a_bzrdir: A BzrDir that contains a branch.
1697
:param name: Name of colocated branch to open
1698
:param _found: a private parameter, do not use it. It is used to
1699
indicate if format probing has already be done.
1700
:param ignore_fallbacks: when set, no fallback branches will be opened
1701
(if there are any). Default is to open fallbacks.
1025
1703
raise NotImplementedError(self.open)
1706
@deprecated_method(deprecated_in((2, 4, 0)))
1028
1707
def register_format(klass, format):
1029
klass._formats[format.get_format_string()] = format
1708
"""Register a metadir format.
1710
See MetaDirBranchFormatFactory for the ability to register a format
1711
without loading the code the format needs until it is actually used.
1713
format_registry.register(format)
1716
@deprecated_method(deprecated_in((2, 4, 0)))
1032
1717
def set_default_format(klass, format):
1033
klass._default_format = format
1718
format_registry.set_default(format)
1720
def supports_set_append_revisions_only(self):
1721
"""True if this format supports set_append_revisions_only."""
1035
1724
def supports_stacking(self):
1036
1725
"""True if this format records a stacked-on branch."""
1728
def supports_leaving_lock(self):
1729
"""True if this format supports leaving locks in place."""
1730
return False # by default
1733
@deprecated_method(deprecated_in((2, 4, 0)))
1040
1734
def unregister_format(klass, format):
1041
del klass._formats[format.get_format_string()]
1735
format_registry.remove(format)
1043
1737
def __str__(self):
1044
return self.get_format_string().rstrip()
1738
return self.get_format_description().rstrip()
1046
1740
def supports_tags(self):
1047
1741
"""True if this format supports tags stored in the branch"""
1048
1742
return False # by default
1745
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1746
"""A factory for a BranchFormat object, permitting simple lazy registration.
1748
While none of the built in BranchFormats are lazy registered yet,
1749
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1750
use it, and the bzr-loom plugin uses it as well (see
1751
bzrlib.plugins.loom.formats).
1754
def __init__(self, format_string, module_name, member_name):
1755
"""Create a MetaDirBranchFormatFactory.
1757
:param format_string: The format string the format has.
1758
:param module_name: Module to load the format class from.
1759
:param member_name: Attribute name within the module for the format class.
1761
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1762
self._format_string = format_string
1764
def get_format_string(self):
1765
"""See BranchFormat.get_format_string."""
1766
return self._format_string
1769
"""Used for network_format_registry support."""
1770
return self.get_obj()()
1051
1773
class BranchHooks(Hooks):
1052
1774
"""A dictionary mapping hook name to a list of callables for branch hooks.
1054
1776
e.g. ['set_rh'] Is the list of items to be called when the
1055
1777
set_revision_history function is invoked.
1061
1783
These are all empty initially, because by default nothing should get
1064
Hooks.__init__(self)
1065
# Introduced in 0.15:
1066
# invoked whenever the revision history has been set
1067
# with set_revision_history. The api signature is
1068
# (branch, revision_history), and the branch will
1071
# invoked after a push operation completes.
1072
# the api signature is
1074
# containing the members
1075
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1076
# where local is the local target branch or None, master is the target
1077
# master branch, and the rest should be self explanatory. The source
1078
# is read locked and the target branches write locked. Source will
1079
# be the local low-latency branch.
1080
self['post_push'] = []
1081
# invoked after a pull operation completes.
1082
# the api signature is
1084
# containing the members
1085
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1086
# where local is the local branch or None, master is the target
1087
# master branch, and the rest should be self explanatory. The source
1088
# is read locked and the target branches write locked. The local
1089
# branch is the low-latency branch.
1090
self['post_pull'] = []
1091
# invoked before a commit operation takes place.
1092
# the api signature is
1093
# (local, master, old_revno, old_revid, future_revno, future_revid,
1094
# tree_delta, future_tree).
1095
# old_revid is NULL_REVISION for the first commit to a branch
1096
# tree_delta is a TreeDelta object describing changes from the basis
1097
# revision, hooks MUST NOT modify this delta
1098
# future_tree is an in-memory tree obtained from
1099
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1100
self['pre_commit'] = []
1101
# invoked after a commit operation completes.
1102
# the api signature is
1103
# (local, master, old_revno, old_revid, new_revno, new_revid)
1104
# old_revid is NULL_REVISION for the first commit to a branch.
1105
self['post_commit'] = []
1106
# invoked after a uncommit operation completes.
1107
# the api signature is
1108
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1109
# local is the local branch or None, master is the target branch,
1110
# and an empty branch recieves new_revno of 0, new_revid of None.
1111
self['post_uncommit'] = []
1113
# Invoked before the tip of a branch changes.
1114
# the api signature is
1115
# (params) where params is a ChangeBranchTipParams with the members
1116
# (branch, old_revno, new_revno, old_revid, new_revid)
1117
self['pre_change_branch_tip'] = []
1119
# Invoked after the tip of a branch changes.
1120
# the api signature is
1121
# (params) where params is a ChangeBranchTipParams with the members
1122
# (branch, old_revno, new_revno, old_revid, new_revid)
1123
self['post_change_branch_tip'] = []
1786
Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1787
self.add_hook('set_rh',
1788
"Invoked whenever the revision history has been set via "
1789
"set_revision_history. The api signature is (branch, "
1790
"revision_history), and the branch will be write-locked. "
1791
"The set_rh hook can be expensive for bzr to trigger, a better "
1792
"hook to use is Branch.post_change_branch_tip.", (0, 15))
1793
self.add_hook('open',
1794
"Called with the Branch object that has been opened after a "
1795
"branch is opened.", (1, 8))
1796
self.add_hook('post_push',
1797
"Called after a push operation completes. post_push is called "
1798
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1799
"bzr client.", (0, 15))
1800
self.add_hook('post_pull',
1801
"Called after a pull operation completes. post_pull is called "
1802
"with a bzrlib.branch.PullResult object and only runs in the "
1803
"bzr client.", (0, 15))
1804
self.add_hook('pre_commit',
1805
"Called after a commit is calculated but before it is "
1806
"completed. pre_commit is called with (local, master, old_revno, "
1807
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1808
"). old_revid is NULL_REVISION for the first commit to a branch, "
1809
"tree_delta is a TreeDelta object describing changes from the "
1810
"basis revision. hooks MUST NOT modify this delta. "
1811
" future_tree is an in-memory tree obtained from "
1812
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1814
self.add_hook('post_commit',
1815
"Called in the bzr client after a commit has completed. "
1816
"post_commit is called with (local, master, old_revno, old_revid, "
1817
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1818
"commit to a branch.", (0, 15))
1819
self.add_hook('post_uncommit',
1820
"Called in the bzr client after an uncommit completes. "
1821
"post_uncommit is called with (local, master, old_revno, "
1822
"old_revid, new_revno, new_revid) where local is the local branch "
1823
"or None, master is the target branch, and an empty branch "
1824
"receives new_revno of 0, new_revid of None.", (0, 15))
1825
self.add_hook('pre_change_branch_tip',
1826
"Called in bzr client and server before a change to the tip of a "
1827
"branch is made. pre_change_branch_tip is called with a "
1828
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1829
"commit, uncommit will all trigger this hook.", (1, 6))
1830
self.add_hook('post_change_branch_tip',
1831
"Called in bzr client and server after a change to the tip of a "
1832
"branch is made. post_change_branch_tip is called with a "
1833
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1834
"commit, uncommit will all trigger this hook.", (1, 4))
1835
self.add_hook('transform_fallback_location',
1836
"Called when a stacked branch is activating its fallback "
1837
"locations. transform_fallback_location is called with (branch, "
1838
"url), and should return a new url. Returning the same url "
1839
"allows it to be used as-is, returning a different one can be "
1840
"used to cause the branch to stack on a closer copy of that "
1841
"fallback_location. Note that the branch cannot have history "
1842
"accessing methods called on it during this hook because the "
1843
"fallback locations have not been activated. When there are "
1844
"multiple hooks installed for transform_fallback_location, "
1845
"all are called with the url returned from the previous hook."
1846
"The order is however undefined.", (1, 9))
1847
self.add_hook('automatic_tag_name',
1848
"Called to determine an automatic tag name for a revision. "
1849
"automatic_tag_name is called with (branch, revision_id) and "
1850
"should return a tag name or None if no tag name could be "
1851
"determined. The first non-None tag name returned will be used.",
1853
self.add_hook('post_branch_init',
1854
"Called after new branch initialization completes. "
1855
"post_branch_init is called with a "
1856
"bzrlib.branch.BranchInitHookParams. "
1857
"Note that init, branch and checkout (both heavyweight and "
1858
"lightweight) will all trigger this hook.", (2, 2))
1859
self.add_hook('post_switch',
1860
"Called after a checkout switches branch. "
1861
"post_switch is called with a "
1862
"bzrlib.branch.SwitchHookParams.", (2, 2))
1126
1866
# install the default hooks into the Branch class.
1159
1899
def __eq__(self, other):
1160
1900
return self.__dict__ == other.__dict__
1162
1902
def __repr__(self):
1163
1903
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1164
self.__class__.__name__, self.branch,
1904
self.__class__.__name__, self.branch,
1165
1905
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1168
class BzrBranchFormat4(BranchFormat):
1169
"""Bzr branch format 4.
1172
- a revision-history file.
1173
- a branch-lock lock file [ to be shared with the bzrdir ]
1176
def get_format_description(self):
1177
"""See BranchFormat.get_format_description()."""
1178
return "Branch format 4"
1180
def initialize(self, a_bzrdir):
1181
"""Create a branch of this format in a_bzrdir."""
1182
utf8_files = [('revision-history', ''),
1183
('branch-name', ''),
1185
return self._initialize_helper(a_bzrdir, utf8_files,
1186
lock_type='branch4', set_format=False)
1189
super(BzrBranchFormat4, self).__init__()
1190
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1192
def open(self, a_bzrdir, _found=False):
1193
"""Return the branch object for a_bzrdir
1195
_found is a private parameter, do not use it. It is used to indicate
1196
if format probing has already be done.
1199
# we are being called directly and must probe.
1200
raise NotImplementedError
1201
return BzrBranch(_format=self,
1202
_control_files=a_bzrdir._control_files,
1204
_repository=a_bzrdir.open_repository())
1207
return "Bazaar-NG branch format 4"
1908
class BranchInitHookParams(object):
1909
"""Object holding parameters passed to `*_branch_init` hooks.
1911
There are 4 fields that hooks may wish to access:
1913
:ivar format: the branch format
1914
:ivar bzrdir: the BzrDir where the branch will be/has been initialized
1915
:ivar name: name of colocated branch, if any (or None)
1916
:ivar branch: the branch created
1918
Note that for lightweight checkouts, the bzrdir and format fields refer to
1919
the checkout, hence they are different from the corresponding fields in
1920
branch, which refer to the original branch.
1923
def __init__(self, format, a_bzrdir, name, branch):
1924
"""Create a group of BranchInitHook parameters.
1926
:param format: the branch format
1927
:param a_bzrdir: the BzrDir where the branch will be/has been
1929
:param name: name of colocated branch, if any (or None)
1930
:param branch: the branch created
1932
Note that for lightweight checkouts, the bzrdir and format fields refer
1933
to the checkout, hence they are different from the corresponding fields
1934
in branch, which refer to the original branch.
1936
self.format = format
1937
self.bzrdir = a_bzrdir
1939
self.branch = branch
1941
def __eq__(self, other):
1942
return self.__dict__ == other.__dict__
1945
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1948
class SwitchHookParams(object):
1949
"""Object holding parameters passed to `*_switch` hooks.
1951
There are 4 fields that hooks may wish to access:
1953
:ivar control_dir: BzrDir of the checkout to change
1954
:ivar to_branch: branch that the checkout is to reference
1955
:ivar force: skip the check for local commits in a heavy checkout
1956
:ivar revision_id: revision ID to switch to (or None)
1959
def __init__(self, control_dir, to_branch, force, revision_id):
1960
"""Create a group of SwitchHook parameters.
1962
:param control_dir: BzrDir of the checkout to change
1963
:param to_branch: branch that the checkout is to reference
1964
:param force: skip the check for local commits in a heavy checkout
1965
:param revision_id: revision ID to switch to (or None)
1967
self.control_dir = control_dir
1968
self.to_branch = to_branch
1970
self.revision_id = revision_id
1972
def __eq__(self, other):
1973
return self.__dict__ == other.__dict__
1976
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1977
self.control_dir, self.to_branch,
1210
1981
class BranchFormatMetadir(BranchFormat):
1214
1985
"""What class to instantiate on open calls."""
1215
1986
raise NotImplementedError(self._branch_class)
1217
def open(self, a_bzrdir, _found=False):
1218
"""Return the branch object for a_bzrdir.
1220
_found is a private parameter, do not use it. It is used to indicate
1221
if format probing has already be done.
1988
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
1990
"""Initialize a branch in a bzrdir, with specified files
1992
:param a_bzrdir: The bzrdir to initialize the branch in
1993
:param utf8_files: The files to create as a list of
1994
(filename, content) tuples
1995
:param name: Name of colocated branch to create, if any
1996
:return: a branch in this format
1998
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
1999
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2000
control_files = lockable_files.LockableFiles(branch_transport,
2001
'lock', lockdir.LockDir)
2002
control_files.create_lock()
2003
control_files.lock_write()
2005
utf8_files += [('format', self.get_format_string())]
2006
for (filename, content) in utf8_files:
2007
branch_transport.put_bytes(
2009
mode=a_bzrdir._get_file_mode())
2011
control_files.unlock()
2012
branch = self.open(a_bzrdir, name, _found=True,
2013
found_repository=repository)
2014
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2017
def network_name(self):
2018
"""A simple byte string uniquely identifying this format for RPC calls.
2020
Metadir branch formats use their format string.
2022
return self.get_format_string()
2024
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2025
found_repository=None):
2026
"""See BranchFormat.open()."""
1224
format = BranchFormat.find_format(a_bzrdir)
2028
format = BranchFormat.find_format(a_bzrdir, name=name)
1225
2029
if format.__class__ != self.__class__:
1226
2030
raise AssertionError("wrong format %r found for %r" %
1227
2031
(format, self))
2032
transport = a_bzrdir.get_branch_transport(None, name=name)
1229
transport = a_bzrdir.get_branch_transport(None)
1230
2034
control_files = lockable_files.LockableFiles(transport, 'lock',
1231
2035
lockdir.LockDir)
2036
if found_repository is None:
2037
found_repository = a_bzrdir.find_repository()
1232
2038
return self._branch_class()(_format=self,
1233
2039
_control_files=control_files,
1234
2041
a_bzrdir=a_bzrdir,
1235
_repository=a_bzrdir.find_repository())
2042
_repository=found_repository,
2043
ignore_fallbacks=ignore_fallbacks)
1236
2044
except errors.NoSuchFile:
1237
raise errors.NotBranchError(path=transport.base)
2045
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
1239
2047
def __init__(self):
1240
2048
super(BranchFormatMetadir, self).__init__()
1241
2049
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2050
self._matchingbzrdir.set_branch_format(self)
1243
2052
def supports_tags(self):
2055
def supports_leaving_lock(self):
1247
2059
class BzrBranchFormat5(BranchFormatMetadir):
1248
2060
"""Bzr branch format 5.
1366
2225
"""See BranchFormat.get_format_description()."""
1367
2226
return "Checkout reference format 1"
1369
def get_reference(self, a_bzrdir):
2228
def get_reference(self, a_bzrdir, name=None):
1370
2229
"""See BranchFormat.get_reference()."""
1371
transport = a_bzrdir.get_branch_transport(None)
1372
return transport.get('location').read()
2230
transport = a_bzrdir.get_branch_transport(None, name=name)
2231
return transport.get_bytes('location')
1374
def set_reference(self, a_bzrdir, to_branch):
2233
def set_reference(self, a_bzrdir, name, to_branch):
1375
2234
"""See BranchFormat.set_reference()."""
1376
transport = a_bzrdir.get_branch_transport(None)
2235
transport = a_bzrdir.get_branch_transport(None, name=name)
1377
2236
location = transport.put_bytes('location', to_branch.base)
1379
def initialize(self, a_bzrdir, target_branch=None):
2238
def initialize(self, a_bzrdir, name=None, target_branch=None,
1380
2240
"""Create a branch of this format in a_bzrdir."""
1381
2241
if target_branch is None:
1382
2242
# this format does not implement branch itself, thus the implicit
1383
2243
# creation contract must see it as uninitializable
1384
2244
raise errors.UninitializableFormat(self)
1385
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1386
branch_transport = a_bzrdir.get_branch_transport(self)
2245
mutter('creating branch reference in %s', a_bzrdir.user_url)
2246
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1387
2247
branch_transport.put_bytes('location',
1388
target_branch.bzrdir.root_transport.base)
2248
target_branch.bzrdir.user_url)
1389
2249
branch_transport.put_bytes('format', self.get_format_string())
1391
a_bzrdir, _found=True,
2251
a_bzrdir, name, _found=True,
1392
2252
possible_transports=[target_branch.bzrdir.root_transport])
2253
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1394
2256
def __init__(self):
1395
2257
super(BranchReferenceFormat, self).__init__()
1396
2258
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2259
self._matchingbzrdir.set_branch_format(self)
1398
2261
def _make_reference_clone_function(format, a_branch):
1399
2262
"""Create a clone() routine for a branch dynamically."""
1400
def clone(to_bzrdir, revision_id=None):
2263
def clone(to_bzrdir, revision_id=None,
2264
repository_policy=None):
1401
2265
"""See Branch.clone()."""
1402
return format.initialize(to_bzrdir, a_branch)
2266
return format.initialize(to_bzrdir, target_branch=a_branch)
1403
2267
# cannot obey revision_id limits when cloning a reference ...
1404
2268
# FIXME RBC 20060210 either nuke revision_id for clone, or
1405
2269
# emit some sort of warning/error to the caller ?!
1408
def open(self, a_bzrdir, _found=False, location=None,
1409
possible_transports=None):
2272
def open(self, a_bzrdir, name=None, _found=False, location=None,
2273
possible_transports=None, ignore_fallbacks=False,
2274
found_repository=None):
1410
2275
"""Return the branch that the branch reference in a_bzrdir points at.
1412
_found is a private parameter, do not use it. It is used to indicate
1413
if format probing has already be done.
2277
:param a_bzrdir: A BzrDir that contains a branch.
2278
:param name: Name of colocated branch to open, if any
2279
:param _found: a private parameter, do not use it. It is used to
2280
indicate if format probing has already be done.
2281
:param ignore_fallbacks: when set, no fallback branches will be opened
2282
(if there are any). Default is to open fallbacks.
2283
:param location: The location of the referenced branch. If
2284
unspecified, this will be determined from the branch reference in
2286
:param possible_transports: An optional reusable transports list.
1416
format = BranchFormat.find_format(a_bzrdir)
2289
format = BranchFormat.find_format(a_bzrdir, name=name)
1417
2290
if format.__class__ != self.__class__:
1418
2291
raise AssertionError("wrong format %r found for %r" %
1419
2292
(format, self))
1420
2293
if location is None:
1421
location = self.get_reference(a_bzrdir)
2294
location = self.get_reference(a_bzrdir, name)
1422
2295
real_bzrdir = bzrdir.BzrDir.open(
1423
2296
location, possible_transports=possible_transports)
1424
result = real_bzrdir.open_branch()
2297
result = real_bzrdir.open_branch(name=name,
2298
ignore_fallbacks=ignore_fallbacks)
1425
2299
# this changes the behaviour of result.clone to create a new reference
1426
2300
# rather than a copy of the content of the branch.
1427
2301
# I did not use a proxy object because that needs much more extensive
2311
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2312
"""Branch format registry."""
2314
def __init__(self, other_registry=None):
2315
super(BranchFormatRegistry, self).__init__(other_registry)
2316
self._default_format = None
2318
def set_default(self, format):
2319
self._default_format = format
2321
def get_default(self):
2322
return self._default_format
2325
network_format_registry = registry.FormatRegistry()
2326
"""Registry of formats indexed by their network name.
2328
The network name for a branch format is an identifier that can be used when
2329
referring to formats with smart server operations. See
2330
BranchFormat.network_name() for more detail.
2333
format_registry = BranchFormatRegistry(network_format_registry)
1437
2336
# formats which have no format string are not discoverable
1438
2337
# and not independently creatable, so are not registered.
1439
2338
__format5 = BzrBranchFormat5()
1440
2339
__format6 = BzrBranchFormat6()
1441
2340
__format7 = BzrBranchFormat7()
1442
BranchFormat.register_format(__format5)
1443
BranchFormat.register_format(BranchReferenceFormat())
1444
BranchFormat.register_format(__format6)
1445
BranchFormat.register_format(__format7)
1446
BranchFormat.set_default_format(__format6)
1447
_legacy_formats = [BzrBranchFormat4(),
1450
class BzrBranch(Branch):
2341
__format8 = BzrBranchFormat8()
2342
format_registry.register(__format5)
2343
format_registry.register(BranchReferenceFormat())
2344
format_registry.register(__format6)
2345
format_registry.register(__format7)
2346
format_registry.register(__format8)
2347
format_registry.set_default(__format7)
2350
class BranchWriteLockResult(LogicalLockResult):
2351
"""The result of write locking a branch.
2353
:ivar branch_token: The token obtained from the underlying branch lock, or
2355
:ivar unlock: A callable which will unlock the lock.
2358
def __init__(self, unlock, branch_token):
2359
LogicalLockResult.__init__(self, unlock)
2360
self.branch_token = branch_token
2363
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2367
class BzrBranch(Branch, _RelockDebugMixin):
1451
2368
"""A branch stored in the actual filesystem.
1453
2370
Note that it's "local" in the context of the filesystem; it doesn't
1454
2371
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1455
2372
it's writable, and can be accessed via the normal filesystem API.
1457
:ivar _transport: Transport for file operations on this branch's
2374
:ivar _transport: Transport for file operations on this branch's
1458
2375
control files, typically pointing to the .bzr/branch directory.
1459
2376
:ivar repository: Repository for this branch.
1460
:ivar base: The url of the base directory for this branch; the one
2377
:ivar base: The url of the base directory for this branch; the one
1461
2378
containing the .bzr directory.
2379
:ivar name: Optional colocated branch name as it exists in the control
1464
2383
def __init__(self, _format=None,
1465
_control_files=None, a_bzrdir=None, _repository=None):
2384
_control_files=None, a_bzrdir=None, name=None,
2385
_repository=None, ignore_fallbacks=False):
1466
2386
"""Create new branch object at a particular location."""
1467
2387
if a_bzrdir is None:
1468
2388
raise ValueError('a_bzrdir must be supplied')
1470
2390
self.bzrdir = a_bzrdir
1471
2391
self._base = self.bzrdir.transport.clone('..').base
1472
2393
# XXX: We should be able to just do
1473
2394
# self.base = self.bzrdir.root_transport.base
1474
2395
# but this does not quite work yet -- mbp 20080522
1535
2498
"""See Branch.print_file."""
1536
2499
return self.repository.print_file(file, revision_id)
1538
def _write_revision_history(self, history):
1539
"""Factored out of set_revision_history.
1541
This performs the actual writing to disk.
1542
It is intended to be called by BzrBranch5.set_revision_history."""
1543
self._transport.put_bytes(
1544
'revision-history', '\n'.join(history),
1545
mode=self.bzrdir._get_file_mode())
1548
def set_revision_history(self, rev_history):
1549
"""See Branch.set_revision_history."""
1550
if 'evil' in debug.debug_flags:
1551
mutter_callsite(3, "set_revision_history scales with history.")
1552
check_not_reserved_id = _mod_revision.check_not_reserved_id
1553
for rev_id in rev_history:
1554
check_not_reserved_id(rev_id)
1555
if Branch.hooks['post_change_branch_tip']:
1556
# Don't calculate the last_revision_info() if there are no hooks
1558
old_revno, old_revid = self.last_revision_info()
1559
if len(rev_history) == 0:
1560
revid = _mod_revision.NULL_REVISION
1562
revid = rev_history[-1]
1563
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1564
self._write_revision_history(rev_history)
1565
self._clear_cached_state()
1566
self._cache_revision_history(rev_history)
1567
for hook in Branch.hooks['set_rh']:
1568
hook(self, rev_history)
1569
if Branch.hooks['post_change_branch_tip']:
1570
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1572
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1573
"""Run the pre_change_branch_tip hooks."""
1574
hooks = Branch.hooks['pre_change_branch_tip']
1577
old_revno, old_revid = self.last_revision_info()
1578
params = ChangeBranchTipParams(
1579
self, old_revno, new_revno, old_revid, new_revid)
1583
except errors.TipChangeRejected:
1586
exc_info = sys.exc_info()
1587
hook_name = Branch.hooks.get_hook_name(hook)
1588
raise errors.HookFailed(
1589
'pre_change_branch_tip', hook_name, exc_info)
1591
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1592
"""Run the post_change_branch_tip hooks."""
1593
hooks = Branch.hooks['post_change_branch_tip']
1596
new_revno, new_revid = self.last_revision_info()
1597
params = ChangeBranchTipParams(
1598
self, old_revno, new_revno, old_revid, new_revid)
1602
2501
@needs_write_lock
1603
2502
def set_last_revision_info(self, revno, revision_id):
1604
"""Set the last revision of this branch.
1606
The caller is responsible for checking that the revno is correct
1607
for this revision id.
1609
It may be possible to set the branch last revision to an id not
1610
present in the repository. However, branches can also be
1611
configured to check constraints on history, in which case this may not
2503
if not revision_id or not isinstance(revision_id, basestring):
2504
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
1614
2505
revision_id = _mod_revision.ensure_null(revision_id)
1615
# this old format stores the full history, but this api doesn't
1616
# provide it, so we must generate, and might as well check it's
1618
history = self._lefthand_history(revision_id)
1619
if len(history) != revno:
1620
raise AssertionError('%d != %d' % (len(history), revno))
1621
self.set_revision_history(history)
1623
def _gen_revision_history(self):
1624
history = self._transport.get_bytes('revision-history').split('\n')
1625
if history[-1:] == ['']:
1626
# There shouldn't be a trailing newline, but just in case.
1630
def _lefthand_history(self, revision_id, last_rev=None,
1632
if 'evil' in debug.debug_flags:
1633
mutter_callsite(4, "_lefthand_history scales with history.")
1634
# stop_revision must be a descendant of last_revision
1635
graph = self.repository.get_graph()
1636
if last_rev is not None:
1637
if not graph.is_ancestor(last_rev, revision_id):
1638
# our previous tip is not merged into stop_revision
1639
raise errors.DivergedBranches(self, other_branch)
1640
# make a new revision history from the graph
1641
parents_map = graph.get_parent_map([revision_id])
1642
if revision_id not in parents_map:
1643
raise errors.NoSuchRevision(self, revision_id)
1644
current_rev_id = revision_id
1646
check_not_reserved_id = _mod_revision.check_not_reserved_id
1647
# Do not include ghosts or graph origin in revision_history
1648
while (current_rev_id in parents_map and
1649
len(parents_map[current_rev_id]) > 0):
1650
check_not_reserved_id(current_rev_id)
1651
new_history.append(current_rev_id)
1652
current_rev_id = parents_map[current_rev_id][0]
1653
parents_map = graph.get_parent_map([current_rev_id])
1654
new_history.reverse()
1658
def generate_revision_history(self, revision_id, last_rev=None,
1660
"""Create a new revision history that will finish with revision_id.
1662
:param revision_id: the new tip to use.
1663
:param last_rev: The previous last_revision. If not None, then this
1664
must be a ancestory of revision_id, or DivergedBranches is raised.
1665
:param other_branch: The other branch that DivergedBranches should
1666
raise with respect to.
1668
self.set_revision_history(self._lefthand_history(revision_id,
1669
last_rev, other_branch))
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)
1671
2515
def basis_tree(self):
1672
2516
"""See Branch.basis_tree."""
1673
2517
return self.repository.revision_tree(self.last_revision())
1676
def pull(self, source, overwrite=False, stop_revision=None,
1677
_hook_master=None, run_hooks=True, possible_transports=None,
1678
_override_hook_target=None):
1681
:param _hook_master: Private parameter - set the branch to
1682
be supplied as the master to pull hooks.
1683
:param run_hooks: Private parameter - if false, this branch
1684
is being called because it's the master of the primary branch,
1685
so it should not run its hooks.
1686
:param _override_hook_target: Private parameter - set the branch to be
1687
supplied as the target_branch to pull hooks.
1689
result = PullResult()
1690
result.source_branch = source
1691
if _override_hook_target is None:
1692
result.target_branch = self
1694
result.target_branch = _override_hook_target
1697
# We assume that during 'pull' the local repository is closer than
1699
graph = self.repository.get_graph(source.repository)
1700
result.old_revno, result.old_revid = self.last_revision_info()
1701
self.update_revisions(source, stop_revision, overwrite=overwrite,
1703
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1704
result.new_revno, result.new_revid = self.last_revision_info()
1706
result.master_branch = _hook_master
1707
result.local_branch = result.target_branch
1709
result.master_branch = result.target_branch
1710
result.local_branch = None
1712
for hook in Branch.hooks['post_pull']:
1718
2519
def _get_parent_location(self):
1719
2520
_locs = ['parent', 'pull', 'x-pull']
1720
2521
for l in _locs:
1728
def push(self, target, overwrite=False, stop_revision=None,
1729
_override_hook_source_branch=None):
1732
This is the basic concrete implementation of push()
1734
:param _override_hook_source_branch: If specified, run
1735
the hooks passing this Branch as the source, rather than self.
1736
This is for use of RemoteBranch, where push is delegated to the
1737
underlying vfs-based Branch.
1739
# TODO: Public option to disable running hooks - should be trivial but
1743
result = self._push_with_bound_branches(target, overwrite,
1745
_override_hook_source_branch=_override_hook_source_branch)
1750
def _push_with_bound_branches(self, target, overwrite,
1752
_override_hook_source_branch=None):
1753
"""Push from self into target, and into target's master if any.
1755
This is on the base BzrBranch class even though it doesn't support
1756
bound branches because the *target* might be bound.
1759
if _override_hook_source_branch:
1760
result.source_branch = _override_hook_source_branch
1761
for hook in Branch.hooks['post_push']:
1764
bound_location = target.get_bound_location()
1765
if bound_location and target.base != bound_location:
1766
# there is a master branch.
1768
# XXX: Why the second check? Is it even supported for a branch to
1769
# be bound to itself? -- mbp 20070507
1770
master_branch = target.get_master_branch()
1771
master_branch.lock_write()
1773
# push into the master from this branch.
1774
self._basic_push(master_branch, overwrite, stop_revision)
1775
# and push into the target branch from this. Note that we push from
1776
# this branch again, because its considered the highest bandwidth
1778
result = self._basic_push(target, overwrite, stop_revision)
1779
result.master_branch = master_branch
1780
result.local_branch = target
1784
master_branch.unlock()
1787
result = self._basic_push(target, overwrite, stop_revision)
1788
# TODO: Why set master_branch and local_branch if there's no
1789
# binding? Maybe cleaner to just leave them unset? -- mbp
1791
result.master_branch = target
1792
result.local_branch = None
1796
def _basic_push(self, target, overwrite, stop_revision):
1797
"""Basic implementation of push without bound branches or hooks.
1799
Must be called with self read locked and target write locked.
1801
result = PushResult()
1802
result.source_branch = self
1803
result.target_branch = target
1804
result.old_revno, result.old_revid = target.last_revision_info()
1806
# We assume that during 'push' this repository is closer than
1808
graph = self.repository.get_graph(target.repository)
1809
target.update_revisions(self, stop_revision, overwrite=overwrite,
1811
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
1812
result.new_revno, result.new_revid = target.last_revision_info()
1815
def get_parent(self):
1816
"""See Branch.get_parent."""
1817
parent = self._get_parent_location()
1820
# This is an old-format absolute path to a local branch
1821
# turn it into a url
1822
if parent.startswith('/'):
1823
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1825
return urlutils.join(self.base[:-1], parent)
1826
except errors.InvalidURLJoin, e:
1827
raise errors.InaccessibleParent(parent, self.base)
1829
2528
def get_stacked_on_url(self):
1830
raise errors.UnstackableBranchFormat(self._format, self.base)
2529
raise errors.UnstackableBranchFormat(self._format, self.user_url)
1832
2531
def set_push_location(self, location):
1833
2532
"""See Branch.set_push_location."""
1860
2541
self._transport.put_bytes('parent', url + '\n',
1861
2542
mode=self.bzrdir._get_file_mode())
1863
def set_stacked_on_url(self, url):
1864
raise errors.UnstackableBranchFormat(self._format, self.base)
1867
class BzrBranch5(BzrBranch):
1868
"""A format 5 branch. This supports new features over plain branches.
1870
It has support for a master_branch which is the data for bound branches.
1874
def pull(self, source, overwrite=False, stop_revision=None,
1875
run_hooks=True, possible_transports=None,
1876
_override_hook_target=None):
1877
"""Pull from source into self, updating my master if any.
1879
:param run_hooks: Private parameter - if false, this branch
1880
is being called because it's the master of the primary branch,
1881
so it should not run its hooks.
1883
bound_location = self.get_bound_location()
1884
master_branch = None
1885
if bound_location and source.base != bound_location:
1886
# not pulling from master, so we need to update master.
1887
master_branch = self.get_master_branch(possible_transports)
1888
master_branch.lock_write()
1891
# pull from source into master.
1892
master_branch.pull(source, overwrite, stop_revision,
1894
return super(BzrBranch5, self).pull(source, overwrite,
1895
stop_revision, _hook_master=master_branch,
1896
run_hooks=run_hooks,
1897
_override_hook_target=_override_hook_target)
1900
master_branch.unlock()
1902
def get_bound_location(self):
1904
return self._transport.get_bytes('bound')[:-1]
1905
except errors.NoSuchFile:
1909
def get_master_branch(self, possible_transports=None):
1910
"""Return the branch we are bound to.
1912
:return: Either a Branch, or None
1914
This could memoise the branch, but if thats done
1915
it must be revalidated on each new lock.
1916
So for now we just don't memoise it.
1917
# RBC 20060304 review this decision.
1919
bound_loc = self.get_bound_location()
1923
return Branch.open(bound_loc,
1924
possible_transports=possible_transports)
1925
except (errors.NotBranchError, errors.ConnectionError), e:
1926
raise errors.BoundBranchConnectionFailure(
1930
def set_bound_location(self, location):
1931
"""Set the target where this branch is bound to.
1933
:param location: URL to the target branch
1936
self._transport.put_bytes('bound', location+'\n',
1937
mode=self.bzrdir._get_file_mode())
1940
self._transport.delete('bound')
1941
except errors.NoSuchFile:
2546
"""If bound, unbind"""
2547
return self.set_bound_location(None)
1945
2549
@needs_write_lock
1946
2550
def bind(self, other):
2041
2647
Use set_last_revision_info to perform this safely.
2043
2649
Does not update the revision_history cache.
2044
Intended to be called by set_last_revision_info and
2045
_write_revision_history.
2047
2651
revision_id = _mod_revision.ensure_null(revision_id)
2048
2652
out_string = '%d %s\n' % (revno, revision_id)
2049
2653
self._transport.put_bytes('last-revision', out_string,
2050
2654
mode=self.bzrdir._get_file_mode())
2657
class FullHistoryBzrBranch(BzrBranch):
2658
"""Bzr branch which contains the full revision history."""
2052
2660
@needs_write_lock
2053
2661
def set_last_revision_info(self, revno, revision_id):
2662
if not revision_id or not isinstance(revision_id, basestring):
2663
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2054
2664
revision_id = _mod_revision.ensure_null(revision_id)
2055
old_revno, old_revid = self.last_revision_info()
2056
if self._get_append_revisions_only():
2057
self._check_history_violation(revision_id)
2058
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2059
self._write_last_revision_info(revno, revision_id)
2665
# this old format stores the full history, but this api doesn't
2666
# provide it, so we must generate, and might as well check it's
2668
history = self._lefthand_history(revision_id)
2669
if len(history) != revno:
2670
raise AssertionError('%d != %d' % (len(history), revno))
2671
self._set_revision_history(history)
2673
def _read_last_revision_info(self):
2674
rh = self.revision_history()
2677
return (revno, rh[-1])
2679
return (0, _mod_revision.NULL_REVISION)
2681
@deprecated_method(deprecated_in((2, 4, 0)))
2683
def set_revision_history(self, rev_history):
2684
"""See Branch.set_revision_history."""
2685
self._set_revision_history(rev_history)
2687
def _set_revision_history(self, rev_history):
2688
if 'evil' in debug.debug_flags:
2689
mutter_callsite(3, "set_revision_history scales with history.")
2690
check_not_reserved_id = _mod_revision.check_not_reserved_id
2691
for rev_id in rev_history:
2692
check_not_reserved_id(rev_id)
2693
if Branch.hooks['post_change_branch_tip']:
2694
# Don't calculate the last_revision_info() if there are no hooks
2696
old_revno, old_revid = self.last_revision_info()
2697
if len(rev_history) == 0:
2698
revid = _mod_revision.NULL_REVISION
2700
revid = rev_history[-1]
2701
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2702
self._write_revision_history(rev_history)
2060
2703
self._clear_cached_state()
2061
self._last_revision_info_cache = revno, revision_id
2062
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2704
self._cache_revision_history(rev_history)
2705
for hook in Branch.hooks['set_rh']:
2706
hook(self, rev_history)
2707
if Branch.hooks['post_change_branch_tip']:
2708
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2710
def _write_revision_history(self, history):
2711
"""Factored out of set_revision_history.
2713
This performs the actual writing to disk.
2714
It is intended to be called by set_revision_history."""
2715
self._transport.put_bytes(
2716
'revision-history', '\n'.join(history),
2717
mode=self.bzrdir._get_file_mode())
2719
def _gen_revision_history(self):
2720
history = self._transport.get_bytes('revision-history').split('\n')
2721
if history[-1:] == ['']:
2722
# There shouldn't be a trailing newline, but just in case.
2726
def _synchronize_history(self, destination, revision_id):
2727
if not isinstance(destination, FullHistoryBzrBranch):
2728
super(BzrBranch, self)._synchronize_history(
2729
destination, revision_id)
2731
if revision_id == _mod_revision.NULL_REVISION:
2734
new_history = self.revision_history()
2735
if revision_id is not None and new_history != []:
2737
new_history = new_history[:new_history.index(revision_id) + 1]
2739
rev = self.repository.get_revision(revision_id)
2740
new_history = rev.get_history(self.repository)[1:]
2741
destination._set_revision_history(new_history)
2744
def generate_revision_history(self, revision_id, last_rev=None,
2746
"""Create a new revision history that will finish with revision_id.
2748
:param revision_id: the new tip to use.
2749
:param last_rev: The previous last_revision. If not None, then this
2750
must be a ancestory of revision_id, or DivergedBranches is raised.
2751
:param other_branch: The other branch that DivergedBranches should
2752
raise with respect to.
2754
self._set_revision_history(self._lefthand_history(revision_id,
2755
last_rev, other_branch))
2758
class BzrBranch5(FullHistoryBzrBranch):
2759
"""A format 5 branch. This supports new features over plain branches.
2761
It has support for a master_branch which is the data for bound branches.
2765
class BzrBranch8(BzrBranch):
2766
"""A branch that stores tree-reference locations."""
2768
def _open_hook(self):
2769
if self._ignore_fallbacks:
2772
url = self.get_stacked_on_url()
2773
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2774
errors.UnstackableBranchFormat):
2777
for hook in Branch.hooks['transform_fallback_location']:
2778
url = hook(self, url)
2780
hook_name = Branch.hooks.get_hook_name(hook)
2781
raise AssertionError(
2782
"'transform_fallback_location' hook %s returned "
2783
"None, not a URL." % hook_name)
2784
self._activate_fallback_location(url)
2786
def __init__(self, *args, **kwargs):
2787
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2788
super(BzrBranch8, self).__init__(*args, **kwargs)
2789
self._last_revision_info_cache = None
2790
self._reference_info = None
2792
def _clear_cached_state(self):
2793
super(BzrBranch8, self)._clear_cached_state()
2794
self._last_revision_info_cache = None
2795
self._reference_info = None
2064
2797
def _check_history_violation(self, revision_id):
2065
last_revision = _mod_revision.ensure_null(self.last_revision())
2798
current_revid = self.last_revision()
2799
last_revision = _mod_revision.ensure_null(current_revid)
2066
2800
if _mod_revision.is_null(last_revision):
2068
if last_revision not in self._lefthand_history(revision_id):
2069
raise errors.AppendRevisionsOnlyViolation(self.base)
2802
graph = self.repository.get_graph()
2803
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2804
if lh_ancestor == current_revid:
2806
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2071
2808
def _gen_revision_history(self):
2072
2809
"""Generate the revision history from last revision
2130
2822
"""Set the parent branch"""
2131
2823
return self._get_config_location('parent_location')
2826
def _set_all_reference_info(self, info_dict):
2827
"""Replace all reference info stored in a branch.
2829
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2832
writer = rio.RioWriter(s)
2833
for key, (tree_path, branch_location) in info_dict.iteritems():
2834
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2835
branch_location=branch_location)
2836
writer.write_stanza(stanza)
2837
self._transport.put_bytes('references', s.getvalue())
2838
self._reference_info = info_dict
2841
def _get_all_reference_info(self):
2842
"""Return all the reference info stored in a branch.
2844
:return: A dict of {file_id: (tree_path, branch_location)}
2846
if self._reference_info is not None:
2847
return self._reference_info
2848
rio_file = self._transport.get('references')
2850
stanzas = rio.read_stanzas(rio_file)
2851
info_dict = dict((s['file_id'], (s['tree_path'],
2852
s['branch_location'])) for s in stanzas)
2855
self._reference_info = info_dict
2858
def set_reference_info(self, file_id, tree_path, branch_location):
2859
"""Set the branch location to use for a tree reference.
2861
:param file_id: The file-id of the tree reference.
2862
:param tree_path: The path of the tree reference in the tree.
2863
:param branch_location: The location of the branch to retrieve tree
2866
info_dict = self._get_all_reference_info()
2867
info_dict[file_id] = (tree_path, branch_location)
2868
if None in (tree_path, branch_location):
2869
if tree_path is not None:
2870
raise ValueError('tree_path must be None when branch_location'
2872
if branch_location is not None:
2873
raise ValueError('branch_location must be None when tree_path'
2875
del info_dict[file_id]
2876
self._set_all_reference_info(info_dict)
2878
def get_reference_info(self, file_id):
2879
"""Get the tree_path and branch_location for a tree reference.
2881
:return: a tuple of (tree_path, branch_location)
2883
return self._get_all_reference_info().get(file_id, (None, None))
2885
def reference_parent(self, file_id, path, possible_transports=None):
2886
"""Return the parent branch for a tree-reference file_id.
2888
:param file_id: The file_id of the tree reference
2889
:param path: The path of the file_id in the tree
2890
:return: A branch associated with the file_id
2892
branch_location = self.get_reference_info(file_id)[1]
2893
if branch_location is None:
2894
return Branch.reference_parent(self, file_id, path,
2895
possible_transports)
2896
branch_location = urlutils.join(self.user_url, branch_location)
2897
return Branch.open(branch_location,
2898
possible_transports=possible_transports)
2133
2900
def set_push_location(self, location):
2134
2901
"""See Branch.set_push_location."""
2135
2902
self._set_config_location('push_location', location)
2137
2904
def set_bound_location(self, location):
2138
2905
"""See Branch.set_push_location."""
2906
self._master_branch_cache = None
2140
2908
config = self.get_config()
2141
2909
if location is None:
2169
2937
return self._get_bound_location(False)
2171
2939
def get_stacked_on_url(self):
2172
self._check_stackable_repo()
2940
# you can always ask for the URL; but you might not be able to use it
2941
# if the repo can't support stacking.
2942
## self._check_stackable_repo()
2173
2943
stacked_url = self._get_config_location('stacked_on_location')
2174
2944
if stacked_url is None:
2175
2945
raise errors.NotStacked(self)
2176
2946
return stacked_url
2178
def set_append_revisions_only(self, enabled):
2183
self.get_config().set_user_option('append_revisions_only', value,
2186
def set_stacked_on_url(self, url):
2187
self._check_stackable_repo()
2190
old_url = self.get_stacked_on_url()
2191
except (errors.NotStacked, errors.UnstackableBranchFormat,
2192
errors.UnstackableRepositoryFormat):
2195
# repositories don't offer an interface to remove fallback
2196
# repositories today; take the conceptually simpler option and just
2198
self.repository = self.bzrdir.find_repository()
2199
# for every revision reference the branch has, ensure it is pulled
2201
source_repository = self._get_fallback_repository(old_url)
2202
for revision_id in chain([self.last_revision()],
2203
self.tags.get_reverse_tag_dict()):
2204
self.repository.fetch(source_repository, revision_id,
2207
self._activate_fallback_location(url)
2208
# write this out after the repository is stacked to avoid setting a
2209
# stacked config that doesn't work.
2210
self._set_config_location('stacked_on_location', url)
2212
2948
def _get_append_revisions_only(self):
2213
value = self.get_config().get_user_option('append_revisions_only')
2214
return value == 'True'
2216
def _synchronize_history(self, destination, revision_id):
2217
"""Synchronize last revision and revision history between branches.
2219
This version is most efficient when the destination is also a
2220
BzrBranch6, but works for BzrBranch5, as long as the destination's
2221
repository contains all the lefthand ancestors of the intended
2222
last_revision. If not, set_last_revision_info will fail.
2224
:param destination: The branch to copy the history into
2225
:param revision_id: The revision-id to truncate history at. May
2226
be None to copy complete history.
2228
source_revno, source_revision_id = self.last_revision_info()
2229
if revision_id is None:
2230
revno, revision_id = source_revno, source_revision_id
2231
elif source_revision_id == revision_id:
2232
# we know the revno without needing to walk all of history
2233
revno = source_revno
2235
# To figure out the revno for a random revision, we need to build
2236
# the revision history, and count its length.
2237
# We don't care about the order, just how long it is.
2238
# Alternatively, we could start at the current location, and count
2239
# backwards. But there is no guarantee that we will find it since
2240
# it may be a merged revision.
2241
revno = len(list(self.repository.iter_reverse_revision_history(
2243
destination.set_last_revision_info(revno, revision_id)
2245
def _make_tags(self):
2246
return BasicTags(self)
2249
def generate_revision_history(self, revision_id, last_rev=None,
2251
"""See BzrBranch5.generate_revision_history"""
2252
history = self._lefthand_history(revision_id, last_rev, other_branch)
2253
revno = len(history)
2254
self.set_last_revision_info(revno, revision_id)
2949
return self.get_config(
2950
).get_user_option_as_bool('append_revisions_only')
2256
2952
@needs_read_lock
2257
2953
def get_rev_id(self, revno, history=None):
2429
3156
branch._set_config_location('stacked_on_location', '')
2430
3157
# update target format
2431
3158
branch._transport.put_bytes('format', format.get_format_string())
3161
class Converter7to8(object):
3162
"""Perform an in-place upgrade of format 6 to format 7"""
3164
def convert(self, branch):
3165
format = BzrBranchFormat8()
3166
branch._transport.put_bytes('references', '')
3167
# update target format
3168
branch._transport.put_bytes('format', format.get_format_string())
3171
def _run_with_write_locked_target(target, callable, *args, **kwargs):
3172
"""Run ``callable(*args, **kwargs)``, write-locking target for the
3175
_run_with_write_locked_target will attempt to release the lock it acquires.
3177
If an exception is raised by callable, then that exception *will* be
3178
propagated, even if the unlock attempt raises its own error. Thus
3179
_run_with_write_locked_target should be preferred to simply doing::
3183
return callable(*args, **kwargs)
3188
# This is very similar to bzrlib.decorators.needs_write_lock. Perhaps they
3189
# should share code?
3192
result = callable(*args, **kwargs)
3194
exc_info = sys.exc_info()
3198
raise exc_info[0], exc_info[1], exc_info[2]
3204
class InterBranch(InterObject):
3205
"""This class represents operations taking place between two branches.
3207
Its instances have methods like pull() and push() and contain
3208
references to the source and target repositories these operations
3209
can be carried out on.
3213
"""The available optimised InterBranch types."""
3216
def _get_branch_formats_to_test(klass):
3217
"""Return an iterable of format tuples for testing.
3219
:return: An iterable of (from_format, to_format) to use when testing
3220
this InterBranch class. Each InterBranch class should define this
3223
raise NotImplementedError(klass._get_branch_formats_to_test)
3226
def pull(self, overwrite=False, stop_revision=None,
3227
possible_transports=None, local=False):
3228
"""Mirror source into target branch.
3230
The target branch is considered to be 'local', having low latency.
3232
:returns: PullResult instance
3234
raise NotImplementedError(self.pull)
3237
def push(self, overwrite=False, stop_revision=None, lossy=False,
3238
_override_hook_source_branch=None):
3239
"""Mirror the source branch into the target branch.
3241
The source branch is considered to be 'local', having low latency.
3243
raise NotImplementedError(self.push)
3246
def copy_content_into(self, revision_id=None):
3247
"""Copy the content of source into target
3249
revision_id: if not None, the revision history in the new branch will
3250
be truncated to end with revision_id.
3252
raise NotImplementedError(self.copy_content_into)
3255
def fetch(self, stop_revision=None, limit=None):
3258
:param stop_revision: Last revision to fetch
3259
:param limit: Optional rough limit of revisions to fetch
3261
raise NotImplementedError(self.fetch)
3264
class GenericInterBranch(InterBranch):
3265
"""InterBranch implementation that uses public Branch functions."""
3268
def is_compatible(klass, source, target):
3269
# GenericBranch uses the public API, so always compatible
3273
def _get_branch_formats_to_test(klass):
3274
return [(format_registry.get_default(), format_registry.get_default())]
3277
def unwrap_format(klass, format):
3278
if isinstance(format, remote.RemoteBranchFormat):
3279
format._ensure_real()
3280
return format._custom_format
3284
def copy_content_into(self, revision_id=None):
3285
"""Copy the content of source into target
3287
revision_id: if not None, the revision history in the new branch will
3288
be truncated to end with revision_id.
3290
self.source.update_references(self.target)
3291
self.source._synchronize_history(self.target, revision_id)
3293
parent = self.source.get_parent()
3294
except errors.InaccessibleParent, e:
3295
mutter('parent was not accessible to copy: %s', e)
3298
self.target.set_parent(parent)
3299
if self.source._push_should_merge_tags():
3300
self.source.tags.merge_to(self.target.tags)
3303
def fetch(self, stop_revision=None, limit=None):
3304
if self.target.base == self.source.base:
3306
self.source.lock_read()
3308
fetch_spec_factory = fetch.FetchSpecFactory()
3309
fetch_spec_factory.source_branch = self.source
3310
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3311
fetch_spec_factory.source_repo = self.source.repository
3312
fetch_spec_factory.target_repo = self.target.repository
3313
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3314
fetch_spec_factory.limit = limit
3315
fetch_spec = fetch_spec_factory.make_fetch_spec()
3316
return self.target.repository.fetch(self.source.repository,
3317
fetch_spec=fetch_spec)
3319
self.source.unlock()
3322
def _update_revisions(self, stop_revision=None, overwrite=False,
3324
other_revno, other_last_revision = self.source.last_revision_info()
3325
stop_revno = None # unknown
3326
if stop_revision is None:
3327
stop_revision = other_last_revision
3328
if _mod_revision.is_null(stop_revision):
3329
# if there are no commits, we're done.
3331
stop_revno = other_revno
3333
# what's the current last revision, before we fetch [and change it
3335
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3336
# we fetch here so that we don't process data twice in the common
3337
# case of having something to pull, and so that the check for
3338
# already merged can operate on the just fetched graph, which will
3339
# be cached in memory.
3340
self.fetch(stop_revision=stop_revision)
3341
# Check to see if one is an ancestor of the other
3344
graph = self.target.repository.get_graph()
3345
if self.target._check_if_descendant_or_diverged(
3346
stop_revision, last_rev, graph, self.source):
3347
# stop_revision is a descendant of last_rev, but we aren't
3348
# overwriting, so we're done.
3350
if stop_revno is None:
3352
graph = self.target.repository.get_graph()
3353
this_revno, this_last_revision = \
3354
self.target.last_revision_info()
3355
stop_revno = graph.find_distance_to_null(stop_revision,
3356
[(other_last_revision, other_revno),
3357
(this_last_revision, this_revno)])
3358
self.target.set_last_revision_info(stop_revno, stop_revision)
3361
def pull(self, overwrite=False, stop_revision=None,
3362
possible_transports=None, run_hooks=True,
3363
_override_hook_target=None, local=False):
3364
"""Pull from source into self, updating my master if any.
3366
:param run_hooks: Private parameter - if false, this branch
3367
is being called because it's the master of the primary branch,
3368
so it should not run its hooks.
3370
bound_location = self.target.get_bound_location()
3371
if local and not bound_location:
3372
raise errors.LocalRequiresBoundBranch()
3373
master_branch = None
3374
source_is_master = (self.source.user_url == bound_location)
3375
if not local and bound_location and not source_is_master:
3376
# not pulling from master, so we need to update master.
3377
master_branch = self.target.get_master_branch(possible_transports)
3378
master_branch.lock_write()
3381
# pull from source into master.
3382
master_branch.pull(self.source, overwrite, stop_revision,
3384
return self._pull(overwrite,
3385
stop_revision, _hook_master=master_branch,
3386
run_hooks=run_hooks,
3387
_override_hook_target=_override_hook_target,
3388
merge_tags_to_master=not source_is_master)
3391
master_branch.unlock()
3393
def push(self, overwrite=False, stop_revision=None, lossy=False,
3394
_override_hook_source_branch=None):
3395
"""See InterBranch.push.
3397
This is the basic concrete implementation of push()
3399
:param _override_hook_source_branch: If specified, run the hooks
3400
passing this Branch as the source, rather than self. This is for
3401
use of RemoteBranch, where push is delegated to the underlying
3405
raise errors.LossyPushToSameVCS(self.source, self.target)
3406
# TODO: Public option to disable running hooks - should be trivial but
3408
self.source.lock_read()
3410
return _run_with_write_locked_target(
3411
self.target, self._push_with_bound_branches, overwrite,
3413
_override_hook_source_branch=_override_hook_source_branch)
3415
self.source.unlock()
3417
def _basic_push(self, overwrite, stop_revision):
3418
"""Basic implementation of push without bound branches or hooks.
3420
Must be called with source read locked and target write locked.
3422
result = BranchPushResult()
3423
result.source_branch = self.source
3424
result.target_branch = self.target
3425
result.old_revno, result.old_revid = self.target.last_revision_info()
3426
self.source.update_references(self.target)
3427
if result.old_revid != stop_revision:
3428
# We assume that during 'push' this repository is closer than
3430
graph = self.source.repository.get_graph(self.target.repository)
3431
self._update_revisions(stop_revision, overwrite=overwrite,
3433
if self.source._push_should_merge_tags():
3434
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3436
result.new_revno, result.new_revid = self.target.last_revision_info()
3439
def _push_with_bound_branches(self, overwrite, stop_revision,
3440
_override_hook_source_branch=None):
3441
"""Push from source into target, and into target's master if any.
3444
if _override_hook_source_branch:
3445
result.source_branch = _override_hook_source_branch
3446
for hook in Branch.hooks['post_push']:
3449
bound_location = self.target.get_bound_location()
3450
if bound_location and self.target.base != bound_location:
3451
# there is a master branch.
3453
# XXX: Why the second check? Is it even supported for a branch to
3454
# be bound to itself? -- mbp 20070507
3455
master_branch = self.target.get_master_branch()
3456
master_branch.lock_write()
3458
# push into the master from the source branch.
3459
master_inter = InterBranch.get(self.source, master_branch)
3460
master_inter._basic_push(overwrite, stop_revision)
3461
# and push into the target branch from the source. Note that
3462
# we push from the source branch again, because it's considered
3463
# the highest bandwidth repository.
3464
result = self._basic_push(overwrite, stop_revision)
3465
result.master_branch = master_branch
3466
result.local_branch = self.target
3470
master_branch.unlock()
3473
result = self._basic_push(overwrite, stop_revision)
3474
# TODO: Why set master_branch and local_branch if there's no
3475
# binding? Maybe cleaner to just leave them unset? -- mbp
3477
result.master_branch = self.target
3478
result.local_branch = None
3482
def _pull(self, overwrite=False, stop_revision=None,
3483
possible_transports=None, _hook_master=None, run_hooks=True,
3484
_override_hook_target=None, local=False,
3485
merge_tags_to_master=True):
3488
This function is the core worker, used by GenericInterBranch.pull to
3489
avoid duplication when pulling source->master and source->local.
3491
:param _hook_master: Private parameter - set the branch to
3492
be supplied as the master to pull hooks.
3493
:param run_hooks: Private parameter - if false, this branch
3494
is being called because it's the master of the primary branch,
3495
so it should not run its hooks.
3496
is being called because it's the master of the primary branch,
3497
so it should not run its hooks.
3498
:param _override_hook_target: Private parameter - set the branch to be
3499
supplied as the target_branch to pull hooks.
3500
:param local: Only update the local branch, and not the bound branch.
3502
# This type of branch can't be bound.
3504
raise errors.LocalRequiresBoundBranch()
3505
result = PullResult()
3506
result.source_branch = self.source
3507
if _override_hook_target is None:
3508
result.target_branch = self.target
3510
result.target_branch = _override_hook_target
3511
self.source.lock_read()
3513
# We assume that during 'pull' the target repository is closer than
3515
self.source.update_references(self.target)
3516
graph = self.target.repository.get_graph(self.source.repository)
3517
# TODO: Branch formats should have a flag that indicates
3518
# that revno's are expensive, and pull() should honor that flag.
3520
result.old_revno, result.old_revid = \
3521
self.target.last_revision_info()
3522
self._update_revisions(stop_revision, overwrite=overwrite,
3524
# TODO: The old revid should be specified when merging tags,
3525
# so a tags implementation that versions tags can only
3526
# pull in the most recent changes. -- JRV20090506
3527
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3528
overwrite, ignore_master=not merge_tags_to_master)
3529
result.new_revno, result.new_revid = self.target.last_revision_info()
3531
result.master_branch = _hook_master
3532
result.local_branch = result.target_branch
3534
result.master_branch = result.target_branch
3535
result.local_branch = None
3537
for hook in Branch.hooks['post_pull']:
3540
self.source.unlock()
3544
InterBranch.register_optimiser(GenericInterBranch)