13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18
18
from cStringIO import StringIO
20
20
from bzrlib.lazy_import import lazy_import
21
21
lazy_import(globals(), """
22
from copy import deepcopy
23
from unittest import TestSuite
24
from warnings import warn
23
27
from bzrlib import (
27
30
config as _mod_config,
36
35
revision as _mod_revision,
43
from bzrlib.i18n import gettext, ngettext
41
from bzrlib.config import BranchConfig, TreeConfig
42
from bzrlib.lockable_files import LockableFiles, TransportLock
43
from bzrlib.tag import (
49
from bzrlib.decorators import (
54
from bzrlib.hooks import Hooks
55
from bzrlib.inter import InterObject
56
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
57
from bzrlib import registry
58
from bzrlib.symbol_versioning import (
62
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
65
class Branch(controldir.ControlComponent):
49
from bzrlib.decorators import needs_read_lock, needs_write_lock
50
from bzrlib.errors import (BzrError, BzrCheckError, DivergedBranches,
51
HistoryMissing, InvalidRevisionId,
52
InvalidRevisionNumber, LockError, NoSuchFile,
53
NoSuchRevision, NoWorkingTree, NotVersionedError,
54
NotBranchError, UninitializableFormat,
55
UnlistableStore, UnlistableBranch,
57
from bzrlib.symbol_versioning import (deprecated_function,
61
zero_eight, zero_nine,
63
from bzrlib.trace import mutter, note
66
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
67
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
68
BZR_BRANCH_FORMAT_6 = "Bazaar-NG branch, format 6\n"
71
# TODO: Maybe include checks for common corruption of newlines, etc?
73
# TODO: Some operations like log might retrieve the same revisions
74
# repeatedly to calculate deltas. We could perhaps have a weakref
75
# cache in memory to make this faster. In general anything can be
76
# cached in memory between lock and unlock operations. .. nb thats
77
# what the transaction identity map provides
80
######################################################################
66
84
"""Branch holding a history of revisions.
69
Base directory/url of the branch; using control_url and
70
control_transport is more standardized.
71
:ivar hooks: An instance of BranchHooks.
72
:ivar _master_branch_cache: cached result of get_master_branch, see
87
Base directory/url of the branch.
89
hooks: An instance of BranchHooks.
75
91
# this is really an instance variable - FIXME move it there
80
def control_transport(self):
81
return self._transport
84
def user_transport(self):
85
return self.bzrdir.user_transport
95
# override this to set the strategy for storing tags
97
return DisabledTags(self)
87
99
def __init__(self, *ignored, **ignored_too):
88
self.tags = self._format.make_tags(self)
89
self._revision_history_cache = None
90
self._revision_id_to_revno_cache = None
91
self._partial_revision_id_to_revno_cache = {}
92
self._partial_revision_history_cache = []
93
self._tags_bytes = None
94
self._last_revision_info_cache = None
95
self._master_branch_cache = None
96
self._merge_sorted_revisions_cache = None
98
hooks = Branch.hooks['open']
102
def _open_hook(self):
103
"""Called by init to allow simpler extension of the base class."""
105
def _activate_fallback_location(self, url):
106
"""Activate the branch/repository from url as a fallback repository."""
107
for existing_fallback_repo in self.repository._fallback_repositories:
108
if existing_fallback_repo.user_url == url:
109
# This fallback is already configured. This probably only
110
# happens because BzrDir.sprout is a horrible mess. To avoid
111
# confusing _unstack we don't add this a second time.
112
mutter('duplicate activation of fallback %r on %r', url, self)
114
repo = self._get_fallback_repository(url)
115
if repo.has_same_location(self.repository):
116
raise errors.UnstackableLocationError(self.user_url, url)
117
self.repository.add_fallback_repository(repo)
100
self.tags = self._make_tags()
119
102
def break_lock(self):
120
103
"""Break a lock if one is present from another instance.
130
113
if master is not None:
131
114
master.break_lock()
133
def _check_stackable_repo(self):
134
if not self.repository._format.supports_external_lookups:
135
raise errors.UnstackableRepositoryFormat(self.repository._format,
136
self.repository.base)
138
def _extend_partial_history(self, stop_index=None, stop_revision=None):
139
"""Extend the partial history to include a given index
141
If a stop_index is supplied, stop when that index has been reached.
142
If a stop_revision is supplied, stop when that revision is
143
encountered. Otherwise, stop when the beginning of history is
146
:param stop_index: The index which should be present. When it is
147
present, history extension will stop.
148
:param stop_revision: The revision id which should be present. When
149
it is encountered, history extension will stop.
151
if len(self._partial_revision_history_cache) == 0:
152
self._partial_revision_history_cache = [self.last_revision()]
153
repository._iter_for_revno(
154
self.repository, self._partial_revision_history_cache,
155
stop_index=stop_index, stop_revision=stop_revision)
156
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
157
self._partial_revision_history_cache.pop()
159
def _get_check_refs(self):
160
"""Get the references needed for check().
164
revid = self.last_revision()
165
return [('revision-existence', revid), ('lefthand-distance', revid)]
168
def open(base, _unsupported=False, possible_transports=None):
117
@deprecated_method(zero_eight)
118
def open_downlevel(base):
119
"""Open a branch which may be of an old format."""
120
return Branch.open(base, _unsupported=True)
123
def open(base, _unsupported=False):
169
124
"""Open the branch rooted at base.
171
126
For instance, if the branch is at URL/.bzr/branch,
172
127
Branch.open(URL) -> a Branch instance.
174
control = bzrdir.BzrDir.open(base, _unsupported,
175
possible_transports=possible_transports)
176
return control.open_branch(unsupported=_unsupported)
179
def open_from_transport(transport, name=None, _unsupported=False):
180
"""Open the branch rooted at transport"""
181
control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
182
return control.open_branch(name=name, unsupported=_unsupported)
185
def open_containing(url, possible_transports=None):
129
control = bzrdir.BzrDir.open(base, _unsupported)
130
return control.open_branch(_unsupported)
133
def open_containing(url):
186
134
"""Open an existing branch which contains url.
188
136
This probes for a branch at url, and searches upwards from there.
190
138
Basically we keep looking up until we find the control directory or
191
139
run into the root. If there isn't one, raises NotBranchError.
192
If there is one and it is either an unrecognised format or an unsupported
140
If there is one and it is either an unrecognised format or an unsupported
193
141
format, UnknownFormatError or UnsupportedFormatError are raised.
194
142
If there is one, it is returned, along with the unused portion of url.
196
control, relpath = bzrdir.BzrDir.open_containing(url,
144
control, relpath = bzrdir.BzrDir.open_containing(url)
198
145
return control.open_branch(), relpath
200
def _push_should_merge_tags(self):
201
"""Should _basic_push merge this branch's tags into the target?
203
The default implementation returns False if this branch has no tags,
204
and True the rest of the time. Subclasses may override this.
206
return self.supports_tags() and self.tags.get_tag_dict()
148
@deprecated_function(zero_eight)
149
def initialize(base):
150
"""Create a new working tree and branch, rooted at 'base' (url)
152
NOTE: This will soon be deprecated in favour of creation
155
return bzrdir.BzrDir.create_standalone_workingtree(base).branch
157
@deprecated_function(zero_eight)
158
def setup_caching(self, cache_root):
159
"""Subclasses that care about caching should override this, and set
160
up cached stores located under cache_root.
162
NOTE: This is unused.
208
166
def get_config(self):
209
"""Get a bzrlib.config.BranchConfig for this Branch.
211
This can then be used to get and set configuration options for the
214
:return: A bzrlib.config.BranchConfig.
216
return _mod_config.BranchConfig(self)
218
def get_config_stack(self):
219
"""Get a bzrlib.config.BranchStack for this Branch.
221
This can then be used to get and set configuration options for the
224
:return: A bzrlib.config.BranchStack.
226
return _mod_config.BranchStack(self)
228
def _get_config(self):
229
"""Get the concrete config for just the config in this branch.
231
This is not intended for client use; see Branch.get_config for the
236
:return: An object supporting get_option and set_option.
238
raise NotImplementedError(self._get_config)
240
def _get_fallback_repository(self, url):
241
"""Get the repository we fallback to at url."""
242
url = urlutils.join(self.base, url)
243
a_branch = Branch.open(url,
244
possible_transports=[self.bzrdir.root_transport])
245
return a_branch.repository
248
def _get_tags_bytes(self):
249
"""Get the bytes of a serialised tags dict.
251
Note that not all branches support tags, nor do all use the same tags
252
logic: this method is specific to BasicTags. Other tag implementations
253
may use the same method name and behave differently, safely, because
254
of the double-dispatch via
255
format.make_tags->tags_instance->get_tags_dict.
257
:return: The bytes of the tags file.
258
:seealso: Branch._set_tags_bytes.
260
if self._tags_bytes is None:
261
self._tags_bytes = self._transport.get_bytes('tags')
262
return self._tags_bytes
264
def _get_nick(self, local=False, possible_transports=None):
265
config = self.get_config()
266
# explicit overrides master, but don't look for master if local is True
267
if not local and not config.has_explicit_nickname():
269
master = self.get_master_branch(possible_transports)
270
if master and self.user_url == master.user_url:
271
raise errors.RecursiveBind(self.user_url)
272
if master is not None:
273
# return the master branch value
275
except errors.RecursiveBind, e:
277
except errors.BzrError, e:
278
# Silently fall back to local implicit nick if the master is
280
mutter("Could not connect to bound branch, "
281
"falling back to local nick.\n " + str(e))
282
return config.get_nickname()
167
return BranchConfig(self)
170
return self.get_config().get_nickname()
284
172
def _set_nick(self, nick):
285
self.get_config().set_user_option('nickname', nick, warn_masked=True)
173
self.get_config().set_user_option('nickname', nick)
287
175
nick = property(_get_nick, _set_nick)
289
177
def is_locked(self):
290
178
raise NotImplementedError(self.is_locked)
292
def _lefthand_history(self, revision_id, last_rev=None,
294
if 'evil' in debug.debug_flags:
295
mutter_callsite(4, "_lefthand_history scales with history.")
296
# stop_revision must be a descendant of last_revision
297
graph = self.repository.get_graph()
298
if last_rev is not None:
299
if not graph.is_ancestor(last_rev, revision_id):
300
# our previous tip is not merged into stop_revision
301
raise errors.DivergedBranches(self, other_branch)
302
# make a new revision history from the graph
303
parents_map = graph.get_parent_map([revision_id])
304
if revision_id not in parents_map:
305
raise errors.NoSuchRevision(self, revision_id)
306
current_rev_id = revision_id
308
check_not_reserved_id = _mod_revision.check_not_reserved_id
309
# Do not include ghosts or graph origin in revision_history
310
while (current_rev_id in parents_map and
311
len(parents_map[current_rev_id]) > 0):
312
check_not_reserved_id(current_rev_id)
313
new_history.append(current_rev_id)
314
current_rev_id = parents_map[current_rev_id][0]
315
parents_map = graph.get_parent_map([current_rev_id])
316
new_history.reverse()
319
def lock_write(self, token=None):
320
"""Lock the branch for write operations.
322
:param token: A token to permit reacquiring a previously held and
324
:return: A BranchWriteLockResult.
180
def lock_write(self):
326
181
raise NotImplementedError(self.lock_write)
328
183
def lock_read(self):
329
"""Lock the branch for read operations.
331
:return: A bzrlib.lock.LogicalLockResult.
333
184
raise NotImplementedError(self.lock_read)
335
186
def unlock(self):
342
193
def get_physical_lock_status(self):
343
194
raise NotImplementedError(self.get_physical_lock_status)
346
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
347
"""Return the revision_id for a dotted revno.
349
:param revno: a tuple like (1,) or (1,1,2)
350
:param _cache_reverse: a private parameter enabling storage
351
of the reverse mapping in a top level cache. (This should
352
only be done in selective circumstances as we want to
353
avoid having the mapping cached multiple times.)
354
:return: the revision_id
355
:raises errors.NoSuchRevision: if the revno doesn't exist
357
rev_id = self._do_dotted_revno_to_revision_id(revno)
359
self._partial_revision_id_to_revno_cache[rev_id] = revno
362
def _do_dotted_revno_to_revision_id(self, revno):
363
"""Worker function for dotted_revno_to_revision_id.
365
Subclasses should override this if they wish to
366
provide a more efficient implementation.
369
return self.get_rev_id(revno[0])
370
revision_id_to_revno = self.get_revision_id_to_revno_map()
371
revision_ids = [revision_id for revision_id, this_revno
372
in revision_id_to_revno.iteritems()
373
if revno == this_revno]
374
if len(revision_ids) == 1:
375
return revision_ids[0]
377
revno_str = '.'.join(map(str, revno))
378
raise errors.NoSuchRevision(self, revno_str)
381
def revision_id_to_dotted_revno(self, revision_id):
382
"""Given a revision id, return its dotted revno.
384
:return: a tuple like (1,) or (400,1,3).
386
return self._do_revision_id_to_dotted_revno(revision_id)
388
def _do_revision_id_to_dotted_revno(self, revision_id):
389
"""Worker function for revision_id_to_revno."""
390
# Try the caches if they are loaded
391
result = self._partial_revision_id_to_revno_cache.get(revision_id)
392
if result is not None:
394
if self._revision_id_to_revno_cache:
395
result = self._revision_id_to_revno_cache.get(revision_id)
397
raise errors.NoSuchRevision(self, revision_id)
398
# Try the mainline as it's optimised
400
revno = self.revision_id_to_revno(revision_id)
402
except errors.NoSuchRevision:
403
# We need to load and use the full revno map after all
404
result = self.get_revision_id_to_revno_map().get(revision_id)
406
raise errors.NoSuchRevision(self, revision_id)
410
def get_revision_id_to_revno_map(self):
411
"""Return the revision_id => dotted revno map.
413
This will be regenerated on demand, but will be cached.
415
:return: A dictionary mapping revision_id => dotted revno.
416
This dictionary should not be modified by the caller.
418
if self._revision_id_to_revno_cache is not None:
419
mapping = self._revision_id_to_revno_cache
421
mapping = self._gen_revno_map()
422
self._cache_revision_id_to_revno(mapping)
423
# TODO: jam 20070417 Since this is being cached, should we be returning
425
# I would rather not, and instead just declare that users should not
426
# modify the return value.
429
def _gen_revno_map(self):
430
"""Create a new mapping from revision ids to dotted revnos.
432
Dotted revnos are generated based on the current tip in the revision
434
This is the worker function for get_revision_id_to_revno_map, which
435
just caches the return value.
437
:return: A dictionary mapping revision_id => dotted revno.
439
revision_id_to_revno = dict((rev_id, revno)
440
for rev_id, depth, revno, end_of_merge
441
in self.iter_merge_sorted_revisions())
442
return revision_id_to_revno
445
def iter_merge_sorted_revisions(self, start_revision_id=None,
446
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
447
"""Walk the revisions for a branch in merge sorted order.
449
Merge sorted order is the output from a merge-aware,
450
topological sort, i.e. all parents come before their
451
children going forward; the opposite for reverse.
453
:param start_revision_id: the revision_id to begin walking from.
454
If None, the branch tip is used.
455
:param stop_revision_id: the revision_id to terminate the walk
456
after. If None, the rest of history is included.
457
:param stop_rule: if stop_revision_id is not None, the precise rule
458
to use for termination:
460
* 'exclude' - leave the stop revision out of the result (default)
461
* 'include' - the stop revision is the last item in the result
462
* 'with-merges' - include the stop revision and all of its
463
merged revisions in the result
464
* 'with-merges-without-common-ancestry' - filter out revisions
465
that are in both ancestries
466
:param direction: either 'reverse' or 'forward':
468
* reverse means return the start_revision_id first, i.e.
469
start at the most recent revision and go backwards in history
470
* forward returns tuples in the opposite order to reverse.
471
Note in particular that forward does *not* do any intelligent
472
ordering w.r.t. depth as some clients of this API may like.
473
(If required, that ought to be done at higher layers.)
475
:return: an iterator over (revision_id, depth, revno, end_of_merge)
478
* revision_id: the unique id of the revision
479
* depth: How many levels of merging deep this node has been
481
* revno_sequence: This field provides a sequence of
482
revision numbers for all revisions. The format is:
483
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
484
branch that the revno is on. From left to right the REVNO numbers
485
are the sequence numbers within that branch of the revision.
486
* end_of_merge: When True the next node (earlier in history) is
487
part of a different merge.
489
# Note: depth and revno values are in the context of the branch so
490
# we need the full graph to get stable numbers, regardless of the
492
if self._merge_sorted_revisions_cache is None:
493
last_revision = self.last_revision()
494
known_graph = self.repository.get_known_graph_ancestry(
496
self._merge_sorted_revisions_cache = known_graph.merge_sort(
498
filtered = self._filter_merge_sorted_revisions(
499
self._merge_sorted_revisions_cache, start_revision_id,
500
stop_revision_id, stop_rule)
501
# Make sure we don't return revisions that are not part of the
502
# start_revision_id ancestry.
503
filtered = self._filter_start_non_ancestors(filtered)
504
if direction == 'reverse':
506
if direction == 'forward':
507
return reversed(list(filtered))
509
raise ValueError('invalid direction %r' % direction)
511
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
512
start_revision_id, stop_revision_id, stop_rule):
513
"""Iterate over an inclusive range of sorted revisions."""
514
rev_iter = iter(merge_sorted_revisions)
515
if start_revision_id is not None:
516
for node in rev_iter:
518
if rev_id != start_revision_id:
521
# The decision to include the start or not
522
# depends on the stop_rule if a stop is provided
523
# so pop this node back into the iterator
524
rev_iter = itertools.chain(iter([node]), rev_iter)
526
if stop_revision_id is None:
528
for node in rev_iter:
530
yield (rev_id, node.merge_depth, node.revno,
532
elif stop_rule == 'exclude':
533
for node in rev_iter:
535
if rev_id == stop_revision_id:
537
yield (rev_id, node.merge_depth, node.revno,
539
elif stop_rule == 'include':
540
for node in rev_iter:
542
yield (rev_id, node.merge_depth, node.revno,
544
if rev_id == stop_revision_id:
546
elif stop_rule == 'with-merges-without-common-ancestry':
547
# We want to exclude all revisions that are already part of the
548
# stop_revision_id ancestry.
549
graph = self.repository.get_graph()
550
ancestors = graph.find_unique_ancestors(start_revision_id,
552
for node in rev_iter:
554
if rev_id not in ancestors:
556
yield (rev_id, node.merge_depth, node.revno,
558
elif stop_rule == 'with-merges':
559
stop_rev = self.repository.get_revision(stop_revision_id)
560
if stop_rev.parent_ids:
561
left_parent = stop_rev.parent_ids[0]
563
left_parent = _mod_revision.NULL_REVISION
564
# left_parent is the actual revision we want to stop logging at,
565
# since we want to show the merged revisions after the stop_rev too
566
reached_stop_revision_id = False
567
revision_id_whitelist = []
568
for node in rev_iter:
570
if rev_id == left_parent:
571
# reached the left parent after the stop_revision
573
if (not reached_stop_revision_id or
574
rev_id in revision_id_whitelist):
575
yield (rev_id, node.merge_depth, node.revno,
577
if reached_stop_revision_id or rev_id == stop_revision_id:
578
# only do the merged revs of rev_id from now on
579
rev = self.repository.get_revision(rev_id)
581
reached_stop_revision_id = True
582
revision_id_whitelist.extend(rev.parent_ids)
584
raise ValueError('invalid stop_rule %r' % stop_rule)
586
def _filter_start_non_ancestors(self, rev_iter):
587
# If we started from a dotted revno, we want to consider it as a tip
588
# and don't want to yield revisions that are not part of its
589
# ancestry. Given the order guaranteed by the merge sort, we will see
590
# uninteresting descendants of the first parent of our tip before the
592
first = rev_iter.next()
593
(rev_id, merge_depth, revno, end_of_merge) = first
596
# We start at a mainline revision so by definition, all others
597
# revisions in rev_iter are ancestors
598
for node in rev_iter:
603
pmap = self.repository.get_parent_map([rev_id])
604
parents = pmap.get(rev_id, [])
606
whitelist.update(parents)
608
# If there is no parents, there is nothing of interest left
610
# FIXME: It's hard to test this scenario here as this code is never
611
# called in that case. -- vila 20100322
614
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
616
if rev_id in whitelist:
617
pmap = self.repository.get_parent_map([rev_id])
618
parents = pmap.get(rev_id, [])
619
whitelist.remove(rev_id)
620
whitelist.update(parents)
622
# We've reached the mainline, there is nothing left to
626
# A revision that is not part of the ancestry of our
629
yield (rev_id, merge_depth, revno, end_of_merge)
631
def leave_lock_in_place(self):
632
"""Tell this branch object not to release the physical lock when this
635
If lock_write doesn't return a token, then this method is not supported.
637
self.control_files.leave_in_place()
639
def dont_leave_lock_in_place(self):
640
"""Tell this branch object to release the physical lock when this
641
object is unlocked, even if it didn't originally acquire it.
643
If lock_write doesn't return a token, then this method is not supported.
645
self.control_files.dont_leave_in_place()
196
def abspath(self, name):
197
"""Return absolute filename for something in the branch
199
XXX: Robert Collins 20051017 what is this used for? why is it a branch
200
method and not a tree method.
202
raise NotImplementedError(self.abspath)
647
204
def bind(self, other):
648
205
"""Bind the local branch the other branch.
739
290
The delta is relative to its mainline predecessor, or the
740
291
empty tree for revision 1.
293
assert isinstance(revno, int)
742
294
rh = self.revision_history()
743
295
if not (1 <= revno <= len(rh)):
744
raise errors.InvalidRevisionNumber(revno)
296
raise InvalidRevisionNumber(revno)
745
297
return self.repository.get_revision_delta(rh[revno-1])
747
def get_stacked_on_url(self):
748
"""Get the URL this branch is stacked against.
750
:raises NotStacked: If the branch is not stacked.
751
:raises UnstackableBranchFormat: If the branch does not support
754
raise NotImplementedError(self.get_stacked_on_url)
299
def get_root_id(self):
300
"""Return the id of this branches root"""
301
raise NotImplementedError(self.get_root_id)
756
303
def print_file(self, file, revision_id):
757
304
"""Print `file` to stdout."""
758
305
raise NotImplementedError(self.print_file)
760
@deprecated_method(deprecated_in((2, 4, 0)))
307
def append_revision(self, *revision_ids):
308
raise NotImplementedError(self.append_revision)
761
310
def set_revision_history(self, rev_history):
762
"""See Branch.set_revision_history."""
763
self._set_revision_history(rev_history)
766
def _set_revision_history(self, rev_history):
767
if len(rev_history) == 0:
768
revid = _mod_revision.NULL_REVISION
770
revid = rev_history[-1]
771
if rev_history != self._lefthand_history(revid):
772
raise errors.NotLefthandHistory(rev_history)
773
self.set_last_revision_info(len(rev_history), revid)
774
self._cache_revision_history(rev_history)
775
for hook in Branch.hooks['set_rh']:
776
hook(self, rev_history)
779
def set_last_revision_info(self, revno, revision_id):
780
"""Set the last revision of this branch.
782
The caller is responsible for checking that the revno is correct
783
for this revision id.
785
It may be possible to set the branch last revision to an id not
786
present in the repository. However, branches can also be
787
configured to check constraints on history, in which case this may not
790
raise NotImplementedError(self.set_last_revision_info)
793
def generate_revision_history(self, revision_id, last_rev=None,
795
"""See Branch.generate_revision_history"""
796
graph = self.repository.get_graph()
797
(last_revno, last_revid) = self.last_revision_info()
798
known_revision_ids = [
799
(last_revid, last_revno),
800
(_mod_revision.NULL_REVISION, 0),
802
if last_rev is not None:
803
if not graph.is_ancestor(last_rev, revision_id):
804
# our previous tip is not merged into stop_revision
805
raise errors.DivergedBranches(self, other_branch)
806
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
807
self.set_last_revision_info(revno, revision_id)
810
def set_parent(self, url):
811
"""See Branch.set_parent."""
812
# TODO: Maybe delete old location files?
813
# URLs should never be unicode, even on the local fs,
814
# FIXUP this and get_parent in a future branch format bump:
815
# read and rewrite the file. RBC 20060125
817
if isinstance(url, unicode):
819
url = url.encode('ascii')
820
except UnicodeEncodeError:
821
raise errors.InvalidURL(url,
822
"Urls must be 7-bit ascii, "
823
"use bzrlib.urlutils.escape")
824
url = urlutils.relative_url(self.base, url)
825
self._set_parent_location(url)
828
def set_stacked_on_url(self, url):
829
"""Set the URL this branch is stacked against.
831
:raises UnstackableBranchFormat: If the branch does not support
833
:raises UnstackableRepositoryFormat: If the repository does not support
836
if not self._format.supports_stacking():
837
raise errors.UnstackableBranchFormat(self._format, self.user_url)
838
# XXX: Changing from one fallback repository to another does not check
839
# that all the data you need is present in the new fallback.
840
# Possibly it should.
841
self._check_stackable_repo()
844
old_url = self.get_stacked_on_url()
845
except (errors.NotStacked, errors.UnstackableBranchFormat,
846
errors.UnstackableRepositoryFormat):
850
self._activate_fallback_location(url)
851
# write this out after the repository is stacked to avoid setting a
852
# stacked config that doesn't work.
853
self._set_config_location('stacked_on_location', url)
856
"""Change a branch to be unstacked, copying data as needed.
858
Don't call this directly, use set_stacked_on_url(None).
860
pb = ui.ui_factory.nested_progress_bar()
862
pb.update(gettext("Unstacking"))
863
# The basic approach here is to fetch the tip of the branch,
864
# including all available ghosts, from the existing stacked
865
# repository into a new repository object without the fallbacks.
867
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
868
# correct for CHKMap repostiories
869
old_repository = self.repository
870
if len(old_repository._fallback_repositories) != 1:
871
raise AssertionError("can't cope with fallback repositories "
872
"of %r (fallbacks: %r)" % (old_repository,
873
old_repository._fallback_repositories))
874
# Open the new repository object.
875
# Repositories don't offer an interface to remove fallback
876
# repositories today; take the conceptually simpler option and just
877
# reopen it. We reopen it starting from the URL so that we
878
# get a separate connection for RemoteRepositories and can
879
# stream from one of them to the other. This does mean doing
880
# separate SSH connection setup, but unstacking is not a
881
# common operation so it's tolerable.
882
new_bzrdir = bzrdir.BzrDir.open(self.bzrdir.root_transport.base)
883
new_repository = new_bzrdir.find_repository()
884
if new_repository._fallback_repositories:
885
raise AssertionError("didn't expect %r to have "
886
"fallback_repositories"
887
% (self.repository,))
888
# Replace self.repository with the new repository.
889
# Do our best to transfer the lock state (i.e. lock-tokens and
890
# lock count) of self.repository to the new repository.
891
lock_token = old_repository.lock_write().repository_token
892
self.repository = new_repository
893
if isinstance(self, remote.RemoteBranch):
894
# Remote branches can have a second reference to the old
895
# repository that need to be replaced.
896
if self._real_branch is not None:
897
self._real_branch.repository = new_repository
898
self.repository.lock_write(token=lock_token)
899
if lock_token is not None:
900
old_repository.leave_lock_in_place()
901
old_repository.unlock()
902
if lock_token is not None:
903
# XXX: self.repository.leave_lock_in_place() before this
904
# function will not be preserved. Fortunately that doesn't
905
# affect the current default format (2a), and would be a
906
# corner-case anyway.
907
# - Andrew Bennetts, 2010/06/30
908
self.repository.dont_leave_lock_in_place()
912
old_repository.unlock()
913
except errors.LockNotHeld:
916
if old_lock_count == 0:
917
raise AssertionError(
918
'old_repository should have been locked at least once.')
919
for i in range(old_lock_count-1):
920
self.repository.lock_write()
921
# Fetch from the old repository into the new.
922
old_repository.lock_read()
924
# XXX: If you unstack a branch while it has a working tree
925
# with a pending merge, the pending-merged revisions will no
926
# longer be present. You can (probably) revert and remerge.
928
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
929
except errors.TagsNotSupported:
930
tags_to_fetch = set()
931
fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
932
old_repository, required_ids=[self.last_revision()],
933
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
934
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
936
old_repository.unlock()
940
def _set_tags_bytes(self, bytes):
941
"""Mirror method for _get_tags_bytes.
943
:seealso: Branch._get_tags_bytes.
945
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
946
op.add_cleanup(self.lock_write().unlock)
947
return op.run_simple(bytes)
949
def _set_tags_bytes_locked(self, bytes):
950
self._tags_bytes = bytes
951
return self._transport.put_bytes('tags', bytes)
953
def _cache_revision_history(self, rev_history):
954
"""Set the cached revision history to rev_history.
956
The revision_history method will use this cache to avoid regenerating
957
the revision history.
959
This API is semi-public; it only for use by subclasses, all other code
960
should consider it to be private.
962
self._revision_history_cache = rev_history
964
def _cache_revision_id_to_revno(self, revision_id_to_revno):
965
"""Set the cached revision_id => revno map to revision_id_to_revno.
967
This API is semi-public; it only for use by subclasses, all other code
968
should consider it to be private.
970
self._revision_id_to_revno_cache = revision_id_to_revno
972
def _clear_cached_state(self):
973
"""Clear any cached data on this branch, e.g. cached revision history.
975
This means the next call to revision_history will need to call
976
_gen_revision_history.
978
This API is semi-public; it only for use by subclasses, all other code
979
should consider it to be private.
981
self._revision_history_cache = None
982
self._revision_id_to_revno_cache = None
983
self._last_revision_info_cache = None
984
self._master_branch_cache = None
985
self._merge_sorted_revisions_cache = None
986
self._partial_revision_history_cache = []
987
self._partial_revision_id_to_revno_cache = {}
988
self._tags_bytes = None
990
def _gen_revision_history(self):
991
"""Return sequence of revision hashes on to this branch.
993
Unlike revision_history, this method always regenerates or rereads the
994
revision history, i.e. it does not cache the result, so repeated calls
997
Concrete subclasses should override this instead of revision_history so
998
that subclasses do not need to deal with caching logic.
1000
This API is semi-public; it only for use by subclasses, all other code
1001
should consider it to be private.
1003
raise NotImplementedError(self._gen_revision_history)
311
raise NotImplementedError(self.set_revision_history)
1006
313
def revision_history(self):
1007
"""Return sequence of revision ids on this branch.
1009
This method will cache the revision history for as long as it is safe to
1012
if 'evil' in debug.debug_flags:
1013
mutter_callsite(3, "revision_history scales with history.")
1014
if self._revision_history_cache is not None:
1015
history = self._revision_history_cache
1017
history = self._gen_revision_history()
1018
self._cache_revision_history(history)
1019
return list(history)
314
"""Return sequence of revision hashes on to this branch."""
315
raise NotImplementedError(self.revision_history)
1021
317
def revno(self):
1022
318
"""Return current revision number for this branch.
1024
320
That is equivalent to the number of revisions committed to
1027
return self.last_revision_info()[0]
323
return len(self.revision_history())
1029
325
def unbind(self):
1030
326
"""Older format branches cannot bind or unbind."""
1031
raise errors.UpgradeRequired(self.user_url)
327
raise errors.UpgradeRequired(self.base)
329
def set_append_revisions_only(self, enabled):
330
"""Older format branches are never restricted to append-only"""
331
raise errors.UpgradeRequired(self.base)
1033
333
def last_revision(self):
1034
"""Return last revision id, or NULL_REVISION."""
1035
return self.last_revision_info()[1]
334
"""Return last revision id, or None"""
335
ph = self.revision_history()
1038
341
def last_revision_info(self):
1039
342
"""Return information about the last revision.
1041
:return: A tuple (revno, revision_id).
1043
if self._last_revision_info_cache is None:
1044
self._last_revision_info_cache = self._read_last_revision_info()
1045
return self._last_revision_info_cache
1047
def _read_last_revision_info(self):
1048
raise NotImplementedError(self._read_last_revision_info)
1050
@deprecated_method(deprecated_in((2, 4, 0)))
1051
def import_last_revision_info(self, source_repo, revno, revid):
1052
"""Set the last revision info, importing from another repo if necessary.
1054
:param source_repo: Source repository to optionally fetch from
1055
:param revno: Revision number of the new tip
1056
:param revid: Revision id of the new tip
1058
if not self.repository.has_same_location(source_repo):
1059
self.repository.fetch(source_repo, revision_id=revid)
1060
self.set_last_revision_info(revno, revid)
1062
def import_last_revision_info_and_tags(self, source, revno, revid,
1064
"""Set the last revision info, importing from another repo if necessary.
1066
This is used by the bound branch code to upload a revision to
1067
the master branch first before updating the tip of the local branch.
1068
Revisions referenced by source's tags are also transferred.
1070
:param source: Source branch to optionally fetch from
1071
:param revno: Revision number of the new tip
1072
:param revid: Revision id of the new tip
1073
:param lossy: Whether to discard metadata that can not be
1074
natively represented
1075
:return: Tuple with the new revision number and revision id
1076
(should only be different from the arguments when lossy=True)
1078
if not self.repository.has_same_location(source.repository):
1079
self.fetch(source, revid)
1080
self.set_last_revision_info(revno, revid)
1081
return (revno, revid)
344
:return: A tuple (revno, last_revision_id).
346
rh = self.revision_history()
349
return (revno, rh[-1])
351
return (0, _mod_revision.NULL_REVISION)
353
def missing_revisions(self, other, stop_revision=None):
354
"""Return a list of new revisions that would perfectly fit.
356
If self and other have not diverged, return a list of the revisions
357
present in other, but missing from self.
359
self_history = self.revision_history()
360
self_len = len(self_history)
361
other_history = other.revision_history()
362
other_len = len(other_history)
363
common_index = min(self_len, other_len) -1
364
if common_index >= 0 and \
365
self_history[common_index] != other_history[common_index]:
366
raise DivergedBranches(self, other)
368
if stop_revision is None:
369
stop_revision = other_len
371
assert isinstance(stop_revision, int)
372
if stop_revision > other_len:
373
raise errors.NoSuchRevision(self, stop_revision)
374
return other_history[self_len:stop_revision]
376
def update_revisions(self, other, stop_revision=None):
377
"""Pull in new perfect-fit revisions.
379
:param other: Another Branch to pull from
380
:param stop_revision: Updated until the given revision
383
raise NotImplementedError(self.update_revisions)
1083
385
def revision_id_to_revno(self, revision_id):
1084
386
"""Given a revision id, return its revno"""
1085
if _mod_revision.is_null(revision_id):
387
if revision_id is None:
389
revision_id = osutils.safe_revision_id(revision_id)
1087
390
history = self.revision_history()
1089
392
return history.index(revision_id) + 1
1090
393
except ValueError:
1091
raise errors.NoSuchRevision(self, revision_id)
394
raise bzrlib.errors.NoSuchRevision(self, revision_id)
1094
396
def get_rev_id(self, revno, history=None):
1095
397
"""Find the revision id of the specified revno."""
1097
return _mod_revision.NULL_REVISION
1098
last_revno, last_revid = self.last_revision_info()
1099
if revno == last_revno:
1101
if revno <= 0 or revno > last_revno:
1102
raise errors.NoSuchRevision(self, revno)
1103
distance_from_last = last_revno - revno
1104
if len(self._partial_revision_history_cache) <= distance_from_last:
1105
self._extend_partial_history(distance_from_last)
1106
return self._partial_revision_history_cache[distance_from_last]
401
history = self.revision_history()
402
if revno <= 0 or revno > len(history):
403
raise bzrlib.errors.NoSuchRevision(self, revno)
404
return history[revno - 1]
1108
def pull(self, source, overwrite=False, stop_revision=None,
1109
possible_transports=None, *args, **kwargs):
406
def pull(self, source, overwrite=False, stop_revision=None):
1110
407
"""Mirror source into this branch.
1112
409
This branch is considered to be 'local', having low latency.
1114
411
:returns: PullResult instance
1116
return InterBranch.get(source, self).pull(overwrite=overwrite,
1117
stop_revision=stop_revision,
1118
possible_transports=possible_transports, *args, **kwargs)
413
raise NotImplementedError(self.pull)
1120
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
415
def push(self, target, overwrite=False, stop_revision=None):
1122
416
"""Mirror this branch into target.
1124
418
This branch is considered to be 'local', having low latency.
1126
return InterBranch.get(self, target).push(overwrite, stop_revision,
1127
lossy, *args, **kwargs)
420
raise NotImplementedError(self.push)
1129
422
def basis_tree(self):
1130
423
"""Return `Tree` object for last revision."""
1131
424
return self.repository.revision_tree(self.last_revision())
426
def rename_one(self, from_rel, to_rel):
429
This can change the directory or the filename or both.
431
raise NotImplementedError(self.rename_one)
433
def move(self, from_paths, to_name):
436
to_name must exist as a versioned directory.
438
If to_name exists and is a directory, the files are moved into
439
it, keeping their old names. If it is a directory,
441
Note that to_name is only the last component of the new name;
442
this doesn't change the directory.
444
This returns a list of (from_path, to_path) pairs for each
447
raise NotImplementedError(self.move)
1133
449
def get_parent(self):
1134
450
"""Return the parent location of the branch.
1136
This is the default location for pull/missing. The usual
452
This is the default location for push/pull/missing. The usual
1137
453
pattern is that the user can override it by specifying a
1140
parent = self._get_parent_location()
1143
# This is an old-format absolute path to a local branch
1144
# turn it into a url
1145
if parent.startswith('/'):
1146
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1148
return urlutils.join(self.base[:-1], parent)
1149
except errors.InvalidURLJoin, e:
1150
raise errors.InaccessibleParent(parent, self.user_url)
1152
def _get_parent_location(self):
1153
raise NotImplementedError(self._get_parent_location)
1155
def _set_config_location(self, name, url, config=None,
1156
make_relative=False):
1158
config = self.get_config()
1162
url = urlutils.relative_url(self.base, url)
1163
config.set_user_option(name, url, warn_masked=True)
1165
def _get_config_location(self, name, config=None):
1167
config = self.get_config()
1168
location = config.get_user_option(name)
1173
def get_child_submit_format(self):
1174
"""Return the preferred format of submissions to this branch."""
1175
return self.get_config().get_user_option("child_submit_format")
456
raise NotImplementedError(self.get_parent)
1177
458
def get_submit_branch(self):
1178
459
"""Return the submit location of the branch.
1257
501
self.check_real_revno(revno)
1259
503
def check_real_revno(self, revno):
1261
505
Check whether a revno corresponds to a real revision.
1262
506
Zero (the NULL revision) is considered invalid
1264
508
if revno < 1 or revno > self.revno():
1265
raise errors.InvalidRevisionNumber(revno)
509
raise InvalidRevisionNumber(revno)
1267
511
@needs_read_lock
1268
def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
512
def clone(self, *args, **kwargs):
1269
513
"""Clone this branch into to_bzrdir preserving all semantic values.
1271
Most API users will want 'create_clone_on_transport', which creates a
1272
new bzrdir and branch on the fly.
1274
515
revision_id: if not None, the revision history in the new branch will
1275
516
be truncated to end with revision_id.
1277
result = to_bzrdir.create_branch()
1280
if repository_policy is not None:
1281
repository_policy.configure_branch(result)
1282
self.copy_content_into(result, revision_id=revision_id)
518
# for API compatibility, until 0.8 releases we provide the old api:
519
# def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
520
# after 0.8 releases, the *args and **kwargs should be changed:
521
# def clone(self, to_bzrdir, revision_id=None):
522
if (kwargs.get('to_location', None) or
523
kwargs.get('revision', None) or
524
kwargs.get('basis_branch', None) or
525
(len(args) and isinstance(args[0], basestring))):
526
# backwards compatibility api:
527
warn("Branch.clone() has been deprecated for BzrDir.clone() from"
528
" bzrlib 0.8.", DeprecationWarning, stacklevel=3)
531
basis_branch = args[2]
533
basis_branch = kwargs.get('basis_branch', None)
535
basis = basis_branch.bzrdir
540
revision_id = args[1]
542
revision_id = kwargs.get('revision', None)
547
# no default to raise if not provided.
548
url = kwargs.get('to_location')
549
return self.bzrdir.clone(url,
550
revision_id=revision_id,
551
basis=basis).open_branch()
553
# generate args by hand
555
revision_id = args[1]
557
revision_id = kwargs.get('revision_id', None)
561
# no default to raise if not provided.
562
to_bzrdir = kwargs.get('to_bzrdir')
563
result = self._format.initialize(to_bzrdir)
564
self.copy_content_into(result, revision_id=revision_id)
1287
567
@needs_read_lock
1288
def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
568
def sprout(self, to_bzrdir, revision_id=None):
1290
569
"""Create a new line of development from the branch, into to_bzrdir.
1292
to_bzrdir controls the branch format.
1294
571
revision_id: if not None, the revision history in the new branch will
1295
572
be truncated to end with revision_id.
1297
if (repository_policy is not None and
1298
repository_policy.requires_stacking()):
1299
to_bzrdir._format.require_stacking(_skip_repo=True)
1300
result = to_bzrdir.create_branch(repository=repository)
1303
if repository_policy is not None:
1304
repository_policy.configure_branch(result)
1305
self.copy_content_into(result, revision_id=revision_id)
1306
master_url = self.get_bound_location()
1307
if master_url is None:
1308
result.set_parent(self.bzrdir.root_transport.base)
1310
result.set_parent(master_url)
574
result = self._format.initialize(to_bzrdir)
575
self.copy_content_into(result, revision_id=revision_id)
576
result.set_parent(self.bzrdir.root_transport.base)
1315
579
def _synchronize_history(self, destination, revision_id):
1316
580
"""Synchronize last revision and revision history between branches.
1318
582
This version is most efficient when the destination is also a
1319
BzrBranch6, but works for BzrBranch5, as long as the destination's
1320
repository contains all the lefthand ancestors of the intended
1321
last_revision. If not, set_last_revision_info will fail.
583
BzrBranch5, but works for BzrBranch6 as long as the revision
584
history is the true lefthand parent history, and all of the revisions
585
are in the destination's repository. If not, set_revision_history
1323
588
:param destination: The branch to copy the history into
1324
589
:param revision_id: The revision-id to truncate history at. May
1325
590
be None to copy complete history.
1327
source_revno, source_revision_id = self.last_revision_info()
1328
if revision_id is None:
1329
revno, revision_id = source_revno, source_revision_id
1331
graph = self.repository.get_graph()
592
new_history = self.revision_history()
593
if revision_id is not None:
594
revision_id = osutils.safe_revision_id(revision_id)
1333
revno = graph.find_distance_to_null(revision_id,
1334
[(source_revision_id, source_revno)])
1335
except errors.GhostRevisionsHaveNoRevno:
1336
# Default to 1, if we can't find anything else
1338
destination.set_last_revision_info(revno, revision_id)
596
new_history = new_history[:new_history.index(revision_id) + 1]
598
rev = self.repository.get_revision(revision_id)
599
new_history = rev.get_history(self.repository)[1:]
600
destination.set_revision_history(new_history)
1340
603
def copy_content_into(self, destination, revision_id=None):
1341
604
"""Copy the content of self into destination.
1343
606
revision_id: if not None, the revision history in the new branch will
1344
607
be truncated to end with revision_id.
1346
return InterBranch.get(self, destination).copy_content_into(
1347
revision_id=revision_id)
1349
def update_references(self, target):
1350
if not getattr(self._format, 'supports_reference_locations', False):
1352
reference_dict = self._get_all_reference_info()
1353
if len(reference_dict) == 0:
1355
old_base = self.base
1356
new_base = target.base
1357
target_reference_dict = target._get_all_reference_info()
1358
for file_id, (tree_path, branch_location) in (
1359
reference_dict.items()):
1360
branch_location = urlutils.rebase_url(branch_location,
1362
target_reference_dict.setdefault(
1363
file_id, (tree_path, branch_location))
1364
target._set_all_reference_info(target_reference_dict)
609
self._synchronize_history(destination, revision_id)
611
parent = self.get_parent()
612
except errors.InaccessibleParent, e:
613
mutter('parent was not accessible to copy: %s', e)
616
destination.set_parent(parent)
1366
618
@needs_read_lock
1367
def check(self, refs):
1368
620
"""Check consistency of the branch.
1370
622
In particular this checks that revisions given in the revision-history
1371
do actually match up in the revision graph, and that they're all
623
do actually match up in the revision graph, and that they're all
1372
624
present in the repository.
1374
626
Callers will typically also want to check the repository.
1376
:param refs: Calculated refs for this branch as specified by
1377
branch._get_check_refs()
1378
628
:return: A BranchCheckResult.
1380
result = BranchCheckResult(self)
1381
last_revno, last_revision_id = self.last_revision_info()
1382
actual_revno = refs[('lefthand-distance', last_revision_id)]
1383
if actual_revno != last_revno:
1384
result.errors.append(errors.BzrCheckError(
1385
'revno does not match len(mainline) %s != %s' % (
1386
last_revno, actual_revno)))
1387
# TODO: We should probably also check that self.revision_history
1388
# matches the repository for older branch formats.
1389
# If looking for the code that cross-checks repository parents against
1390
# the iter_reverse_revision_history output, that is now a repository
630
mainline_parent_id = None
631
for revision_id in self.revision_history():
633
revision = self.repository.get_revision(revision_id)
634
except errors.NoSuchRevision, e:
635
raise errors.BzrCheckError("mainline revision {%s} not in repository"
637
# In general the first entry on the revision history has no parents.
638
# But it's not illegal for it to have parents listed; this can happen
639
# in imports from Arch when the parents weren't reachable.
640
if mainline_parent_id is not None:
641
if mainline_parent_id not in revision.parent_ids:
642
raise errors.BzrCheckError("previous revision {%s} not listed among "
644
% (mainline_parent_id, revision_id))
645
mainline_parent_id = revision_id
646
return BranchCheckResult(self)
1394
def _get_checkout_format(self, lightweight=False):
648
def _get_checkout_format(self):
1395
649
"""Return the most suitable metadir for a checkout of this branch.
1396
Weaves are used if this branch's repository uses weaves.
650
Weaves are used if this branch's repostory uses weaves.
1398
format = self.repository.bzrdir.checkout_metadir()
1399
format.set_branch_format(self._format)
652
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
653
from bzrlib.repofmt import weaverepo
654
format = bzrdir.BzrDirMetaFormat1()
655
format.repository_format = weaverepo.RepositoryFormat7()
657
format = self.repository.bzrdir.checkout_metadir()
658
format.branch_format = self._format
1402
def create_clone_on_transport(self, to_transport, revision_id=None,
1403
stacked_on=None, create_prefix=False, use_existing_dir=False,
1405
"""Create a clone of this branch and its bzrdir.
1407
:param to_transport: The transport to clone onto.
1408
:param revision_id: The revision id to use as tip in the new branch.
1409
If None the tip is obtained from this branch.
1410
:param stacked_on: An optional URL to stack the clone on.
1411
:param create_prefix: Create any missing directories leading up to
1413
:param use_existing_dir: Use an existing directory if one exists.
1415
# XXX: Fix the bzrdir API to allow getting the branch back from the
1416
# clone call. Or something. 20090224 RBC/spiv.
1417
# XXX: Should this perhaps clone colocated branches as well,
1418
# rather than just the default branch? 20100319 JRV
1419
if revision_id is None:
1420
revision_id = self.last_revision()
1421
dir_to = self.bzrdir.clone_on_transport(to_transport,
1422
revision_id=revision_id, stacked_on=stacked_on,
1423
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1425
return dir_to.open_branch()
1427
661
def create_checkout(self, to_location, revision_id=None,
1428
lightweight=False, accelerator_tree=None,
1430
663
"""Create a checkout of a branch.
1432
665
:param to_location: The url to produce the checkout at
1433
666
:param revision_id: The revision to check out
1434
667
:param lightweight: If True, produce a lightweight checkout, otherwise,
1435
produce a bound branch (heavyweight checkout)
1436
:param accelerator_tree: A tree which can be used for retrieving file
1437
contents more quickly than the revision tree, i.e. a workingtree.
1438
The revision tree will be used for cases where accelerator_tree's
1439
content is different.
1440
:param hardlink: If true, hard-link files from accelerator_tree,
668
produce a bound branch (heavyweight checkout)
1442
669
:return: The tree of the created checkout
1444
671
t = transport.get_transport(to_location)
1446
format = self._get_checkout_format(lightweight=lightweight)
674
except errors.FileExists:
677
format = self._get_checkout_format()
1448
678
checkout = format.initialize_on_transport(t)
1449
from_branch = BranchReferenceFormat().initialize(checkout,
679
BranchReferenceFormat().initialize(checkout, self)
681
format = self._get_checkout_format()
1452
682
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1453
683
to_location, force_new_tree=False, format=format)
1454
684
checkout = checkout_branch.bzrdir
1455
685
checkout_branch.bind(self)
1456
# pull up to the specified revision_id to set the initial
686
# pull up to the specified revision_id to set the initial
1457
687
# branch tip correctly, and seed it with history.
1458
688
checkout_branch.pull(self, stop_revision=revision_id)
1460
tree = checkout.create_workingtree(revision_id,
1461
from_branch=from_branch,
1462
accelerator_tree=accelerator_tree,
1464
basis_tree = tree.basis_tree()
1465
basis_tree.lock_read()
1467
for path, file_id in basis_tree.iter_references():
1468
reference_parent = self.reference_parent(file_id, path)
1469
reference_parent.create_checkout(tree.abspath(path),
1470
basis_tree.get_reference_revision(file_id, path),
689
tree = checkout.create_workingtree(revision_id)
690
for path, entry in tree.iter_reference_entries():
691
path = tree.id2path(entry.file_id)
692
reference_parent = self.reference_parent(entry.file_id, path)
693
reference_parent.create_checkout(tree.abspath(path),
694
entry.reference_revision,
1477
def reconcile(self, thorough=True):
1478
"""Make sure the data stored in this branch is consistent."""
1479
from bzrlib.reconcile import BranchReconciler
1480
reconciler = BranchReconciler(self, thorough=thorough)
1481
reconciler.reconcile()
1484
def reference_parent(self, file_id, path, possible_transports=None):
698
def reference_parent(self, file_id, path):
1485
699
"""Return the parent branch for a tree-reference file_id
1487
700
:param file_id: The file_id of the tree reference
1488
701
:param path: The path of the file_id in the tree
1489
702
:return: A branch associated with the file_id
1491
704
# FIXME should provide multiple branches, based on config
1492
return Branch.open(self.bzrdir.root_transport.clone(path).base,
1493
possible_transports=possible_transports)
705
return Branch.open(self.bzrdir.root_transport.clone(path).base)
1495
707
def supports_tags(self):
1496
708
return self._format.supports_tags()
1498
def automatic_tag_name(self, revision_id):
1499
"""Try to automatically find the tag name for a revision.
1501
:param revision_id: Revision id of the revision.
1502
:return: A tag name or None if no tag name could be determined.
1504
for hook in Branch.hooks['automatic_tag_name']:
1505
ret = hook(self, revision_id)
1510
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1512
"""Ensure that revision_b is a descendant of revision_a.
1514
This is a helper function for update_revisions.
1516
:raises: DivergedBranches if revision_b has diverged from revision_a.
1517
:returns: True if revision_b is a descendant of revision_a.
1519
relation = self._revision_relations(revision_a, revision_b, graph)
1520
if relation == 'b_descends_from_a':
1522
elif relation == 'diverged':
1523
raise errors.DivergedBranches(self, other_branch)
1524
elif relation == 'a_descends_from_b':
1527
raise AssertionError("invalid relation: %r" % (relation,))
1529
def _revision_relations(self, revision_a, revision_b, graph):
1530
"""Determine the relationship between two revisions.
1532
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1534
heads = graph.heads([revision_a, revision_b])
1535
if heads == set([revision_b]):
1536
return 'b_descends_from_a'
1537
elif heads == set([revision_a, revision_b]):
1538
# These branches have diverged
1540
elif heads == set([revision_a]):
1541
return 'a_descends_from_b'
1543
raise AssertionError("invalid heads: %r" % (heads,))
1545
def heads_to_fetch(self):
1546
"""Return the heads that must and that should be fetched to copy this
1547
branch into another repo.
1549
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1550
set of heads that must be fetched. if_present_fetch is a set of
1551
heads that must be fetched if present, but no error is necessary if
1552
they are not present.
1554
# For bzr native formats must_fetch is just the tip, and if_present_fetch
1556
must_fetch = set([self.last_revision()])
1557
if_present_fetch = set()
1558
c = self.get_config()
1559
include_tags = c.get_user_option_as_bool('branch.fetch_tags',
1563
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1564
except errors.TagsNotSupported:
1566
must_fetch.discard(_mod_revision.NULL_REVISION)
1567
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1568
return must_fetch, if_present_fetch
1571
class BranchFormat(controldir.ControlComponentFormat):
711
class BranchFormat(object):
1572
712
"""An encapsulation of the initialization and open routines for a format.
1574
714
Formats provide three things:
1576
716
* a format string,
1577
717
* an open routine.
1579
Formats are placed in an dict by their format string for reference
1580
during branch opening. It's not required that these be instances, they
1581
can be classes themselves with class methods - it simply depends on
719
Formats are placed in an dict by their format string for reference
720
during branch opening. Its not required that these be instances, they
721
can be classes themselves with class methods - it simply depends on
1582
722
whether state is needed for a given format or not.
1584
724
Once a format is deprecated, just deprecate the initialize and open
1585
methods on the format class. Do not deprecate the object, as the
725
methods on the format class. Do not deprecate the object, as the
1586
726
object will be created every time regardless.
1589
def __eq__(self, other):
1590
return self.__class__ is other.__class__
729
_default_format = None
730
"""The default format used for new branches."""
1592
def __ne__(self, other):
1593
return not (self == other)
733
"""The known formats."""
1596
def find_format(klass, a_bzrdir, name=None):
736
def find_format(klass, a_bzrdir):
1597
737
"""Return the format for the branch object in a_bzrdir."""
1599
transport = a_bzrdir.get_branch_transport(None, name=name)
1600
format_string = transport.get_bytes("format")
1601
return format_registry.get(format_string)
1602
except errors.NoSuchFile:
1603
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
739
transport = a_bzrdir.get_branch_transport(None)
740
format_string = transport.get("format").read()
741
return klass._formats[format_string]
743
raise NotBranchError(path=transport.base)
1604
744
except KeyError:
1605
raise errors.UnknownFormatError(format=format_string, kind='branch')
745
raise errors.UnknownFormatError(format=format_string)
1608
@deprecated_method(deprecated_in((2, 4, 0)))
1609
748
def get_default_format(klass):
1610
749
"""Return the current default format."""
1611
return format_registry.get_default()
1614
@deprecated_method(deprecated_in((2, 4, 0)))
1615
def get_formats(klass):
1616
"""Get all the known formats.
1618
Warning: This triggers a load of all lazy registered formats: do not
1619
use except when that is desireed.
1621
return format_registry._get_all()
1623
def get_reference(self, a_bzrdir, name=None):
1624
"""Get the target reference of the branch in a_bzrdir.
1626
format probing must have been completed before calling
1627
this method - it is assumed that the format of the branch
1628
in a_bzrdir is correct.
1630
:param a_bzrdir: The bzrdir to get the branch data from.
1631
:param name: Name of the colocated branch to fetch
1632
:return: None if the branch is not a reference branch.
1637
def set_reference(self, a_bzrdir, name, to_branch):
1638
"""Set the target reference of the branch in a_bzrdir.
1640
format probing must have been completed before calling
1641
this method - it is assumed that the format of the branch
1642
in a_bzrdir is correct.
1644
:param a_bzrdir: The bzrdir to set the branch reference for.
1645
:param name: Name of colocated branch to set, None for default
1646
:param to_branch: branch that the checkout is to reference
1648
raise NotImplementedError(self.set_reference)
750
return klass._default_format
1650
752
def get_format_string(self):
1651
753
"""Return the ASCII format string that identifies this format."""
1655
757
"""Return the short format description for this format."""
1656
758
raise NotImplementedError(self.get_format_description)
1658
def _run_post_branch_init_hooks(self, a_bzrdir, name, branch):
1659
hooks = Branch.hooks['post_branch_init']
1662
params = BranchInitHookParams(self, a_bzrdir, name, branch)
760
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
762
"""Initialize a branch in a bzrdir, with specified files
1666
def initialize(self, a_bzrdir, name=None, repository=None,
1667
append_revisions_only=None):
1668
"""Create a branch of this format in a_bzrdir.
1670
:param name: Name of the colocated branch to create.
764
:param a_bzrdir: The bzrdir to initialize the branch in
765
:param utf8_files: The files to create as a list of
766
(filename, content) tuples
767
:param set_format: If True, set the format with
768
self.get_format_string. (BzrBranch4 has its format set
770
:return: a branch in this format
772
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
773
branch_transport = a_bzrdir.get_branch_transport(self)
775
'metadir': ('lock', lockdir.LockDir),
776
'branch4': ('branch-lock', lockable_files.TransportLock),
778
lock_name, lock_class = lock_map[lock_type]
779
control_files = lockable_files.LockableFiles(branch_transport,
780
lock_name, lock_class)
781
control_files.create_lock()
782
control_files.lock_write()
784
control_files.put_utf8('format', self.get_format_string())
786
for file, content in utf8_files:
787
control_files.put_utf8(file, content)
789
control_files.unlock()
790
return self.open(a_bzrdir, _found=True)
792
def initialize(self, a_bzrdir):
793
"""Create a branch of this format in a_bzrdir."""
1672
794
raise NotImplementedError(self.initialize)
1674
796
def is_supported(self):
1675
797
"""Is this format supported?
1677
799
Supported formats can be initialized and opened.
1678
Unsupported formats may not support initialization or committing or
800
Unsupported formats may not support initialization or committing or
1679
801
some other features depending on the reason for not being supported.
1683
def make_tags(self, branch):
1684
"""Create a tags object for branch.
1686
This method is on BranchFormat, because BranchFormats are reflected
1687
over the wire via network_name(), whereas full Branch instances require
1688
multiple VFS method calls to operate at all.
1690
The default implementation returns a disabled-tags instance.
1692
Note that it is normal for branch to be a RemoteBranch when using tags
1695
return _mod_tag.DisabledTags(branch)
1697
def network_name(self):
1698
"""A simple byte string uniquely identifying this format for RPC calls.
1700
MetaDir branch formats use their disk format string to identify the
1701
repository over the wire. All in one formats such as bzr < 0.8, and
1702
foreign formats like svn/git and hg should use some marker which is
1703
unique and immutable.
1705
raise NotImplementedError(self.network_name)
1707
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
1708
found_repository=None):
805
def open(self, a_bzrdir, _found=False):
1709
806
"""Return the branch object for a_bzrdir
1711
:param a_bzrdir: A BzrDir that contains a branch.
1712
:param name: Name of colocated branch to open
1713
:param _found: a private parameter, do not use it. It is used to
1714
indicate if format probing has already be done.
1715
:param ignore_fallbacks: when set, no fallback branches will be opened
1716
(if there are any). Default is to open fallbacks.
808
_found is a private parameter, do not use it. It is used to indicate
809
if format probing has already be done.
1718
811
raise NotImplementedError(self.open)
1721
@deprecated_method(deprecated_in((2, 4, 0)))
1722
814
def register_format(klass, format):
1723
"""Register a metadir format.
1725
See MetaDirBranchFormatFactory for the ability to register a format
1726
without loading the code the format needs until it is actually used.
1728
format_registry.register(format)
815
klass._formats[format.get_format_string()] = format
1731
@deprecated_method(deprecated_in((2, 4, 0)))
1732
818
def set_default_format(klass, format):
1733
format_registry.set_default(format)
1735
def supports_set_append_revisions_only(self):
1736
"""True if this format supports set_append_revisions_only."""
1739
def supports_stacking(self):
1740
"""True if this format records a stacked-on branch."""
1743
def supports_leaving_lock(self):
1744
"""True if this format supports leaving locks in place."""
1745
return False # by default
819
klass._default_format = format
1748
@deprecated_method(deprecated_in((2, 4, 0)))
1749
822
def unregister_format(klass, format):
1750
format_registry.remove(format)
823
assert klass._formats[format.get_format_string()] is format
824
del klass._formats[format.get_format_string()]
1752
826
def __str__(self):
1753
return self.get_format_description().rstrip()
827
return self.get_format_string().rstrip()
1755
829
def supports_tags(self):
1756
830
"""True if this format supports tags stored in the branch"""
1757
831
return False # by default
1759
def tags_are_versioned(self):
1760
"""Whether the tag container for this branch versions tags."""
1763
def supports_tags_referencing_ghosts(self):
1764
"""True if tags can reference ghost revisions."""
1768
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1769
"""A factory for a BranchFormat object, permitting simple lazy registration.
1771
While none of the built in BranchFormats are lazy registered yet,
1772
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1773
use it, and the bzr-loom plugin uses it as well (see
1774
bzrlib.plugins.loom.formats).
1777
def __init__(self, format_string, module_name, member_name):
1778
"""Create a MetaDirBranchFormatFactory.
1780
:param format_string: The format string the format has.
1781
:param module_name: Module to load the format class from.
1782
:param member_name: Attribute name within the module for the format class.
1784
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1785
self._format_string = format_string
1787
def get_format_string(self):
1788
"""See BranchFormat.get_format_string."""
1789
return self._format_string
1792
"""Used for network_format_registry support."""
1793
return self.get_obj()()
1796
class BranchHooks(Hooks):
833
# XXX: Probably doesn't really belong here -- mbp 20070212
834
def _initialize_control_files(self, a_bzrdir, utf8_files, lock_filename,
836
branch_transport = a_bzrdir.get_branch_transport(self)
837
control_files = lockable_files.LockableFiles(branch_transport,
838
lock_filename, lock_class)
839
control_files.create_lock()
840
control_files.lock_write()
842
for filename, content in utf8_files:
843
control_files.put_utf8(filename, content)
845
control_files.unlock()
848
class BranchHooks(dict):
1797
849
"""A dictionary mapping hook name to a list of callables for branch hooks.
1799
851
e.g. ['set_rh'] Is the list of items to be called when the
1800
852
set_revision_history function is invoked.
1806
858
These are all empty initially, because by default nothing should get
1809
Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1810
self.add_hook('set_rh',
1811
"Invoked whenever the revision history has been set via "
1812
"set_revision_history. The api signature is (branch, "
1813
"revision_history), and the branch will be write-locked. "
1814
"The set_rh hook can be expensive for bzr to trigger, a better "
1815
"hook to use is Branch.post_change_branch_tip.", (0, 15))
1816
self.add_hook('open',
1817
"Called with the Branch object that has been opened after a "
1818
"branch is opened.", (1, 8))
1819
self.add_hook('post_push',
1820
"Called after a push operation completes. post_push is called "
1821
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1822
"bzr client.", (0, 15))
1823
self.add_hook('post_pull',
1824
"Called after a pull operation completes. post_pull is called "
1825
"with a bzrlib.branch.PullResult object and only runs in the "
1826
"bzr client.", (0, 15))
1827
self.add_hook('pre_commit',
1828
"Called after a commit is calculated but before it is "
1829
"completed. pre_commit is called with (local, master, old_revno, "
1830
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1831
"). old_revid is NULL_REVISION for the first commit to a branch, "
1832
"tree_delta is a TreeDelta object describing changes from the "
1833
"basis revision. hooks MUST NOT modify this delta. "
1834
" future_tree is an in-memory tree obtained from "
1835
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1837
self.add_hook('post_commit',
1838
"Called in the bzr client after a commit has completed. "
1839
"post_commit is called with (local, master, old_revno, old_revid, "
1840
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1841
"commit to a branch.", (0, 15))
1842
self.add_hook('post_uncommit',
1843
"Called in the bzr client after an uncommit completes. "
1844
"post_uncommit is called with (local, master, old_revno, "
1845
"old_revid, new_revno, new_revid) where local is the local branch "
1846
"or None, master is the target branch, and an empty branch "
1847
"receives new_revno of 0, new_revid of None.", (0, 15))
1848
self.add_hook('pre_change_branch_tip',
1849
"Called in bzr client and server before a change to the tip of a "
1850
"branch is made. pre_change_branch_tip is called with a "
1851
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1852
"commit, uncommit will all trigger this hook.", (1, 6))
1853
self.add_hook('post_change_branch_tip',
1854
"Called in bzr client and server after a change to the tip of a "
1855
"branch is made. post_change_branch_tip is called with a "
1856
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1857
"commit, uncommit will all trigger this hook.", (1, 4))
1858
self.add_hook('transform_fallback_location',
1859
"Called when a stacked branch is activating its fallback "
1860
"locations. transform_fallback_location is called with (branch, "
1861
"url), and should return a new url. Returning the same url "
1862
"allows it to be used as-is, returning a different one can be "
1863
"used to cause the branch to stack on a closer copy of that "
1864
"fallback_location. Note that the branch cannot have history "
1865
"accessing methods called on it during this hook because the "
1866
"fallback locations have not been activated. When there are "
1867
"multiple hooks installed for transform_fallback_location, "
1868
"all are called with the url returned from the previous hook."
1869
"The order is however undefined.", (1, 9))
1870
self.add_hook('automatic_tag_name',
1871
"Called to determine an automatic tag name for a revision. "
1872
"automatic_tag_name is called with (branch, revision_id) and "
1873
"should return a tag name or None if no tag name could be "
1874
"determined. The first non-None tag name returned will be used.",
1876
self.add_hook('post_branch_init',
1877
"Called after new branch initialization completes. "
1878
"post_branch_init is called with a "
1879
"bzrlib.branch.BranchInitHookParams. "
1880
"Note that init, branch and checkout (both heavyweight and "
1881
"lightweight) will all trigger this hook.", (2, 2))
1882
self.add_hook('post_switch',
1883
"Called after a checkout switches branch. "
1884
"post_switch is called with a "
1885
"bzrlib.branch.SwitchHookParams.", (2, 2))
862
# Introduced in 0.15:
863
# invoked whenever the revision history has been set
864
# with set_revision_history. The api signature is
865
# (branch, revision_history), and the branch will
868
# invoked after a push operation completes.
869
# the api signature is
871
# containing the members
872
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
873
# where local is the local branch or None, master is the target
874
# master branch, and the rest should be self explanatory. The source
875
# is read locked and the target branches write locked. Source will
876
# be the local low-latency branch.
877
self['post_push'] = []
878
# invoked after a pull operation completes.
879
# the api signature is
881
# containing the members
882
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
883
# where local is the local branch or None, master is the target
884
# master branch, and the rest should be self explanatory. The source
885
# is read locked and the target branches write locked. The local
886
# branch is the low-latency branch.
887
self['post_pull'] = []
888
# invoked after a commit operation completes.
889
# the api signature is
890
# (local, master, old_revno, old_revid, new_revno, new_revid)
891
# old_revid is NULL_REVISION for the first commit to a branch.
892
self['post_commit'] = []
893
# invoked after a uncommit operation completes.
894
# the api signature is
895
# (local, master, old_revno, old_revid, new_revno, new_revid) where
896
# local is the local branch or None, master is the target branch,
897
# and an empty branch recieves new_revno of 0, new_revid of None.
898
self['post_uncommit'] = []
900
def install_hook(self, hook_name, a_callable):
901
"""Install a_callable in to the hook hook_name.
903
:param hook_name: A hook name. See the __init__ method of BranchHooks
904
for the complete list of hooks.
905
:param a_callable: The callable to be invoked when the hook triggers.
906
The exact signature will depend on the hook - see the __init__
907
method of BranchHooks for details on each hook.
910
self[hook_name].append(a_callable)
912
raise errors.UnknownHook('branch', hook_name)
1889
915
# install the default hooks into the Branch class.
1890
916
Branch.hooks = BranchHooks()
1893
class ChangeBranchTipParams(object):
1894
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1896
There are 5 fields that hooks may wish to access:
1898
:ivar branch: the branch being changed
1899
:ivar old_revno: revision number before the change
1900
:ivar new_revno: revision number after the change
1901
:ivar old_revid: revision id before the change
1902
:ivar new_revid: revision id after the change
1904
The revid fields are strings. The revno fields are integers.
1907
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1908
"""Create a group of ChangeBranchTip parameters.
1910
:param branch: The branch being changed.
1911
:param old_revno: Revision number before the change.
1912
:param new_revno: Revision number after the change.
1913
:param old_revid: Tip revision id before the change.
1914
:param new_revid: Tip revision id after the change.
1916
self.branch = branch
1917
self.old_revno = old_revno
1918
self.new_revno = new_revno
1919
self.old_revid = old_revid
1920
self.new_revid = new_revid
1922
def __eq__(self, other):
1923
return self.__dict__ == other.__dict__
1926
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1927
self.__class__.__name__, self.branch,
1928
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1931
class BranchInitHookParams(object):
1932
"""Object holding parameters passed to `*_branch_init` hooks.
1934
There are 4 fields that hooks may wish to access:
1936
:ivar format: the branch format
1937
:ivar bzrdir: the BzrDir where the branch will be/has been initialized
1938
:ivar name: name of colocated branch, if any (or None)
1939
:ivar branch: the branch created
1941
Note that for lightweight checkouts, the bzrdir and format fields refer to
1942
the checkout, hence they are different from the corresponding fields in
1943
branch, which refer to the original branch.
1946
def __init__(self, format, a_bzrdir, name, branch):
1947
"""Create a group of BranchInitHook parameters.
1949
:param format: the branch format
1950
:param a_bzrdir: the BzrDir where the branch will be/has been
1952
:param name: name of colocated branch, if any (or None)
1953
:param branch: the branch created
1955
Note that for lightweight checkouts, the bzrdir and format fields refer
1956
to the checkout, hence they are different from the corresponding fields
1957
in branch, which refer to the original branch.
1959
self.format = format
1960
self.bzrdir = a_bzrdir
1962
self.branch = branch
1964
def __eq__(self, other):
1965
return self.__dict__ == other.__dict__
1968
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1971
class SwitchHookParams(object):
1972
"""Object holding parameters passed to `*_switch` hooks.
1974
There are 4 fields that hooks may wish to access:
1976
:ivar control_dir: BzrDir of the checkout to change
1977
:ivar to_branch: branch that the checkout is to reference
1978
:ivar force: skip the check for local commits in a heavy checkout
1979
:ivar revision_id: revision ID to switch to (or None)
1982
def __init__(self, control_dir, to_branch, force, revision_id):
1983
"""Create a group of SwitchHook parameters.
1985
:param control_dir: BzrDir of the checkout to change
1986
:param to_branch: branch that the checkout is to reference
1987
:param force: skip the check for local commits in a heavy checkout
1988
:param revision_id: revision ID to switch to (or None)
1990
self.control_dir = control_dir
1991
self.to_branch = to_branch
1993
self.revision_id = revision_id
1995
def __eq__(self, other):
1996
return self.__dict__ == other.__dict__
1999
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
2000
self.control_dir, self.to_branch,
2004
class BranchFormatMetadir(BranchFormat):
2005
"""Common logic for meta-dir based branch formats."""
2007
def _branch_class(self):
2008
"""What class to instantiate on open calls."""
2009
raise NotImplementedError(self._branch_class)
2011
def _get_initial_config(self, append_revisions_only=None):
2012
if append_revisions_only:
2013
return "append_revisions_only = True\n"
2015
# Avoid writing anything if append_revisions_only is disabled,
2016
# as that is the default.
2019
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2021
"""Initialize a branch in a bzrdir, with specified files
2023
:param a_bzrdir: The bzrdir to initialize the branch in
2024
:param utf8_files: The files to create as a list of
2025
(filename, content) tuples
2026
:param name: Name of colocated branch to create, if any
2027
:return: a branch in this format
2029
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2030
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2031
control_files = lockable_files.LockableFiles(branch_transport,
2032
'lock', lockdir.LockDir)
2033
control_files.create_lock()
2034
control_files.lock_write()
2036
utf8_files += [('format', self.get_format_string())]
2037
for (filename, content) in utf8_files:
2038
branch_transport.put_bytes(
2040
mode=a_bzrdir._get_file_mode())
2042
control_files.unlock()
2043
branch = self.open(a_bzrdir, name, _found=True,
2044
found_repository=repository)
2045
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
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
found_repository=None):
2057
"""See BranchFormat.open()."""
919
class BzrBranchFormat4(BranchFormat):
920
"""Bzr branch format 4.
923
- a revision-history file.
924
- a branch-lock lock file [ to be shared with the bzrdir ]
927
def get_format_description(self):
928
"""See BranchFormat.get_format_description()."""
929
return "Branch format 4"
931
def initialize(self, a_bzrdir):
932
"""Create a branch of this format in a_bzrdir."""
933
utf8_files = [('revision-history', ''),
936
return self._initialize_helper(a_bzrdir, utf8_files,
937
lock_type='branch4', set_format=False)
940
super(BzrBranchFormat4, self).__init__()
941
self._matchingbzrdir = bzrdir.BzrDirFormat6()
943
def open(self, a_bzrdir, _found=False):
944
"""Return the branch object for a_bzrdir
946
_found is a private parameter, do not use it. It is used to indicate
947
if format probing has already be done.
2059
format = BranchFormat.find_format(a_bzrdir, name=name)
2060
if format.__class__ != self.__class__:
2061
raise AssertionError("wrong format %r found for %r" %
2063
transport = a_bzrdir.get_branch_transport(None, name=name)
2065
control_files = lockable_files.LockableFiles(transport, 'lock',
2067
if found_repository is None:
2068
found_repository = a_bzrdir.find_repository()
2069
return self._branch_class()(_format=self,
2070
_control_files=control_files,
2073
_repository=found_repository,
2074
ignore_fallbacks=ignore_fallbacks)
2075
except errors.NoSuchFile:
2076
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2079
super(BranchFormatMetadir, self).__init__()
2080
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2081
self._matchingbzrdir.set_branch_format(self)
2083
def supports_tags(self):
2086
def supports_leaving_lock(self):
2090
class BzrBranchFormat5(BranchFormatMetadir):
950
# we are being called directly and must probe.
951
raise NotImplementedError
952
return BzrBranch(_format=self,
953
_control_files=a_bzrdir._control_files,
955
_repository=a_bzrdir.open_repository())
958
return "Bazaar-NG branch format 4"
961
class BzrBranchFormat5(BranchFormat):
2091
962
"""Bzr branch format 5.
2093
964
This format has:
2110
978
def get_format_description(self):
2111
979
"""See BranchFormat.get_format_description()."""
2112
980
return "Branch format 5"
2114
def initialize(self, a_bzrdir, name=None, repository=None,
2115
append_revisions_only=None):
982
def initialize(self, a_bzrdir):
2116
983
"""Create a branch of this format in a_bzrdir."""
2117
if append_revisions_only:
2118
raise errors.UpgradeRequired(a_bzrdir.user_url)
2119
984
utf8_files = [('revision-history', ''),
2120
985
('branch-name', ''),
2122
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2124
def supports_tags(self):
2128
class BzrBranchFormat6(BranchFormatMetadir):
2129
"""Branch format with last-revision and tags.
987
return self._initialize_helper(a_bzrdir, utf8_files)
990
super(BzrBranchFormat5, self).__init__()
991
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
993
def open(self, a_bzrdir, _found=False):
994
"""Return the branch object for a_bzrdir
996
_found is a private parameter, do not use it. It is used to indicate
997
if format probing has already be done.
1000
format = BranchFormat.find_format(a_bzrdir)
1001
assert format.__class__ == self.__class__
1002
transport = a_bzrdir.get_branch_transport(None)
1003
control_files = lockable_files.LockableFiles(transport, 'lock',
1005
return BzrBranch5(_format=self,
1006
_control_files=control_files,
1008
_repository=a_bzrdir.find_repository())
1011
class BzrBranchFormat6(BzrBranchFormat5):
1012
"""Branch format with last-revision
2131
1014
Unlike previous formats, this has no explicit revision history. Instead,
2132
1015
this just stores the last-revision, and the left-hand history leading
2133
1016
up to there is the history.
2135
1018
This format was introduced in bzr 0.15
2136
and became the default in 0.91.
2139
def _branch_class(self):
2142
1021
def get_format_string(self):
2143
1022
"""See BranchFormat.get_format_string()."""
2144
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1023
return "Bazaar-NG branch format 6\n"
2146
1025
def get_format_description(self):
2147
1026
"""See BranchFormat.get_format_description()."""
2148
1027
return "Branch format 6"
2150
def initialize(self, a_bzrdir, name=None, repository=None,
2151
append_revisions_only=None):
2152
"""Create a branch of this format in a_bzrdir."""
2153
utf8_files = [('last-revision', '0 null:\n'),
2155
self._get_initial_config(append_revisions_only)),
2158
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2160
def make_tags(self, branch):
2161
"""See bzrlib.branch.BranchFormat.make_tags()."""
2162
return _mod_tag.BasicTags(branch)
2164
def supports_set_append_revisions_only(self):
2168
class BzrBranchFormat8(BranchFormatMetadir):
2169
"""Metadir format supporting storing locations of subtree branches."""
2171
def _branch_class(self):
2174
def get_format_string(self):
2175
"""See BranchFormat.get_format_string()."""
2176
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2178
def get_format_description(self):
2179
"""See BranchFormat.get_format_description()."""
2180
return "Branch format 8"
2182
def initialize(self, a_bzrdir, name=None, repository=None,
2183
append_revisions_only=None):
2184
"""Create a branch of this format in a_bzrdir."""
2185
utf8_files = [('last-revision', '0 null:\n'),
2187
self._get_initial_config(append_revisions_only)),
2191
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2193
def make_tags(self, branch):
2194
"""See bzrlib.branch.BranchFormat.make_tags()."""
2195
return _mod_tag.BasicTags(branch)
2197
def supports_set_append_revisions_only(self):
2200
def supports_stacking(self):
2203
supports_reference_locations = True
2206
class BzrBranchFormat7(BranchFormatMetadir):
2207
"""Branch format with last-revision, tags, and a stacked location pointer.
2209
The stacked location pointer is passed down to the repository and requires
2210
a repository format with supports_external_lookups = True.
2212
This format was introduced in bzr 1.6.
2215
def initialize(self, a_bzrdir, name=None, repository=None,
2216
append_revisions_only=None):
2217
"""Create a branch of this format in a_bzrdir."""
2218
utf8_files = [('last-revision', '0 null:\n'),
2220
self._get_initial_config(append_revisions_only)),
2223
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2225
def _branch_class(self):
2228
def get_format_string(self):
2229
"""See BranchFormat.get_format_string()."""
2230
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2232
def get_format_description(self):
2233
"""See BranchFormat.get_format_description()."""
2234
return "Branch format 7"
2236
def supports_set_append_revisions_only(self):
2239
def supports_stacking(self):
2242
def make_tags(self, branch):
2243
"""See bzrlib.branch.BranchFormat.make_tags()."""
2244
return _mod_tag.BasicTags(branch)
2246
supports_reference_locations = False
1029
def initialize(self, a_bzrdir):
1030
"""Create a branch of this format in a_bzrdir."""
1031
utf8_files = [('last-revision', '0 null:\n'),
1032
('branch-name', ''),
1033
('branch.conf', ''),
1036
return self._initialize_helper(a_bzrdir, utf8_files)
1038
def open(self, a_bzrdir, _found=False):
1039
"""Return the branch object for a_bzrdir
1041
_found is a private parameter, do not use it. It is used to indicate
1042
if format probing has already be done.
1045
format = BranchFormat.find_format(a_bzrdir)
1046
assert format.__class__ == self.__class__
1047
transport = a_bzrdir.get_branch_transport(None)
1048
control_files = lockable_files.LockableFiles(transport, 'lock',
1050
return BzrBranch6(_format=self,
1051
_control_files=control_files,
1053
_repository=a_bzrdir.find_repository())
1055
def supports_tags(self):
2249
1059
class BranchReferenceFormat(BranchFormat):
2264
1074
def get_format_description(self):
2265
1075
"""See BranchFormat.get_format_description()."""
2266
1076
return "Checkout reference format 1"
2268
def get_reference(self, a_bzrdir, name=None):
2269
"""See BranchFormat.get_reference()."""
2270
transport = a_bzrdir.get_branch_transport(None, name=name)
2271
return transport.get_bytes('location')
2273
def set_reference(self, a_bzrdir, name, to_branch):
2274
"""See BranchFormat.set_reference()."""
2275
transport = a_bzrdir.get_branch_transport(None, name=name)
2276
location = transport.put_bytes('location', to_branch.base)
2278
def initialize(self, a_bzrdir, name=None, target_branch=None,
2279
repository=None, append_revisions_only=None):
1078
def initialize(self, a_bzrdir, target_branch=None):
2280
1079
"""Create a branch of this format in a_bzrdir."""
2281
1080
if target_branch is None:
2282
1081
# this format does not implement branch itself, thus the implicit
2283
1082
# creation contract must see it as uninitializable
2284
1083
raise errors.UninitializableFormat(self)
2285
mutter('creating branch reference in %s', a_bzrdir.user_url)
2286
if a_bzrdir._format.fixed_components:
2287
raise errors.IncompatibleFormat(self, a_bzrdir._format)
2288
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
1084
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1085
branch_transport = a_bzrdir.get_branch_transport(self)
2289
1086
branch_transport.put_bytes('location',
2290
target_branch.bzrdir.user_url)
1087
target_branch.bzrdir.root_transport.base)
2291
1088
branch_transport.put_bytes('format', self.get_format_string())
2293
a_bzrdir, name, _found=True,
2294
possible_transports=[target_branch.bzrdir.root_transport])
2295
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
1089
return self.open(a_bzrdir, _found=True)
2298
1091
def __init__(self):
2299
1092
super(BranchReferenceFormat, self).__init__()
2300
1093
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
2301
self._matchingbzrdir.set_branch_format(self)
2303
1095
def _make_reference_clone_function(format, a_branch):
2304
1096
"""Create a clone() routine for a branch dynamically."""
2305
def clone(to_bzrdir, revision_id=None,
2306
repository_policy=None):
1097
def clone(to_bzrdir, revision_id=None):
2307
1098
"""See Branch.clone()."""
2308
return format.initialize(to_bzrdir, target_branch=a_branch)
1099
return format.initialize(to_bzrdir, a_branch)
2309
1100
# cannot obey revision_id limits when cloning a reference ...
2310
1101
# FIXME RBC 20060210 either nuke revision_id for clone, or
2311
1102
# emit some sort of warning/error to the caller ?!
2314
def open(self, a_bzrdir, name=None, _found=False, location=None,
2315
possible_transports=None, ignore_fallbacks=False,
2316
found_repository=None):
1105
def open(self, a_bzrdir, _found=False):
2317
1106
"""Return the branch that the branch reference in a_bzrdir points at.
2319
:param a_bzrdir: A BzrDir that contains a branch.
2320
:param name: Name of colocated branch to open, if any
2321
:param _found: a private parameter, do not use it. It is used to
2322
indicate if format probing has already be done.
2323
:param ignore_fallbacks: when set, no fallback branches will be opened
2324
(if there are any). Default is to open fallbacks.
2325
:param location: The location of the referenced branch. If
2326
unspecified, this will be determined from the branch reference in
2328
:param possible_transports: An optional reusable transports list.
1108
_found is a private parameter, do not use it. It is used to indicate
1109
if format probing has already be done.
2331
format = BranchFormat.find_format(a_bzrdir, name=name)
2332
if format.__class__ != self.__class__:
2333
raise AssertionError("wrong format %r found for %r" %
2335
if location is None:
2336
location = self.get_reference(a_bzrdir, name)
2337
real_bzrdir = bzrdir.BzrDir.open(
2338
location, possible_transports=possible_transports)
2339
result = real_bzrdir.open_branch(name=name,
2340
ignore_fallbacks=ignore_fallbacks)
1112
format = BranchFormat.find_format(a_bzrdir)
1113
assert format.__class__ == self.__class__
1114
transport = a_bzrdir.get_branch_transport(None)
1115
real_bzrdir = bzrdir.BzrDir.open(transport.get('location').read())
1116
result = real_bzrdir.open_branch()
2341
1117
# this changes the behaviour of result.clone to create a new reference
2342
1118
# rather than a copy of the content of the branch.
2343
1119
# I did not use a proxy object because that needs much more extensive
2353
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2354
"""Branch format registry."""
2356
def __init__(self, other_registry=None):
2357
super(BranchFormatRegistry, self).__init__(other_registry)
2358
self._default_format = None
2360
def set_default(self, format):
2361
self._default_format = format
2363
def get_default(self):
2364
return self._default_format
2367
network_format_registry = registry.FormatRegistry()
2368
"""Registry of formats indexed by their network name.
2370
The network name for a branch format is an identifier that can be used when
2371
referring to formats with smart server operations. See
2372
BranchFormat.network_name() for more detail.
2375
format_registry = BranchFormatRegistry(network_format_registry)
2378
1129
# formats which have no format string are not discoverable
2379
1130
# and not independently creatable, so are not registered.
2380
__format5 = BzrBranchFormat5()
2381
__format6 = BzrBranchFormat6()
2382
__format7 = BzrBranchFormat7()
2383
__format8 = BzrBranchFormat8()
2384
format_registry.register(__format5)
2385
format_registry.register(BranchReferenceFormat())
2386
format_registry.register(__format6)
2387
format_registry.register(__format7)
2388
format_registry.register(__format8)
2389
format_registry.set_default(__format7)
2392
class BranchWriteLockResult(LogicalLockResult):
2393
"""The result of write locking a branch.
2395
:ivar branch_token: The token obtained from the underlying branch lock, or
2397
:ivar unlock: A callable which will unlock the lock.
2400
def __init__(self, unlock, branch_token):
2401
LogicalLockResult.__init__(self, unlock)
2402
self.branch_token = branch_token
2405
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2409
class BzrBranch(Branch, _RelockDebugMixin):
1131
__default_format = BzrBranchFormat5()
1132
BranchFormat.register_format(__default_format)
1133
BranchFormat.register_format(BranchReferenceFormat())
1134
BranchFormat.register_format(BzrBranchFormat6())
1135
BranchFormat.set_default_format(__default_format)
1136
_legacy_formats = [BzrBranchFormat4(),
1139
class BzrBranch(Branch):
2410
1140
"""A branch stored in the actual filesystem.
2412
1142
Note that it's "local" in the context of the filesystem; it doesn't
2413
1143
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2414
1144
it's writable, and can be accessed via the normal filesystem API.
2416
:ivar _transport: Transport for file operations on this branch's
2417
control files, typically pointing to the .bzr/branch directory.
2418
:ivar repository: Repository for this branch.
2419
:ivar base: The url of the base directory for this branch; the one
2420
containing the .bzr directory.
2421
:ivar name: Optional colocated branch name as it exists in the control
2425
def __init__(self, _format=None,
2426
_control_files=None, a_bzrdir=None, name=None,
2427
_repository=None, ignore_fallbacks=False):
2428
"""Create new branch object at a particular location."""
1147
def __init__(self, transport=DEPRECATED_PARAMETER, init=DEPRECATED_PARAMETER,
1148
relax_version_check=DEPRECATED_PARAMETER, _format=None,
1149
_control_files=None, a_bzrdir=None, _repository=None):
1150
"""Create new branch object at a particular location.
1152
transport -- A Transport object, defining how to access files.
1154
init -- If True, create new control files in a previously
1155
unversioned directory. If False, the branch must already
1158
relax_version_check -- If true, the usual check for the branch
1159
version is not applied. This is intended only for
1160
upgrade/recovery type use; it's not guaranteed that
1161
all operations will work on old format branches.
1163
Branch.__init__(self)
2429
1164
if a_bzrdir is None:
2430
raise ValueError('a_bzrdir must be supplied')
1165
self.bzrdir = bzrdir.BzrDir.open(transport.base)
2432
1167
self.bzrdir = a_bzrdir
1168
# self._transport used to point to the directory containing the
1169
# control directory, but was not used - now it's just the transport
1170
# for the branch control files. mbp 20070212
2433
1171
self._base = self.bzrdir.transport.clone('..').base
2435
# XXX: We should be able to just do
2436
# self.base = self.bzrdir.root_transport.base
2437
# but this does not quite work yet -- mbp 20080522
2438
1172
self._format = _format
2439
1173
if _control_files is None:
2440
1174
raise ValueError('BzrBranch _control_files is None')
2441
1175
self.control_files = _control_files
2442
1176
self._transport = _control_files._transport
1177
if deprecated_passed(init):
1178
warn("BzrBranch.__init__(..., init=XXX): The init parameter is "
1179
"deprecated as of bzr 0.8. Please use Branch.create().",
1183
# this is slower than before deprecation, oh well never mind.
1184
# -> its deprecated.
1185
self._initialize(transport.base)
1186
self._check_format(_format)
1187
if deprecated_passed(relax_version_check):
1188
warn("BzrBranch.__init__(..., relax_version_check=XXX_: The "
1189
"relax_version_check parameter is deprecated as of bzr 0.8. "
1190
"Please use BzrDir.open_downlevel, or a BzrBranchFormat's "
1194
if (not relax_version_check
1195
and not self._format.is_supported()):
1196
raise errors.UnsupportedFormatError(format=fmt)
1197
if deprecated_passed(transport):
1198
warn("BzrBranch.__init__(transport=XXX...): The transport "
1199
"parameter is deprecated as of bzr 0.8. "
1200
"Please use Branch.open, or bzrdir.open_branch().",
2443
1203
self.repository = _repository
2444
Branch.__init__(self)
2446
1205
def __str__(self):
2447
if self.name is None:
2448
return '%s(%s)' % (self.__class__.__name__, self.user_url)
2450
return '%s(%s,%s)' % (self.__class__.__name__, self.user_url,
1206
return '%s(%r)' % (self.__class__.__name__, self.base)
2453
1208
__repr__ = __str__
2459
1214
base = property(_get_base, doc="The URL for the root of this branch.")
2461
def _get_config(self):
2462
return _mod_config.TransportConfig(self._transport, 'branch.conf')
1216
def _finish_transaction(self):
1217
"""Exit the current transaction."""
1218
return self.control_files._finish_transaction()
1220
def get_transaction(self):
1221
"""Return the current active transaction.
1223
If no transaction is active, this returns a passthrough object
1224
for which all data is immediately flushed and no caching happens.
1226
# this is an explicit function so that we can do tricky stuff
1227
# when the storage in rev_storage is elsewhere.
1228
# we probably need to hook the two 'lock a location' and
1229
# 'have a transaction' together more delicately, so that
1230
# we can have two locks (branch and storage) and one transaction
1231
# ... and finishing the transaction unlocks both, but unlocking
1232
# does not. - RBC 20051121
1233
return self.control_files.get_transaction()
1235
def _set_transaction(self, transaction):
1236
"""Set a new active transaction."""
1237
return self.control_files._set_transaction(transaction)
1239
def abspath(self, name):
1240
"""See Branch.abspath."""
1241
return self.control_files._transport.abspath(name)
1243
def _check_format(self, format):
1244
"""Identify the branch format if needed.
1246
The format is stored as a reference to the format object in
1247
self._format for code that needs to check it later.
1249
The format parameter is either None or the branch format class
1250
used to open this branch.
1252
FIXME: DELETE THIS METHOD when pre 0.8 support is removed.
1255
format = BranchFormat.find_format(self.bzrdir)
1256
self._format = format
1257
mutter("got branch format %s", self._format)
1260
def get_root_id(self):
1261
"""See Branch.get_root_id."""
1262
tree = self.repository.revision_tree(self.last_revision())
1263
return tree.inventory.root.file_id
2464
1265
def is_locked(self):
2465
1266
return self.control_files.is_locked()
2467
def lock_write(self, token=None):
2468
"""Lock the branch for write operations.
2470
:param token: A token to permit reacquiring a previously held and
2472
:return: A BranchWriteLockResult.
2474
if not self.is_locked():
2475
self._note_lock('w')
2476
# All-in-one needs to always unlock/lock.
2477
repo_control = getattr(self.repository, 'control_files', None)
2478
if self.control_files == repo_control or not self.is_locked():
2479
self.repository._warn_if_deprecated(self)
2480
self.repository.lock_write()
1268
def lock_write(self):
1269
self.repository.lock_write()
2485
return BranchWriteLockResult(self.unlock,
2486
self.control_files.lock_write(token=token))
1271
self.control_files.lock_write()
2489
self.repository.unlock()
1273
self.repository.unlock()
2492
1276
def lock_read(self):
2493
"""Lock the branch for read operations.
2495
:return: A bzrlib.lock.LogicalLockResult.
2497
if not self.is_locked():
2498
self._note_lock('r')
2499
# All-in-one needs to always unlock/lock.
2500
repo_control = getattr(self.repository, 'control_files', None)
2501
if self.control_files == repo_control or not self.is_locked():
2502
self.repository._warn_if_deprecated(self)
2503
self.repository.lock_read()
1277
self.repository.lock_read()
2508
1279
self.control_files.lock_read()
2509
return LogicalLockResult(self.unlock)
2512
self.repository.unlock()
1281
self.repository.unlock()
2515
@only_raises(errors.LockNotHeld, errors.LockBroken)
2516
1284
def unlock(self):
1285
# TODO: test for failed two phase locks. This is known broken.
2518
1287
self.control_files.unlock()
2520
# All-in-one needs to always unlock/lock.
2521
repo_control = getattr(self.repository, 'control_files', None)
2522
if (self.control_files == repo_control or
2523
not self.control_files.is_locked()):
2524
self.repository.unlock()
2525
if not self.control_files.is_locked():
2526
# we just released the lock
2527
self._clear_cached_state()
1289
self.repository.unlock()
2529
1291
def peek_lock_mode(self):
2530
1292
if self.control_files._lock_count == 0:
2541
1303
return self.repository.print_file(file, revision_id)
2543
1305
@needs_write_lock
1306
def append_revision(self, *revision_ids):
1307
"""See Branch.append_revision."""
1308
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1309
for revision_id in revision_ids:
1310
_mod_revision.check_not_reserved_id(revision_id)
1311
mutter("add {%s} to revision-history" % revision_id)
1312
rev_history = self.revision_history()
1313
rev_history.extend(revision_ids)
1314
self.set_revision_history(rev_history)
1316
def _write_revision_history(self, history):
1317
"""Factored out of set_revision_history.
1319
This performs the actual writing to disk.
1320
It is intended to be called by BzrBranch5.set_revision_history."""
1321
self.control_files.put_bytes(
1322
'revision-history', '\n'.join(history))
1325
def set_revision_history(self, rev_history):
1326
"""See Branch.set_revision_history."""
1327
rev_history = [osutils.safe_revision_id(r) for r in rev_history]
1328
self._write_revision_history(rev_history)
1329
transaction = self.get_transaction()
1330
history = transaction.map.find_revision_history()
1331
if history is not None:
1332
# update the revision history in the identity map.
1333
history[:] = list(rev_history)
1334
# this call is disabled because revision_history is
1335
# not really an object yet, and the transaction is for objects.
1336
# transaction.register_dirty(history)
1338
transaction.map.add_revision_history(rev_history)
1339
# this call is disabled because revision_history is
1340
# not really an object yet, and the transaction is for objects.
1341
# transaction.register_clean(history)
1342
for hook in Branch.hooks['set_rh']:
1343
hook(self, rev_history)
2544
1346
def set_last_revision_info(self, revno, revision_id):
2545
if not revision_id or not isinstance(revision_id, basestring):
2546
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2547
revision_id = _mod_revision.ensure_null(revision_id)
2548
old_revno, old_revid = self.last_revision_info()
2549
if self.get_append_revisions_only():
2550
self._check_history_violation(revision_id)
2551
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2552
self._write_last_revision_info(revno, revision_id)
2553
self._clear_cached_state()
2554
self._last_revision_info_cache = revno, revision_id
2555
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1347
revision_id = osutils.safe_revision_id(revision_id)
1348
history = self._lefthand_history(revision_id)
1349
assert len(history) == revno, '%d != %d' % (len(history), revno)
1350
self.set_revision_history(history)
1352
def _gen_revision_history(self):
1353
history = [l.rstrip('\r\n') for l in
1354
self.control_files.get('revision-history').readlines()]
1358
def revision_history(self):
1359
"""See Branch.revision_history."""
1360
transaction = self.get_transaction()
1361
history = transaction.map.find_revision_history()
1362
if history is not None:
1363
# mutter("cache hit for revision-history in %s", self)
1364
return list(history)
1365
history = self._gen_revision_history()
1366
transaction.map.add_revision_history(history)
1367
# this call is disabled because revision_history is
1368
# not really an object yet, and the transaction is for objects.
1369
# transaction.register_clean(history, precious=True)
1370
return list(history)
1372
def _lefthand_history(self, revision_id, last_rev=None,
1374
# stop_revision must be a descendant of last_revision
1375
stop_graph = self.repository.get_revision_graph(revision_id)
1376
if last_rev is not None and last_rev not in stop_graph:
1377
# our previous tip is not merged into stop_revision
1378
raise errors.DivergedBranches(self, other_branch)
1379
# make a new revision history from the graph
1380
current_rev_id = revision_id
1382
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1383
new_history.append(current_rev_id)
1384
current_rev_id_parents = stop_graph[current_rev_id]
1386
current_rev_id = current_rev_id_parents[0]
1388
current_rev_id = None
1389
new_history.reverse()
1393
def generate_revision_history(self, revision_id, last_rev=None,
1395
"""Create a new revision history that will finish with revision_id.
1397
:param revision_id: the new tip to use.
1398
:param last_rev: The previous last_revision. If not None, then this
1399
must be a ancestory of revision_id, or DivergedBranches is raised.
1400
:param other_branch: The other branch that DivergedBranches should
1401
raise with respect to.
1403
revision_id = osutils.safe_revision_id(revision_id)
1404
self.set_revision_history(self._lefthand_history(revision_id,
1405
last_rev, other_branch))
1408
def update_revisions(self, other, stop_revision=None):
1409
"""See Branch.update_revisions."""
1412
if stop_revision is None:
1413
stop_revision = other.last_revision()
1414
if stop_revision is None:
1415
# if there are no commits, we're done.
1418
stop_revision = osutils.safe_revision_id(stop_revision)
1419
# whats the current last revision, before we fetch [and change it
1421
last_rev = self.last_revision()
1422
# we fetch here regardless of whether we need to so that we pickup
1424
self.fetch(other, stop_revision)
1425
my_ancestry = self.repository.get_ancestry(last_rev)
1426
if stop_revision in my_ancestry:
1427
# last_revision is a descendant of stop_revision
1429
self.generate_revision_history(stop_revision, last_rev=last_rev,
2557
1434
def basis_tree(self):
2558
1435
"""See Branch.basis_tree."""
2559
1436
return self.repository.revision_tree(self.last_revision())
1438
@deprecated_method(zero_eight)
1439
def working_tree(self):
1440
"""Create a Working tree object for this branch."""
1442
from bzrlib.transport.local import LocalTransport
1443
if (self.base.find('://') != -1 or
1444
not isinstance(self._transport, LocalTransport)):
1445
raise NoWorkingTree(self.base)
1446
return self.bzrdir.open_workingtree()
1449
def pull(self, source, overwrite=False, stop_revision=None,
1450
_hook_master=None, _run_hooks=True):
1453
:param _hook_master: Private parameter - set the branch to
1454
be supplied as the master to push hooks.
1455
:param _run_hooks: Private parameter - allow disabling of
1456
hooks, used when pushing to a master branch.
1458
result = PullResult()
1459
result.source_branch = source
1460
result.target_branch = self
1463
result.old_revno, result.old_revid = self.last_revision_info()
1465
self.update_revisions(source, stop_revision)
1466
except DivergedBranches:
1470
if stop_revision is None:
1471
stop_revision = source.last_revision()
1472
self.generate_revision_history(stop_revision)
1473
result.tag_conflicts = source.tags.merge_to(self.tags)
1474
result.new_revno, result.new_revid = self.last_revision_info()
1476
result.master_branch = _hook_master
1477
result.local_branch = self
1479
result.master_branch = self
1480
result.local_branch = None
1482
for hook in Branch.hooks['post_pull']:
2561
1488
def _get_parent_location(self):
2562
1489
_locs = ['parent', 'pull', 'x-pull']
2563
1490
for l in _locs:
2565
return self._transport.get_bytes(l).strip('\n')
2566
except errors.NoSuchFile:
1492
return self.control_files.get(l).read().strip('\n')
2570
def get_stacked_on_url(self):
2571
raise errors.UnstackableBranchFormat(self._format, self.user_url)
1498
def push(self, target, overwrite=False, stop_revision=None,
1499
_hook_master=None, _run_hooks=True):
1502
:param _hook_master: Private parameter - set the branch to
1503
be supplied as the master to push hooks.
1504
:param _run_hooks: Private parameter - allow disabling of
1505
hooks, used when pushing to a master branch.
1507
result = PushResult()
1508
result.source_branch = self
1509
result.target_branch = target
1512
result.old_revno, result.old_revid = target.last_revision_info()
1514
target.update_revisions(self, stop_revision)
1515
except DivergedBranches:
1519
target.set_revision_history(self.revision_history())
1520
result.tag_conflicts = self.tags.merge_to(target.tags)
1521
result.new_revno, result.new_revid = target.last_revision_info()
1523
result.master_branch = _hook_master
1524
result.local_branch = target
1526
result.master_branch = target
1527
result.local_branch = None
1529
for hook in Branch.hooks['post_push']:
1535
def get_parent(self):
1536
"""See Branch.get_parent."""
1538
assert self.base[-1] == '/'
1539
parent = self._get_parent_location()
1542
# This is an old-format absolute path to a local branch
1543
# turn it into a url
1544
if parent.startswith('/'):
1545
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1547
return urlutils.join(self.base[:-1], parent)
1548
except errors.InvalidURLJoin, e:
1549
raise errors.InaccessibleParent(parent, self.base)
1551
def get_push_location(self):
1552
"""See Branch.get_push_location."""
1553
push_loc = self.get_config().get_user_option('push_location')
2573
1556
def set_push_location(self, location):
2574
1557
"""See Branch.set_push_location."""
2576
1559
'push_location', location,
2577
1560
store=_mod_config.STORE_LOCATION_NORECURSE)
1563
def set_parent(self, url):
1564
"""See Branch.set_parent."""
1565
# TODO: Maybe delete old location files?
1566
# URLs should never be unicode, even on the local fs,
1567
# FIXUP this and get_parent in a future branch format bump:
1568
# read and rewrite the file, and have the new format code read
1569
# using .get not .get_utf8. RBC 20060125
1571
if isinstance(url, unicode):
1573
url = url.encode('ascii')
1574
except UnicodeEncodeError:
1575
raise bzrlib.errors.InvalidURL(url,
1576
"Urls must be 7-bit ascii, "
1577
"use bzrlib.urlutils.escape")
1578
url = urlutils.relative_url(self.base, url)
1579
self._set_parent_location(url)
2579
1581
def _set_parent_location(self, url):
2580
1582
if url is None:
2581
self._transport.delete('parent')
2583
self._transport.put_bytes('parent', url + '\n',
2584
mode=self.bzrdir._get_file_mode())
2588
"""If bound, unbind"""
2589
return self.set_bound_location(None)
1583
self.control_files._transport.delete('parent')
1585
assert isinstance(url, str)
1586
self.control_files.put_bytes('parent', url + '\n')
1588
@deprecated_function(zero_nine)
1589
def tree_config(self):
1590
"""DEPRECATED; call get_config instead.
1591
TreeConfig has become part of BranchConfig."""
1592
return TreeConfig(self)
1595
class BzrBranch5(BzrBranch):
1596
"""A format 5 branch. This supports new features over plan branches.
1598
It has support for a master_branch which is the data for bound branches.
1606
super(BzrBranch5, self).__init__(_format=_format,
1607
_control_files=_control_files,
1609
_repository=_repository)
1612
def pull(self, source, overwrite=False, stop_revision=None,
1614
"""Extends branch.pull to be bound branch aware.
1616
:param _run_hooks: Private parameter used to force hook running
1617
off during bound branch double-pushing.
1619
bound_location = self.get_bound_location()
1620
master_branch = None
1621
if bound_location and source.base != bound_location:
1622
# not pulling from master, so we need to update master.
1623
master_branch = self.get_master_branch()
1624
master_branch.lock_write()
1627
# pull from source into master.
1628
master_branch.pull(source, overwrite, stop_revision,
1630
return super(BzrBranch5, self).pull(source, overwrite,
1631
stop_revision, _hook_master=master_branch,
1632
_run_hooks=_run_hooks)
1635
master_branch.unlock()
1638
def push(self, target, overwrite=False, stop_revision=None):
1639
"""Updates branch.push to be bound branch aware."""
1640
bound_location = target.get_bound_location()
1641
master_branch = None
1642
if bound_location and target.base != bound_location:
1643
# not pushing to master, so we need to update master.
1644
master_branch = target.get_master_branch()
1645
master_branch.lock_write()
1648
# push into the master from this branch.
1649
super(BzrBranch5, self).push(master_branch, overwrite,
1650
stop_revision, _run_hooks=False)
1651
# and push into the target branch from this. Note that we push from
1652
# this branch again, because its considered the highest bandwidth
1654
return super(BzrBranch5, self).push(target, overwrite,
1655
stop_revision, _hook_master=master_branch)
1658
master_branch.unlock()
1660
def get_bound_location(self):
1662
return self.control_files.get_utf8('bound').read()[:-1]
1663
except errors.NoSuchFile:
1667
def get_master_branch(self):
1668
"""Return the branch we are bound to.
1670
:return: Either a Branch, or None
1672
This could memoise the branch, but if thats done
1673
it must be revalidated on each new lock.
1674
So for now we just don't memoise it.
1675
# RBC 20060304 review this decision.
1677
bound_loc = self.get_bound_location()
1681
return Branch.open(bound_loc)
1682
except (errors.NotBranchError, errors.ConnectionError), e:
1683
raise errors.BoundBranchConnectionFailure(
1687
def set_bound_location(self, location):
1688
"""Set the target where this branch is bound to.
1690
:param location: URL to the target branch
1693
self.control_files.put_utf8('bound', location+'\n')
1696
self.control_files._transport.delete('bound')
2591
1701
@needs_write_lock
2592
1702
def bind(self, other):
2612
1722
# last_rev is not in the other_last_rev history, AND
2613
1723
# other_last_rev is not in our history, and do it without pulling
2614
1724
# history around
1725
last_rev = self.last_revision()
1726
if last_rev is not None:
1729
other_last_rev = other.last_revision()
1730
if other_last_rev is not None:
1731
# neither branch is new, we have to do some work to
1732
# ascertain diversion.
1733
remote_graph = other.repository.get_revision_graph(
1735
local_graph = self.repository.get_revision_graph(last_rev)
1736
if (last_rev not in remote_graph and
1737
other_last_rev not in local_graph):
1738
raise errors.DivergedBranches(self, other)
2615
1741
self.set_bound_location(other.base)
2617
def get_bound_location(self):
2619
return self._transport.get_bytes('bound')[:-1]
2620
except errors.NoSuchFile:
2624
def get_master_branch(self, possible_transports=None):
2625
"""Return the branch we are bound to.
2627
:return: Either a Branch, or None
2629
if self._master_branch_cache is None:
2630
self._master_branch_cache = self._get_master_branch(
2631
possible_transports)
2632
return self._master_branch_cache
2634
def _get_master_branch(self, possible_transports):
2635
bound_loc = self.get_bound_location()
2639
return Branch.open(bound_loc,
2640
possible_transports=possible_transports)
2641
except (errors.NotBranchError, errors.ConnectionError), e:
2642
raise errors.BoundBranchConnectionFailure(
2646
def set_bound_location(self, location):
2647
"""Set the target where this branch is bound to.
2649
:param location: URL to the target branch
2651
self._master_branch_cache = None
2653
self._transport.put_bytes('bound', location+'\n',
2654
mode=self.bzrdir._get_file_mode())
2657
self._transport.delete('bound')
2658
except errors.NoSuchFile:
2663
def update(self, possible_transports=None):
2664
"""Synchronise this branch with the master branch if any.
1745
"""If bound, unbind"""
1746
return self.set_bound_location(None)
1750
"""Synchronise this branch with the master branch if any.
2666
1752
:return: None or the last_revision that was pivoted out during the
2669
master = self.get_master_branch(possible_transports)
1755
master = self.get_master_branch()
2670
1756
if master is not None:
2671
old_tip = _mod_revision.ensure_null(self.last_revision())
1757
old_tip = self.last_revision()
2672
1758
self.pull(master, overwrite=True)
2673
if self.repository.get_graph().is_ancestor(old_tip,
2674
_mod_revision.ensure_null(self.last_revision())):
1759
if old_tip in self.repository.get_ancestry(self.last_revision()):
2679
def _read_last_revision_info(self):
2680
revision_string = self._transport.get_bytes('last-revision')
1765
class BzrBranchExperimental(BzrBranch5):
1766
"""Bzr experimental branch format
1769
- a revision-history file.
1771
- a lock dir guarding the branch itself
1772
- all of this stored in a branch/ subdirectory
1773
- works with shared repositories.
1774
- a tag dictionary in the branch
1776
This format is new in bzr 0.15, but shouldn't be used for real data,
1779
This class acts as it's own BranchFormat.
1782
_matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1785
def get_format_string(cls):
1786
"""See BranchFormat.get_format_string()."""
1787
return "Bazaar-NG branch format experimental\n"
1790
def get_format_description(cls):
1791
"""See BranchFormat.get_format_description()."""
1792
return "Experimental branch format"
1795
def _initialize_control_files(cls, a_bzrdir, utf8_files, lock_filename,
1797
branch_transport = a_bzrdir.get_branch_transport(cls)
1798
control_files = lockable_files.LockableFiles(branch_transport,
1799
lock_filename, lock_class)
1800
control_files.create_lock()
1801
control_files.lock_write()
1803
for filename, content in utf8_files:
1804
control_files.put_utf8(filename, content)
1806
control_files.unlock()
1809
def initialize(cls, a_bzrdir):
1810
"""Create a branch of this format in a_bzrdir."""
1811
utf8_files = [('format', cls.get_format_string()),
1812
('revision-history', ''),
1813
('branch-name', ''),
1816
cls._initialize_control_files(a_bzrdir, utf8_files,
1817
'lock', lockdir.LockDir)
1818
return cls.open(a_bzrdir, _found=True)
1821
def open(cls, a_bzrdir, _found=False):
1822
"""Return the branch object for a_bzrdir
1824
_found is a private parameter, do not use it. It is used to indicate
1825
if format probing has already be done.
1828
format = BranchFormat.find_format(a_bzrdir)
1829
assert format.__class__ == cls
1830
transport = a_bzrdir.get_branch_transport(None)
1831
control_files = lockable_files.LockableFiles(transport, 'lock',
1833
return cls(_format=cls,
1834
_control_files=control_files,
1836
_repository=a_bzrdir.find_repository())
1839
def is_supported(cls):
1842
def _make_tags(self):
1843
return BasicTags(self)
1846
def supports_tags(cls):
1850
BranchFormat.register_format(BzrBranchExperimental)
1853
class BzrBranch6(BzrBranch5):
1856
def last_revision_info(self):
1857
revision_string = self.control_files.get('last-revision').read()
2681
1858
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2682
1859
revision_id = cache_utf8.get_cached_utf8(revision_id)
2683
1860
revno = int(revno)
2684
1861
return revno, revision_id
1863
def last_revision(self):
1864
"""Return last revision id, or None"""
1865
revision_id = self.last_revision_info()[1]
1866
if revision_id == _mod_revision.NULL_REVISION:
2686
1870
def _write_last_revision_info(self, revno, revision_id):
2687
1871
"""Simply write out the revision id, with no checks.
2689
1873
Use set_last_revision_info to perform this safely.
2691
1875
Does not update the revision_history cache.
1876
Intended to be called by set_last_revision_info and
1877
_write_revision_history.
2693
revision_id = _mod_revision.ensure_null(revision_id)
1879
if revision_id is None:
1880
revision_id = 'null:'
2694
1881
out_string = '%d %s\n' % (revno, revision_id)
2695
self._transport.put_bytes('last-revision', out_string,
2696
mode=self.bzrdir._get_file_mode())
2699
class FullHistoryBzrBranch(BzrBranch):
2700
"""Bzr branch which contains the full revision history."""
1882
self.control_files.put_bytes('last-revision', out_string)
2702
1884
@needs_write_lock
2703
1885
def set_last_revision_info(self, revno, revision_id):
2704
if not revision_id or not isinstance(revision_id, basestring):
2705
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2706
revision_id = _mod_revision.ensure_null(revision_id)
2707
# this old format stores the full history, but this api doesn't
2708
# provide it, so we must generate, and might as well check it's
2710
history = self._lefthand_history(revision_id)
2711
if len(history) != revno:
2712
raise AssertionError('%d != %d' % (len(history), revno))
2713
self._set_revision_history(history)
2715
def _read_last_revision_info(self):
2716
rh = self.revision_history()
2719
return (revno, rh[-1])
2721
return (0, _mod_revision.NULL_REVISION)
2723
@deprecated_method(deprecated_in((2, 4, 0)))
2725
def set_revision_history(self, rev_history):
2726
"""See Branch.set_revision_history."""
2727
self._set_revision_history(rev_history)
2729
def _set_revision_history(self, rev_history):
2730
if 'evil' in debug.debug_flags:
2731
mutter_callsite(3, "set_revision_history scales with history.")
2732
check_not_reserved_id = _mod_revision.check_not_reserved_id
2733
for rev_id in rev_history:
2734
check_not_reserved_id(rev_id)
2735
if Branch.hooks['post_change_branch_tip']:
2736
# Don't calculate the last_revision_info() if there are no hooks
2738
old_revno, old_revid = self.last_revision_info()
2739
if len(rev_history) == 0:
2740
revid = _mod_revision.NULL_REVISION
2742
revid = rev_history[-1]
2743
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2744
self._write_revision_history(rev_history)
2745
self._clear_cached_state()
2746
self._cache_revision_history(rev_history)
2747
for hook in Branch.hooks['set_rh']:
2748
hook(self, rev_history)
2749
if Branch.hooks['post_change_branch_tip']:
2750
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2752
def _write_revision_history(self, history):
2753
"""Factored out of set_revision_history.
2755
This performs the actual writing to disk.
2756
It is intended to be called by set_revision_history."""
2757
self._transport.put_bytes(
2758
'revision-history', '\n'.join(history),
2759
mode=self.bzrdir._get_file_mode())
2761
def _gen_revision_history(self):
2762
history = self._transport.get_bytes('revision-history').split('\n')
2763
if history[-1:] == ['']:
2764
# There shouldn't be a trailing newline, but just in case.
2768
def _synchronize_history(self, destination, revision_id):
2769
if not isinstance(destination, FullHistoryBzrBranch):
2770
super(BzrBranch, self)._synchronize_history(
2771
destination, revision_id)
2773
if revision_id == _mod_revision.NULL_REVISION:
2776
new_history = self.revision_history()
2777
if revision_id is not None and new_history != []:
2779
new_history = new_history[:new_history.index(revision_id) + 1]
2781
rev = self.repository.get_revision(revision_id)
2782
new_history = rev.get_history(self.repository)[1:]
2783
destination._set_revision_history(new_history)
2786
def generate_revision_history(self, revision_id, last_rev=None,
2788
"""Create a new revision history that will finish with revision_id.
2790
:param revision_id: the new tip to use.
2791
:param last_rev: The previous last_revision. If not None, then this
2792
must be a ancestory of revision_id, or DivergedBranches is raised.
2793
:param other_branch: The other branch that DivergedBranches should
2794
raise with respect to.
2796
self._set_revision_history(self._lefthand_history(revision_id,
2797
last_rev, other_branch))
2800
class BzrBranch5(FullHistoryBzrBranch):
2801
"""A format 5 branch. This supports new features over plain branches.
2803
It has support for a master_branch which is the data for bound branches.
2807
class BzrBranch8(BzrBranch):
2808
"""A branch that stores tree-reference locations."""
2810
def _open_hook(self):
2811
if self._ignore_fallbacks:
2814
url = self.get_stacked_on_url()
2815
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2816
errors.UnstackableBranchFormat):
2819
for hook in Branch.hooks['transform_fallback_location']:
2820
url = hook(self, url)
2822
hook_name = Branch.hooks.get_hook_name(hook)
2823
raise AssertionError(
2824
"'transform_fallback_location' hook %s returned "
2825
"None, not a URL." % hook_name)
2826
self._activate_fallback_location(url)
2828
def __init__(self, *args, **kwargs):
2829
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2830
super(BzrBranch8, self).__init__(*args, **kwargs)
2831
self._last_revision_info_cache = None
2832
self._reference_info = None
2834
def _clear_cached_state(self):
2835
super(BzrBranch8, self)._clear_cached_state()
2836
self._last_revision_info_cache = None
2837
self._reference_info = None
1886
revision_id = osutils.safe_revision_id(revision_id)
1887
if self._get_append_revisions_only():
1888
self._check_history_violation(revision_id)
1889
self._write_last_revision_info(revno, revision_id)
1890
transaction = self.get_transaction()
1891
cached_history = transaction.map.find_revision_history()
1892
if cached_history is not None:
1893
transaction.map.remove_object(cached_history)
2839
1895
def _check_history_violation(self, revision_id):
2840
current_revid = self.last_revision()
2841
last_revision = _mod_revision.ensure_null(current_revid)
2842
if _mod_revision.is_null(last_revision):
1896
last_revision = self.last_revision()
1897
if last_revision is None:
2844
graph = self.repository.get_graph()
2845
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2846
if lh_ancestor == current_revid:
2848
raise errors.AppendRevisionsOnlyViolation(self.user_url)
1899
if last_revision not in self._lefthand_history(revision_id):
1900
raise errors.AppendRevisionsOnlyViolation(self.base)
2850
1902
def _gen_revision_history(self):
2851
1903
"""Generate the revision history from last revision
2853
last_revno, last_revision = self.last_revision_info()
2854
self._extend_partial_history(stop_index=last_revno-1)
2855
return list(reversed(self._partial_revision_history_cache))
1905
history = list(self.repository.iter_reverse_revision_history(
1906
self.last_revision()))
1910
def _write_revision_history(self, history):
1911
"""Factored out of set_revision_history.
1913
This performs the actual writing to disk, with format-specific checks.
1914
It is intended to be called by BzrBranch5.set_revision_history.
1916
if len(history) == 0:
1917
last_revision = 'null:'
1919
if history != self._lefthand_history(history[-1]):
1920
raise errors.NotLefthandHistory(history)
1921
last_revision = history[-1]
1922
if self._get_append_revisions_only():
1923
self._check_history_violation(last_revision)
1924
self._write_last_revision_info(len(history), last_revision)
1927
def append_revision(self, *revision_ids):
1928
revision_ids = [osutils.safe_revision_id(r) for r in revision_ids]
1929
if len(revision_ids) == 0:
1931
prev_revno, prev_revision = self.last_revision_info()
1932
for revision in self.repository.get_revisions(revision_ids):
1933
if prev_revision == _mod_revision.NULL_REVISION:
1934
if revision.parent_ids != []:
1935
raise errors.NotLeftParentDescendant(self, prev_revision,
1936
revision.revision_id)
1938
if revision.parent_ids[0] != prev_revision:
1939
raise errors.NotLeftParentDescendant(self, prev_revision,
1940
revision.revision_id)
1941
prev_revision = revision.revision_id
1942
self.set_last_revision_info(prev_revno + len(revision_ids),
1945
def _set_config_location(self, name, url, config=None,
1946
make_relative=False):
1948
config = self.get_config()
1952
url = urlutils.relative_url(self.base, url)
1953
config.set_user_option(name, url)
1956
def _get_config_location(self, name, config=None):
1958
config = self.get_config()
1959
location = config.get_user_option(name)
2857
1964
@needs_write_lock
2858
1965
def _set_parent_location(self, url):
2864
1971
"""Set the parent branch"""
2865
1972
return self._get_config_location('parent_location')
2868
def _set_all_reference_info(self, info_dict):
2869
"""Replace all reference info stored in a branch.
2871
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2874
writer = rio.RioWriter(s)
2875
for key, (tree_path, branch_location) in info_dict.iteritems():
2876
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2877
branch_location=branch_location)
2878
writer.write_stanza(stanza)
2879
self._transport.put_bytes('references', s.getvalue())
2880
self._reference_info = info_dict
2883
def _get_all_reference_info(self):
2884
"""Return all the reference info stored in a branch.
2886
:return: A dict of {file_id: (tree_path, branch_location)}
2888
if self._reference_info is not None:
2889
return self._reference_info
2890
rio_file = self._transport.get('references')
2892
stanzas = rio.read_stanzas(rio_file)
2893
info_dict = dict((s['file_id'], (s['tree_path'],
2894
s['branch_location'])) for s in stanzas)
2897
self._reference_info = info_dict
2900
def set_reference_info(self, file_id, tree_path, branch_location):
2901
"""Set the branch location to use for a tree reference.
2903
:param file_id: The file-id of the tree reference.
2904
:param tree_path: The path of the tree reference in the tree.
2905
:param branch_location: The location of the branch to retrieve tree
2908
info_dict = self._get_all_reference_info()
2909
info_dict[file_id] = (tree_path, branch_location)
2910
if None in (tree_path, branch_location):
2911
if tree_path is not None:
2912
raise ValueError('tree_path must be None when branch_location'
2914
if branch_location is not None:
2915
raise ValueError('branch_location must be None when tree_path'
2917
del info_dict[file_id]
2918
self._set_all_reference_info(info_dict)
2920
def get_reference_info(self, file_id):
2921
"""Get the tree_path and branch_location for a tree reference.
2923
:return: a tuple of (tree_path, branch_location)
2925
return self._get_all_reference_info().get(file_id, (None, None))
2927
def reference_parent(self, file_id, path, possible_transports=None):
2928
"""Return the parent branch for a tree-reference file_id.
2930
:param file_id: The file_id of the tree reference
2931
:param path: The path of the file_id in the tree
2932
:return: A branch associated with the file_id
2934
branch_location = self.get_reference_info(file_id)[1]
2935
if branch_location is None:
2936
return Branch.reference_parent(self, file_id, path,
2937
possible_transports)
2938
branch_location = urlutils.join(self.user_url, branch_location)
2939
return Branch.open(branch_location,
2940
possible_transports=possible_transports)
2942
1974
def set_push_location(self, location):
2943
1975
"""See Branch.set_push_location."""
2944
1976
self._set_config_location('push_location', location)
2946
1978
def set_bound_location(self, location):
2947
1979
"""See Branch.set_push_location."""
2948
self._master_branch_cache = None
2950
1981
config = self.get_config()
2951
1982
if location is None:
2952
1983
if config.get_user_option('bound') != 'True':
2955
config.set_user_option('bound', 'False', warn_masked=True)
1986
config.set_user_option('bound', 'False')
2958
1989
self._set_config_location('bound_location', location,
2960
config.set_user_option('bound', 'True', warn_masked=True)
1991
config.set_user_option('bound', 'True')
2963
1994
def _get_bound_location(self, bound):
2978
2009
"""See Branch.get_old_bound_location"""
2979
2010
return self._get_bound_location(False)
2981
def get_stacked_on_url(self):
2982
# you can always ask for the URL; but you might not be able to use it
2983
# if the repo can't support stacking.
2984
## self._check_stackable_repo()
2985
# stacked_on_location is only ever defined in branch.conf, so don't
2986
# waste effort reading the whole stack of config files.
2987
config = self.get_config()._get_branch_data_config()
2988
stacked_url = self._get_config_location('stacked_on_location',
2990
if stacked_url is None:
2991
raise errors.NotStacked(self)
2995
def get_rev_id(self, revno, history=None):
2996
"""Find the revision id of the specified revno."""
2998
return _mod_revision.NULL_REVISION
3000
last_revno, last_revision_id = self.last_revision_info()
3001
if revno <= 0 or revno > last_revno:
3002
raise errors.NoSuchRevision(self, revno)
3004
if history is not None:
3005
return history[revno - 1]
3007
index = last_revno - revno
3008
if len(self._partial_revision_history_cache) <= index:
3009
self._extend_partial_history(stop_index=index)
3010
if len(self._partial_revision_history_cache) > index:
3011
return self._partial_revision_history_cache[index]
3013
raise errors.NoSuchRevision(self, revno)
3016
def revision_id_to_revno(self, revision_id):
3017
"""Given a revision id, return its revno"""
3018
if _mod_revision.is_null(revision_id):
3021
index = self._partial_revision_history_cache.index(revision_id)
3024
self._extend_partial_history(stop_revision=revision_id)
3025
except errors.RevisionNotPresent, e:
3026
raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
3027
index = len(self._partial_revision_history_cache) - 1
3028
if self._partial_revision_history_cache[index] != revision_id:
3029
raise errors.NoSuchRevision(self, revision_id)
3030
return self.revno() - index
3033
class BzrBranch7(BzrBranch8):
3034
"""A branch with support for a fallback repository."""
3036
def set_reference_info(self, file_id, tree_path, branch_location):
3037
Branch.set_reference_info(self, file_id, tree_path, branch_location)
3039
def get_reference_info(self, file_id):
3040
Branch.get_reference_info(self, file_id)
3042
def reference_parent(self, file_id, path, possible_transports=None):
3043
return Branch.reference_parent(self, file_id, path,
3044
possible_transports)
3047
class BzrBranch6(BzrBranch7):
3048
"""See BzrBranchFormat6 for the capabilities of this branch.
3050
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2012
def set_append_revisions_only(self, enabled):
2017
self.get_config().set_user_option('append_revisions_only', value)
2019
def _get_append_revisions_only(self):
2020
value = self.get_config().get_user_option('append_revisions_only')
2021
return value == 'True'
2023
def _synchronize_history(self, destination, revision_id):
2024
"""Synchronize last revision and revision history between branches.
2026
This version is most efficient when the destination is also a
2027
BzrBranch6, but works for BzrBranch5, as long as the destination's
2028
repository contains all the lefthand ancestors of the intended
2029
last_revision. If not, set_last_revision_info will fail.
2031
:param destination: The branch to copy the history into
2032
:param revision_id: The revision-id to truncate history at. May
2033
be None to copy complete history.
2035
if revision_id is None:
2036
revno, revision_id = self.last_revision_info()
2038
revno = self.revision_id_to_revno(revision_id)
2039
destination.set_last_revision_info(revno, revision_id)
2041
def _make_tags(self):
2042
return BasicTags(self)
2045
class BranchTestProviderAdapter(object):
2046
"""A tool to generate a suite testing multiple branch formats at once.
2048
This is done by copying the test once for each transport and injecting
2049
the transport_server, transport_readonly_server, and branch_format
2050
classes into each copy. Each copy is also given a new id() to make it
3054
def get_stacked_on_url(self):
3055
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2054
def __init__(self, transport_server, transport_readonly_server, formats):
2055
self._transport_server = transport_server
2056
self._transport_readonly_server = transport_readonly_server
2057
self._formats = formats
2059
def adapt(self, test):
2060
result = TestSuite()
2061
for branch_format, bzrdir_format in self._formats:
2062
new_test = deepcopy(test)
2063
new_test.transport_server = self._transport_server
2064
new_test.transport_readonly_server = self._transport_readonly_server
2065
new_test.bzrdir_format = bzrdir_format
2066
new_test.branch_format = branch_format
2067
def make_new_test_id():
2068
# the format can be either a class or an instance
2069
name = getattr(branch_format, '__name__',
2070
branch_format.__class__.__name__)
2071
new_id = "%s(%s)" % (new_test.id(), name)
2072
return lambda: new_id
2073
new_test.id = make_new_test_id()
2074
result.addTest(new_test)
3058
2078
######################################################################
3076
2096
:ivar new_revno: Revision number after pull.
3077
2097
:ivar old_revid: Tip revision id before pull.
3078
2098
:ivar new_revid: Tip revision id after pull.
3079
:ivar source_branch: Source (local) branch object. (read locked)
3080
:ivar master_branch: Master branch of the target, or the target if no
3082
:ivar local_branch: target branch if there is a Master, else None
3083
:ivar target_branch: Target/destination branch object. (write locked)
3084
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3085
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
2099
:ivar source_branch: Source (local) branch object.
2100
:ivar master_branch: Master branch of the target, or None.
2101
:ivar target_branch: Target/destination branch object.
3088
@deprecated_method(deprecated_in((2, 3, 0)))
3089
2104
def __int__(self):
3090
"""Return the relative change in revno.
3092
:deprecated: Use `new_revno` and `old_revno` instead.
2105
# DEPRECATED: pull used to return the change in revno
3094
2106
return self.new_revno - self.old_revno
3096
2108
def report(self, to_file):
3097
tag_conflicts = getattr(self, "tag_conflicts", None)
3098
tag_updates = getattr(self, "tag_updates", None)
3100
if self.old_revid != self.new_revid:
3101
to_file.write('Now on revision %d.\n' % self.new_revno)
3103
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3104
if self.old_revid == self.new_revid and not tag_updates:
3105
if not tag_conflicts:
3106
to_file.write('No revisions or tags to pull.\n')
3108
to_file.write('No revisions to pull.\n')
2109
if self.old_revid == self.new_revid:
2110
to_file.write('No revisions to pull.\n')
2112
to_file.write('Now on revision %d.\n' % self.new_revno)
3109
2113
self._show_tag_conficts(to_file)
3112
class BranchPushResult(_Result):
2116
class PushResult(_Result):
3113
2117
"""Result of a Branch.push operation.
3115
:ivar old_revno: Revision number (eg 10) of the target before push.
3116
:ivar new_revno: Revision number (eg 12) of the target after push.
3117
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
3119
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
3121
:ivar source_branch: Source branch object that the push was from. This is
3122
read locked, and generally is a local (and thus low latency) branch.
3123
:ivar master_branch: If target is a bound branch, the master branch of
3124
target, or target itself. Always write locked.
3125
:ivar target_branch: The direct Branch where data is being sent (write
3127
:ivar local_branch: If the target is a bound branch this will be the
3128
target, otherwise it will be None.
2119
:ivar old_revno: Revision number before push.
2120
:ivar new_revno: Revision number after push.
2121
:ivar old_revid: Tip revision id before push.
2122
:ivar new_revid: Tip revision id after push.
2123
:ivar source_branch: Source branch object.
2124
:ivar master_branch: Master branch of the target, or None.
2125
:ivar target_branch: Target/destination branch object.
3131
@deprecated_method(deprecated_in((2, 3, 0)))
3132
2128
def __int__(self):
3133
"""Return the relative change in revno.
3135
:deprecated: Use `new_revno` and `old_revno` instead.
2129
# DEPRECATED: push used to return the change in revno
3137
2130
return self.new_revno - self.old_revno
3139
2132
def report(self, to_file):
3140
# TODO: This function gets passed a to_file, but then
3141
# ignores it and calls note() instead. This is also
3142
# inconsistent with PullResult(), which writes to stdout.
3143
# -- JRV20110901, bug #838853
3144
tag_conflicts = getattr(self, "tag_conflicts", None)
3145
tag_updates = getattr(self, "tag_updates", None)
3147
if self.old_revid != self.new_revid:
3148
note(gettext('Pushed up to revision %d.') % self.new_revno)
3150
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3151
if self.old_revid == self.new_revid and not tag_updates:
3152
if not tag_conflicts:
3153
note(gettext('No new revisions or tags to push.'))
3155
note(gettext('No new revisions to push.'))
2133
"""Write a human-readable description of the result."""
2134
if self.old_revid == self.new_revid:
2135
to_file.write('No new revisions to push.\n')
2137
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
3156
2138
self._show_tag_conficts(to_file)
3196
2176
new_branch.tags._set_tag_dict({})
3198
2178
# Copying done; now update target format
3199
new_branch._transport.put_bytes('format',
3200
format.get_format_string(),
3201
mode=new_branch.bzrdir._get_file_mode())
2179
new_branch.control_files.put_utf8('format',
2180
format.get_format_string())
3203
2182
# Clean up old files
3204
new_branch._transport.delete('revision-history')
2183
new_branch.control_files._transport.delete('revision-history')
3206
2185
branch.set_parent(None)
3207
except errors.NoSuchFile:
3209
2188
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 7 to format 8"""
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
class InterBranch(InterObject):
3233
"""This class represents operations taking place between two branches.
3235
Its instances have methods like pull() and push() and contain
3236
references to the source and target repositories these operations
3237
can be carried out on.
3241
"""The available optimised InterBranch types."""
3244
def _get_branch_formats_to_test(klass):
3245
"""Return an iterable of format tuples for testing.
3247
:return: An iterable of (from_format, to_format) to use when testing
3248
this InterBranch class. Each InterBranch class should define this
3251
raise NotImplementedError(klass._get_branch_formats_to_test)
3254
def pull(self, overwrite=False, stop_revision=None,
3255
possible_transports=None, local=False):
3256
"""Mirror source into target branch.
3258
The target branch is considered to be 'local', having low latency.
3260
:returns: PullResult instance
3262
raise NotImplementedError(self.pull)
3265
def push(self, overwrite=False, stop_revision=None, lossy=False,
3266
_override_hook_source_branch=None):
3267
"""Mirror the source branch into the target branch.
3269
The source branch is considered to be 'local', having low latency.
3271
raise NotImplementedError(self.push)
3274
def copy_content_into(self, revision_id=None):
3275
"""Copy the content of source into target
3277
revision_id: if not None, the revision history in the new branch will
3278
be truncated to end with revision_id.
3280
raise NotImplementedError(self.copy_content_into)
3283
def fetch(self, stop_revision=None, limit=None):
3286
:param stop_revision: Last revision to fetch
3287
:param limit: Optional rough limit of revisions to fetch
3289
raise NotImplementedError(self.fetch)
3292
class GenericInterBranch(InterBranch):
3293
"""InterBranch implementation that uses public Branch functions."""
3296
def is_compatible(klass, source, target):
3297
# GenericBranch uses the public API, so always compatible
3301
def _get_branch_formats_to_test(klass):
3302
return [(format_registry.get_default(), format_registry.get_default())]
3305
def unwrap_format(klass, format):
3306
if isinstance(format, remote.RemoteBranchFormat):
3307
format._ensure_real()
3308
return format._custom_format
3312
def copy_content_into(self, revision_id=None):
3313
"""Copy the content of source into target
3315
revision_id: if not None, the revision history in the new branch will
3316
be truncated to end with revision_id.
3318
self.source.update_references(self.target)
3319
self.source._synchronize_history(self.target, revision_id)
3321
parent = self.source.get_parent()
3322
except errors.InaccessibleParent, e:
3323
mutter('parent was not accessible to copy: %s', e)
3326
self.target.set_parent(parent)
3327
if self.source._push_should_merge_tags():
3328
self.source.tags.merge_to(self.target.tags)
3331
def fetch(self, stop_revision=None, limit=None):
3332
if self.target.base == self.source.base:
3334
self.source.lock_read()
3336
fetch_spec_factory = fetch.FetchSpecFactory()
3337
fetch_spec_factory.source_branch = self.source
3338
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3339
fetch_spec_factory.source_repo = self.source.repository
3340
fetch_spec_factory.target_repo = self.target.repository
3341
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3342
fetch_spec_factory.limit = limit
3343
fetch_spec = fetch_spec_factory.make_fetch_spec()
3344
return self.target.repository.fetch(self.source.repository,
3345
fetch_spec=fetch_spec)
3347
self.source.unlock()
3350
def _update_revisions(self, stop_revision=None, overwrite=False,
3352
other_revno, other_last_revision = self.source.last_revision_info()
3353
stop_revno = None # unknown
3354
if stop_revision is None:
3355
stop_revision = other_last_revision
3356
if _mod_revision.is_null(stop_revision):
3357
# if there are no commits, we're done.
3359
stop_revno = other_revno
3361
# what's the current last revision, before we fetch [and change it
3363
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3364
# we fetch here so that we don't process data twice in the common
3365
# case of having something to pull, and so that the check for
3366
# already merged can operate on the just fetched graph, which will
3367
# be cached in memory.
3368
self.fetch(stop_revision=stop_revision)
3369
# Check to see if one is an ancestor of the other
3372
graph = self.target.repository.get_graph()
3373
if self.target._check_if_descendant_or_diverged(
3374
stop_revision, last_rev, graph, self.source):
3375
# stop_revision is a descendant of last_rev, but we aren't
3376
# overwriting, so we're done.
3378
if stop_revno is None:
3380
graph = self.target.repository.get_graph()
3381
this_revno, this_last_revision = \
3382
self.target.last_revision_info()
3383
stop_revno = graph.find_distance_to_null(stop_revision,
3384
[(other_last_revision, other_revno),
3385
(this_last_revision, this_revno)])
3386
self.target.set_last_revision_info(stop_revno, stop_revision)
3389
def pull(self, overwrite=False, stop_revision=None,
3390
possible_transports=None, run_hooks=True,
3391
_override_hook_target=None, local=False):
3392
"""Pull from source into self, updating my master if any.
3394
:param run_hooks: Private parameter - if false, this branch
3395
is being called because it's the master of the primary branch,
3396
so it should not run its hooks.
3398
bound_location = self.target.get_bound_location()
3399
if local and not bound_location:
3400
raise errors.LocalRequiresBoundBranch()
3401
master_branch = None
3402
source_is_master = False
3404
# bound_location comes from a config file, some care has to be
3405
# taken to relate it to source.user_url
3406
normalized = urlutils.normalize_url(bound_location)
3408
relpath = self.source.user_transport.relpath(normalized)
3409
source_is_master = (relpath == '')
3410
except (errors.PathNotChild, errors.InvalidURL):
3411
source_is_master = False
3412
if not local and bound_location and not source_is_master:
3413
# not pulling from master, so we need to update master.
3414
master_branch = self.target.get_master_branch(possible_transports)
3415
master_branch.lock_write()
3418
# pull from source into master.
3419
master_branch.pull(self.source, overwrite, stop_revision,
3421
return self._pull(overwrite,
3422
stop_revision, _hook_master=master_branch,
3423
run_hooks=run_hooks,
3424
_override_hook_target=_override_hook_target,
3425
merge_tags_to_master=not source_is_master)
3428
master_branch.unlock()
3430
def push(self, overwrite=False, stop_revision=None, lossy=False,
3431
_override_hook_source_branch=None):
3432
"""See InterBranch.push.
3434
This is the basic concrete implementation of push()
3436
:param _override_hook_source_branch: If specified, run the hooks
3437
passing this Branch as the source, rather than self. This is for
3438
use of RemoteBranch, where push is delegated to the underlying
3442
raise errors.LossyPushToSameVCS(self.source, self.target)
3443
# TODO: Public option to disable running hooks - should be trivial but
3446
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3447
op.add_cleanup(self.source.lock_read().unlock)
3448
op.add_cleanup(self.target.lock_write().unlock)
3449
return op.run(overwrite, stop_revision,
3450
_override_hook_source_branch=_override_hook_source_branch)
3452
def _basic_push(self, overwrite, stop_revision):
3453
"""Basic implementation of push without bound branches or hooks.
3455
Must be called with source read locked and target write locked.
3457
result = BranchPushResult()
3458
result.source_branch = self.source
3459
result.target_branch = self.target
3460
result.old_revno, result.old_revid = self.target.last_revision_info()
3461
self.source.update_references(self.target)
3462
if result.old_revid != stop_revision:
3463
# We assume that during 'push' this repository is closer than
3465
graph = self.source.repository.get_graph(self.target.repository)
3466
self._update_revisions(stop_revision, overwrite=overwrite,
3468
if self.source._push_should_merge_tags():
3469
result.tag_updates, result.tag_conflicts = (
3470
self.source.tags.merge_to(self.target.tags, overwrite))
3471
result.new_revno, result.new_revid = self.target.last_revision_info()
3474
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3475
_override_hook_source_branch=None):
3476
"""Push from source into target, and into target's master if any.
3479
if _override_hook_source_branch:
3480
result.source_branch = _override_hook_source_branch
3481
for hook in Branch.hooks['post_push']:
3484
bound_location = self.target.get_bound_location()
3485
if bound_location and self.target.base != bound_location:
3486
# there is a master branch.
3488
# XXX: Why the second check? Is it even supported for a branch to
3489
# be bound to itself? -- mbp 20070507
3490
master_branch = self.target.get_master_branch()
3491
master_branch.lock_write()
3492
operation.add_cleanup(master_branch.unlock)
3493
# push into the master from the source branch.
3494
master_inter = InterBranch.get(self.source, master_branch)
3495
master_inter._basic_push(overwrite, stop_revision)
3496
# and push into the target branch from the source. Note that
3497
# we push from the source branch again, because it's considered
3498
# the highest bandwidth repository.
3499
result = self._basic_push(overwrite, stop_revision)
3500
result.master_branch = master_branch
3501
result.local_branch = self.target
3503
master_branch = None
3505
result = self._basic_push(overwrite, stop_revision)
3506
# TODO: Why set master_branch and local_branch if there's no
3507
# binding? Maybe cleaner to just leave them unset? -- mbp
3509
result.master_branch = self.target
3510
result.local_branch = None
3514
def _pull(self, overwrite=False, stop_revision=None,
3515
possible_transports=None, _hook_master=None, run_hooks=True,
3516
_override_hook_target=None, local=False,
3517
merge_tags_to_master=True):
3520
This function is the core worker, used by GenericInterBranch.pull to
3521
avoid duplication when pulling source->master and source->local.
3523
:param _hook_master: Private parameter - set the branch to
3524
be supplied as the master to pull hooks.
3525
:param run_hooks: Private parameter - if false, this branch
3526
is being called because it's the master of the primary branch,
3527
so it should not run its hooks.
3528
is being called because it's the master of the primary branch,
3529
so it should not run its hooks.
3530
:param _override_hook_target: Private parameter - set the branch to be
3531
supplied as the target_branch to pull hooks.
3532
:param local: Only update the local branch, and not the bound branch.
3534
# This type of branch can't be bound.
3536
raise errors.LocalRequiresBoundBranch()
3537
result = PullResult()
3538
result.source_branch = self.source
3539
if _override_hook_target is None:
3540
result.target_branch = self.target
3542
result.target_branch = _override_hook_target
3543
self.source.lock_read()
3545
# We assume that during 'pull' the target repository is closer than
3547
self.source.update_references(self.target)
3548
graph = self.target.repository.get_graph(self.source.repository)
3549
# TODO: Branch formats should have a flag that indicates
3550
# that revno's are expensive, and pull() should honor that flag.
3552
result.old_revno, result.old_revid = \
3553
self.target.last_revision_info()
3554
self._update_revisions(stop_revision, overwrite=overwrite,
3556
# TODO: The old revid should be specified when merging tags,
3557
# so a tags implementation that versions tags can only
3558
# pull in the most recent changes. -- JRV20090506
3559
result.tag_updates, result.tag_conflicts = (
3560
self.source.tags.merge_to(self.target.tags, overwrite,
3561
ignore_master=not merge_tags_to_master))
3562
result.new_revno, result.new_revid = self.target.last_revision_info()
3564
result.master_branch = _hook_master
3565
result.local_branch = result.target_branch
3567
result.master_branch = result.target_branch
3568
result.local_branch = None
3570
for hook in Branch.hooks['post_pull']:
3573
self.source.unlock()
3577
InterBranch.register_optimiser(GenericInterBranch)