1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from itertools import chain
26
config as _mod_config,
32
revision as _mod_revision,
38
from bzrlib.config import BranchConfig
39
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
40
from bzrlib.tag import (
46
from bzrlib.decorators import needs_read_lock, needs_write_lock
47
from bzrlib.hooks import Hooks
48
from bzrlib.symbol_versioning import (
52
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
55
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
56
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
57
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
60
# TODO: Maybe include checks for common corruption of newlines, etc?
62
# TODO: Some operations like log might retrieve the same revisions
63
# repeatedly to calculate deltas. We could perhaps have a weakref
64
# cache in memory to make this faster. In general anything can be
65
# cached in memory between lock and unlock operations. .. nb thats
66
# what the transaction identity map provides
69
######################################################################
73
"""Branch holding a history of revisions.
76
Base directory/url of the branch.
78
hooks: An instance of BranchHooks.
80
# this is really an instance variable - FIXME move it there
84
# override this to set the strategy for storing tags
86
return DisabledTags(self)
88
def __init__(self, *ignored, **ignored_too):
89
self.tags = self._make_tags()
90
self._revision_history_cache = None
91
self._revision_id_to_revno_cache = None
92
self._last_revision_info_cache = None
94
hooks = Branch.hooks['open']
99
"""Called by init to allow simpler extension of the base class."""
101
def break_lock(self):
102
"""Break a lock if one is present from another instance.
104
Uses the ui factory to ask for confirmation if the lock may be from
107
This will probe the repository for its lock as well.
109
self.control_files.break_lock()
110
self.repository.break_lock()
111
master = self.get_master_branch()
112
if master is not None:
116
def open(base, _unsupported=False, possible_transports=None):
117
"""Open the branch rooted at base.
119
For instance, if the branch is at URL/.bzr/branch,
120
Branch.open(URL) -> a Branch instance.
122
control = bzrdir.BzrDir.open(base, _unsupported,
123
possible_transports=possible_transports)
124
return control.open_branch(_unsupported)
127
def open_from_transport(transport, _unsupported=False):
128
"""Open the branch rooted at transport"""
129
control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
130
return control.open_branch(_unsupported)
133
def open_containing(url, possible_transports=None):
134
"""Open an existing branch which contains url.
136
This probes for a branch at url, and searches upwards from there.
138
Basically we keep looking up until we find the control directory or
139
run into the root. If there isn't one, raises NotBranchError.
140
If there is one and it is either an unrecognised format or an unsupported
141
format, UnknownFormatError or UnsupportedFormatError are raised.
142
If there is one, it is returned, along with the unused portion of url.
144
control, relpath = bzrdir.BzrDir.open_containing(url,
146
return control.open_branch(), relpath
148
def get_config(self):
149
return BranchConfig(self)
151
def _get_nick(self, possible_transports=None):
152
config = self.get_config()
153
if not config.has_explicit_nickname(): # explicit overrides master
155
master = self.get_master_branch(possible_transports)
156
if master is not None:
157
# return the master branch value
158
config = master.get_config()
159
except errors.BzrError, e:
160
# Silently fall back to local implicit nick if the master is
162
mutter("Could not connect to bound branch, "
163
"falling back to local nick.\n " + str(e))
164
return config.get_nickname()
166
def _set_nick(self, nick):
167
self.get_config().set_user_option('nickname', nick, warn_masked=True)
169
nick = property(_get_nick, _set_nick)
172
raise NotImplementedError(self.is_locked)
174
def lock_write(self):
175
raise NotImplementedError(self.lock_write)
178
raise NotImplementedError(self.lock_read)
181
raise NotImplementedError(self.unlock)
183
def peek_lock_mode(self):
184
"""Return lock mode for the Branch: 'r', 'w' or None"""
185
raise NotImplementedError(self.peek_lock_mode)
187
def get_physical_lock_status(self):
188
raise NotImplementedError(self.get_physical_lock_status)
191
def get_revision_id_to_revno_map(self):
192
"""Return the revision_id => dotted revno map.
194
This will be regenerated on demand, but will be cached.
196
:return: A dictionary mapping revision_id => dotted revno.
197
This dictionary should not be modified by the caller.
199
if self._revision_id_to_revno_cache is not None:
200
mapping = self._revision_id_to_revno_cache
202
mapping = self._gen_revno_map()
203
self._cache_revision_id_to_revno(mapping)
204
# TODO: jam 20070417 Since this is being cached, should we be returning
206
# I would rather not, and instead just declare that users should not
207
# modify the return value.
210
def _gen_revno_map(self):
211
"""Create a new mapping from revision ids to dotted revnos.
213
Dotted revnos are generated based on the current tip in the revision
215
This is the worker function for get_revision_id_to_revno_map, which
216
just caches the return value.
218
:return: A dictionary mapping revision_id => dotted revno.
220
last_revision = self.last_revision()
221
revision_graph = repository._old_get_graph(self.repository,
223
merge_sorted_revisions = tsort.merge_sort(
228
revision_id_to_revno = dict((rev_id, revno)
229
for seq_num, rev_id, depth, revno, end_of_merge
230
in merge_sorted_revisions)
231
return revision_id_to_revno
233
def leave_lock_in_place(self):
234
"""Tell this branch object not to release the physical lock when this
237
If lock_write doesn't return a token, then this method is not supported.
239
self.control_files.leave_in_place()
241
def dont_leave_lock_in_place(self):
242
"""Tell this branch object to release the physical lock when this
243
object is unlocked, even if it didn't originally acquire it.
245
If lock_write doesn't return a token, then this method is not supported.
247
self.control_files.dont_leave_in_place()
249
def bind(self, other):
250
"""Bind the local branch the other branch.
252
:param other: The branch to bind to
255
raise errors.UpgradeRequired(self.base)
258
def fetch(self, from_branch, last_revision=None, pb=None):
259
"""Copy revisions from from_branch into this branch.
261
:param from_branch: Where to copy from.
262
:param last_revision: What revision to stop at (None for at the end
264
:param pb: An optional progress bar to use.
266
Returns the copied revision count and the failed revisions in a tuple:
269
if self.base == from_branch.base:
272
nested_pb = ui.ui_factory.nested_progress_bar()
277
from_branch.lock_read()
279
if last_revision is None:
280
pb.update('get source history')
281
last_revision = from_branch.last_revision()
282
last_revision = _mod_revision.ensure_null(last_revision)
283
return self.repository.fetch(from_branch.repository,
284
revision_id=last_revision,
287
if nested_pb is not None:
291
def get_bound_location(self):
292
"""Return the URL of the branch we are bound to.
294
Older format branches cannot bind, please be sure to use a metadir
299
def get_old_bound_location(self):
300
"""Return the URL of the branch we used to be bound to
302
raise errors.UpgradeRequired(self.base)
304
def get_commit_builder(self, parents, config=None, timestamp=None,
305
timezone=None, committer=None, revprops=None,
307
"""Obtain a CommitBuilder for this branch.
309
:param parents: Revision ids of the parents of the new revision.
310
:param config: Optional configuration to use.
311
:param timestamp: Optional timestamp recorded for commit.
312
:param timezone: Optional timezone for timestamp.
313
:param committer: Optional committer to set for commit.
314
:param revprops: Optional dictionary of revision properties.
315
:param revision_id: Optional revision id.
319
config = self.get_config()
321
return self.repository.get_commit_builder(self, parents, config,
322
timestamp, timezone, committer, revprops, revision_id)
324
def get_master_branch(self, possible_transports=None):
325
"""Return the branch we are bound to.
327
:return: Either a Branch, or None
331
def get_revision_delta(self, revno):
332
"""Return the delta for one revision.
334
The delta is relative to its mainline predecessor, or the
335
empty tree for revision 1.
337
rh = self.revision_history()
338
if not (1 <= revno <= len(rh)):
339
raise errors.InvalidRevisionNumber(revno)
340
return self.repository.get_revision_delta(rh[revno-1])
342
def get_stacked_on_url(self):
343
"""Get the URL this branch is stacked against.
345
:raises NotStacked: If the branch is not stacked.
346
:raises UnstackableBranchFormat: If the branch does not support
349
raise NotImplementedError(self.get_stacked_on_url)
351
def print_file(self, file, revision_id):
352
"""Print `file` to stdout."""
353
raise NotImplementedError(self.print_file)
355
def set_revision_history(self, rev_history):
356
raise NotImplementedError(self.set_revision_history)
358
def set_stacked_on_url(self, url):
359
"""Set the URL this branch is stacked against.
361
:raises UnstackableBranchFormat: If the branch does not support
363
:raises UnstackableRepositoryFormat: If the repository does not support
366
raise NotImplementedError(self.set_stacked_on_url)
368
def _cache_revision_history(self, rev_history):
369
"""Set the cached revision history to rev_history.
371
The revision_history method will use this cache to avoid regenerating
372
the revision history.
374
This API is semi-public; it only for use by subclasses, all other code
375
should consider it to be private.
377
self._revision_history_cache = rev_history
379
def _cache_revision_id_to_revno(self, revision_id_to_revno):
380
"""Set the cached revision_id => revno map to revision_id_to_revno.
382
This API is semi-public; it only for use by subclasses, all other code
383
should consider it to be private.
385
self._revision_id_to_revno_cache = revision_id_to_revno
387
def _clear_cached_state(self):
388
"""Clear any cached data on this branch, e.g. cached revision history.
390
This means the next call to revision_history will need to call
391
_gen_revision_history.
393
This API is semi-public; it only for use by subclasses, all other code
394
should consider it to be private.
396
self._revision_history_cache = None
397
self._revision_id_to_revno_cache = None
398
self._last_revision_info_cache = None
400
def _gen_revision_history(self):
401
"""Return sequence of revision hashes on to this branch.
403
Unlike revision_history, this method always regenerates or rereads the
404
revision history, i.e. it does not cache the result, so repeated calls
407
Concrete subclasses should override this instead of revision_history so
408
that subclasses do not need to deal with caching logic.
410
This API is semi-public; it only for use by subclasses, all other code
411
should consider it to be private.
413
raise NotImplementedError(self._gen_revision_history)
416
def revision_history(self):
417
"""Return sequence of revision ids on this branch.
419
This method will cache the revision history for as long as it is safe to
422
if 'evil' in debug.debug_flags:
423
mutter_callsite(3, "revision_history scales with history.")
424
if self._revision_history_cache is not None:
425
history = self._revision_history_cache
427
history = self._gen_revision_history()
428
self._cache_revision_history(history)
432
"""Return current revision number for this branch.
434
That is equivalent to the number of revisions committed to
437
return self.last_revision_info()[0]
440
"""Older format branches cannot bind or unbind."""
441
raise errors.UpgradeRequired(self.base)
443
def set_append_revisions_only(self, enabled):
444
"""Older format branches are never restricted to append-only"""
445
raise errors.UpgradeRequired(self.base)
447
def last_revision(self):
448
"""Return last revision id, or NULL_REVISION."""
449
return self.last_revision_info()[1]
452
def last_revision_info(self):
453
"""Return information about the last revision.
455
:return: A tuple (revno, revision_id).
457
if self._last_revision_info_cache is None:
458
self._last_revision_info_cache = self._last_revision_info()
459
return self._last_revision_info_cache
461
def _last_revision_info(self):
462
rh = self.revision_history()
465
return (revno, rh[-1])
467
return (0, _mod_revision.NULL_REVISION)
469
@deprecated_method(deprecated_in((1, 6, 0)))
470
def missing_revisions(self, other, stop_revision=None):
471
"""Return a list of new revisions that would perfectly fit.
473
If self and other have not diverged, return a list of the revisions
474
present in other, but missing from self.
476
self_history = self.revision_history()
477
self_len = len(self_history)
478
other_history = other.revision_history()
479
other_len = len(other_history)
480
common_index = min(self_len, other_len) -1
481
if common_index >= 0 and \
482
self_history[common_index] != other_history[common_index]:
483
raise errors.DivergedBranches(self, other)
485
if stop_revision is None:
486
stop_revision = other_len
488
if stop_revision > other_len:
489
raise errors.NoSuchRevision(self, stop_revision)
490
return other_history[self_len:stop_revision]
493
def update_revisions(self, other, stop_revision=None, overwrite=False,
495
"""Pull in new perfect-fit revisions.
497
:param other: Another Branch to pull from
498
:param stop_revision: Updated until the given revision
499
:param overwrite: Always set the branch pointer, rather than checking
500
to see if it is a proper descendant.
501
:param graph: A Graph object that can be used to query history
502
information. This can be None.
507
other_revno, other_last_revision = other.last_revision_info()
508
stop_revno = None # unknown
509
if stop_revision is None:
510
stop_revision = other_last_revision
511
if _mod_revision.is_null(stop_revision):
512
# if there are no commits, we're done.
514
stop_revno = other_revno
516
# what's the current last revision, before we fetch [and change it
518
last_rev = _mod_revision.ensure_null(self.last_revision())
519
# we fetch here so that we don't process data twice in the common
520
# case of having something to pull, and so that the check for
521
# already merged can operate on the just fetched graph, which will
522
# be cached in memory.
523
self.fetch(other, stop_revision)
524
# Check to see if one is an ancestor of the other
527
graph = self.repository.get_graph()
528
if self._check_if_descendant_or_diverged(
529
stop_revision, last_rev, graph, other):
530
# stop_revision is a descendant of last_rev, but we aren't
531
# overwriting, so we're done.
533
if stop_revno is None:
535
graph = self.repository.get_graph()
536
this_revno, this_last_revision = self.last_revision_info()
537
stop_revno = graph.find_distance_to_null(stop_revision,
538
[(other_last_revision, other_revno),
539
(this_last_revision, this_revno)])
540
self.set_last_revision_info(stop_revno, stop_revision)
544
def revision_id_to_revno(self, revision_id):
545
"""Given a revision id, return its revno"""
546
if _mod_revision.is_null(revision_id):
548
history = self.revision_history()
550
return history.index(revision_id) + 1
552
raise errors.NoSuchRevision(self, revision_id)
554
def get_rev_id(self, revno, history=None):
555
"""Find the revision id of the specified revno."""
557
return _mod_revision.NULL_REVISION
559
history = self.revision_history()
560
if revno <= 0 or revno > len(history):
561
raise errors.NoSuchRevision(self, revno)
562
return history[revno - 1]
564
def pull(self, source, overwrite=False, stop_revision=None,
565
possible_transports=None, _override_hook_target=None):
566
"""Mirror source into this branch.
568
This branch is considered to be 'local', having low latency.
570
:returns: PullResult instance
572
raise NotImplementedError(self.pull)
574
def push(self, target, overwrite=False, stop_revision=None):
575
"""Mirror this branch into target.
577
This branch is considered to be 'local', having low latency.
579
raise NotImplementedError(self.push)
581
def basis_tree(self):
582
"""Return `Tree` object for last revision."""
583
return self.repository.revision_tree(self.last_revision())
585
def get_parent(self):
586
"""Return the parent location of the branch.
588
This is the default location for push/pull/missing. The usual
589
pattern is that the user can override it by specifying a
592
raise NotImplementedError(self.get_parent)
594
def _set_config_location(self, name, url, config=None,
595
make_relative=False):
597
config = self.get_config()
601
url = urlutils.relative_url(self.base, url)
602
config.set_user_option(name, url, warn_masked=True)
604
def _get_config_location(self, name, config=None):
606
config = self.get_config()
607
location = config.get_user_option(name)
612
def get_submit_branch(self):
613
"""Return the submit location of the branch.
615
This is the default location for bundle. The usual
616
pattern is that the user can override it by specifying a
619
return self.get_config().get_user_option('submit_branch')
621
def set_submit_branch(self, location):
622
"""Return the submit location of the branch.
624
This is the default location for bundle. The usual
625
pattern is that the user can override it by specifying a
628
self.get_config().set_user_option('submit_branch', location,
631
def get_public_branch(self):
632
"""Return the public location of the branch.
634
This is is used by merge directives.
636
return self._get_config_location('public_branch')
638
def set_public_branch(self, location):
639
"""Return the submit location of the branch.
641
This is the default location for bundle. The usual
642
pattern is that the user can override it by specifying a
645
self._set_config_location('public_branch', location)
647
def get_push_location(self):
648
"""Return the None or the location to push this branch to."""
649
push_loc = self.get_config().get_user_option('push_location')
652
def set_push_location(self, location):
653
"""Set a new push location for this branch."""
654
raise NotImplementedError(self.set_push_location)
656
def set_parent(self, url):
657
raise NotImplementedError(self.set_parent)
661
"""Synchronise this branch with the master branch if any.
663
:return: None or the last_revision pivoted out during the update.
667
def check_revno(self, revno):
669
Check whether a revno corresponds to any revision.
670
Zero (the NULL revision) is considered valid.
673
self.check_real_revno(revno)
675
def check_real_revno(self, revno):
677
Check whether a revno corresponds to a real revision.
678
Zero (the NULL revision) is considered invalid
680
if revno < 1 or revno > self.revno():
681
raise errors.InvalidRevisionNumber(revno)
684
def clone(self, to_bzrdir, revision_id=None):
685
"""Clone this branch into to_bzrdir preserving all semantic values.
687
revision_id: if not None, the revision history in the new branch will
688
be truncated to end with revision_id.
690
result = to_bzrdir.create_branch()
691
self.copy_content_into(result, revision_id=revision_id)
695
def sprout(self, to_bzrdir, revision_id=None):
696
"""Create a new line of development from the branch, into to_bzrdir.
698
to_bzrdir controls the branch format.
700
revision_id: if not None, the revision history in the new branch will
701
be truncated to end with revision_id.
703
result = to_bzrdir.create_branch()
704
self.copy_content_into(result, revision_id=revision_id)
705
result.set_parent(self.bzrdir.root_transport.base)
708
def _synchronize_history(self, destination, revision_id):
709
"""Synchronize last revision and revision history between branches.
711
This version is most efficient when the destination is also a
712
BzrBranch5, but works for BzrBranch6 as long as the revision
713
history is the true lefthand parent history, and all of the revisions
714
are in the destination's repository. If not, set_revision_history
717
:param destination: The branch to copy the history into
718
:param revision_id: The revision-id to truncate history at. May
719
be None to copy complete history.
721
if revision_id == _mod_revision.NULL_REVISION:
724
new_history = self.revision_history()
725
if revision_id is not None and new_history != []:
727
new_history = new_history[:new_history.index(revision_id) + 1]
729
rev = self.repository.get_revision(revision_id)
730
new_history = rev.get_history(self.repository)[1:]
731
destination.set_revision_history(new_history)
734
def copy_content_into(self, destination, revision_id=None):
735
"""Copy the content of self into destination.
737
revision_id: if not None, the revision history in the new branch will
738
be truncated to end with revision_id.
740
self._synchronize_history(destination, revision_id)
742
parent = self.get_parent()
743
except errors.InaccessibleParent, e:
744
mutter('parent was not accessible to copy: %s', e)
747
destination.set_parent(parent)
748
self.tags.merge_to(destination.tags)
752
"""Check consistency of the branch.
754
In particular this checks that revisions given in the revision-history
755
do actually match up in the revision graph, and that they're all
756
present in the repository.
758
Callers will typically also want to check the repository.
760
:return: A BranchCheckResult.
762
mainline_parent_id = None
763
last_revno, last_revision_id = self.last_revision_info()
764
real_rev_history = list(self.repository.iter_reverse_revision_history(
766
real_rev_history.reverse()
767
if len(real_rev_history) != last_revno:
768
raise errors.BzrCheckError('revno does not match len(mainline)'
769
' %s != %s' % (last_revno, len(real_rev_history)))
770
# TODO: We should probably also check that real_rev_history actually
771
# matches self.revision_history()
772
for revision_id in real_rev_history:
774
revision = self.repository.get_revision(revision_id)
775
except errors.NoSuchRevision, e:
776
raise errors.BzrCheckError("mainline revision {%s} not in repository"
778
# In general the first entry on the revision history has no parents.
779
# But it's not illegal for it to have parents listed; this can happen
780
# in imports from Arch when the parents weren't reachable.
781
if mainline_parent_id is not None:
782
if mainline_parent_id not in revision.parent_ids:
783
raise errors.BzrCheckError("previous revision {%s} not listed among "
785
% (mainline_parent_id, revision_id))
786
mainline_parent_id = revision_id
787
return BranchCheckResult(self)
789
def _get_checkout_format(self):
790
"""Return the most suitable metadir for a checkout of this branch.
791
Weaves are used if this branch's repository uses weaves.
793
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
794
from bzrlib.repofmt import weaverepo
795
format = bzrdir.BzrDirMetaFormat1()
796
format.repository_format = weaverepo.RepositoryFormat7()
798
format = self.repository.bzrdir.checkout_metadir()
799
format.set_branch_format(self._format)
802
def create_checkout(self, to_location, revision_id=None,
803
lightweight=False, accelerator_tree=None,
805
"""Create a checkout of a branch.
807
:param to_location: The url to produce the checkout at
808
:param revision_id: The revision to check out
809
:param lightweight: If True, produce a lightweight checkout, otherwise,
810
produce a bound branch (heavyweight checkout)
811
:param accelerator_tree: A tree which can be used for retrieving file
812
contents more quickly than the revision tree, i.e. a workingtree.
813
The revision tree will be used for cases where accelerator_tree's
814
content is different.
815
:param hardlink: If true, hard-link files from accelerator_tree,
817
:return: The tree of the created checkout
819
t = transport.get_transport(to_location)
822
format = self._get_checkout_format()
823
checkout = format.initialize_on_transport(t)
824
from_branch = BranchReferenceFormat().initialize(checkout, self)
826
format = self._get_checkout_format()
827
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
828
to_location, force_new_tree=False, format=format)
829
checkout = checkout_branch.bzrdir
830
checkout_branch.bind(self)
831
# pull up to the specified revision_id to set the initial
832
# branch tip correctly, and seed it with history.
833
checkout_branch.pull(self, stop_revision=revision_id)
835
tree = checkout.create_workingtree(revision_id,
836
from_branch=from_branch,
837
accelerator_tree=accelerator_tree,
839
basis_tree = tree.basis_tree()
840
basis_tree.lock_read()
842
for path, file_id in basis_tree.iter_references():
843
reference_parent = self.reference_parent(file_id, path)
844
reference_parent.create_checkout(tree.abspath(path),
845
basis_tree.get_reference_revision(file_id, path),
852
def reconcile(self, thorough=True):
853
"""Make sure the data stored in this branch is consistent."""
854
from bzrlib.reconcile import BranchReconciler
855
reconciler = BranchReconciler(self, thorough=thorough)
856
reconciler.reconcile()
859
def reference_parent(self, file_id, path):
860
"""Return the parent branch for a tree-reference file_id
861
:param file_id: The file_id of the tree reference
862
:param path: The path of the file_id in the tree
863
:return: A branch associated with the file_id
865
# FIXME should provide multiple branches, based on config
866
return Branch.open(self.bzrdir.root_transport.clone(path).base)
868
def supports_tags(self):
869
return self._format.supports_tags()
871
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
873
"""Ensure that revision_b is a descendant of revision_a.
875
This is a helper function for update_revisions.
877
:raises: DivergedBranches if revision_b has diverged from revision_a.
878
:returns: True if revision_b is a descendant of revision_a.
880
relation = self._revision_relations(revision_a, revision_b, graph)
881
if relation == 'b_descends_from_a':
883
elif relation == 'diverged':
884
raise errors.DivergedBranches(self, other_branch)
885
elif relation == 'a_descends_from_b':
888
raise AssertionError("invalid relation: %r" % (relation,))
890
def _revision_relations(self, revision_a, revision_b, graph):
891
"""Determine the relationship between two revisions.
893
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
895
heads = graph.heads([revision_a, revision_b])
896
if heads == set([revision_b]):
897
return 'b_descends_from_a'
898
elif heads == set([revision_a, revision_b]):
899
# These branches have diverged
901
elif heads == set([revision_a]):
902
return 'a_descends_from_b'
904
raise AssertionError("invalid heads: %r" % (heads,))
907
class BranchFormat(object):
908
"""An encapsulation of the initialization and open routines for a format.
910
Formats provide three things:
911
* An initialization routine,
915
Formats are placed in an dict by their format string for reference
916
during branch opening. Its not required that these be instances, they
917
can be classes themselves with class methods - it simply depends on
918
whether state is needed for a given format or not.
920
Once a format is deprecated, just deprecate the initialize and open
921
methods on the format class. Do not deprecate the object, as the
922
object will be created every time regardless.
925
_default_format = None
926
"""The default format used for new branches."""
929
"""The known formats."""
931
def __eq__(self, other):
932
return self.__class__ is other.__class__
934
def __ne__(self, other):
935
return not (self == other)
938
def find_format(klass, a_bzrdir):
939
"""Return the format for the branch object in a_bzrdir."""
941
transport = a_bzrdir.get_branch_transport(None)
942
format_string = transport.get("format").read()
943
return klass._formats[format_string]
944
except errors.NoSuchFile:
945
raise errors.NotBranchError(path=transport.base)
947
raise errors.UnknownFormatError(format=format_string, kind='branch')
950
def get_default_format(klass):
951
"""Return the current default format."""
952
return klass._default_format
954
def get_reference(self, a_bzrdir):
955
"""Get the target reference of the branch in a_bzrdir.
957
format probing must have been completed before calling
958
this method - it is assumed that the format of the branch
959
in a_bzrdir is correct.
961
:param a_bzrdir: The bzrdir to get the branch data from.
962
:return: None if the branch is not a reference branch.
967
def set_reference(self, a_bzrdir, to_branch):
968
"""Set the target reference of the branch in a_bzrdir.
970
format probing must have been completed before calling
971
this method - it is assumed that the format of the branch
972
in a_bzrdir is correct.
974
:param a_bzrdir: The bzrdir to set the branch reference for.
975
:param to_branch: branch that the checkout is to reference
977
raise NotImplementedError(self.set_reference)
979
def get_format_string(self):
980
"""Return the ASCII format string that identifies this format."""
981
raise NotImplementedError(self.get_format_string)
983
def get_format_description(self):
984
"""Return the short format description for this format."""
985
raise NotImplementedError(self.get_format_description)
987
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
989
"""Initialize a branch in a bzrdir, with specified files
991
:param a_bzrdir: The bzrdir to initialize the branch in
992
:param utf8_files: The files to create as a list of
993
(filename, content) tuples
994
:param set_format: If True, set the format with
995
self.get_format_string. (BzrBranch4 has its format set
997
:return: a branch in this format
999
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1000
branch_transport = a_bzrdir.get_branch_transport(self)
1002
'metadir': ('lock', lockdir.LockDir),
1003
'branch4': ('branch-lock', lockable_files.TransportLock),
1005
lock_name, lock_class = lock_map[lock_type]
1006
control_files = lockable_files.LockableFiles(branch_transport,
1007
lock_name, lock_class)
1008
control_files.create_lock()
1009
control_files.lock_write()
1011
utf8_files += [('format', self.get_format_string())]
1013
for (filename, content) in utf8_files:
1014
branch_transport.put_bytes(
1016
mode=a_bzrdir._get_file_mode())
1018
control_files.unlock()
1019
return self.open(a_bzrdir, _found=True)
1021
def initialize(self, a_bzrdir):
1022
"""Create a branch of this format in a_bzrdir."""
1023
raise NotImplementedError(self.initialize)
1025
def is_supported(self):
1026
"""Is this format supported?
1028
Supported formats can be initialized and opened.
1029
Unsupported formats may not support initialization or committing or
1030
some other features depending on the reason for not being supported.
1034
def open(self, a_bzrdir, _found=False):
1035
"""Return the branch object for a_bzrdir
1037
_found is a private parameter, do not use it. It is used to indicate
1038
if format probing has already be done.
1040
raise NotImplementedError(self.open)
1043
def register_format(klass, format):
1044
klass._formats[format.get_format_string()] = format
1047
def set_default_format(klass, format):
1048
klass._default_format = format
1050
def supports_stacking(self):
1051
"""True if this format records a stacked-on branch."""
1055
def unregister_format(klass, format):
1056
del klass._formats[format.get_format_string()]
1059
return self.get_format_string().rstrip()
1061
def supports_tags(self):
1062
"""True if this format supports tags stored in the branch"""
1063
return False # by default
1066
class BranchHooks(Hooks):
1067
"""A dictionary mapping hook name to a list of callables for branch hooks.
1069
e.g. ['set_rh'] Is the list of items to be called when the
1070
set_revision_history function is invoked.
1074
"""Create the default hooks.
1076
These are all empty initially, because by default nothing should get
1079
Hooks.__init__(self)
1080
# Introduced in 0.15:
1081
# invoked whenever the revision history has been set
1082
# with set_revision_history. The api signature is
1083
# (branch, revision_history), and the branch will
1086
# Invoked after a branch is opened. The api signature is (branch).
1088
# invoked after a push operation completes.
1089
# the api signature is
1091
# containing the members
1092
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1093
# where local is the local target branch or None, master is the target
1094
# master branch, and the rest should be self explanatory. The source
1095
# is read locked and the target branches write locked. Source will
1096
# be the local low-latency branch.
1097
self['post_push'] = []
1098
# invoked after a pull operation completes.
1099
# the api signature is
1101
# containing the members
1102
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1103
# where local is the local branch or None, master is the target
1104
# master branch, and the rest should be self explanatory. The source
1105
# is read locked and the target branches write locked. The local
1106
# branch is the low-latency branch.
1107
self['post_pull'] = []
1108
# invoked before a commit operation takes place.
1109
# the api signature is
1110
# (local, master, old_revno, old_revid, future_revno, future_revid,
1111
# tree_delta, future_tree).
1112
# old_revid is NULL_REVISION for the first commit to a branch
1113
# tree_delta is a TreeDelta object describing changes from the basis
1114
# revision, hooks MUST NOT modify this delta
1115
# future_tree is an in-memory tree obtained from
1116
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1117
self['pre_commit'] = []
1118
# invoked after a commit operation completes.
1119
# the api signature is
1120
# (local, master, old_revno, old_revid, new_revno, new_revid)
1121
# old_revid is NULL_REVISION for the first commit to a branch.
1122
self['post_commit'] = []
1123
# invoked after a uncommit operation completes.
1124
# the api signature is
1125
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1126
# local is the local branch or None, master is the target branch,
1127
# and an empty branch recieves new_revno of 0, new_revid of None.
1128
self['post_uncommit'] = []
1130
# Invoked before the tip of a branch changes.
1131
# the api signature is
1132
# (params) where params is a ChangeBranchTipParams with the members
1133
# (branch, old_revno, new_revno, old_revid, new_revid)
1134
self['pre_change_branch_tip'] = []
1136
# Invoked after the tip of a branch changes.
1137
# the api signature is
1138
# (params) where params is a ChangeBranchTipParams with the members
1139
# (branch, old_revno, new_revno, old_revid, new_revid)
1140
self['post_change_branch_tip'] = []
1143
# install the default hooks into the Branch class.
1144
Branch.hooks = BranchHooks()
1147
class ChangeBranchTipParams(object):
1148
"""Object holding parameters passed to *_change_branch_tip hooks.
1150
There are 5 fields that hooks may wish to access:
1152
:ivar branch: the branch being changed
1153
:ivar old_revno: revision number before the change
1154
:ivar new_revno: revision number after the change
1155
:ivar old_revid: revision id before the change
1156
:ivar new_revid: revision id after the change
1158
The revid fields are strings. The revno fields are integers.
1161
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1162
"""Create a group of ChangeBranchTip parameters.
1164
:param branch: The branch being changed.
1165
:param old_revno: Revision number before the change.
1166
:param new_revno: Revision number after the change.
1167
:param old_revid: Tip revision id before the change.
1168
:param new_revid: Tip revision id after the change.
1170
self.branch = branch
1171
self.old_revno = old_revno
1172
self.new_revno = new_revno
1173
self.old_revid = old_revid
1174
self.new_revid = new_revid
1176
def __eq__(self, other):
1177
return self.__dict__ == other.__dict__
1180
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1181
self.__class__.__name__, self.branch,
1182
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1185
class BzrBranchFormat4(BranchFormat):
1186
"""Bzr branch format 4.
1189
- a revision-history file.
1190
- a branch-lock lock file [ to be shared with the bzrdir ]
1193
def get_format_description(self):
1194
"""See BranchFormat.get_format_description()."""
1195
return "Branch format 4"
1197
def initialize(self, a_bzrdir):
1198
"""Create a branch of this format in a_bzrdir."""
1199
utf8_files = [('revision-history', ''),
1200
('branch-name', ''),
1202
return self._initialize_helper(a_bzrdir, utf8_files,
1203
lock_type='branch4', set_format=False)
1206
super(BzrBranchFormat4, self).__init__()
1207
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1209
def open(self, a_bzrdir, _found=False):
1210
"""Return the branch object for a_bzrdir
1212
_found is a private parameter, do not use it. It is used to indicate
1213
if format probing has already be done.
1216
# we are being called directly and must probe.
1217
raise NotImplementedError
1218
return BzrBranch(_format=self,
1219
_control_files=a_bzrdir._control_files,
1221
_repository=a_bzrdir.open_repository())
1224
return "Bazaar-NG branch format 4"
1227
class BranchFormatMetadir(BranchFormat):
1228
"""Common logic for meta-dir based branch formats."""
1230
def _branch_class(self):
1231
"""What class to instantiate on open calls."""
1232
raise NotImplementedError(self._branch_class)
1234
def open(self, a_bzrdir, _found=False):
1235
"""Return the branch object for a_bzrdir.
1237
_found is a private parameter, do not use it. It is used to indicate
1238
if format probing has already be done.
1241
format = BranchFormat.find_format(a_bzrdir)
1242
if format.__class__ != self.__class__:
1243
raise AssertionError("wrong format %r found for %r" %
1246
transport = a_bzrdir.get_branch_transport(None)
1247
control_files = lockable_files.LockableFiles(transport, 'lock',
1249
return self._branch_class()(_format=self,
1250
_control_files=control_files,
1252
_repository=a_bzrdir.find_repository())
1253
except errors.NoSuchFile:
1254
raise errors.NotBranchError(path=transport.base)
1257
super(BranchFormatMetadir, self).__init__()
1258
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1260
def supports_tags(self):
1264
class BzrBranchFormat5(BranchFormatMetadir):
1265
"""Bzr branch format 5.
1268
- a revision-history file.
1270
- a lock dir guarding the branch itself
1271
- all of this stored in a branch/ subdirectory
1272
- works with shared repositories.
1274
This format is new in bzr 0.8.
1277
def _branch_class(self):
1280
def get_format_string(self):
1281
"""See BranchFormat.get_format_string()."""
1282
return "Bazaar-NG branch format 5\n"
1284
def get_format_description(self):
1285
"""See BranchFormat.get_format_description()."""
1286
return "Branch format 5"
1288
def initialize(self, a_bzrdir):
1289
"""Create a branch of this format in a_bzrdir."""
1290
utf8_files = [('revision-history', ''),
1291
('branch-name', ''),
1293
return self._initialize_helper(a_bzrdir, utf8_files)
1295
def supports_tags(self):
1299
class BzrBranchFormat6(BranchFormatMetadir):
1300
"""Branch format with last-revision and tags.
1302
Unlike previous formats, this has no explicit revision history. Instead,
1303
this just stores the last-revision, and the left-hand history leading
1304
up to there is the history.
1306
This format was introduced in bzr 0.15
1307
and became the default in 0.91.
1310
def _branch_class(self):
1313
def get_format_string(self):
1314
"""See BranchFormat.get_format_string()."""
1315
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1317
def get_format_description(self):
1318
"""See BranchFormat.get_format_description()."""
1319
return "Branch format 6"
1321
def initialize(self, a_bzrdir):
1322
"""Create a branch of this format in a_bzrdir."""
1323
utf8_files = [('last-revision', '0 null:\n'),
1324
('branch.conf', ''),
1327
return self._initialize_helper(a_bzrdir, utf8_files)
1330
class BzrBranchFormat7(BranchFormatMetadir):
1331
"""Branch format with last-revision, tags, and a stacked location pointer.
1333
The stacked location pointer is passed down to the repository and requires
1334
a repository format with supports_external_lookups = True.
1336
This format was introduced in bzr 1.6.
1339
def _branch_class(self):
1342
def get_format_string(self):
1343
"""See BranchFormat.get_format_string()."""
1344
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
1346
def get_format_description(self):
1347
"""See BranchFormat.get_format_description()."""
1348
return "Branch format 7"
1350
def initialize(self, a_bzrdir):
1351
"""Create a branch of this format in a_bzrdir."""
1352
utf8_files = [('last-revision', '0 null:\n'),
1353
('branch.conf', ''),
1356
return self._initialize_helper(a_bzrdir, utf8_files)
1359
super(BzrBranchFormat7, self).__init__()
1360
self._matchingbzrdir.repository_format = \
1361
RepositoryFormatKnitPack5RichRoot()
1363
def supports_stacking(self):
1367
class BranchReferenceFormat(BranchFormat):
1368
"""Bzr branch reference format.
1370
Branch references are used in implementing checkouts, they
1371
act as an alias to the real branch which is at some other url.
1378
def get_format_string(self):
1379
"""See BranchFormat.get_format_string()."""
1380
return "Bazaar-NG Branch Reference Format 1\n"
1382
def get_format_description(self):
1383
"""See BranchFormat.get_format_description()."""
1384
return "Checkout reference format 1"
1386
def get_reference(self, a_bzrdir):
1387
"""See BranchFormat.get_reference()."""
1388
transport = a_bzrdir.get_branch_transport(None)
1389
return transport.get('location').read()
1391
def set_reference(self, a_bzrdir, to_branch):
1392
"""See BranchFormat.set_reference()."""
1393
transport = a_bzrdir.get_branch_transport(None)
1394
location = transport.put_bytes('location', to_branch.base)
1396
def initialize(self, a_bzrdir, target_branch=None):
1397
"""Create a branch of this format in a_bzrdir."""
1398
if target_branch is None:
1399
# this format does not implement branch itself, thus the implicit
1400
# creation contract must see it as uninitializable
1401
raise errors.UninitializableFormat(self)
1402
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1403
branch_transport = a_bzrdir.get_branch_transport(self)
1404
branch_transport.put_bytes('location',
1405
target_branch.bzrdir.root_transport.base)
1406
branch_transport.put_bytes('format', self.get_format_string())
1408
a_bzrdir, _found=True,
1409
possible_transports=[target_branch.bzrdir.root_transport])
1412
super(BranchReferenceFormat, self).__init__()
1413
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1415
def _make_reference_clone_function(format, a_branch):
1416
"""Create a clone() routine for a branch dynamically."""
1417
def clone(to_bzrdir, revision_id=None):
1418
"""See Branch.clone()."""
1419
return format.initialize(to_bzrdir, a_branch)
1420
# cannot obey revision_id limits when cloning a reference ...
1421
# FIXME RBC 20060210 either nuke revision_id for clone, or
1422
# emit some sort of warning/error to the caller ?!
1425
def open(self, a_bzrdir, _found=False, location=None,
1426
possible_transports=None):
1427
"""Return the branch that the branch reference in a_bzrdir points at.
1429
_found is a private parameter, do not use it. It is used to indicate
1430
if format probing has already be done.
1433
format = BranchFormat.find_format(a_bzrdir)
1434
if format.__class__ != self.__class__:
1435
raise AssertionError("wrong format %r found for %r" %
1437
if location is None:
1438
location = self.get_reference(a_bzrdir)
1439
real_bzrdir = bzrdir.BzrDir.open(
1440
location, possible_transports=possible_transports)
1441
result = real_bzrdir.open_branch()
1442
# this changes the behaviour of result.clone to create a new reference
1443
# rather than a copy of the content of the branch.
1444
# I did not use a proxy object because that needs much more extensive
1445
# testing, and we are only changing one behaviour at the moment.
1446
# If we decide to alter more behaviours - i.e. the implicit nickname
1447
# then this should be refactored to introduce a tested proxy branch
1448
# and a subclass of that for use in overriding clone() and ....
1450
result.clone = self._make_reference_clone_function(result)
1454
# formats which have no format string are not discoverable
1455
# and not independently creatable, so are not registered.
1456
__format5 = BzrBranchFormat5()
1457
__format6 = BzrBranchFormat6()
1458
__format7 = BzrBranchFormat7()
1459
BranchFormat.register_format(__format5)
1460
BranchFormat.register_format(BranchReferenceFormat())
1461
BranchFormat.register_format(__format6)
1462
BranchFormat.register_format(__format7)
1463
BranchFormat.set_default_format(__format6)
1464
_legacy_formats = [BzrBranchFormat4(),
1467
class BzrBranch(Branch):
1468
"""A branch stored in the actual filesystem.
1470
Note that it's "local" in the context of the filesystem; it doesn't
1471
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1472
it's writable, and can be accessed via the normal filesystem API.
1474
:ivar _transport: Transport for file operations on this branch's
1475
control files, typically pointing to the .bzr/branch directory.
1476
:ivar repository: Repository for this branch.
1477
:ivar base: The url of the base directory for this branch; the one
1478
containing the .bzr directory.
1481
def __init__(self, _format=None,
1482
_control_files=None, a_bzrdir=None, _repository=None):
1483
"""Create new branch object at a particular location."""
1484
if a_bzrdir is None:
1485
raise ValueError('a_bzrdir must be supplied')
1487
self.bzrdir = a_bzrdir
1488
self._base = self.bzrdir.transport.clone('..').base
1489
# XXX: We should be able to just do
1490
# self.base = self.bzrdir.root_transport.base
1491
# but this does not quite work yet -- mbp 20080522
1492
self._format = _format
1493
if _control_files is None:
1494
raise ValueError('BzrBranch _control_files is None')
1495
self.control_files = _control_files
1496
self._transport = _control_files._transport
1497
self.repository = _repository
1498
Branch.__init__(self)
1501
return '%s(%r)' % (self.__class__.__name__, self.base)
1505
def _get_base(self):
1506
"""Returns the directory containing the control directory."""
1509
base = property(_get_base, doc="The URL for the root of this branch.")
1511
def is_locked(self):
1512
return self.control_files.is_locked()
1514
def lock_write(self, token=None):
1515
repo_token = self.repository.lock_write()
1517
token = self.control_files.lock_write(token=token)
1519
self.repository.unlock()
1523
def lock_read(self):
1524
self.repository.lock_read()
1526
self.control_files.lock_read()
1528
self.repository.unlock()
1532
# TODO: test for failed two phase locks. This is known broken.
1534
self.control_files.unlock()
1536
self.repository.unlock()
1537
if not self.control_files.is_locked():
1538
# we just released the lock
1539
self._clear_cached_state()
1541
def peek_lock_mode(self):
1542
if self.control_files._lock_count == 0:
1545
return self.control_files._lock_mode
1547
def get_physical_lock_status(self):
1548
return self.control_files.get_physical_lock_status()
1551
def print_file(self, file, revision_id):
1552
"""See Branch.print_file."""
1553
return self.repository.print_file(file, revision_id)
1555
def _write_revision_history(self, history):
1556
"""Factored out of set_revision_history.
1558
This performs the actual writing to disk.
1559
It is intended to be called by BzrBranch5.set_revision_history."""
1560
self._transport.put_bytes(
1561
'revision-history', '\n'.join(history),
1562
mode=self.bzrdir._get_file_mode())
1565
def set_revision_history(self, rev_history):
1566
"""See Branch.set_revision_history."""
1567
if 'evil' in debug.debug_flags:
1568
mutter_callsite(3, "set_revision_history scales with history.")
1569
check_not_reserved_id = _mod_revision.check_not_reserved_id
1570
for rev_id in rev_history:
1571
check_not_reserved_id(rev_id)
1572
if Branch.hooks['post_change_branch_tip']:
1573
# Don't calculate the last_revision_info() if there are no hooks
1575
old_revno, old_revid = self.last_revision_info()
1576
if len(rev_history) == 0:
1577
revid = _mod_revision.NULL_REVISION
1579
revid = rev_history[-1]
1580
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1581
self._write_revision_history(rev_history)
1582
self._clear_cached_state()
1583
self._cache_revision_history(rev_history)
1584
for hook in Branch.hooks['set_rh']:
1585
hook(self, rev_history)
1586
if Branch.hooks['post_change_branch_tip']:
1587
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1589
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1590
"""Run the pre_change_branch_tip hooks."""
1591
hooks = Branch.hooks['pre_change_branch_tip']
1594
old_revno, old_revid = self.last_revision_info()
1595
params = ChangeBranchTipParams(
1596
self, old_revno, new_revno, old_revid, new_revid)
1600
except errors.TipChangeRejected:
1603
exc_info = sys.exc_info()
1604
hook_name = Branch.hooks.get_hook_name(hook)
1605
raise errors.HookFailed(
1606
'pre_change_branch_tip', hook_name, exc_info)
1608
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1609
"""Run the post_change_branch_tip hooks."""
1610
hooks = Branch.hooks['post_change_branch_tip']
1613
new_revno, new_revid = self.last_revision_info()
1614
params = ChangeBranchTipParams(
1615
self, old_revno, new_revno, old_revid, new_revid)
1620
def set_last_revision_info(self, revno, revision_id):
1621
"""Set the last revision of this branch.
1623
The caller is responsible for checking that the revno is correct
1624
for this revision id.
1626
It may be possible to set the branch last revision to an id not
1627
present in the repository. However, branches can also be
1628
configured to check constraints on history, in which case this may not
1631
revision_id = _mod_revision.ensure_null(revision_id)
1632
# this old format stores the full history, but this api doesn't
1633
# provide it, so we must generate, and might as well check it's
1635
history = self._lefthand_history(revision_id)
1636
if len(history) != revno:
1637
raise AssertionError('%d != %d' % (len(history), revno))
1638
self.set_revision_history(history)
1640
def _gen_revision_history(self):
1641
history = self._transport.get_bytes('revision-history').split('\n')
1642
if history[-1:] == ['']:
1643
# There shouldn't be a trailing newline, but just in case.
1647
def _lefthand_history(self, revision_id, last_rev=None,
1649
if 'evil' in debug.debug_flags:
1650
mutter_callsite(4, "_lefthand_history scales with history.")
1651
# stop_revision must be a descendant of last_revision
1652
graph = self.repository.get_graph()
1653
if last_rev is not None:
1654
if not graph.is_ancestor(last_rev, revision_id):
1655
# our previous tip is not merged into stop_revision
1656
raise errors.DivergedBranches(self, other_branch)
1657
# make a new revision history from the graph
1658
parents_map = graph.get_parent_map([revision_id])
1659
if revision_id not in parents_map:
1660
raise errors.NoSuchRevision(self, revision_id)
1661
current_rev_id = revision_id
1663
check_not_reserved_id = _mod_revision.check_not_reserved_id
1664
# Do not include ghosts or graph origin in revision_history
1665
while (current_rev_id in parents_map and
1666
len(parents_map[current_rev_id]) > 0):
1667
check_not_reserved_id(current_rev_id)
1668
new_history.append(current_rev_id)
1669
current_rev_id = parents_map[current_rev_id][0]
1670
parents_map = graph.get_parent_map([current_rev_id])
1671
new_history.reverse()
1675
def generate_revision_history(self, revision_id, last_rev=None,
1677
"""Create a new revision history that will finish with revision_id.
1679
:param revision_id: the new tip to use.
1680
:param last_rev: The previous last_revision. If not None, then this
1681
must be a ancestory of revision_id, or DivergedBranches is raised.
1682
:param other_branch: The other branch that DivergedBranches should
1683
raise with respect to.
1685
self.set_revision_history(self._lefthand_history(revision_id,
1686
last_rev, other_branch))
1688
def basis_tree(self):
1689
"""See Branch.basis_tree."""
1690
return self.repository.revision_tree(self.last_revision())
1693
def pull(self, source, overwrite=False, stop_revision=None,
1694
_hook_master=None, run_hooks=True, possible_transports=None,
1695
_override_hook_target=None):
1698
:param _hook_master: Private parameter - set the branch to
1699
be supplied as the master to pull hooks.
1700
:param run_hooks: Private parameter - if false, this branch
1701
is being called because it's the master of the primary branch,
1702
so it should not run its hooks.
1703
:param _override_hook_target: Private parameter - set the branch to be
1704
supplied as the target_branch to pull hooks.
1706
result = PullResult()
1707
result.source_branch = source
1708
if _override_hook_target is None:
1709
result.target_branch = self
1711
result.target_branch = _override_hook_target
1714
# We assume that during 'pull' the local repository is closer than
1716
graph = self.repository.get_graph(source.repository)
1717
result.old_revno, result.old_revid = self.last_revision_info()
1718
self.update_revisions(source, stop_revision, overwrite=overwrite,
1720
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1721
result.new_revno, result.new_revid = self.last_revision_info()
1723
result.master_branch = _hook_master
1724
result.local_branch = result.target_branch
1726
result.master_branch = result.target_branch
1727
result.local_branch = None
1729
for hook in Branch.hooks['post_pull']:
1735
def _get_parent_location(self):
1736
_locs = ['parent', 'pull', 'x-pull']
1739
return self._transport.get_bytes(l).strip('\n')
1740
except errors.NoSuchFile:
1745
def push(self, target, overwrite=False, stop_revision=None,
1746
_override_hook_source_branch=None):
1749
This is the basic concrete implementation of push()
1751
:param _override_hook_source_branch: If specified, run
1752
the hooks passing this Branch as the source, rather than self.
1753
This is for use of RemoteBranch, where push is delegated to the
1754
underlying vfs-based Branch.
1756
# TODO: Public option to disable running hooks - should be trivial but
1760
result = self._push_with_bound_branches(target, overwrite,
1762
_override_hook_source_branch=_override_hook_source_branch)
1767
def _push_with_bound_branches(self, target, overwrite,
1769
_override_hook_source_branch=None):
1770
"""Push from self into target, and into target's master if any.
1772
This is on the base BzrBranch class even though it doesn't support
1773
bound branches because the *target* might be bound.
1776
if _override_hook_source_branch:
1777
result.source_branch = _override_hook_source_branch
1778
for hook in Branch.hooks['post_push']:
1781
bound_location = target.get_bound_location()
1782
if bound_location and target.base != bound_location:
1783
# there is a master branch.
1785
# XXX: Why the second check? Is it even supported for a branch to
1786
# be bound to itself? -- mbp 20070507
1787
master_branch = target.get_master_branch()
1788
master_branch.lock_write()
1790
# push into the master from this branch.
1791
self._basic_push(master_branch, overwrite, stop_revision)
1792
# and push into the target branch from this. Note that we push from
1793
# this branch again, because its considered the highest bandwidth
1795
result = self._basic_push(target, overwrite, stop_revision)
1796
result.master_branch = master_branch
1797
result.local_branch = target
1801
master_branch.unlock()
1804
result = self._basic_push(target, overwrite, stop_revision)
1805
# TODO: Why set master_branch and local_branch if there's no
1806
# binding? Maybe cleaner to just leave them unset? -- mbp
1808
result.master_branch = target
1809
result.local_branch = None
1813
def _basic_push(self, target, overwrite, stop_revision):
1814
"""Basic implementation of push without bound branches or hooks.
1816
Must be called with self read locked and target write locked.
1818
result = PushResult()
1819
result.source_branch = self
1820
result.target_branch = target
1821
result.old_revno, result.old_revid = target.last_revision_info()
1822
if result.old_revid != self.last_revision():
1823
# We assume that during 'push' this repository is closer than
1825
graph = self.repository.get_graph(target.repository)
1826
target.update_revisions(self, stop_revision, overwrite=overwrite,
1828
if self._push_should_merge_tags():
1829
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
1830
result.new_revno, result.new_revid = target.last_revision_info()
1833
def _push_should_merge_tags(self):
1834
"""Should _basic_push merge this branch's tags into the target?
1836
The default implementation returns False if this branch has no tags,
1837
and True the rest of the time. Subclasses may override this.
1839
return self.tags.supports_tags() and self.tags.get_tag_dict()
1841
def get_parent(self):
1842
"""See Branch.get_parent."""
1843
parent = self._get_parent_location()
1846
# This is an old-format absolute path to a local branch
1847
# turn it into a url
1848
if parent.startswith('/'):
1849
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1851
return urlutils.join(self.base[:-1], parent)
1852
except errors.InvalidURLJoin, e:
1853
raise errors.InaccessibleParent(parent, self.base)
1855
def get_stacked_on_url(self):
1856
raise errors.UnstackableBranchFormat(self._format, self.base)
1858
def set_push_location(self, location):
1859
"""See Branch.set_push_location."""
1860
self.get_config().set_user_option(
1861
'push_location', location,
1862
store=_mod_config.STORE_LOCATION_NORECURSE)
1865
def set_parent(self, url):
1866
"""See Branch.set_parent."""
1867
# TODO: Maybe delete old location files?
1868
# URLs should never be unicode, even on the local fs,
1869
# FIXUP this and get_parent in a future branch format bump:
1870
# read and rewrite the file. RBC 20060125
1872
if isinstance(url, unicode):
1874
url = url.encode('ascii')
1875
except UnicodeEncodeError:
1876
raise errors.InvalidURL(url,
1877
"Urls must be 7-bit ascii, "
1878
"use bzrlib.urlutils.escape")
1879
url = urlutils.relative_url(self.base, url)
1880
self._set_parent_location(url)
1882
def _set_parent_location(self, url):
1884
self._transport.delete('parent')
1886
self._transport.put_bytes('parent', url + '\n',
1887
mode=self.bzrdir._get_file_mode())
1889
def set_stacked_on_url(self, url):
1890
raise errors.UnstackableBranchFormat(self._format, self.base)
1893
class BzrBranch5(BzrBranch):
1894
"""A format 5 branch. This supports new features over plain branches.
1896
It has support for a master_branch which is the data for bound branches.
1900
def pull(self, source, overwrite=False, stop_revision=None,
1901
run_hooks=True, possible_transports=None,
1902
_override_hook_target=None):
1903
"""Pull from source into self, updating my master if any.
1905
:param run_hooks: Private parameter - if false, this branch
1906
is being called because it's the master of the primary branch,
1907
so it should not run its hooks.
1909
bound_location = self.get_bound_location()
1910
master_branch = None
1911
if bound_location and source.base != bound_location:
1912
# not pulling from master, so we need to update master.
1913
master_branch = self.get_master_branch(possible_transports)
1914
master_branch.lock_write()
1917
# pull from source into master.
1918
master_branch.pull(source, overwrite, stop_revision,
1920
return super(BzrBranch5, self).pull(source, overwrite,
1921
stop_revision, _hook_master=master_branch,
1922
run_hooks=run_hooks,
1923
_override_hook_target=_override_hook_target)
1926
master_branch.unlock()
1928
def get_bound_location(self):
1930
return self._transport.get_bytes('bound')[:-1]
1931
except errors.NoSuchFile:
1935
def get_master_branch(self, possible_transports=None):
1936
"""Return the branch we are bound to.
1938
:return: Either a Branch, or None
1940
This could memoise the branch, but if thats done
1941
it must be revalidated on each new lock.
1942
So for now we just don't memoise it.
1943
# RBC 20060304 review this decision.
1945
bound_loc = self.get_bound_location()
1949
return Branch.open(bound_loc,
1950
possible_transports=possible_transports)
1951
except (errors.NotBranchError, errors.ConnectionError), e:
1952
raise errors.BoundBranchConnectionFailure(
1956
def set_bound_location(self, location):
1957
"""Set the target where this branch is bound to.
1959
:param location: URL to the target branch
1962
self._transport.put_bytes('bound', location+'\n',
1963
mode=self.bzrdir._get_file_mode())
1966
self._transport.delete('bound')
1967
except errors.NoSuchFile:
1972
def bind(self, other):
1973
"""Bind this branch to the branch other.
1975
This does not push or pull data between the branches, though it does
1976
check for divergence to raise an error when the branches are not
1977
either the same, or one a prefix of the other. That behaviour may not
1978
be useful, so that check may be removed in future.
1980
:param other: The branch to bind to
1983
# TODO: jam 20051230 Consider checking if the target is bound
1984
# It is debatable whether you should be able to bind to
1985
# a branch which is itself bound.
1986
# Committing is obviously forbidden,
1987
# but binding itself may not be.
1988
# Since we *have* to check at commit time, we don't
1989
# *need* to check here
1991
# we want to raise diverged if:
1992
# last_rev is not in the other_last_rev history, AND
1993
# other_last_rev is not in our history, and do it without pulling
1995
self.set_bound_location(other.base)
1999
"""If bound, unbind"""
2000
return self.set_bound_location(None)
2003
def update(self, possible_transports=None):
2004
"""Synchronise this branch with the master branch if any.
2006
:return: None or the last_revision that was pivoted out during the
2009
master = self.get_master_branch(possible_transports)
2010
if master is not None:
2011
old_tip = _mod_revision.ensure_null(self.last_revision())
2012
self.pull(master, overwrite=True)
2013
if self.repository.get_graph().is_ancestor(old_tip,
2014
_mod_revision.ensure_null(self.last_revision())):
2020
class BzrBranch7(BzrBranch5):
2021
"""A branch with support for a fallback repository."""
2023
def _get_fallback_repository(self, url):
2024
"""Get the repository we fallback to at url."""
2025
url = urlutils.join(self.base, url)
2026
return bzrdir.BzrDir.open(url).open_branch().repository
2028
def _activate_fallback_location(self, url):
2029
"""Activate the branch/repository from url as a fallback repository."""
2030
self.repository.add_fallback_repository(
2031
self._get_fallback_repository(url))
2033
def _open_hook(self):
2035
url = self.get_stacked_on_url()
2036
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2037
errors.UnstackableBranchFormat):
2040
self._activate_fallback_location(url)
2042
def _check_stackable_repo(self):
2043
if not self.repository._format.supports_external_lookups:
2044
raise errors.UnstackableRepositoryFormat(self.repository._format,
2045
self.repository.base)
2047
def __init__(self, *args, **kwargs):
2048
super(BzrBranch7, self).__init__(*args, **kwargs)
2049
self._last_revision_info_cache = None
2050
self._partial_revision_history_cache = []
2052
def _clear_cached_state(self):
2053
super(BzrBranch7, self)._clear_cached_state()
2054
self._last_revision_info_cache = None
2055
self._partial_revision_history_cache = []
2057
def _last_revision_info(self):
2058
revision_string = self._transport.get_bytes('last-revision')
2059
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2060
revision_id = cache_utf8.get_cached_utf8(revision_id)
2062
return revno, revision_id
2064
def _write_last_revision_info(self, revno, revision_id):
2065
"""Simply write out the revision id, with no checks.
2067
Use set_last_revision_info to perform this safely.
2069
Does not update the revision_history cache.
2070
Intended to be called by set_last_revision_info and
2071
_write_revision_history.
2073
revision_id = _mod_revision.ensure_null(revision_id)
2074
out_string = '%d %s\n' % (revno, revision_id)
2075
self._transport.put_bytes('last-revision', out_string,
2076
mode=self.bzrdir._get_file_mode())
2079
def set_last_revision_info(self, revno, revision_id):
2080
revision_id = _mod_revision.ensure_null(revision_id)
2081
old_revno, old_revid = self.last_revision_info()
2082
if self._get_append_revisions_only():
2083
self._check_history_violation(revision_id)
2084
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2085
self._write_last_revision_info(revno, revision_id)
2086
self._clear_cached_state()
2087
self._last_revision_info_cache = revno, revision_id
2088
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2090
def _check_history_violation(self, revision_id):
2091
last_revision = _mod_revision.ensure_null(self.last_revision())
2092
if _mod_revision.is_null(last_revision):
2094
if last_revision not in self._lefthand_history(revision_id):
2095
raise errors.AppendRevisionsOnlyViolation(self.base)
2097
def _gen_revision_history(self):
2098
"""Generate the revision history from last revision
2100
last_revno, last_revision = self.last_revision_info()
2101
self._extend_partial_history(stop_index=last_revno-1)
2102
return list(reversed(self._partial_revision_history_cache))
2104
def _extend_partial_history(self, stop_index=None, stop_revision=None):
2105
"""Extend the partial history to include a given index
2107
If a stop_index is supplied, stop when that index has been reached.
2108
If a stop_revision is supplied, stop when that revision is
2109
encountered. Otherwise, stop when the beginning of history is
2112
:param stop_index: The index which should be present. When it is
2113
present, history extension will stop.
2114
:param revision_id: The revision id which should be present. When
2115
it is encountered, history extension will stop.
2117
repo = self.repository
2118
if len(self._partial_revision_history_cache) == 0:
2119
iterator = repo.iter_reverse_revision_history(self.last_revision())
2121
start_revision = self._partial_revision_history_cache[-1]
2122
iterator = repo.iter_reverse_revision_history(start_revision)
2123
#skip the last revision in the list
2124
next_revision = iterator.next()
2125
for revision_id in iterator:
2126
self._partial_revision_history_cache.append(revision_id)
2127
if (stop_index is not None and
2128
len(self._partial_revision_history_cache) > stop_index):
2130
if revision_id == stop_revision:
2133
def _write_revision_history(self, history):
2134
"""Factored out of set_revision_history.
2136
This performs the actual writing to disk, with format-specific checks.
2137
It is intended to be called by BzrBranch5.set_revision_history.
2139
if len(history) == 0:
2140
last_revision = 'null:'
2142
if history != self._lefthand_history(history[-1]):
2143
raise errors.NotLefthandHistory(history)
2144
last_revision = history[-1]
2145
if self._get_append_revisions_only():
2146
self._check_history_violation(last_revision)
2147
self._write_last_revision_info(len(history), last_revision)
2150
def _set_parent_location(self, url):
2151
"""Set the parent branch"""
2152
self._set_config_location('parent_location', url, make_relative=True)
2155
def _get_parent_location(self):
2156
"""Set the parent branch"""
2157
return self._get_config_location('parent_location')
2159
def set_push_location(self, location):
2160
"""See Branch.set_push_location."""
2161
self._set_config_location('push_location', location)
2163
def set_bound_location(self, location):
2164
"""See Branch.set_push_location."""
2166
config = self.get_config()
2167
if location is None:
2168
if config.get_user_option('bound') != 'True':
2171
config.set_user_option('bound', 'False', warn_masked=True)
2174
self._set_config_location('bound_location', location,
2176
config.set_user_option('bound', 'True', warn_masked=True)
2179
def _get_bound_location(self, bound):
2180
"""Return the bound location in the config file.
2182
Return None if the bound parameter does not match"""
2183
config = self.get_config()
2184
config_bound = (config.get_user_option('bound') == 'True')
2185
if config_bound != bound:
2187
return self._get_config_location('bound_location', config=config)
2189
def get_bound_location(self):
2190
"""See Branch.set_push_location."""
2191
return self._get_bound_location(True)
2193
def get_old_bound_location(self):
2194
"""See Branch.get_old_bound_location"""
2195
return self._get_bound_location(False)
2197
def get_stacked_on_url(self):
2198
# you can always ask for the URL; but you might not be able to use it
2199
# if the repo can't support stacking.
2200
## self._check_stackable_repo()
2201
stacked_url = self._get_config_location('stacked_on_location')
2202
if stacked_url is None:
2203
raise errors.NotStacked(self)
2206
def set_append_revisions_only(self, enabled):
2211
self.get_config().set_user_option('append_revisions_only', value,
2214
def set_stacked_on_url(self, url):
2215
self._check_stackable_repo()
2218
old_url = self.get_stacked_on_url()
2219
except (errors.NotStacked, errors.UnstackableBranchFormat,
2220
errors.UnstackableRepositoryFormat):
2223
# repositories don't offer an interface to remove fallback
2224
# repositories today; take the conceptually simpler option and just
2226
self.repository = self.bzrdir.find_repository()
2227
# for every revision reference the branch has, ensure it is pulled
2229
source_repository = self._get_fallback_repository(old_url)
2230
for revision_id in chain([self.last_revision()],
2231
self.tags.get_reverse_tag_dict()):
2232
self.repository.fetch(source_repository, revision_id,
2235
self._activate_fallback_location(url)
2236
# write this out after the repository is stacked to avoid setting a
2237
# stacked config that doesn't work.
2238
self._set_config_location('stacked_on_location', url)
2240
def _get_append_revisions_only(self):
2241
value = self.get_config().get_user_option('append_revisions_only')
2242
return value == 'True'
2244
def _synchronize_history(self, destination, revision_id):
2245
"""Synchronize last revision and revision history between branches.
2247
This version is most efficient when the destination is also a
2248
BzrBranch6, but works for BzrBranch5, as long as the destination's
2249
repository contains all the lefthand ancestors of the intended
2250
last_revision. If not, set_last_revision_info will fail.
2252
:param destination: The branch to copy the history into
2253
:param revision_id: The revision-id to truncate history at. May
2254
be None to copy complete history.
2256
source_revno, source_revision_id = self.last_revision_info()
2257
if revision_id is None:
2258
revno, revision_id = source_revno, source_revision_id
2259
elif source_revision_id == revision_id:
2260
# we know the revno without needing to walk all of history
2261
revno = source_revno
2263
# To figure out the revno for a random revision, we need to build
2264
# the revision history, and count its length.
2265
# We don't care about the order, just how long it is.
2266
# Alternatively, we could start at the current location, and count
2267
# backwards. But there is no guarantee that we will find it since
2268
# it may be a merged revision.
2269
revno = len(list(self.repository.iter_reverse_revision_history(
2271
destination.set_last_revision_info(revno, revision_id)
2273
def _make_tags(self):
2274
return BasicTags(self)
2277
def generate_revision_history(self, revision_id, last_rev=None,
2279
"""See BzrBranch5.generate_revision_history"""
2280
history = self._lefthand_history(revision_id, last_rev, other_branch)
2281
revno = len(history)
2282
self.set_last_revision_info(revno, revision_id)
2285
def get_rev_id(self, revno, history=None):
2286
"""Find the revision id of the specified revno."""
2288
return _mod_revision.NULL_REVISION
2290
last_revno, last_revision_id = self.last_revision_info()
2291
if revno <= 0 or revno > last_revno:
2292
raise errors.NoSuchRevision(self, revno)
2294
if history is not None:
2295
return history[revno - 1]
2297
index = last_revno - revno
2298
if len(self._partial_revision_history_cache) <= index:
2299
self._extend_partial_history(stop_index=index)
2300
if len(self._partial_revision_history_cache) > index:
2301
return self._partial_revision_history_cache[index]
2303
raise errors.NoSuchRevision(self, revno)
2306
def revision_id_to_revno(self, revision_id):
2307
"""Given a revision id, return its revno"""
2308
if _mod_revision.is_null(revision_id):
2311
index = self._partial_revision_history_cache.index(revision_id)
2313
self._extend_partial_history(stop_revision=revision_id)
2314
index = len(self._partial_revision_history_cache) - 1
2315
if self._partial_revision_history_cache[index] != revision_id:
2316
raise errors.NoSuchRevision(self, revision_id)
2317
return self.revno() - index
2320
class BzrBranch6(BzrBranch7):
2321
"""See BzrBranchFormat6 for the capabilities of this branch.
2323
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2327
def get_stacked_on_url(self):
2328
raise errors.UnstackableBranchFormat(self._format, self.base)
2330
def set_stacked_on_url(self, url):
2331
raise errors.UnstackableBranchFormat(self._format, self.base)
2334
######################################################################
2335
# results of operations
2338
class _Result(object):
2340
def _show_tag_conficts(self, to_file):
2341
if not getattr(self, 'tag_conflicts', None):
2343
to_file.write('Conflicting tags:\n')
2344
for name, value1, value2 in self.tag_conflicts:
2345
to_file.write(' %s\n' % (name, ))
2348
class PullResult(_Result):
2349
"""Result of a Branch.pull operation.
2351
:ivar old_revno: Revision number before pull.
2352
:ivar new_revno: Revision number after pull.
2353
:ivar old_revid: Tip revision id before pull.
2354
:ivar new_revid: Tip revision id after pull.
2355
:ivar source_branch: Source (local) branch object.
2356
:ivar master_branch: Master branch of the target, or the target if no
2358
:ivar local_branch: target branch if there is a Master, else None
2359
:ivar target_branch: Target/destination branch object.
2360
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2364
# DEPRECATED: pull used to return the change in revno
2365
return self.new_revno - self.old_revno
2367
def report(self, to_file):
2369
if self.old_revid == self.new_revid:
2370
to_file.write('No revisions to pull.\n')
2372
to_file.write('Now on revision %d.\n' % self.new_revno)
2373
self._show_tag_conficts(to_file)
2376
class PushResult(_Result):
2377
"""Result of a Branch.push operation.
2379
:ivar old_revno: Revision number before push.
2380
:ivar new_revno: Revision number after push.
2381
:ivar old_revid: Tip revision id before push.
2382
:ivar new_revid: Tip revision id after push.
2383
:ivar source_branch: Source branch object.
2384
:ivar master_branch: Master branch of the target, or None.
2385
:ivar target_branch: Target/destination branch object.
2389
# DEPRECATED: push used to return the change in revno
2390
return self.new_revno - self.old_revno
2392
def report(self, to_file):
2393
"""Write a human-readable description of the result."""
2394
if self.old_revid == self.new_revid:
2395
to_file.write('No new revisions to push.\n')
2397
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2398
self._show_tag_conficts(to_file)
2401
class BranchCheckResult(object):
2402
"""Results of checking branch consistency.
2407
def __init__(self, branch):
2408
self.branch = branch
2410
def report_results(self, verbose):
2411
"""Report the check results via trace.note.
2413
:param verbose: Requests more detailed display of what was checked,
2416
note('checked branch %s format %s',
2418
self.branch._format)
2421
class Converter5to6(object):
2422
"""Perform an in-place upgrade of format 5 to format 6"""
2424
def convert(self, branch):
2425
# Data for 5 and 6 can peacefully coexist.
2426
format = BzrBranchFormat6()
2427
new_branch = format.open(branch.bzrdir, _found=True)
2429
# Copy source data into target
2430
new_branch._write_last_revision_info(*branch.last_revision_info())
2431
new_branch.set_parent(branch.get_parent())
2432
new_branch.set_bound_location(branch.get_bound_location())
2433
new_branch.set_push_location(branch.get_push_location())
2435
# New branch has no tags by default
2436
new_branch.tags._set_tag_dict({})
2438
# Copying done; now update target format
2439
new_branch._transport.put_bytes('format',
2440
format.get_format_string(),
2441
mode=new_branch.bzrdir._get_file_mode())
2443
# Clean up old files
2444
new_branch._transport.delete('revision-history')
2446
branch.set_parent(None)
2447
except errors.NoSuchFile:
2449
branch.set_bound_location(None)
2452
class Converter6to7(object):
2453
"""Perform an in-place upgrade of format 6 to format 7"""
2455
def convert(self, branch):
2456
format = BzrBranchFormat7()
2457
branch._set_config_location('stacked_on_location', '')
2458
# update target format
2459
branch._transport.put_bytes('format', format.get_format_string())