190
147
possible_transports)
191
148
return control.open_branch(), relpath
193
def _push_should_merge_tags(self):
194
"""Should _basic_push merge this branch's tags into the target?
196
The default implementation returns False if this branch has no tags,
197
and True the rest of the time. Subclasses may override this.
199
return self.supports_tags() and self.tags.get_tag_dict()
201
150
def get_config(self):
202
"""Get a bzrlib.config.BranchConfig for this Branch.
204
This can then be used to get and set configuration options for the
207
:return: A bzrlib.config.BranchConfig.
209
151
return BranchConfig(self)
211
def _get_config(self):
212
"""Get the concrete config for just the config in this branch.
214
This is not intended for client use; see Branch.get_config for the
219
:return: An object supporting get_option and set_option.
221
raise NotImplementedError(self._get_config)
223
def _get_fallback_repository(self, url):
224
"""Get the repository we fallback to at url."""
225
url = urlutils.join(self.base, url)
226
a_branch = Branch.open(url,
227
possible_transports=[self.bzrdir.root_transport])
228
return a_branch.repository
230
def _get_tags_bytes(self):
231
"""Get the bytes of a serialised tags dict.
233
Note that not all branches support tags, nor do all use the same tags
234
logic: this method is specific to BasicTags. Other tag implementations
235
may use the same method name and behave differently, safely, because
236
of the double-dispatch via
237
format.make_tags->tags_instance->get_tags_dict.
239
:return: The bytes of the tags file.
240
:seealso: Branch._set_tags_bytes.
242
return self._transport.get_bytes('tags')
244
153
def _get_nick(self, local=False, possible_transports=None):
245
154
config = self.get_config()
246
155
# explicit overrides master, but don't look for master if local is True
247
156
if not local and not config.has_explicit_nickname():
249
158
master = self.get_master_branch(possible_transports)
250
if master and self.user_url == master.user_url:
251
raise errors.RecursiveBind(self.user_url)
252
159
if master is not None:
253
160
# return the master branch value
254
161
return master.nick
255
except errors.RecursiveBind, e:
257
162
except errors.BzrError, e:
258
163
# Silently fall back to local implicit nick if the master is
491
359
"""Iterate over an inclusive range of sorted revisions."""
492
360
rev_iter = iter(merge_sorted_revisions)
493
361
if start_revision_id is not None:
494
for node in rev_iter:
495
rev_id = node.key[-1]
362
for rev_id, depth, revno, end_of_merge in rev_iter:
496
363
if rev_id != start_revision_id:
499
366
# The decision to include the start or not
500
367
# depends on the stop_rule if a stop is provided
501
# so pop this node back into the iterator
502
rev_iter = chain(iter([node]), rev_iter)
369
iter([(rev_id, depth, revno, end_of_merge)]),
504
372
if stop_revision_id is None:
506
for node in rev_iter:
507
rev_id = node.key[-1]
508
yield (rev_id, node.merge_depth, node.revno,
373
for rev_id, depth, revno, end_of_merge in rev_iter:
374
yield rev_id, depth, revno, end_of_merge
510
375
elif stop_rule == 'exclude':
511
for node in rev_iter:
512
rev_id = node.key[-1]
376
for rev_id, depth, revno, end_of_merge in rev_iter:
513
377
if rev_id == stop_revision_id:
515
yield (rev_id, node.merge_depth, node.revno,
379
yield rev_id, depth, revno, end_of_merge
517
380
elif stop_rule == 'include':
518
for node in rev_iter:
519
rev_id = node.key[-1]
520
yield (rev_id, node.merge_depth, node.revno,
381
for rev_id, depth, revno, end_of_merge in rev_iter:
382
yield rev_id, depth, revno, end_of_merge
522
383
if rev_id == stop_revision_id:
524
elif stop_rule == 'with-merges-without-common-ancestry':
525
# We want to exclude all revisions that are already part of the
526
# stop_revision_id ancestry.
527
graph = self.repository.get_graph()
528
ancestors = graph.find_unique_ancestors(start_revision_id,
530
for node in rev_iter:
531
rev_id = node.key[-1]
532
if rev_id not in ancestors:
534
yield (rev_id, node.merge_depth, node.revno,
536
385
elif stop_rule == 'with-merges':
537
386
stop_rev = self.repository.get_revision(stop_revision_id)
538
387
if stop_rev.parent_ids:
539
388
left_parent = stop_rev.parent_ids[0]
541
390
left_parent = _mod_revision.NULL_REVISION
542
# left_parent is the actual revision we want to stop logging at,
543
# since we want to show the merged revisions after the stop_rev too
544
reached_stop_revision_id = False
545
revision_id_whitelist = []
546
for node in rev_iter:
547
rev_id = node.key[-1]
391
for rev_id, depth, revno, end_of_merge in rev_iter:
548
392
if rev_id == left_parent:
549
# reached the left parent after the stop_revision
551
if (not reached_stop_revision_id or
552
rev_id in revision_id_whitelist):
553
yield (rev_id, node.merge_depth, node.revno,
555
if reached_stop_revision_id or rev_id == stop_revision_id:
556
# only do the merged revs of rev_id from now on
557
rev = self.repository.get_revision(rev_id)
559
reached_stop_revision_id = True
560
revision_id_whitelist.extend(rev.parent_ids)
394
yield rev_id, depth, revno, end_of_merge
562
396
raise ValueError('invalid stop_rule %r' % stop_rule)
564
def _filter_start_non_ancestors(self, rev_iter):
565
# If we started from a dotted revno, we want to consider it as a tip
566
# and don't want to yield revisions that are not part of its
567
# ancestry. Given the order guaranteed by the merge sort, we will see
568
# uninteresting descendants of the first parent of our tip before the
570
first = rev_iter.next()
571
(rev_id, merge_depth, revno, end_of_merge) = first
574
# We start at a mainline revision so by definition, all others
575
# revisions in rev_iter are ancestors
576
for node in rev_iter:
581
pmap = self.repository.get_parent_map([rev_id])
582
parents = pmap.get(rev_id, [])
584
whitelist.update(parents)
586
# If there is no parents, there is nothing of interest left
588
# FIXME: It's hard to test this scenario here as this code is never
589
# called in that case. -- vila 20100322
592
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
594
if rev_id in whitelist:
595
pmap = self.repository.get_parent_map([rev_id])
596
parents = pmap.get(rev_id, [])
597
whitelist.remove(rev_id)
598
whitelist.update(parents)
600
# We've reached the mainline, there is nothing left to
604
# A revision that is not part of the ancestry of our
607
yield (rev_id, merge_depth, revno, end_of_merge)
609
398
def leave_lock_in_place(self):
610
399
"""Tell this branch object not to release the physical lock when this
611
400
object is unlocked.
613
402
If lock_write doesn't return a token, then this method is not supported.
615
404
self.control_files.leave_in_place()
769
528
:raises UnstackableRepositoryFormat: If the repository does not support
772
if not self._format.supports_stacking():
773
raise errors.UnstackableBranchFormat(self._format, self.user_url)
774
# XXX: Changing from one fallback repository to another does not check
775
# that all the data you need is present in the new fallback.
776
# Possibly it should.
777
self._check_stackable_repo()
780
old_url = self.get_stacked_on_url()
781
except (errors.NotStacked, errors.UnstackableBranchFormat,
782
errors.UnstackableRepositoryFormat):
786
self._activate_fallback_location(url)
787
# write this out after the repository is stacked to avoid setting a
788
# stacked config that doesn't work.
789
self._set_config_location('stacked_on_location', url)
792
"""Change a branch to be unstacked, copying data as needed.
794
Don't call this directly, use set_stacked_on_url(None).
796
pb = ui.ui_factory.nested_progress_bar()
798
pb.update("Unstacking")
799
# The basic approach here is to fetch the tip of the branch,
800
# including all available ghosts, from the existing stacked
801
# repository into a new repository object without the fallbacks.
803
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
804
# correct for CHKMap repostiories
805
old_repository = self.repository
806
if len(old_repository._fallback_repositories) != 1:
807
raise AssertionError("can't cope with fallback repositories "
808
"of %r" % (self.repository,))
809
# Open the new repository object.
810
# Repositories don't offer an interface to remove fallback
811
# repositories today; take the conceptually simpler option and just
812
# reopen it. We reopen it starting from the URL so that we
813
# get a separate connection for RemoteRepositories and can
814
# stream from one of them to the other. This does mean doing
815
# separate SSH connection setup, but unstacking is not a
816
# common operation so it's tolerable.
817
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
818
new_repository = new_bzrdir.find_repository()
819
if new_repository._fallback_repositories:
820
raise AssertionError("didn't expect %r to have "
821
"fallback_repositories"
822
% (self.repository,))
823
# Replace self.repository with the new repository.
824
# Do our best to transfer the lock state (i.e. lock-tokens and
825
# lock count) of self.repository to the new repository.
826
lock_token = old_repository.lock_write().repository_token
827
self.repository = new_repository
828
if isinstance(self, remote.RemoteBranch):
829
# Remote branches can have a second reference to the old
830
# repository that need to be replaced.
831
if self._real_branch is not None:
832
self._real_branch.repository = new_repository
833
self.repository.lock_write(token=lock_token)
834
if lock_token is not None:
835
old_repository.leave_lock_in_place()
836
old_repository.unlock()
837
if lock_token is not None:
838
# XXX: self.repository.leave_lock_in_place() before this
839
# function will not be preserved. Fortunately that doesn't
840
# affect the current default format (2a), and would be a
841
# corner-case anyway.
842
# - Andrew Bennetts, 2010/06/30
843
self.repository.dont_leave_lock_in_place()
847
old_repository.unlock()
848
except errors.LockNotHeld:
851
if old_lock_count == 0:
852
raise AssertionError(
853
'old_repository should have been locked at least once.')
854
for i in range(old_lock_count-1):
855
self.repository.lock_write()
856
# Fetch from the old repository into the new.
857
old_repository.lock_read()
859
# XXX: If you unstack a branch while it has a working tree
860
# with a pending merge, the pending-merged revisions will no
861
# longer be present. You can (probably) revert and remerge.
863
# XXX: This only fetches up to the tip of the repository; it
864
# doesn't bring across any tags. That's fairly consistent
865
# with how branch works, but perhaps not ideal.
866
self.repository.fetch(old_repository,
867
revision_id=self.last_revision(),
870
old_repository.unlock()
874
def _set_tags_bytes(self, bytes):
875
"""Mirror method for _get_tags_bytes.
877
:seealso: Branch._get_tags_bytes.
879
return _run_with_write_locked_target(self, self._transport.put_bytes,
531
raise NotImplementedError(self.set_stacked_on_url)
882
533
def _cache_revision_history(self, rev_history):
883
534
"""Set the cached revision history to rev_history.
1014
668
information. This can be None.
1017
return InterBranch.get(other, self).update_revisions(stop_revision,
1020
def import_last_revision_info(self, source_repo, revno, revid):
1021
"""Set the last revision info, importing from another repo if necessary.
1023
This is used by the bound branch code to upload a revision to
1024
the master branch first before updating the tip of the local branch.
1026
:param source_repo: Source repository to optionally fetch from
1027
:param revno: Revision number of the new tip
1028
:param revid: Revision id of the new tip
1030
if not self.repository.has_same_location(source_repo):
1031
self.repository.fetch(source_repo, revision_id=revid)
1032
self.set_last_revision_info(revno, revid)
673
other_revno, other_last_revision = other.last_revision_info()
674
stop_revno = None # unknown
675
if stop_revision is None:
676
stop_revision = other_last_revision
677
if _mod_revision.is_null(stop_revision):
678
# if there are no commits, we're done.
680
stop_revno = other_revno
682
# what's the current last revision, before we fetch [and change it
684
last_rev = _mod_revision.ensure_null(self.last_revision())
685
# we fetch here so that we don't process data twice in the common
686
# case of having something to pull, and so that the check for
687
# already merged can operate on the just fetched graph, which will
688
# be cached in memory.
689
self.fetch(other, stop_revision)
690
# Check to see if one is an ancestor of the other
693
graph = self.repository.get_graph()
694
if self._check_if_descendant_or_diverged(
695
stop_revision, last_rev, graph, other):
696
# stop_revision is a descendant of last_rev, but we aren't
697
# overwriting, so we're done.
699
if stop_revno is None:
701
graph = self.repository.get_graph()
702
this_revno, this_last_revision = self.last_revision_info()
703
stop_revno = graph.find_distance_to_null(stop_revision,
704
[(other_last_revision, other_revno),
705
(this_last_revision, this_revno)])
706
self.set_last_revision_info(stop_revno, stop_revision)
1034
710
def revision_id_to_revno(self, revision_id):
1035
711
"""Given a revision id, return its revno"""
1041
717
except ValueError:
1042
718
raise errors.NoSuchRevision(self, revision_id)
1045
720
def get_rev_id(self, revno, history=None):
1046
721
"""Find the revision id of the specified revno."""
1048
723
return _mod_revision.NULL_REVISION
1049
last_revno, last_revid = self.last_revision_info()
1050
if revno == last_revno:
1052
if revno <= 0 or revno > last_revno:
725
history = self.revision_history()
726
if revno <= 0 or revno > len(history):
1053
727
raise errors.NoSuchRevision(self, revno)
1054
distance_from_last = last_revno - revno
1055
if len(self._partial_revision_history_cache) <= distance_from_last:
1056
self._extend_partial_history(distance_from_last)
1057
return self._partial_revision_history_cache[distance_from_last]
728
return history[revno - 1]
1059
730
def pull(self, source, overwrite=False, stop_revision=None,
1060
possible_transports=None, *args, **kwargs):
731
possible_transports=None, _override_hook_target=None):
1061
732
"""Mirror source into this branch.
1063
734
This branch is considered to be 'local', having low latency.
1065
736
:returns: PullResult instance
1067
return InterBranch.get(source, self).pull(overwrite=overwrite,
1068
stop_revision=stop_revision,
1069
possible_transports=possible_transports, *args, **kwargs)
738
raise NotImplementedError(self.pull)
1071
def push(self, target, overwrite=False, stop_revision=None, *args,
740
def push(self, target, overwrite=False, stop_revision=None):
1073
741
"""Mirror this branch into target.
1075
743
This branch is considered to be 'local', having low latency.
1077
return InterBranch.get(self, target).push(overwrite, stop_revision,
1080
def lossy_push(self, target, stop_revision=None):
1081
"""Push deltas into another branch.
1083
:note: This does not, like push, retain the revision ids from
1084
the source branch and will, rather than adding bzr-specific
1085
metadata, push only those semantics of the revision that can be
1086
natively represented by this branch' VCS.
1088
:param target: Target branch
1089
:param stop_revision: Revision to push, defaults to last revision.
1090
:return: BranchPushResult with an extra member revidmap:
1091
A dictionary mapping revision ids from the target branch
1092
to new revision ids in the target branch, for each
1093
revision that was pushed.
1095
inter = InterBranch.get(self, target)
1096
lossy_push = getattr(inter, "lossy_push", None)
1097
if lossy_push is None:
1098
raise errors.LossyPushToSameVCS(self, target)
1099
return lossy_push(stop_revision)
745
raise NotImplementedError(self.push)
1101
747
def basis_tree(self):
1102
748
"""Return `Tree` object for last revision."""
1294
886
source_revno, source_revision_id = self.last_revision_info()
1295
887
if revision_id is None:
1296
888
revno, revision_id = source_revno, source_revision_id
889
elif source_revision_id == revision_id:
890
# we know the revno without needing to walk all of history
1298
graph = self.repository.get_graph()
1300
revno = graph.find_distance_to_null(revision_id,
1301
[(source_revision_id, source_revno)])
1302
except errors.GhostRevisionsHaveNoRevno:
1303
# Default to 1, if we can't find anything else
893
# To figure out the revno for a random revision, we need to build
894
# the revision history, and count its length.
895
# We don't care about the order, just how long it is.
896
# Alternatively, we could start at the current location, and count
897
# backwards. But there is no guarantee that we will find it since
898
# it may be a merged revision.
899
revno = len(list(self.repository.iter_reverse_revision_history(
1305
901
destination.set_last_revision_info(revno, revision_id)
1307
904
def copy_content_into(self, destination, revision_id=None):
1308
905
"""Copy the content of self into destination.
1310
907
revision_id: if not None, the revision history in the new branch will
1311
908
be truncated to end with revision_id.
1313
return InterBranch.get(self, destination).copy_content_into(
1314
revision_id=revision_id)
1316
def update_references(self, target):
1317
if not getattr(self._format, 'supports_reference_locations', False):
1319
reference_dict = self._get_all_reference_info()
1320
if len(reference_dict) == 0:
1322
old_base = self.base
1323
new_base = target.base
1324
target_reference_dict = target._get_all_reference_info()
1325
for file_id, (tree_path, branch_location) in (
1326
reference_dict.items()):
1327
branch_location = urlutils.rebase_url(branch_location,
1329
target_reference_dict.setdefault(
1330
file_id, (tree_path, branch_location))
1331
target._set_all_reference_info(target_reference_dict)
910
self._synchronize_history(destination, revision_id)
912
parent = self.get_parent()
913
except errors.InaccessibleParent, e:
914
mutter('parent was not accessible to copy: %s', e)
917
destination.set_parent(parent)
918
self.tags.merge_to(destination.tags)
1333
920
@needs_read_lock
1334
def check(self, refs):
1335
922
"""Check consistency of the branch.
1337
924
In particular this checks that revisions given in the revision-history
1338
do actually match up in the revision graph, and that they're all
925
do actually match up in the revision graph, and that they're all
1339
926
present in the repository.
1341
928
Callers will typically also want to check the repository.
1343
:param refs: Calculated refs for this branch as specified by
1344
branch._get_check_refs()
1345
930
:return: A BranchCheckResult.
1347
result = BranchCheckResult(self)
932
mainline_parent_id = None
1348
933
last_revno, last_revision_id = self.last_revision_info()
1349
actual_revno = refs[('lefthand-distance', last_revision_id)]
1350
if actual_revno != last_revno:
1351
result.errors.append(errors.BzrCheckError(
1352
'revno does not match len(mainline) %s != %s' % (
1353
last_revno, actual_revno)))
1354
# TODO: We should probably also check that self.revision_history
1355
# matches the repository for older branch formats.
1356
# If looking for the code that cross-checks repository parents against
1357
# the iter_reverse_revision_history output, that is now a repository
934
real_rev_history = list(self.repository.iter_reverse_revision_history(
936
real_rev_history.reverse()
937
if len(real_rev_history) != last_revno:
938
raise errors.BzrCheckError('revno does not match len(mainline)'
939
' %s != %s' % (last_revno, len(real_rev_history)))
940
# TODO: We should probably also check that real_rev_history actually
941
# matches self.revision_history()
942
for revision_id in real_rev_history:
944
revision = self.repository.get_revision(revision_id)
945
except errors.NoSuchRevision, e:
946
raise errors.BzrCheckError("mainline revision {%s} not in repository"
948
# In general the first entry on the revision history has no parents.
949
# But it's not illegal for it to have parents listed; this can happen
950
# in imports from Arch when the parents weren't reachable.
951
if mainline_parent_id is not None:
952
if mainline_parent_id not in revision.parent_ids:
953
raise errors.BzrCheckError("previous revision {%s} not listed among "
955
% (mainline_parent_id, revision_id))
956
mainline_parent_id = revision_id
957
return BranchCheckResult(self)
1361
959
def _get_checkout_format(self):
1362
960
"""Return the most suitable metadir for a checkout of this branch.
1661
1185
filename, content,
1662
1186
mode=a_bzrdir._get_file_mode())
1665
control_files.unlock()
1666
branch = self.open(a_bzrdir, name, _found=True)
1667
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1188
control_files.unlock()
1189
return self.open(a_bzrdir, _found=True)
1670
def initialize(self, a_bzrdir, name=None):
1671
"""Create a branch of this format in a_bzrdir.
1673
:param name: Name of the colocated branch to create.
1191
def initialize(self, a_bzrdir):
1192
"""Create a branch of this format in a_bzrdir."""
1675
1193
raise NotImplementedError(self.initialize)
1677
1195
def is_supported(self):
1678
1196
"""Is this format supported?
1680
1198
Supported formats can be initialized and opened.
1681
Unsupported formats may not support initialization or committing or
1199
Unsupported formats may not support initialization or committing or
1682
1200
some other features depending on the reason for not being supported.
1686
def make_tags(self, branch):
1687
"""Create a tags object for branch.
1689
This method is on BranchFormat, because BranchFormats are reflected
1690
over the wire via network_name(), whereas full Branch instances require
1691
multiple VFS method calls to operate at all.
1693
The default implementation returns a disabled-tags instance.
1695
Note that it is normal for branch to be a RemoteBranch when using tags
1698
return DisabledTags(branch)
1700
def network_name(self):
1701
"""A simple byte string uniquely identifying this format for RPC calls.
1703
MetaDir branch formats use their disk format string to identify the
1704
repository over the wire. All in one formats such as bzr < 0.8, and
1705
foreign formats like svn/git and hg should use some marker which is
1706
unique and immutable.
1708
raise NotImplementedError(self.network_name)
1710
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
1204
def open(self, a_bzrdir, _found=False):
1711
1205
"""Return the branch object for a_bzrdir
1713
:param a_bzrdir: A BzrDir that contains a branch.
1714
:param name: Name of colocated branch to open
1715
:param _found: a private parameter, do not use it. It is used to
1716
indicate if format probing has already be done.
1717
:param ignore_fallbacks: when set, no fallback branches will be opened
1718
(if there are any). Default is to open fallbacks.
1207
_found is a private parameter, do not use it. It is used to indicate
1208
if format probing has already be done.
1720
1210
raise NotImplementedError(self.open)
1723
1213
def register_format(klass, format):
1724
"""Register a metadir format.
1726
See MetaDirBranchFormatFactory for the ability to register a format
1727
without loading the code the format needs until it is actually used.
1729
1214
klass._formats[format.get_format_string()] = format
1730
# Metadir formats have a network name of their format string, and get
1731
# registered as factories.
1732
if isinstance(format, MetaDirBranchFormatFactory):
1733
network_format_registry.register(format.get_format_string(), format)
1735
network_format_registry.register(format.get_format_string(),
1739
1217
def set_default_format(klass, format):
1740
1218
klass._default_format = format
1742
def supports_set_append_revisions_only(self):
1743
"""True if this format supports set_append_revisions_only."""
1746
1220
def supports_stacking(self):
1747
1221
"""True if this format records a stacked-on branch."""
1803
1249
Hooks.__init__(self)
1804
self.create_hook(HookPoint('set_rh',
1805
"Invoked whenever the revision history has been set via "
1806
"set_revision_history. The api signature is (branch, "
1807
"revision_history), and the branch will be write-locked. "
1808
"The set_rh hook can be expensive for bzr to trigger, a better "
1809
"hook to use is Branch.post_change_branch_tip.", (0, 15), None))
1810
self.create_hook(HookPoint('open',
1811
"Called with the Branch object that has been opened after a "
1812
"branch is opened.", (1, 8), None))
1813
self.create_hook(HookPoint('post_push',
1814
"Called after a push operation completes. post_push is called "
1815
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1816
"bzr client.", (0, 15), None))
1817
self.create_hook(HookPoint('post_pull',
1818
"Called after a pull operation completes. post_pull is called "
1819
"with a bzrlib.branch.PullResult object and only runs in the "
1820
"bzr client.", (0, 15), None))
1821
self.create_hook(HookPoint('pre_commit',
1822
"Called after a commit is calculated but before it is is "
1823
"completed. pre_commit is called with (local, master, old_revno, "
1824
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1825
"). old_revid is NULL_REVISION for the first commit to a branch, "
1826
"tree_delta is a TreeDelta object describing changes from the "
1827
"basis revision. hooks MUST NOT modify this delta. "
1828
" future_tree is an in-memory tree obtained from "
1829
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1830
"tree.", (0,91), None))
1831
self.create_hook(HookPoint('post_commit',
1832
"Called in the bzr client after a commit has completed. "
1833
"post_commit is called with (local, master, old_revno, old_revid, "
1834
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1835
"commit to a branch.", (0, 15), None))
1836
self.create_hook(HookPoint('post_uncommit',
1837
"Called in the bzr client after an uncommit completes. "
1838
"post_uncommit is called with (local, master, old_revno, "
1839
"old_revid, new_revno, new_revid) where local is the local branch "
1840
"or None, master is the target branch, and an empty branch "
1841
"receives new_revno of 0, new_revid of None.", (0, 15), None))
1842
self.create_hook(HookPoint('pre_change_branch_tip',
1843
"Called in bzr client and server before a change to the tip of a "
1844
"branch is made. pre_change_branch_tip is called with a "
1845
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1846
"commit, uncommit will all trigger this hook.", (1, 6), None))
1847
self.create_hook(HookPoint('post_change_branch_tip',
1848
"Called in bzr client and server after a change to the tip of a "
1849
"branch is made. post_change_branch_tip is called with a "
1850
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1851
"commit, uncommit will all trigger this hook.", (1, 4), None))
1852
self.create_hook(HookPoint('transform_fallback_location',
1853
"Called when a stacked branch is activating its fallback "
1854
"locations. transform_fallback_location is called with (branch, "
1855
"url), and should return a new url. Returning the same url "
1856
"allows it to be used as-is, returning a different one can be "
1857
"used to cause the branch to stack on a closer copy of that "
1858
"fallback_location. Note that the branch cannot have history "
1859
"accessing methods called on it during this hook because the "
1860
"fallback locations have not been activated. When there are "
1861
"multiple hooks installed for transform_fallback_location, "
1862
"all are called with the url returned from the previous hook."
1863
"The order is however undefined.", (1, 9), None))
1864
self.create_hook(HookPoint('automatic_tag_name',
1865
"Called to determine an automatic tag name for a revision. "
1866
"automatic_tag_name is called with (branch, revision_id) and "
1867
"should return a tag name or None if no tag name could be "
1868
"determined. The first non-None tag name returned will be used.",
1870
self.create_hook(HookPoint('post_branch_init',
1871
"Called after new branch initialization completes. "
1872
"post_branch_init is called with a "
1873
"bzrlib.branch.BranchInitHookParams. "
1874
"Note that init, branch and checkout (both heavyweight and "
1875
"lightweight) will all trigger this hook.", (2, 2), None))
1876
self.create_hook(HookPoint('post_switch',
1877
"Called after a checkout switches branch. "
1878
"post_switch is called with a "
1879
"bzrlib.branch.SwitchHookParams.", (2, 2), None))
1250
# Introduced in 0.15:
1251
# invoked whenever the revision history has been set
1252
# with set_revision_history. The api signature is
1253
# (branch, revision_history), and the branch will
1256
# Invoked after a branch is opened. The api signature is (branch).
1258
# invoked after a push operation completes.
1259
# the api signature is
1261
# containing the members
1262
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1263
# where local is the local target branch or None, master is the target
1264
# master branch, and the rest should be self explanatory. The source
1265
# is read locked and the target branches write locked. Source will
1266
# be the local low-latency branch.
1267
self['post_push'] = []
1268
# invoked after a pull operation completes.
1269
# the api signature is
1271
# containing the members
1272
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1273
# where local is the local branch or None, master is the target
1274
# master branch, and the rest should be self explanatory. The source
1275
# is read locked and the target branches write locked. The local
1276
# branch is the low-latency branch.
1277
self['post_pull'] = []
1278
# invoked before a commit operation takes place.
1279
# the api signature is
1280
# (local, master, old_revno, old_revid, future_revno, future_revid,
1281
# tree_delta, future_tree).
1282
# old_revid is NULL_REVISION for the first commit to a branch
1283
# tree_delta is a TreeDelta object describing changes from the basis
1284
# revision, hooks MUST NOT modify this delta
1285
# future_tree is an in-memory tree obtained from
1286
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1287
self['pre_commit'] = []
1288
# invoked after a commit operation completes.
1289
# the api signature is
1290
# (local, master, old_revno, old_revid, new_revno, new_revid)
1291
# old_revid is NULL_REVISION for the first commit to a branch.
1292
self['post_commit'] = []
1293
# invoked after a uncommit operation completes.
1294
# the api signature is
1295
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1296
# local is the local branch or None, master is the target branch,
1297
# and an empty branch recieves new_revno of 0, new_revid of None.
1298
self['post_uncommit'] = []
1300
# Invoked before the tip of a branch changes.
1301
# the api signature is
1302
# (params) where params is a ChangeBranchTipParams with the members
1303
# (branch, old_revno, new_revno, old_revid, new_revid)
1304
self['pre_change_branch_tip'] = []
1306
# Invoked after the tip of a branch changes.
1307
# the api signature is
1308
# (params) where params is a ChangeBranchTipParams with the members
1309
# (branch, old_revno, new_revno, old_revid, new_revid)
1310
self['post_change_branch_tip'] = []
1312
# Invoked when a stacked branch activates its fallback locations and
1313
# allows the transformation of the url of said location.
1314
# the api signature is
1315
# (branch, url) where branch is the branch having its fallback
1316
# location activated and url is the url for the fallback location.
1317
# The hook should return a url.
1318
self['transform_fallback_location'] = []
1883
1321
# install the default hooks into the Branch class.
1916
1354
def __eq__(self, other):
1917
1355
return self.__dict__ == other.__dict__
1919
1357
def __repr__(self):
1920
1358
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1921
self.__class__.__name__, self.branch,
1359
self.__class__.__name__, self.branch,
1922
1360
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1925
class BranchInitHookParams(object):
1926
"""Object holding parameters passed to *_branch_init hooks.
1928
There are 4 fields that hooks may wish to access:
1930
:ivar format: the branch format
1931
:ivar bzrdir: the BzrDir where the branch will be/has been initialized
1932
:ivar name: name of colocated branch, if any (or None)
1933
:ivar branch: the branch created
1935
Note that for lightweight checkouts, the bzrdir and format fields refer to
1936
the checkout, hence they are different from the corresponding fields in
1937
branch, which refer to the original branch.
1940
def __init__(self, format, a_bzrdir, name, branch):
1941
"""Create a group of BranchInitHook parameters.
1943
:param format: the branch format
1944
:param a_bzrdir: the BzrDir where the branch will be/has been
1946
:param name: name of colocated branch, if any (or None)
1947
:param branch: the branch created
1949
Note that for lightweight checkouts, the bzrdir and format fields refer
1950
to the checkout, hence they are different from the corresponding fields
1951
in branch, which refer to the original branch.
1953
self.format = format
1954
self.bzrdir = a_bzrdir
1956
self.branch = branch
1958
def __eq__(self, other):
1959
return self.__dict__ == other.__dict__
1962
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1965
class SwitchHookParams(object):
1966
"""Object holding parameters passed to *_switch hooks.
1968
There are 4 fields that hooks may wish to access:
1970
:ivar control_dir: BzrDir of the checkout to change
1971
:ivar to_branch: branch that the checkout is to reference
1972
:ivar force: skip the check for local commits in a heavy checkout
1973
:ivar revision_id: revision ID to switch to (or None)
1976
def __init__(self, control_dir, to_branch, force, revision_id):
1977
"""Create a group of SwitchHook parameters.
1979
:param control_dir: BzrDir of the checkout to change
1980
:param to_branch: branch that the checkout is to reference
1981
:param force: skip the check for local commits in a heavy checkout
1982
:param revision_id: revision ID to switch to (or None)
1984
self.control_dir = control_dir
1985
self.to_branch = to_branch
1987
self.revision_id = revision_id
1989
def __eq__(self, other):
1990
return self.__dict__ == other.__dict__
1993
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1994
self.control_dir, self.to_branch,
1998
1363
class BzrBranchFormat4(BranchFormat):
1999
1364
"""Bzr branch format 4.
2138
1497
"""See BranchFormat.get_format_description()."""
2139
1498
return "Branch format 6"
2141
def initialize(self, a_bzrdir, name=None):
2142
"""Create a branch of this format in a_bzrdir."""
2143
utf8_files = [('last-revision', '0 null:\n'),
2144
('branch.conf', ''),
2147
return self._initialize_helper(a_bzrdir, utf8_files, name)
2149
def make_tags(self, branch):
2150
"""See bzrlib.branch.BranchFormat.make_tags()."""
2151
return BasicTags(branch)
2153
def supports_set_append_revisions_only(self):
2157
class BzrBranchFormat8(BranchFormatMetadir):
2158
"""Metadir format supporting storing locations of subtree branches."""
2160
def _branch_class(self):
2163
def get_format_string(self):
2164
"""See BranchFormat.get_format_string()."""
2165
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2167
def get_format_description(self):
2168
"""See BranchFormat.get_format_description()."""
2169
return "Branch format 8"
2171
def initialize(self, a_bzrdir, name=None):
2172
"""Create a branch of this format in a_bzrdir."""
2173
utf8_files = [('last-revision', '0 null:\n'),
2174
('branch.conf', ''),
2178
return self._initialize_helper(a_bzrdir, utf8_files, name)
2181
super(BzrBranchFormat8, self).__init__()
2182
self._matchingbzrdir.repository_format = \
2183
RepositoryFormatKnitPack5RichRoot()
2185
def make_tags(self, branch):
2186
"""See bzrlib.branch.BranchFormat.make_tags()."""
2187
return BasicTags(branch)
2189
def supports_set_append_revisions_only(self):
2192
def supports_stacking(self):
2195
supports_reference_locations = True
2198
class BzrBranchFormat7(BzrBranchFormat8):
1500
def initialize(self, a_bzrdir):
1501
"""Create a branch of this format in a_bzrdir."""
1502
utf8_files = [('last-revision', '0 null:\n'),
1503
('branch.conf', ''),
1506
return self._initialize_helper(a_bzrdir, utf8_files)
1509
class BzrBranchFormat7(BranchFormatMetadir):
2199
1510
"""Branch format with last-revision, tags, and a stacked location pointer.
2201
1512
The stacked location pointer is passed down to the repository and requires
2248
1562
"""See BranchFormat.get_format_description()."""
2249
1563
return "Checkout reference format 1"
2251
def get_reference(self, a_bzrdir, name=None):
1565
def get_reference(self, a_bzrdir):
2252
1566
"""See BranchFormat.get_reference()."""
2253
transport = a_bzrdir.get_branch_transport(None, name=name)
2254
return transport.get_bytes('location')
1567
transport = a_bzrdir.get_branch_transport(None)
1568
return transport.get('location').read()
2256
def set_reference(self, a_bzrdir, name, to_branch):
1570
def set_reference(self, a_bzrdir, to_branch):
2257
1571
"""See BranchFormat.set_reference()."""
2258
transport = a_bzrdir.get_branch_transport(None, name=name)
1572
transport = a_bzrdir.get_branch_transport(None)
2259
1573
location = transport.put_bytes('location', to_branch.base)
2261
def initialize(self, a_bzrdir, name=None, target_branch=None):
1575
def initialize(self, a_bzrdir, target_branch=None):
2262
1576
"""Create a branch of this format in a_bzrdir."""
2263
1577
if target_branch is None:
2264
1578
# this format does not implement branch itself, thus the implicit
2265
1579
# creation contract must see it as uninitializable
2266
1580
raise errors.UninitializableFormat(self)
2267
mutter('creating branch reference in %s', a_bzrdir.user_url)
2268
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1581
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1582
branch_transport = a_bzrdir.get_branch_transport(self)
2269
1583
branch_transport.put_bytes('location',
2270
target_branch.bzrdir.user_url)
1584
target_branch.bzrdir.root_transport.base)
2271
1585
branch_transport.put_bytes('format', self.get_format_string())
2273
a_bzrdir, name, _found=True,
1587
a_bzrdir, _found=True,
2274
1588
possible_transports=[target_branch.bzrdir.root_transport])
2275
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2278
1590
def __init__(self):
2279
1591
super(BranchReferenceFormat, self).__init__()
2283
1595
def _make_reference_clone_function(format, a_branch):
2284
1596
"""Create a clone() routine for a branch dynamically."""
2285
def clone(to_bzrdir, revision_id=None,
2286
repository_policy=None):
1597
def clone(to_bzrdir, revision_id=None):
2287
1598
"""See Branch.clone()."""
2288
return format.initialize(to_bzrdir, target_branch=a_branch)
1599
return format.initialize(to_bzrdir, a_branch)
2289
1600
# cannot obey revision_id limits when cloning a reference ...
2290
1601
# FIXME RBC 20060210 either nuke revision_id for clone, or
2291
1602
# emit some sort of warning/error to the caller ?!
2294
def open(self, a_bzrdir, name=None, _found=False, location=None,
2295
possible_transports=None, ignore_fallbacks=False):
1605
def open(self, a_bzrdir, _found=False, location=None,
1606
possible_transports=None):
2296
1607
"""Return the branch that the branch reference in a_bzrdir points at.
2298
:param a_bzrdir: A BzrDir that contains a branch.
2299
:param name: Name of colocated branch to open, if any
2300
:param _found: a private parameter, do not use it. It is used to
2301
indicate if format probing has already be done.
2302
:param ignore_fallbacks: when set, no fallback branches will be opened
2303
(if there are any). Default is to open fallbacks.
2304
:param location: The location of the referenced branch. If
2305
unspecified, this will be determined from the branch reference in
2307
:param possible_transports: An optional reusable transports list.
1609
_found is a private parameter, do not use it. It is used to indicate
1610
if format probing has already be done.
2310
format = BranchFormat.find_format(a_bzrdir, name=name)
1613
format = BranchFormat.find_format(a_bzrdir)
2311
1614
if format.__class__ != self.__class__:
2312
1615
raise AssertionError("wrong format %r found for %r" %
2313
1616
(format, self))
2314
1617
if location is None:
2315
location = self.get_reference(a_bzrdir, name)
1618
location = self.get_reference(a_bzrdir)
2316
1619
real_bzrdir = bzrdir.BzrDir.open(
2317
1620
location, possible_transports=possible_transports)
2318
result = real_bzrdir.open_branch(name=name,
2319
ignore_fallbacks=ignore_fallbacks)
1621
result = real_bzrdir.open_branch()
2320
1622
# this changes the behaviour of result.clone to create a new reference
2321
1623
# rather than a copy of the content of the branch.
2322
1624
# I did not use a proxy object because that needs much more extensive
2332
network_format_registry = registry.FormatRegistry()
2333
"""Registry of formats indexed by their network name.
2335
The network name for a branch format is an identifier that can be used when
2336
referring to formats with smart server operations. See
2337
BranchFormat.network_name() for more detail.
2341
1634
# formats which have no format string are not discoverable
2342
1635
# and not independently creatable, so are not registered.
2343
1636
__format5 = BzrBranchFormat5()
2344
1637
__format6 = BzrBranchFormat6()
2345
1638
__format7 = BzrBranchFormat7()
2346
__format8 = BzrBranchFormat8()
2347
1639
BranchFormat.register_format(__format5)
2348
1640
BranchFormat.register_format(BranchReferenceFormat())
2349
1641
BranchFormat.register_format(__format6)
2350
1642
BranchFormat.register_format(__format7)
2351
BranchFormat.register_format(__format8)
2352
BranchFormat.set_default_format(__format7)
1643
BranchFormat.set_default_format(__format6)
2353
1644
_legacy_formats = [BzrBranchFormat4(),
2355
network_format_registry.register(
2356
_legacy_formats[0].network_name(), _legacy_formats[0].__class__)
2359
class BranchWriteLockResult(LogicalLockResult):
2360
"""The result of write locking a branch.
2362
:ivar branch_token: The token obtained from the underlying branch lock, or
2364
:ivar unlock: A callable which will unlock the lock.
2367
def __init__(self, unlock, branch_token):
2368
LogicalLockResult.__init__(self, unlock)
2369
self.branch_token = branch_token
2372
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2376
class BzrBranch(Branch, _RelockDebugMixin):
1647
class BzrBranch(Branch):
2377
1648
"""A branch stored in the actual filesystem.
2379
1650
Note that it's "local" in the context of the filesystem; it doesn't
2380
1651
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2381
1652
it's writable, and can be accessed via the normal filesystem API.
2383
:ivar _transport: Transport for file operations on this branch's
1654
:ivar _transport: Transport for file operations on this branch's
2384
1655
control files, typically pointing to the .bzr/branch directory.
2385
1656
:ivar repository: Repository for this branch.
2386
:ivar base: The url of the base directory for this branch; the one
1657
:ivar base: The url of the base directory for this branch; the one
2387
1658
containing the .bzr directory.
2388
:ivar name: Optional colocated branch name as it exists in the control
2392
1661
def __init__(self, _format=None,
2393
_control_files=None, a_bzrdir=None, name=None,
2394
_repository=None, ignore_fallbacks=False):
1662
_control_files=None, a_bzrdir=None, _repository=None):
2395
1663
"""Create new branch object at a particular location."""
2396
1664
if a_bzrdir is None:
2397
1665
raise ValueError('a_bzrdir must be supplied')
2399
1667
self.bzrdir = a_bzrdir
2400
1668
self._base = self.bzrdir.transport.clone('..').base
2402
1669
# XXX: We should be able to just do
2403
1670
# self.base = self.bzrdir.root_transport.base
2404
1671
# but this does not quite work yet -- mbp 20080522
2426
1689
base = property(_get_base, doc="The URL for the root of this branch.")
2428
def _get_config(self):
2429
return TransportConfig(self._transport, 'branch.conf')
2431
1691
def is_locked(self):
2432
1692
return self.control_files.is_locked()
2434
1694
def lock_write(self, token=None):
2435
"""Lock the branch for write operations.
2437
:param token: A token to permit reacquiring a previously held and
2439
:return: A BranchWriteLockResult.
2441
if not self.is_locked():
2442
self._note_lock('w')
2443
# All-in-one needs to always unlock/lock.
2444
repo_control = getattr(self.repository, 'control_files', None)
2445
if self.control_files == repo_control or not self.is_locked():
2446
self.repository._warn_if_deprecated(self)
2447
self.repository.lock_write()
1695
repo_token = self.repository.lock_write()
2452
return BranchWriteLockResult(self.unlock,
2453
self.control_files.lock_write(token=token))
1697
token = self.control_files.lock_write(token=token)
2456
self.repository.unlock()
1699
self.repository.unlock()
2459
1703
def lock_read(self):
2460
"""Lock the branch for read operations.
2462
:return: A bzrlib.lock.LogicalLockResult.
2464
if not self.is_locked():
2465
self._note_lock('r')
2466
# All-in-one needs to always unlock/lock.
2467
repo_control = getattr(self.repository, 'control_files', None)
2468
if self.control_files == repo_control or not self.is_locked():
2469
self.repository._warn_if_deprecated(self)
2470
self.repository.lock_read()
1704
self.repository.lock_read()
2475
1706
self.control_files.lock_read()
2476
return LogicalLockResult(self.unlock)
2479
self.repository.unlock()
1708
self.repository.unlock()
2482
@only_raises(errors.LockNotHeld, errors.LockBroken)
2483
1711
def unlock(self):
1712
# TODO: test for failed two phase locks. This is known broken.
2485
1714
self.control_files.unlock()
2487
# All-in-one needs to always unlock/lock.
2488
repo_control = getattr(self.repository, 'control_files', None)
2489
if (self.control_files == repo_control or
2490
not self.control_files.is_locked()):
2491
self.repository.unlock()
2492
if not self.control_files.is_locked():
2493
# we just released the lock
2494
self._clear_cached_state()
1716
self.repository.unlock()
1717
if not self.control_files.is_locked():
1718
# we just released the lock
1719
self._clear_cached_state()
2496
1721
def peek_lock_mode(self):
2497
1722
if self.control_files._lock_count == 0:
1954
def push(self, target, overwrite=False, stop_revision=None,
1955
_override_hook_source_branch=None):
1958
This is the basic concrete implementation of push()
1960
:param _override_hook_source_branch: If specified, run
1961
the hooks passing this Branch as the source, rather than self.
1962
This is for use of RemoteBranch, where push is delegated to the
1963
underlying vfs-based Branch.
1965
# TODO: Public option to disable running hooks - should be trivial but
1967
return _run_with_write_locked_target(
1968
target, self._push_with_bound_branches, target, overwrite,
1970
_override_hook_source_branch=_override_hook_source_branch)
1972
def _push_with_bound_branches(self, target, overwrite,
1974
_override_hook_source_branch=None):
1975
"""Push from self into target, and into target's master if any.
1977
This is on the base BzrBranch class even though it doesn't support
1978
bound branches because the *target* might be bound.
1981
if _override_hook_source_branch:
1982
result.source_branch = _override_hook_source_branch
1983
for hook in Branch.hooks['post_push']:
1986
bound_location = target.get_bound_location()
1987
if bound_location and target.base != bound_location:
1988
# there is a master branch.
1990
# XXX: Why the second check? Is it even supported for a branch to
1991
# be bound to itself? -- mbp 20070507
1992
master_branch = target.get_master_branch()
1993
master_branch.lock_write()
1995
# push into the master from this branch.
1996
self._basic_push(master_branch, overwrite, stop_revision)
1997
# and push into the target branch from this. Note that we push from
1998
# this branch again, because its considered the highest bandwidth
2000
result = self._basic_push(target, overwrite, stop_revision)
2001
result.master_branch = master_branch
2002
result.local_branch = target
2006
master_branch.unlock()
2009
result = self._basic_push(target, overwrite, stop_revision)
2010
# TODO: Why set master_branch and local_branch if there's no
2011
# binding? Maybe cleaner to just leave them unset? -- mbp
2013
result.master_branch = target
2014
result.local_branch = None
2628
2018
def _basic_push(self, target, overwrite, stop_revision):
2629
2019
"""Basic implementation of push without bound branches or hooks.
2631
Must be called with source read locked and target write locked.
2021
Must be called with self read locked and target write locked.
2633
result = BranchPushResult()
2023
result = PushResult()
2634
2024
result.source_branch = self
2635
2025
result.target_branch = target
2636
2026
result.old_revno, result.old_revid = target.last_revision_info()
2637
self.update_references(target)
2638
2027
if result.old_revid != self.last_revision():
2639
2028
# We assume that during 'push' this repository is closer than
2641
2030
graph = self.repository.get_graph(target.repository)
2642
target.update_revisions(self, stop_revision,
2643
overwrite=overwrite, graph=graph)
2031
target.update_revisions(self, stop_revision, overwrite=overwrite,
2644
2033
if self._push_should_merge_tags():
2645
result.tag_conflicts = self.tags.merge_to(target.tags,
2034
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2647
2035
result.new_revno, result.new_revid = target.last_revision_info()
2038
def _push_should_merge_tags(self):
2039
"""Should _basic_push merge this branch's tags into the target?
2041
The default implementation returns False if this branch has no tags,
2042
and True the rest of the time. Subclasses may override this.
2044
return self.tags.supports_tags() and self.tags.get_tag_dict()
2046
def get_parent(self):
2047
"""See Branch.get_parent."""
2048
parent = self._get_parent_location()
2051
# This is an old-format absolute path to a local branch
2052
# turn it into a url
2053
if parent.startswith('/'):
2054
parent = urlutils.local_path_to_url(parent.decode('utf8'))
2056
return urlutils.join(self.base[:-1], parent)
2057
except errors.InvalidURLJoin, e:
2058
raise errors.InaccessibleParent(parent, self.base)
2650
2060
def get_stacked_on_url(self):
2651
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2061
raise errors.UnstackableBranchFormat(self._format, self.base)
2653
2063
def set_push_location(self, location):
2654
2064
"""See Branch.set_push_location."""
2879
2382
"""Set the parent branch"""
2880
2383
return self._get_config_location('parent_location')
2883
def _set_all_reference_info(self, info_dict):
2884
"""Replace all reference info stored in a branch.
2886
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2889
writer = rio.RioWriter(s)
2890
for key, (tree_path, branch_location) in info_dict.iteritems():
2891
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2892
branch_location=branch_location)
2893
writer.write_stanza(stanza)
2894
self._transport.put_bytes('references', s.getvalue())
2895
self._reference_info = info_dict
2898
def _get_all_reference_info(self):
2899
"""Return all the reference info stored in a branch.
2901
:return: A dict of {file_id: (tree_path, branch_location)}
2903
if self._reference_info is not None:
2904
return self._reference_info
2905
rio_file = self._transport.get('references')
2907
stanzas = rio.read_stanzas(rio_file)
2908
info_dict = dict((s['file_id'], (s['tree_path'],
2909
s['branch_location'])) for s in stanzas)
2912
self._reference_info = info_dict
2915
def set_reference_info(self, file_id, tree_path, branch_location):
2916
"""Set the branch location to use for a tree reference.
2918
:param file_id: The file-id of the tree reference.
2919
:param tree_path: The path of the tree reference in the tree.
2920
:param branch_location: The location of the branch to retrieve tree
2923
info_dict = self._get_all_reference_info()
2924
info_dict[file_id] = (tree_path, branch_location)
2925
if None in (tree_path, branch_location):
2926
if tree_path is not None:
2927
raise ValueError('tree_path must be None when branch_location'
2929
if branch_location is not None:
2930
raise ValueError('branch_location must be None when tree_path'
2932
del info_dict[file_id]
2933
self._set_all_reference_info(info_dict)
2935
def get_reference_info(self, file_id):
2936
"""Get the tree_path and branch_location for a tree reference.
2938
:return: a tuple of (tree_path, branch_location)
2940
return self._get_all_reference_info().get(file_id, (None, None))
2942
def reference_parent(self, file_id, path, possible_transports=None):
2943
"""Return the parent branch for a tree-reference file_id.
2945
:param file_id: The file_id of the tree reference
2946
:param path: The path of the file_id in the tree
2947
:return: A branch associated with the file_id
2949
branch_location = self.get_reference_info(file_id)[1]
2950
if branch_location is None:
2951
return Branch.reference_parent(self, file_id, path,
2952
possible_transports)
2953
branch_location = urlutils.join(self.user_url, branch_location)
2954
return Branch.open(branch_location,
2955
possible_transports=possible_transports)
2957
2385
def set_push_location(self, location):
2958
2386
"""See Branch.set_push_location."""
2959
2387
self._set_config_location('push_location', location)
3253
2689
target.unlock()
3257
class InterBranch(InterObject):
3258
"""This class represents operations taking place between two branches.
3260
Its instances have methods like pull() and push() and contain
3261
references to the source and target repositories these operations
3262
can be carried out on.
3266
"""The available optimised InterBranch types."""
3269
def _get_branch_formats_to_test(klass):
3270
"""Return an iterable of format tuples for testing.
3272
:return: An iterable of (from_format, to_format) to use when testing
3273
this InterBranch class. Each InterBranch class should define this
3276
raise NotImplementedError(klass._get_branch_formats_to_test)
3279
def pull(self, overwrite=False, stop_revision=None,
3280
possible_transports=None, local=False):
3281
"""Mirror source into target branch.
3283
The target branch is considered to be 'local', having low latency.
3285
:returns: PullResult instance
3287
raise NotImplementedError(self.pull)
3290
def update_revisions(self, stop_revision=None, overwrite=False,
3292
"""Pull in new perfect-fit revisions.
3294
:param stop_revision: Updated until the given revision
3295
:param overwrite: Always set the branch pointer, rather than checking
3296
to see if it is a proper descendant.
3297
:param graph: A Graph object that can be used to query history
3298
information. This can be None.
3301
raise NotImplementedError(self.update_revisions)
3304
def push(self, overwrite=False, stop_revision=None,
3305
_override_hook_source_branch=None):
3306
"""Mirror the source branch into the target branch.
3308
The source branch is considered to be 'local', having low latency.
3310
raise NotImplementedError(self.push)
3313
def copy_content_into(self, revision_id=None):
3314
"""Copy the content of source into target
3316
revision_id: if not None, the revision history in the new branch will
3317
be truncated to end with revision_id.
3319
raise NotImplementedError(self.copy_content_into)
3322
class GenericInterBranch(InterBranch):
3323
"""InterBranch implementation that uses public Branch functions."""
3326
def is_compatible(klass, source, target):
3327
# GenericBranch uses the public API, so always compatible
3331
def _get_branch_formats_to_test(klass):
3332
return [(BranchFormat._default_format, BranchFormat._default_format)]
3335
def unwrap_format(klass, format):
3336
if isinstance(format, remote.RemoteBranchFormat):
3337
format._ensure_real()
3338
return format._custom_format
3342
def copy_content_into(self, revision_id=None):
3343
"""Copy the content of source into target
3345
revision_id: if not None, the revision history in the new branch will
3346
be truncated to end with revision_id.
3348
self.source.update_references(self.target)
3349
self.source._synchronize_history(self.target, revision_id)
3351
parent = self.source.get_parent()
3352
except errors.InaccessibleParent, e:
3353
mutter('parent was not accessible to copy: %s', e)
3356
self.target.set_parent(parent)
3357
if self.source._push_should_merge_tags():
3358
self.source.tags.merge_to(self.target.tags)
3361
def update_revisions(self, stop_revision=None, overwrite=False,
3363
"""See InterBranch.update_revisions()."""
3364
other_revno, other_last_revision = self.source.last_revision_info()
3365
stop_revno = None # unknown
3366
if stop_revision is None:
3367
stop_revision = other_last_revision
3368
if _mod_revision.is_null(stop_revision):
3369
# if there are no commits, we're done.
3371
stop_revno = other_revno
3373
# what's the current last revision, before we fetch [and change it
3375
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3376
# we fetch here so that we don't process data twice in the common
3377
# case of having something to pull, and so that the check for
3378
# already merged can operate on the just fetched graph, which will
3379
# be cached in memory.
3380
self.target.fetch(self.source, stop_revision)
3381
# Check to see if one is an ancestor of the other
3384
graph = self.target.repository.get_graph()
3385
if self.target._check_if_descendant_or_diverged(
3386
stop_revision, last_rev, graph, self.source):
3387
# stop_revision is a descendant of last_rev, but we aren't
3388
# overwriting, so we're done.
3390
if stop_revno is None:
3392
graph = self.target.repository.get_graph()
3393
this_revno, this_last_revision = \
3394
self.target.last_revision_info()
3395
stop_revno = graph.find_distance_to_null(stop_revision,
3396
[(other_last_revision, other_revno),
3397
(this_last_revision, this_revno)])
3398
self.target.set_last_revision_info(stop_revno, stop_revision)
3401
def pull(self, overwrite=False, stop_revision=None,
3402
possible_transports=None, run_hooks=True,
3403
_override_hook_target=None, local=False):
3404
"""Pull from source into self, updating my master if any.
3406
:param run_hooks: Private parameter - if false, this branch
3407
is being called because it's the master of the primary branch,
3408
so it should not run its hooks.
3410
bound_location = self.target.get_bound_location()
3411
if local and not bound_location:
3412
raise errors.LocalRequiresBoundBranch()
3413
master_branch = None
3414
if not local and bound_location and self.source.user_url != bound_location:
3415
# not pulling from master, so we need to update master.
3416
master_branch = self.target.get_master_branch(possible_transports)
3417
master_branch.lock_write()
3420
# pull from source into master.
3421
master_branch.pull(self.source, overwrite, stop_revision,
3423
return self._pull(overwrite,
3424
stop_revision, _hook_master=master_branch,
3425
run_hooks=run_hooks,
3426
_override_hook_target=_override_hook_target)
3429
master_branch.unlock()
3431
def push(self, overwrite=False, stop_revision=None,
3432
_override_hook_source_branch=None):
3433
"""See InterBranch.push.
3435
This is the basic concrete implementation of push()
3437
:param _override_hook_source_branch: If specified, run
3438
the hooks passing this Branch as the source, rather than self.
3439
This is for use of RemoteBranch, where push is delegated to the
3440
underlying vfs-based Branch.
3442
# TODO: Public option to disable running hooks - should be trivial but
3444
self.source.lock_read()
3446
return _run_with_write_locked_target(
3447
self.target, self._push_with_bound_branches, overwrite,
3449
_override_hook_source_branch=_override_hook_source_branch)
3451
self.source.unlock()
3453
def _push_with_bound_branches(self, overwrite, stop_revision,
3454
_override_hook_source_branch=None):
3455
"""Push from source into target, and into target's master if any.
3458
if _override_hook_source_branch:
3459
result.source_branch = _override_hook_source_branch
3460
for hook in Branch.hooks['post_push']:
3463
bound_location = self.target.get_bound_location()
3464
if bound_location and self.target.base != bound_location:
3465
# there is a master branch.
3467
# XXX: Why the second check? Is it even supported for a branch to
3468
# be bound to itself? -- mbp 20070507
3469
master_branch = self.target.get_master_branch()
3470
master_branch.lock_write()
3472
# push into the master from the source branch.
3473
self.source._basic_push(master_branch, overwrite, stop_revision)
3474
# and push into the target branch from the source. Note that we
3475
# push from the source branch again, because its considered the
3476
# highest bandwidth repository.
3477
result = self.source._basic_push(self.target, overwrite,
3479
result.master_branch = master_branch
3480
result.local_branch = self.target
3484
master_branch.unlock()
3487
result = self.source._basic_push(self.target, overwrite,
3489
# TODO: Why set master_branch and local_branch if there's no
3490
# binding? Maybe cleaner to just leave them unset? -- mbp
3492
result.master_branch = self.target
3493
result.local_branch = None
3497
def _pull(self, overwrite=False, stop_revision=None,
3498
possible_transports=None, _hook_master=None, run_hooks=True,
3499
_override_hook_target=None, local=False):
3502
This function is the core worker, used by GenericInterBranch.pull to
3503
avoid duplication when pulling source->master and source->local.
3505
:param _hook_master: Private parameter - set the branch to
3506
be supplied as the master to pull hooks.
3507
:param run_hooks: Private parameter - if false, this branch
3508
is being called because it's the master of the primary branch,
3509
so it should not run its hooks.
3510
:param _override_hook_target: Private parameter - set the branch to be
3511
supplied as the target_branch to pull hooks.
3512
:param local: Only update the local branch, and not the bound branch.
3514
# This type of branch can't be bound.
3516
raise errors.LocalRequiresBoundBranch()
3517
result = PullResult()
3518
result.source_branch = self.source
3519
if _override_hook_target is None:
3520
result.target_branch = self.target
3522
result.target_branch = _override_hook_target
3523
self.source.lock_read()
3525
# We assume that during 'pull' the target repository is closer than
3527
self.source.update_references(self.target)
3528
graph = self.target.repository.get_graph(self.source.repository)
3529
# TODO: Branch formats should have a flag that indicates
3530
# that revno's are expensive, and pull() should honor that flag.
3532
result.old_revno, result.old_revid = \
3533
self.target.last_revision_info()
3534
self.target.update_revisions(self.source, stop_revision,
3535
overwrite=overwrite, graph=graph)
3536
# TODO: The old revid should be specified when merging tags,
3537
# so a tags implementation that versions tags can only
3538
# pull in the most recent changes. -- JRV20090506
3539
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3541
result.new_revno, result.new_revid = self.target.last_revision_info()
3543
result.master_branch = _hook_master
3544
result.local_branch = result.target_branch
3546
result.master_branch = result.target_branch
3547
result.local_branch = None
3549
for hook in Branch.hooks['post_pull']:
3552
self.source.unlock()
3556
InterBranch.register_optimiser(GenericInterBranch)