134
190
possible_transports)
135
191
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()
137
201
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.
138
209
return BranchConfig(self)
141
return self.get_config().get_nickname()
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
def _get_nick(self, local=False, possible_transports=None):
245
config = self.get_config()
246
# explicit overrides master, but don't look for master if local is True
247
if not local and not config.has_explicit_nickname():
249
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
if master is not None:
253
# return the master branch value
255
except errors.RecursiveBind, e:
257
except errors.BzrError, e:
258
# Silently fall back to local implicit nick if the master is
260
mutter("Could not connect to bound branch, "
261
"falling back to local nick.\n " + str(e))
262
return config.get_nickname()
143
264
def _set_nick(self, nick):
144
265
self.get_config().set_user_option('nickname', nick, warn_masked=True)
165
323
raise NotImplementedError(self.get_physical_lock_status)
326
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
327
"""Return the revision_id for a dotted revno.
329
:param revno: a tuple like (1,) or (1,1,2)
330
:param _cache_reverse: a private parameter enabling storage
331
of the reverse mapping in a top level cache. (This should
332
only be done in selective circumstances as we want to
333
avoid having the mapping cached multiple times.)
334
:return: the revision_id
335
:raises errors.NoSuchRevision: if the revno doesn't exist
337
rev_id = self._do_dotted_revno_to_revision_id(revno)
339
self._partial_revision_id_to_revno_cache[rev_id] = revno
342
def _do_dotted_revno_to_revision_id(self, revno):
343
"""Worker function for dotted_revno_to_revision_id.
345
Subclasses should override this if they wish to
346
provide a more efficient implementation.
349
return self.get_rev_id(revno[0])
350
revision_id_to_revno = self.get_revision_id_to_revno_map()
351
revision_ids = [revision_id for revision_id, this_revno
352
in revision_id_to_revno.iteritems()
353
if revno == this_revno]
354
if len(revision_ids) == 1:
355
return revision_ids[0]
357
revno_str = '.'.join(map(str, revno))
358
raise errors.NoSuchRevision(self, revno_str)
361
def revision_id_to_dotted_revno(self, revision_id):
362
"""Given a revision id, return its dotted revno.
364
:return: a tuple like (1,) or (400,1,3).
366
return self._do_revision_id_to_dotted_revno(revision_id)
368
def _do_revision_id_to_dotted_revno(self, revision_id):
369
"""Worker function for revision_id_to_revno."""
370
# Try the caches if they are loaded
371
result = self._partial_revision_id_to_revno_cache.get(revision_id)
372
if result is not None:
374
if self._revision_id_to_revno_cache:
375
result = self._revision_id_to_revno_cache.get(revision_id)
377
raise errors.NoSuchRevision(self, revision_id)
378
# Try the mainline as it's optimised
380
revno = self.revision_id_to_revno(revision_id)
382
except errors.NoSuchRevision:
383
# We need to load and use the full revno map after all
384
result = self.get_revision_id_to_revno_map().get(revision_id)
386
raise errors.NoSuchRevision(self, revision_id)
168
390
def get_revision_id_to_revno_map(self):
169
391
"""Return the revision_id => dotted revno map.
195
417
:return: A dictionary mapping revision_id => dotted revno.
197
last_revision = self.last_revision()
198
revision_graph = repository._old_get_graph(self.repository,
200
merge_sorted_revisions = tsort.merge_sort(
205
419
revision_id_to_revno = dict((rev_id, revno)
206
for seq_num, rev_id, depth, revno, end_of_merge
207
in merge_sorted_revisions)
420
for rev_id, depth, revno, end_of_merge
421
in self.iter_merge_sorted_revisions())
208
422
return revision_id_to_revno
425
def iter_merge_sorted_revisions(self, start_revision_id=None,
426
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
427
"""Walk the revisions for a branch in merge sorted order.
429
Merge sorted order is the output from a merge-aware,
430
topological sort, i.e. all parents come before their
431
children going forward; the opposite for reverse.
433
:param start_revision_id: the revision_id to begin walking from.
434
If None, the branch tip is used.
435
:param stop_revision_id: the revision_id to terminate the walk
436
after. If None, the rest of history is included.
437
:param stop_rule: if stop_revision_id is not None, the precise rule
438
to use for termination:
439
* 'exclude' - leave the stop revision out of the result (default)
440
* 'include' - the stop revision is the last item in the result
441
* 'with-merges' - include the stop revision and all of its
442
merged revisions in the result
443
* 'with-merges-without-common-ancestry' - filter out revisions
444
that are in both ancestries
445
:param direction: either 'reverse' or 'forward':
446
* reverse means return the start_revision_id first, i.e.
447
start at the most recent revision and go backwards in history
448
* forward returns tuples in the opposite order to reverse.
449
Note in particular that forward does *not* do any intelligent
450
ordering w.r.t. depth as some clients of this API may like.
451
(If required, that ought to be done at higher layers.)
453
:return: an iterator over (revision_id, depth, revno, end_of_merge)
456
* revision_id: the unique id of the revision
457
* depth: How many levels of merging deep this node has been
459
* revno_sequence: This field provides a sequence of
460
revision numbers for all revisions. The format is:
461
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
462
branch that the revno is on. From left to right the REVNO numbers
463
are the sequence numbers within that branch of the revision.
464
* end_of_merge: When True the next node (earlier in history) is
465
part of a different merge.
467
# Note: depth and revno values are in the context of the branch so
468
# we need the full graph to get stable numbers, regardless of the
470
if self._merge_sorted_revisions_cache is None:
471
last_revision = self.last_revision()
472
known_graph = self.repository.get_known_graph_ancestry(
474
self._merge_sorted_revisions_cache = known_graph.merge_sort(
476
filtered = self._filter_merge_sorted_revisions(
477
self._merge_sorted_revisions_cache, start_revision_id,
478
stop_revision_id, stop_rule)
479
# Make sure we don't return revisions that are not part of the
480
# start_revision_id ancestry.
481
filtered = self._filter_start_non_ancestors(filtered)
482
if direction == 'reverse':
484
if direction == 'forward':
485
return reversed(list(filtered))
487
raise ValueError('invalid direction %r' % direction)
489
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
490
start_revision_id, stop_revision_id, stop_rule):
491
"""Iterate over an inclusive range of sorted revisions."""
492
rev_iter = iter(merge_sorted_revisions)
493
if start_revision_id is not None:
494
for node in rev_iter:
495
rev_id = node.key[-1]
496
if rev_id != start_revision_id:
499
# The decision to include the start or not
500
# 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)
504
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,
510
elif stop_rule == 'exclude':
511
for node in rev_iter:
512
rev_id = node.key[-1]
513
if rev_id == stop_revision_id:
515
yield (rev_id, node.merge_depth, node.revno,
517
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,
522
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
elif stop_rule == 'with-merges':
537
stop_rev = self.repository.get_revision(stop_revision_id)
538
if stop_rev.parent_ids:
539
left_parent = stop_rev.parent_ids[0]
541
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]
548
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)
562
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)
210
609
def leave_lock_in_place(self):
211
610
"""Tell this branch object not to release the physical lock when this
212
611
object is unlocked.
214
613
If lock_write doesn't return a token, then this method is not supported.
216
615
self.control_files.leave_in_place()
332
742
def set_revision_history(self, rev_history):
333
743
raise NotImplementedError(self.set_revision_history)
746
def set_parent(self, url):
747
"""See Branch.set_parent."""
748
# TODO: Maybe delete old location files?
749
# URLs should never be unicode, even on the local fs,
750
# FIXUP this and get_parent in a future branch format bump:
751
# read and rewrite the file. RBC 20060125
753
if isinstance(url, unicode):
755
url = url.encode('ascii')
756
except UnicodeEncodeError:
757
raise errors.InvalidURL(url,
758
"Urls must be 7-bit ascii, "
759
"use bzrlib.urlutils.escape")
760
url = urlutils.relative_url(self.base, url)
761
self._set_parent_location(url)
764
def set_stacked_on_url(self, url):
765
"""Set the URL this branch is stacked against.
767
:raises UnstackableBranchFormat: If the branch does not support
769
: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,
335
882
def _cache_revision_history(self, rev_history):
336
883
"""Set the cached revision history to rev_history.
469
1014
information. This can be None.
474
other_revno, other_last_revision = other.last_revision_info()
475
stop_revno = None # unknown
476
if stop_revision is None:
477
stop_revision = other_last_revision
478
if _mod_revision.is_null(stop_revision):
479
# if there are no commits, we're done.
481
stop_revno = other_revno
483
# what's the current last revision, before we fetch [and change it
485
last_rev = _mod_revision.ensure_null(self.last_revision())
486
# we fetch here so that we don't process data twice in the common
487
# case of having something to pull, and so that the check for
488
# already merged can operate on the just fetched graph, which will
489
# be cached in memory.
490
self.fetch(other, stop_revision)
491
# Check to see if one is an ancestor of the other
494
graph = self.repository.get_graph()
495
if self._check_if_descendant_or_diverged(
496
stop_revision, last_rev, graph, other):
497
# stop_revision is a descendant of last_rev, but we aren't
498
# overwriting, so we're done.
500
if stop_revno is None:
502
graph = self.repository.get_graph()
503
this_revno, this_last_revision = self.last_revision_info()
504
stop_revno = graph.find_distance_to_null(stop_revision,
505
[(other_last_revision, other_revno),
506
(this_last_revision, this_revno)])
507
self.set_last_revision_info(stop_revno, stop_revision)
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)
513
1034
def revision_id_to_revno(self, revision_id):
514
1035
"""Given a revision id, return its revno"""
520
1041
except ValueError:
521
1042
raise errors.NoSuchRevision(self, revision_id)
523
1045
def get_rev_id(self, revno, history=None):
524
1046
"""Find the revision id of the specified revno."""
526
1048
return _mod_revision.NULL_REVISION
528
history = self.revision_history()
529
if revno <= 0 or revno > len(history):
1049
last_revno, last_revid = self.last_revision_info()
1050
if revno == last_revno:
1052
if revno <= 0 or revno > last_revno:
530
1053
raise errors.NoSuchRevision(self, revno)
531
return history[revno - 1]
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]
533
1059
def pull(self, source, overwrite=False, stop_revision=None,
534
possible_transports=None, _override_hook_target=None):
1060
possible_transports=None, *args, **kwargs):
535
1061
"""Mirror source into this branch.
537
1063
This branch is considered to be 'local', having low latency.
539
1065
:returns: PullResult instance
541
raise NotImplementedError(self.pull)
1067
return InterBranch.get(source, self).pull(overwrite=overwrite,
1068
stop_revision=stop_revision,
1069
possible_transports=possible_transports, *args, **kwargs)
543
def push(self, target, overwrite=False, stop_revision=None):
1071
def push(self, target, overwrite=False, stop_revision=None, *args,
544
1073
"""Mirror this branch into target.
546
1075
This branch is considered to be 'local', having low latency.
548
raise NotImplementedError(self.push)
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)
550
1101
def basis_tree(self):
551
1102
"""Return `Tree` object for last revision."""
552
1103
return self.repository.revision_tree(self.last_revision())
554
def rename_one(self, from_rel, to_rel):
557
This can change the directory or the filename or both.
559
raise NotImplementedError(self.rename_one)
561
def move(self, from_paths, to_name):
564
to_name must exist as a versioned directory.
566
If to_name exists and is a directory, the files are moved into
567
it, keeping their old names. If it is a directory,
569
Note that to_name is only the last component of the new name;
570
this doesn't change the directory.
572
This returns a list of (from_path, to_path) pairs for each
575
raise NotImplementedError(self.move)
577
1105
def get_parent(self):
578
1106
"""Return the parent location of the branch.
580
This is the default location for push/pull/missing. The usual
1108
This is the default location for pull/missing. The usual
581
1109
pattern is that the user can override it by specifying a
584
raise NotImplementedError(self.get_parent)
1112
parent = self._get_parent_location()
1115
# This is an old-format absolute path to a local branch
1116
# turn it into a url
1117
if parent.startswith('/'):
1118
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1120
return urlutils.join(self.base[:-1], parent)
1121
except errors.InvalidURLJoin, e:
1122
raise errors.InaccessibleParent(parent, self.user_url)
1124
def _get_parent_location(self):
1125
raise NotImplementedError(self._get_parent_location)
586
1127
def _set_config_location(self, name, url, config=None,
587
1128
make_relative=False):
673
1237
raise errors.InvalidRevisionNumber(revno)
675
1239
@needs_read_lock
676
def clone(self, to_bzrdir, revision_id=None):
1240
def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
677
1241
"""Clone this branch into to_bzrdir preserving all semantic values.
1243
Most API users will want 'create_clone_on_transport', which creates a
1244
new bzrdir and branch on the fly.
679
1246
revision_id: if not None, the revision history in the new branch will
680
1247
be truncated to end with revision_id.
682
result = self._format.initialize(to_bzrdir)
683
self.copy_content_into(result, revision_id=revision_id)
1249
result = to_bzrdir.create_branch()
1252
if repository_policy is not None:
1253
repository_policy.configure_branch(result)
1254
self.copy_content_into(result, revision_id=revision_id)
686
1259
@needs_read_lock
687
def sprout(self, to_bzrdir, revision_id=None):
1260
def sprout(self, to_bzrdir, revision_id=None, repository_policy=None):
688
1261
"""Create a new line of development from the branch, into to_bzrdir.
1263
to_bzrdir controls the branch format.
690
1265
revision_id: if not None, the revision history in the new branch will
691
1266
be truncated to end with revision_id.
693
result = self._format.initialize(to_bzrdir)
694
self.copy_content_into(result, revision_id=revision_id)
695
result.set_parent(self.bzrdir.root_transport.base)
1268
if (repository_policy is not None and
1269
repository_policy.requires_stacking()):
1270
to_bzrdir._format.require_stacking(_skip_repo=True)
1271
result = to_bzrdir.create_branch()
1274
if repository_policy is not None:
1275
repository_policy.configure_branch(result)
1276
self.copy_content_into(result, revision_id=revision_id)
1277
result.set_parent(self.bzrdir.root_transport.base)
698
1282
def _synchronize_history(self, destination, revision_id):
699
1283
"""Synchronize last revision and revision history between branches.
701
1285
This version is most efficient when the destination is also a
702
BzrBranch5, but works for BzrBranch6 as long as the revision
703
history is the true lefthand parent history, and all of the revisions
704
are in the destination's repository. If not, set_revision_history
1286
BzrBranch6, but works for BzrBranch5, as long as the destination's
1287
repository contains all the lefthand ancestors of the intended
1288
last_revision. If not, set_last_revision_info will fail.
707
1290
:param destination: The branch to copy the history into
708
1291
:param revision_id: The revision-id to truncate history at. May
709
1292
be None to copy complete history.
711
if revision_id == _mod_revision.NULL_REVISION:
713
new_history = self.revision_history()
714
if revision_id is not None and new_history != []:
1294
source_revno, source_revision_id = self.last_revision_info()
1295
if revision_id is None:
1296
revno, revision_id = source_revno, source_revision_id
1298
graph = self.repository.get_graph()
716
new_history = new_history[:new_history.index(revision_id) + 1]
718
rev = self.repository.get_revision(revision_id)
719
new_history = rev.get_history(self.repository)[1:]
720
destination.set_revision_history(new_history)
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
1305
destination.set_last_revision_info(revno, revision_id)
723
1307
def copy_content_into(self, destination, revision_id=None):
724
1308
"""Copy the content of self into destination.
726
1310
revision_id: if not None, the revision history in the new branch will
727
1311
be truncated to end with revision_id.
729
self._synchronize_history(destination, revision_id)
731
parent = self.get_parent()
732
except errors.InaccessibleParent, e:
733
mutter('parent was not accessible to copy: %s', e)
736
destination.set_parent(parent)
737
self.tags.merge_to(destination.tags)
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)
739
1333
@needs_read_lock
1334
def check(self, refs):
741
1335
"""Check consistency of the branch.
743
1337
In particular this checks that revisions given in the revision-history
744
do actually match up in the revision graph, and that they're all
1338
do actually match up in the revision graph, and that they're all
745
1339
present in the repository.
747
1341
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()
749
1345
:return: A BranchCheckResult.
751
mainline_parent_id = None
1347
result = BranchCheckResult(self)
752
1348
last_revno, last_revision_id = self.last_revision_info()
753
real_rev_history = list(self.repository.iter_reverse_revision_history(
755
real_rev_history.reverse()
756
if len(real_rev_history) != last_revno:
757
raise errors.BzrCheckError('revno does not match len(mainline)'
758
' %s != %s' % (last_revno, len(real_rev_history)))
759
# TODO: We should probably also check that real_rev_history actually
760
# matches self.revision_history()
761
for revision_id in real_rev_history:
763
revision = self.repository.get_revision(revision_id)
764
except errors.NoSuchRevision, e:
765
raise errors.BzrCheckError("mainline revision {%s} not in repository"
767
# In general the first entry on the revision history has no parents.
768
# But it's not illegal for it to have parents listed; this can happen
769
# in imports from Arch when the parents weren't reachable.
770
if mainline_parent_id is not None:
771
if mainline_parent_id not in revision.parent_ids:
772
raise errors.BzrCheckError("previous revision {%s} not listed among "
774
% (mainline_parent_id, revision_id))
775
mainline_parent_id = revision_id
776
return BranchCheckResult(self)
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
778
1361
def _get_checkout_format(self):
779
1362
"""Return the most suitable metadir for a checkout of this branch.
1004
1661
filename, content,
1005
1662
mode=a_bzrdir._get_file_mode())
1007
control_files.unlock()
1008
return self.open(a_bzrdir, _found=True)
1665
control_files.unlock()
1666
branch = self.open(a_bzrdir, name, _found=True)
1667
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1010
def initialize(self, a_bzrdir):
1011
"""Create a branch of this format in a_bzrdir."""
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.
1012
1675
raise NotImplementedError(self.initialize)
1014
1677
def is_supported(self):
1015
1678
"""Is this format supported?
1017
1680
Supported formats can be initialized and opened.
1018
Unsupported formats may not support initialization or committing or
1681
Unsupported formats may not support initialization or committing or
1019
1682
some other features depending on the reason for not being supported.
1023
def open(self, a_bzrdir, _found=False):
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):
1024
1711
"""Return the branch object for a_bzrdir
1026
_found is a private parameter, do not use it. It is used to indicate
1027
if format probing has already be done.
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.
1029
1720
raise NotImplementedError(self.open)
1032
1723
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.
1033
1729
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(),
1036
1739
def set_default_format(klass, format):
1037
1740
klass._default_format = format
1742
def supports_set_append_revisions_only(self):
1743
"""True if this format supports set_append_revisions_only."""
1746
def supports_stacking(self):
1747
"""True if this format records a stacked-on branch."""
1040
1751
def unregister_format(klass, format):
1041
1752
del klass._formats[format.get_format_string()]
1043
1754
def __str__(self):
1044
return self.get_format_string().rstrip()
1755
return self.get_format_description().rstrip()
1046
1757
def supports_tags(self):
1047
1758
"""True if this format supports tags stored in the branch"""
1048
1759
return False # by default
1762
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1763
"""A factory for a BranchFormat object, permitting simple lazy registration.
1765
While none of the built in BranchFormats are lazy registered yet,
1766
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1767
use it, and the bzr-loom plugin uses it as well (see
1768
bzrlib.plugins.loom.formats).
1771
def __init__(self, format_string, module_name, member_name):
1772
"""Create a MetaDirBranchFormatFactory.
1774
:param format_string: The format string the format has.
1775
:param module_name: Module to load the format class from.
1776
:param member_name: Attribute name within the module for the format class.
1778
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1779
self._format_string = format_string
1781
def get_format_string(self):
1782
"""See BranchFormat.get_format_string."""
1783
return self._format_string
1786
"""Used for network_format_registry support."""
1787
return self.get_obj()()
1051
1790
class BranchHooks(Hooks):
1052
1791
"""A dictionary mapping hook name to a list of callables for branch hooks.
1054
1793
e.g. ['set_rh'] Is the list of items to be called when the
1055
1794
set_revision_history function is invoked.
1064
1803
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'] = []
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 "
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))
1126
1883
# install the default hooks into the Branch class.
1159
1916
def __eq__(self, other):
1160
1917
return self.__dict__ == other.__dict__
1162
1919
def __repr__(self):
1163
1920
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1164
self.__class__.__name__, self.branch,
1921
self.__class__.__name__, self.branch,
1165
1922
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,
1168
1998
class BzrBranchFormat4(BranchFormat):
1169
1999
"""Bzr branch format 4.
1177
2007
"""See BranchFormat.get_format_description()."""
1178
2008
return "Branch format 4"
1180
def initialize(self, a_bzrdir):
2010
def initialize(self, a_bzrdir, name=None):
1181
2011
"""Create a branch of this format in a_bzrdir."""
1182
2012
utf8_files = [('revision-history', ''),
1183
2013
('branch-name', ''),
1185
return self._initialize_helper(a_bzrdir, utf8_files,
2015
return self._initialize_helper(a_bzrdir, utf8_files, name=name,
1186
2016
lock_type='branch4', set_format=False)
1188
2018
def __init__(self):
1189
2019
super(BzrBranchFormat4, self).__init__()
1190
2020
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1192
def open(self, a_bzrdir, _found=False):
1193
"""Return the branch object for a_bzrdir
2022
def network_name(self):
2023
"""The network name for this format is the control dirs disk label."""
2024
return self._matchingbzrdir.get_format_string()
1195
_found is a private parameter, do not use it. It is used to indicate
1196
if format probing has already be done.
2026
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2027
"""See BranchFormat.open()."""
1199
2029
# we are being called directly and must probe.
1200
2030
raise NotImplementedError
1201
2031
return BzrBranch(_format=self,
1202
2032
_control_files=a_bzrdir._control_files,
1203
2033
a_bzrdir=a_bzrdir,
1204
2035
_repository=a_bzrdir.open_repository())
1206
2037
def __str__(self):
1207
2038
return "Bazaar-NG branch format 4"
1210
class BzrBranchFormat5(BranchFormat):
2041
class BranchFormatMetadir(BranchFormat):
2042
"""Common logic for meta-dir based branch formats."""
2044
def _branch_class(self):
2045
"""What class to instantiate on open calls."""
2046
raise NotImplementedError(self._branch_class)
2048
def network_name(self):
2049
"""A simple byte string uniquely identifying this format for RPC calls.
2051
Metadir branch formats use their format string.
2053
return self.get_format_string()
2055
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False):
2056
"""See BranchFormat.open()."""
2058
format = BranchFormat.find_format(a_bzrdir, name=name)
2059
if format.__class__ != self.__class__:
2060
raise AssertionError("wrong format %r found for %r" %
2062
transport = a_bzrdir.get_branch_transport(None, name=name)
2064
control_files = lockable_files.LockableFiles(transport, 'lock',
2066
return self._branch_class()(_format=self,
2067
_control_files=control_files,
2070
_repository=a_bzrdir.find_repository(),
2071
ignore_fallbacks=ignore_fallbacks)
2072
except errors.NoSuchFile:
2073
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2076
super(BranchFormatMetadir, self).__init__()
2077
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2078
self._matchingbzrdir.set_branch_format(self)
2080
def supports_tags(self):
2084
class BzrBranchFormat5(BranchFormatMetadir):
1211
2085
"""Bzr branch format 5.
1213
2087
This format has:
1281
2138
"""See BranchFormat.get_format_description()."""
1282
2139
return "Branch format 6"
1284
def initialize(self, a_bzrdir):
1285
"""Create a branch of this format in a_bzrdir."""
1286
utf8_files = [('last-revision', '0 null:\n'),
1287
('branch.conf', ''),
1290
return self._initialize_helper(a_bzrdir, utf8_files)
1292
def open(self, a_bzrdir, _found=False):
1293
"""Return the branch object for a_bzrdir
1295
_found is a private parameter, do not use it. It is used to indicate
1296
if format probing has already be done.
1299
format = BranchFormat.find_format(a_bzrdir)
1300
if format.__class__ != self.__class__:
1301
raise AssertionError("wrong format %r found for %r" %
1303
transport = a_bzrdir.get_branch_transport(None)
1304
control_files = lockable_files.LockableFiles(transport, 'lock',
1306
return BzrBranch6(_format=self,
1307
_control_files=control_files,
1309
_repository=a_bzrdir.find_repository())
1311
def supports_tags(self):
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):
2199
"""Branch format with last-revision, tags, and a stacked location pointer.
2201
The stacked location pointer is passed down to the repository and requires
2202
a repository format with supports_external_lookups = True.
2204
This format was introduced in bzr 1.6.
2207
def initialize(self, a_bzrdir, name=None):
2208
"""Create a branch of this format in a_bzrdir."""
2209
utf8_files = [('last-revision', '0 null:\n'),
2210
('branch.conf', ''),
2213
return self._initialize_helper(a_bzrdir, utf8_files, name)
2215
def _branch_class(self):
2218
def get_format_string(self):
2219
"""See BranchFormat.get_format_string()."""
2220
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2222
def get_format_description(self):
2223
"""See BranchFormat.get_format_description()."""
2224
return "Branch format 7"
2226
def supports_set_append_revisions_only(self):
2229
supports_reference_locations = False
1315
2232
class BranchReferenceFormat(BranchFormat):
1331
2248
"""See BranchFormat.get_format_description()."""
1332
2249
return "Checkout reference format 1"
1334
def get_reference(self, a_bzrdir):
2251
def get_reference(self, a_bzrdir, name=None):
1335
2252
"""See BranchFormat.get_reference()."""
1336
transport = a_bzrdir.get_branch_transport(None)
1337
return transport.get('location').read()
2253
transport = a_bzrdir.get_branch_transport(None, name=name)
2254
return transport.get_bytes('location')
1339
def set_reference(self, a_bzrdir, to_branch):
2256
def set_reference(self, a_bzrdir, name, to_branch):
1340
2257
"""See BranchFormat.set_reference()."""
1341
transport = a_bzrdir.get_branch_transport(None)
2258
transport = a_bzrdir.get_branch_transport(None, name=name)
1342
2259
location = transport.put_bytes('location', to_branch.base)
1344
def initialize(self, a_bzrdir, target_branch=None):
2261
def initialize(self, a_bzrdir, name=None, target_branch=None):
1345
2262
"""Create a branch of this format in a_bzrdir."""
1346
2263
if target_branch is None:
1347
2264
# this format does not implement branch itself, thus the implicit
1348
2265
# creation contract must see it as uninitializable
1349
2266
raise errors.UninitializableFormat(self)
1350
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1351
branch_transport = a_bzrdir.get_branch_transport(self)
2267
mutter('creating branch reference in %s', a_bzrdir.user_url)
2268
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1352
2269
branch_transport.put_bytes('location',
1353
target_branch.bzrdir.root_transport.base)
2270
target_branch.bzrdir.user_url)
1354
2271
branch_transport.put_bytes('format', self.get_format_string())
1356
a_bzrdir, _found=True,
2273
a_bzrdir, name, _found=True,
1357
2274
possible_transports=[target_branch.bzrdir.root_transport])
2275
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1359
2278
def __init__(self):
1360
2279
super(BranchReferenceFormat, self).__init__()
1361
2280
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2281
self._matchingbzrdir.set_branch_format(self)
1363
2283
def _make_reference_clone_function(format, a_branch):
1364
2284
"""Create a clone() routine for a branch dynamically."""
1365
def clone(to_bzrdir, revision_id=None):
2285
def clone(to_bzrdir, revision_id=None,
2286
repository_policy=None):
1366
2287
"""See Branch.clone()."""
1367
return format.initialize(to_bzrdir, a_branch)
2288
return format.initialize(to_bzrdir, target_branch=a_branch)
1368
2289
# cannot obey revision_id limits when cloning a reference ...
1369
2290
# FIXME RBC 20060210 either nuke revision_id for clone, or
1370
2291
# emit some sort of warning/error to the caller ?!
1373
def open(self, a_bzrdir, _found=False, location=None,
1374
possible_transports=None):
2294
def open(self, a_bzrdir, name=None, _found=False, location=None,
2295
possible_transports=None, ignore_fallbacks=False):
1375
2296
"""Return the branch that the branch reference in a_bzrdir points at.
1377
_found is a private parameter, do not use it. It is used to indicate
1378
if format probing has already be done.
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.
1381
format = BranchFormat.find_format(a_bzrdir)
2310
format = BranchFormat.find_format(a_bzrdir, name=name)
1382
2311
if format.__class__ != self.__class__:
1383
2312
raise AssertionError("wrong format %r found for %r" %
1384
2313
(format, self))
1385
2314
if location is None:
1386
location = self.get_reference(a_bzrdir)
2315
location = self.get_reference(a_bzrdir, name)
1387
2316
real_bzrdir = bzrdir.BzrDir.open(
1388
2317
location, possible_transports=possible_transports)
1389
result = real_bzrdir.open_branch()
2318
result = real_bzrdir.open_branch(name=name,
2319
ignore_fallbacks=ignore_fallbacks)
1390
2320
# this changes the behaviour of result.clone to create a new reference
1391
2321
# rather than a copy of the content of the branch.
1392
2322
# 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.
1402
2341
# formats which have no format string are not discoverable
1403
2342
# and not independently creatable, so are not registered.
1404
2343
__format5 = BzrBranchFormat5()
1405
2344
__format6 = BzrBranchFormat6()
2345
__format7 = BzrBranchFormat7()
2346
__format8 = BzrBranchFormat8()
1406
2347
BranchFormat.register_format(__format5)
1407
2348
BranchFormat.register_format(BranchReferenceFormat())
1408
2349
BranchFormat.register_format(__format6)
1409
BranchFormat.set_default_format(__format6)
2350
BranchFormat.register_format(__format7)
2351
BranchFormat.register_format(__format8)
2352
BranchFormat.set_default_format(__format7)
1410
2353
_legacy_formats = [BzrBranchFormat4(),
1413
class BzrBranch(Branch):
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):
1414
2377
"""A branch stored in the actual filesystem.
1416
2379
Note that it's "local" in the context of the filesystem; it doesn't
1417
2380
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1418
2381
it's writable, and can be accessed via the normal filesystem API.
1420
:ivar _transport: Transport for file operations on this branch's
2383
:ivar _transport: Transport for file operations on this branch's
1421
2384
control files, typically pointing to the .bzr/branch directory.
1422
2385
:ivar repository: Repository for this branch.
1423
:ivar base: The url of the base directory for this branch; the one
2386
:ivar base: The url of the base directory for this branch; the one
1424
2387
containing the .bzr directory.
2388
:ivar name: Optional colocated branch name as it exists in the control
1427
2392
def __init__(self, _format=None,
1428
_control_files=None, a_bzrdir=None, _repository=None):
2393
_control_files=None, a_bzrdir=None, name=None,
2394
_repository=None, ignore_fallbacks=False):
1429
2395
"""Create new branch object at a particular location."""
1430
Branch.__init__(self)
1431
2396
if a_bzrdir is None:
1432
2397
raise ValueError('a_bzrdir must be supplied')
1434
2399
self.bzrdir = a_bzrdir
1435
2400
self._base = self.bzrdir.transport.clone('..').base
1436
2402
# XXX: We should be able to just do
1437
2403
# self.base = self.bzrdir.root_transport.base
1438
2404
# but this does not quite work yet -- mbp 20080522
1455
2426
base = property(_get_base, doc="The URL for the root of this branch.")
1457
@deprecated_method(deprecated_in((0, 16, 0)))
1458
def abspath(self, name):
1459
"""See Branch.abspath."""
1460
return self._transport.abspath(name)
2428
def _get_config(self):
2429
return TransportConfig(self._transport, 'branch.conf')
1462
2431
def is_locked(self):
1463
2432
return self.control_files.is_locked()
1465
2434
def lock_write(self, token=None):
1466
repo_token = self.repository.lock_write()
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()
1468
token = self.control_files.lock_write(token=token)
2452
return BranchWriteLockResult(self.unlock,
2453
self.control_files.lock_write(token=token))
1470
self.repository.unlock()
2456
self.repository.unlock()
1474
2459
def lock_read(self):
1475
self.repository.lock_read()
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()
1477
2475
self.control_files.lock_read()
2476
return LogicalLockResult(self.unlock)
1479
self.repository.unlock()
2479
self.repository.unlock()
2482
@only_raises(errors.LockNotHeld, errors.LockBroken)
1482
2483
def unlock(self):
1483
# TODO: test for failed two phase locks. This is known broken.
1485
2485
self.control_files.unlock()
1487
self.repository.unlock()
1488
if not self.control_files.is_locked():
1489
# we just released the lock
1490
self._clear_cached_state()
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()
1492
2496
def peek_lock_mode(self):
1493
2497
if self.control_files._lock_count == 0:
1520
2524
check_not_reserved_id = _mod_revision.check_not_reserved_id
1521
2525
for rev_id in rev_history:
1522
2526
check_not_reserved_id(rev_id)
2527
if Branch.hooks['post_change_branch_tip']:
2528
# Don't calculate the last_revision_info() if there are no hooks
2530
old_revno, old_revid = self.last_revision_info()
2531
if len(rev_history) == 0:
2532
revid = _mod_revision.NULL_REVISION
2534
revid = rev_history[-1]
2535
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1523
2536
self._write_revision_history(rev_history)
1524
2537
self._clear_cached_state()
1525
2538
self._cache_revision_history(rev_history)
1526
2539
for hook in Branch.hooks['set_rh']:
1527
2540
hook(self, rev_history)
1529
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1530
"""Run the pre_change_branch_tip hooks."""
1531
hooks = Branch.hooks['pre_change_branch_tip']
1534
old_revno, old_revid = self.last_revision_info()
1535
params = ChangeBranchTipParams(
1536
self, old_revno, new_revno, old_revid, new_revid)
1540
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1541
"""Run the post_change_branch_tip hooks."""
1542
hooks = Branch.hooks['post_change_branch_tip']
1545
new_revno, new_revid = self.last_revision_info()
1546
params = ChangeBranchTipParams(
1547
self, old_revno, new_revno, old_revid, new_revid)
2541
if Branch.hooks['post_change_branch_tip']:
2542
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2544
def _synchronize_history(self, destination, revision_id):
2545
"""Synchronize last revision and revision history between branches.
2547
This version is most efficient when the destination is also a
2548
BzrBranch5, but works for BzrBranch6 as long as the revision
2549
history is the true lefthand parent history, and all of the revisions
2550
are in the destination's repository. If not, set_revision_history
2553
:param destination: The branch to copy the history into
2554
:param revision_id: The revision-id to truncate history at. May
2555
be None to copy complete history.
2557
if not isinstance(destination._format, BzrBranchFormat5):
2558
super(BzrBranch, self)._synchronize_history(
2559
destination, revision_id)
2561
if revision_id == _mod_revision.NULL_REVISION:
2564
new_history = self.revision_history()
2565
if revision_id is not None and new_history != []:
2567
new_history = new_history[:new_history.index(revision_id) + 1]
2569
rev = self.repository.get_revision(revision_id)
2570
new_history = rev.get_history(self.repository)[1:]
2571
destination.set_revision_history(new_history)
1551
2573
@needs_write_lock
1552
2574
def set_last_revision_info(self, revno, revision_id):
1553
2575
"""Set the last revision of this branch.
1680
def push(self, target, overwrite=False, stop_revision=None,
1681
_override_hook_source_branch=None):
1684
This is the basic concrete implementation of push()
1686
:param _override_hook_source_branch: If specified, run
1687
the hooks passing this Branch as the source, rather than self.
1688
This is for use of RemoteBranch, where push is delegated to the
1689
underlying vfs-based Branch.
1691
# TODO: Public option to disable running hooks - should be trivial but
1695
result = self._push_with_bound_branches(target, overwrite,
1697
_override_hook_source_branch=_override_hook_source_branch)
1702
def _push_with_bound_branches(self, target, overwrite,
1704
_override_hook_source_branch=None):
1705
"""Push from self into target, and into target's master if any.
1707
This is on the base BzrBranch class even though it doesn't support
1708
bound branches because the *target* might be bound.
1711
if _override_hook_source_branch:
1712
result.source_branch = _override_hook_source_branch
1713
for hook in Branch.hooks['post_push']:
1716
bound_location = target.get_bound_location()
1717
if bound_location and target.base != bound_location:
1718
# there is a master branch.
1720
# XXX: Why the second check? Is it even supported for a branch to
1721
# be bound to itself? -- mbp 20070507
1722
master_branch = target.get_master_branch()
1723
master_branch.lock_write()
1725
# push into the master from this branch.
1726
self._basic_push(master_branch, overwrite, stop_revision)
1727
# and push into the target branch from this. Note that we push from
1728
# this branch again, because its considered the highest bandwidth
1730
result = self._basic_push(target, overwrite, stop_revision)
1731
result.master_branch = master_branch
1732
result.local_branch = target
1736
master_branch.unlock()
1739
result = self._basic_push(target, overwrite, stop_revision)
1740
# TODO: Why set master_branch and local_branch if there's no
1741
# binding? Maybe cleaner to just leave them unset? -- mbp
1743
result.master_branch = target
1744
result.local_branch = None
1748
2628
def _basic_push(self, target, overwrite, stop_revision):
1749
2629
"""Basic implementation of push without bound branches or hooks.
1751
Must be called with self read locked and target write locked.
2631
Must be called with source read locked and target write locked.
1753
result = PushResult()
2633
result = BranchPushResult()
1754
2634
result.source_branch = self
1755
2635
result.target_branch = target
1756
2636
result.old_revno, result.old_revid = target.last_revision_info()
1758
# We assume that during 'push' this repository is closer than
1760
graph = self.repository.get_graph(target.repository)
1761
target.update_revisions(self, stop_revision, overwrite=overwrite,
1763
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2637
self.update_references(target)
2638
if result.old_revid != self.last_revision():
2639
# We assume that during 'push' this repository is closer than
2641
graph = self.repository.get_graph(target.repository)
2642
target.update_revisions(self, stop_revision,
2643
overwrite=overwrite, graph=graph)
2644
if self._push_should_merge_tags():
2645
result.tag_conflicts = self.tags.merge_to(target.tags,
1764
2647
result.new_revno, result.new_revid = target.last_revision_info()
1767
def get_parent(self):
1768
"""See Branch.get_parent."""
1769
parent = self._get_parent_location()
1772
# This is an old-format absolute path to a local branch
1773
# turn it into a url
1774
if parent.startswith('/'):
1775
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1777
return urlutils.join(self.base[:-1], parent)
1778
except errors.InvalidURLJoin, e:
1779
raise errors.InaccessibleParent(parent, self.base)
2650
def get_stacked_on_url(self):
2651
raise errors.UnstackableBranchFormat(self._format, self.user_url)
1781
2653
def set_push_location(self, location):
1782
2654
"""See Branch.set_push_location."""
2059
2879
"""Set the parent branch"""
2060
2880
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)
2062
2957
def set_push_location(self, location):
2063
2958
"""See Branch.set_push_location."""
2064
2959
self._set_config_location('push_location', location)
2301
3207
except errors.NoSuchFile:
2303
3209
branch.set_bound_location(None)
3212
class Converter6to7(object):
3213
"""Perform an in-place upgrade of format 6 to format 7"""
3215
def convert(self, branch):
3216
format = BzrBranchFormat7()
3217
branch._set_config_location('stacked_on_location', '')
3218
# update target format
3219
branch._transport.put_bytes('format', format.get_format_string())
3222
class Converter7to8(object):
3223
"""Perform an in-place upgrade of format 6 to format 7"""
3225
def convert(self, branch):
3226
format = BzrBranchFormat8()
3227
branch._transport.put_bytes('references', '')
3228
# update target format
3229
branch._transport.put_bytes('format', format.get_format_string())
3232
def _run_with_write_locked_target(target, callable, *args, **kwargs):
3233
"""Run ``callable(*args, **kwargs)``, write-locking target for the
3236
_run_with_write_locked_target will attempt to release the lock it acquires.
3238
If an exception is raised by callable, then that exception *will* be
3239
propagated, even if the unlock attempt raises its own error. Thus
3240
_run_with_write_locked_target should be preferred to simply doing::
3244
return callable(*args, **kwargs)
3249
# This is very similar to bzrlib.decorators.needs_write_lock. Perhaps they
3250
# should share code?
3253
result = callable(*args, **kwargs)
3255
exc_info = sys.exc_info()
3259
raise exc_info[0], exc_info[1], exc_info[2]
3265
class InterBranch(InterObject):
3266
"""This class represents operations taking place between two branches.
3268
Its instances have methods like pull() and push() and contain
3269
references to the source and target repositories these operations
3270
can be carried out on.
3274
"""The available optimised InterBranch types."""
3277
def _get_branch_formats_to_test(klass):
3278
"""Return an iterable of format tuples for testing.
3280
:return: An iterable of (from_format, to_format) to use when testing
3281
this InterBranch class. Each InterBranch class should define this
3284
raise NotImplementedError(klass._get_branch_formats_to_test)
3287
def pull(self, overwrite=False, stop_revision=None,
3288
possible_transports=None, local=False):
3289
"""Mirror source into target branch.
3291
The target branch is considered to be 'local', having low latency.
3293
:returns: PullResult instance
3295
raise NotImplementedError(self.pull)
3298
def update_revisions(self, stop_revision=None, overwrite=False,
3300
"""Pull in new perfect-fit revisions.
3302
:param stop_revision: Updated until the given revision
3303
:param overwrite: Always set the branch pointer, rather than checking
3304
to see if it is a proper descendant.
3305
:param graph: A Graph object that can be used to query history
3306
information. This can be None.
3309
raise NotImplementedError(self.update_revisions)
3312
def push(self, overwrite=False, stop_revision=None,
3313
_override_hook_source_branch=None):
3314
"""Mirror the source branch into the target branch.
3316
The source branch is considered to be 'local', having low latency.
3318
raise NotImplementedError(self.push)
3321
def copy_content_into(self, revision_id=None):
3322
"""Copy the content of source into target
3324
revision_id: if not None, the revision history in the new branch will
3325
be truncated to end with revision_id.
3327
raise NotImplementedError(self.copy_content_into)
3330
class GenericInterBranch(InterBranch):
3331
"""InterBranch implementation that uses public Branch functions."""
3334
def is_compatible(klass, source, target):
3335
# GenericBranch uses the public API, so always compatible
3339
def _get_branch_formats_to_test(klass):
3340
return [(BranchFormat._default_format, BranchFormat._default_format)]
3343
def unwrap_format(klass, format):
3344
if isinstance(format, remote.RemoteBranchFormat):
3345
format._ensure_real()
3346
return format._custom_format
3350
def copy_content_into(self, revision_id=None):
3351
"""Copy the content of source into target
3353
revision_id: if not None, the revision history in the new branch will
3354
be truncated to end with revision_id.
3356
self.source.update_references(self.target)
3357
self.source._synchronize_history(self.target, revision_id)
3359
parent = self.source.get_parent()
3360
except errors.InaccessibleParent, e:
3361
mutter('parent was not accessible to copy: %s', e)
3364
self.target.set_parent(parent)
3365
if self.source._push_should_merge_tags():
3366
self.source.tags.merge_to(self.target.tags)
3369
def update_revisions(self, stop_revision=None, overwrite=False,
3371
"""See InterBranch.update_revisions()."""
3372
other_revno, other_last_revision = self.source.last_revision_info()
3373
stop_revno = None # unknown
3374
if stop_revision is None:
3375
stop_revision = other_last_revision
3376
if _mod_revision.is_null(stop_revision):
3377
# if there are no commits, we're done.
3379
stop_revno = other_revno
3381
# what's the current last revision, before we fetch [and change it
3383
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3384
# we fetch here so that we don't process data twice in the common
3385
# case of having something to pull, and so that the check for
3386
# already merged can operate on the just fetched graph, which will
3387
# be cached in memory.
3388
self.target.fetch(self.source, stop_revision)
3389
# Check to see if one is an ancestor of the other
3392
graph = self.target.repository.get_graph()
3393
if self.target._check_if_descendant_or_diverged(
3394
stop_revision, last_rev, graph, self.source):
3395
# stop_revision is a descendant of last_rev, but we aren't
3396
# overwriting, so we're done.
3398
if stop_revno is None:
3400
graph = self.target.repository.get_graph()
3401
this_revno, this_last_revision = \
3402
self.target.last_revision_info()
3403
stop_revno = graph.find_distance_to_null(stop_revision,
3404
[(other_last_revision, other_revno),
3405
(this_last_revision, this_revno)])
3406
self.target.set_last_revision_info(stop_revno, stop_revision)
3409
def pull(self, overwrite=False, stop_revision=None,
3410
possible_transports=None, run_hooks=True,
3411
_override_hook_target=None, local=False):
3412
"""Pull from source into self, updating my master if any.
3414
:param run_hooks: Private parameter - if false, this branch
3415
is being called because it's the master of the primary branch,
3416
so it should not run its hooks.
3418
bound_location = self.target.get_bound_location()
3419
if local and not bound_location:
3420
raise errors.LocalRequiresBoundBranch()
3421
master_branch = None
3422
if not local and bound_location and self.source.user_url != bound_location:
3423
# not pulling from master, so we need to update master.
3424
master_branch = self.target.get_master_branch(possible_transports)
3425
master_branch.lock_write()
3428
# pull from source into master.
3429
master_branch.pull(self.source, overwrite, stop_revision,
3431
return self._pull(overwrite,
3432
stop_revision, _hook_master=master_branch,
3433
run_hooks=run_hooks,
3434
_override_hook_target=_override_hook_target)
3437
master_branch.unlock()
3439
def push(self, overwrite=False, stop_revision=None,
3440
_override_hook_source_branch=None):
3441
"""See InterBranch.push.
3443
This is the basic concrete implementation of push()
3445
:param _override_hook_source_branch: If specified, run
3446
the hooks passing this Branch as the source, rather than self.
3447
This is for use of RemoteBranch, where push is delegated to the
3448
underlying vfs-based Branch.
3450
# TODO: Public option to disable running hooks - should be trivial but
3452
self.source.lock_read()
3454
return _run_with_write_locked_target(
3455
self.target, self._push_with_bound_branches, overwrite,
3457
_override_hook_source_branch=_override_hook_source_branch)
3459
self.source.unlock()
3461
def _push_with_bound_branches(self, overwrite, stop_revision,
3462
_override_hook_source_branch=None):
3463
"""Push from source into target, and into target's master if any.
3466
if _override_hook_source_branch:
3467
result.source_branch = _override_hook_source_branch
3468
for hook in Branch.hooks['post_push']:
3471
bound_location = self.target.get_bound_location()
3472
if bound_location and self.target.base != bound_location:
3473
# there is a master branch.
3475
# XXX: Why the second check? Is it even supported for a branch to
3476
# be bound to itself? -- mbp 20070507
3477
master_branch = self.target.get_master_branch()
3478
master_branch.lock_write()
3480
# push into the master from the source branch.
3481
self.source._basic_push(master_branch, overwrite, stop_revision)
3482
# and push into the target branch from the source. Note that we
3483
# push from the source branch again, because it's considered the
3484
# highest bandwidth repository.
3485
result = self.source._basic_push(self.target, overwrite,
3487
result.master_branch = master_branch
3488
result.local_branch = self.target
3492
master_branch.unlock()
3495
result = self.source._basic_push(self.target, overwrite,
3497
# TODO: Why set master_branch and local_branch if there's no
3498
# binding? Maybe cleaner to just leave them unset? -- mbp
3500
result.master_branch = self.target
3501
result.local_branch = None
3505
def _pull(self, overwrite=False, stop_revision=None,
3506
possible_transports=None, _hook_master=None, run_hooks=True,
3507
_override_hook_target=None, local=False):
3510
This function is the core worker, used by GenericInterBranch.pull to
3511
avoid duplication when pulling source->master and source->local.
3513
:param _hook_master: Private parameter - set the branch to
3514
be supplied as the master to pull hooks.
3515
:param run_hooks: Private parameter - if false, this branch
3516
is being called because it's the master of the primary branch,
3517
so it should not run its hooks.
3518
:param _override_hook_target: Private parameter - set the branch to be
3519
supplied as the target_branch to pull hooks.
3520
:param local: Only update the local branch, and not the bound branch.
3522
# This type of branch can't be bound.
3524
raise errors.LocalRequiresBoundBranch()
3525
result = PullResult()
3526
result.source_branch = self.source
3527
if _override_hook_target is None:
3528
result.target_branch = self.target
3530
result.target_branch = _override_hook_target
3531
self.source.lock_read()
3533
# We assume that during 'pull' the target repository is closer than
3535
self.source.update_references(self.target)
3536
graph = self.target.repository.get_graph(self.source.repository)
3537
# TODO: Branch formats should have a flag that indicates
3538
# that revno's are expensive, and pull() should honor that flag.
3540
result.old_revno, result.old_revid = \
3541
self.target.last_revision_info()
3542
self.target.update_revisions(self.source, stop_revision,
3543
overwrite=overwrite, graph=graph)
3544
# TODO: The old revid should be specified when merging tags,
3545
# so a tags implementation that versions tags can only
3546
# pull in the most recent changes. -- JRV20090506
3547
result.tag_conflicts = self.source.tags.merge_to(self.target.tags,
3549
result.new_revno, result.new_revid = self.target.last_revision_info()
3551
result.master_branch = _hook_master
3552
result.local_branch = result.target_branch
3554
result.master_branch = result.target_branch
3555
result.local_branch = None
3557
for hook in Branch.hooks['post_pull']:
3560
self.source.unlock()
3564
InterBranch.register_optimiser(GenericInterBranch)