1
# Copyright (C) 2005-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19
from cStringIO import StringIO
21
from bzrlib.lazy_import import lazy_import
22
lazy_import(globals(), """
29
config as _mod_config,
38
revision as _mod_revision,
45
from bzrlib.i18n import gettext, ngettext
51
from bzrlib.decorators import (
56
from bzrlib.hooks import Hooks
57
from bzrlib.inter import InterObject
58
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
59
from bzrlib import registry
60
from bzrlib.symbol_versioning import (
64
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
67
class Branch(controldir.ControlComponent):
68
"""Branch holding a history of revisions.
71
Base directory/url of the branch; using control_url and
72
control_transport is more standardized.
73
:ivar hooks: An instance of BranchHooks.
74
:ivar _master_branch_cache: cached result of get_master_branch, see
77
# this is really an instance variable - FIXME move it there
82
def control_transport(self):
83
return self._transport
86
def user_transport(self):
87
return self.bzrdir.user_transport
89
def __init__(self, possible_transports=None):
90
self.tags = self._format.make_tags(self)
91
self._revision_history_cache = None
92
self._revision_id_to_revno_cache = None
93
self._partial_revision_id_to_revno_cache = {}
94
self._partial_revision_history_cache = []
95
self._tags_bytes = None
96
self._last_revision_info_cache = None
97
self._master_branch_cache = None
98
self._merge_sorted_revisions_cache = None
99
self._open_hook(possible_transports)
100
hooks = Branch.hooks['open']
104
def _open_hook(self, possible_transports):
105
"""Called by init to allow simpler extension of the base class."""
107
def _activate_fallback_location(self, url, possible_transports):
108
"""Activate the branch/repository from url as a fallback repository."""
109
for existing_fallback_repo in self.repository._fallback_repositories:
110
if existing_fallback_repo.user_url == url:
111
# This fallback is already configured. This probably only
112
# happens because ControlDir.sprout is a horrible mess. To avoid
113
# confusing _unstack we don't add this a second time.
114
mutter('duplicate activation of fallback %r on %r', url, self)
116
repo = self._get_fallback_repository(url, possible_transports)
117
if repo.has_same_location(self.repository):
118
raise errors.UnstackableLocationError(self.user_url, url)
119
self.repository.add_fallback_repository(repo)
121
def break_lock(self):
122
"""Break a lock if one is present from another instance.
124
Uses the ui factory to ask for confirmation if the lock may be from
127
This will probe the repository for its lock as well.
129
self.control_files.break_lock()
130
self.repository.break_lock()
131
master = self.get_master_branch()
132
if master is not None:
135
def _check_stackable_repo(self):
136
if not self.repository._format.supports_external_lookups:
137
raise errors.UnstackableRepositoryFormat(self.repository._format,
138
self.repository.base)
140
def _extend_partial_history(self, stop_index=None, stop_revision=None):
141
"""Extend the partial history to include a given index
143
If a stop_index is supplied, stop when that index has been reached.
144
If a stop_revision is supplied, stop when that revision is
145
encountered. Otherwise, stop when the beginning of history is
148
:param stop_index: The index which should be present. When it is
149
present, history extension will stop.
150
:param stop_revision: The revision id which should be present. When
151
it is encountered, history extension will stop.
153
if len(self._partial_revision_history_cache) == 0:
154
self._partial_revision_history_cache = [self.last_revision()]
155
repository._iter_for_revno(
156
self.repository, self._partial_revision_history_cache,
157
stop_index=stop_index, stop_revision=stop_revision)
158
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
159
self._partial_revision_history_cache.pop()
161
def _get_check_refs(self):
162
"""Get the references needed for check().
166
revid = self.last_revision()
167
return [('revision-existence', revid), ('lefthand-distance', revid)]
170
def open(base, _unsupported=False, possible_transports=None):
171
"""Open the branch rooted at base.
173
For instance, if the branch is at URL/.bzr/branch,
174
Branch.open(URL) -> a Branch instance.
176
control = controldir.ControlDir.open(base, _unsupported,
177
possible_transports=possible_transports)
178
return control.open_branch(unsupported=_unsupported,
179
possible_transports=possible_transports)
182
def open_from_transport(transport, name=None, _unsupported=False,
183
possible_transports=None):
184
"""Open the branch rooted at transport"""
185
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
186
return control.open_branch(name=name, unsupported=_unsupported,
187
possible_transports=possible_transports)
190
def open_containing(url, possible_transports=None):
191
"""Open an existing branch which contains url.
193
This probes for a branch at url, and searches upwards from there.
195
Basically we keep looking up until we find the control directory or
196
run into the root. If there isn't one, raises NotBranchError.
197
If there is one and it is either an unrecognised format or an unsupported
198
format, UnknownFormatError or UnsupportedFormatError are raised.
199
If there is one, it is returned, along with the unused portion of url.
201
control, relpath = controldir.ControlDir.open_containing(url,
203
branch = control.open_branch(possible_transports=possible_transports)
204
return (branch, relpath)
206
def _push_should_merge_tags(self):
207
"""Should _basic_push merge this branch's tags into the target?
209
The default implementation returns False if this branch has no tags,
210
and True the rest of the time. Subclasses may override this.
212
return self.supports_tags() and self.tags.get_tag_dict()
214
def get_config(self):
215
"""Get a bzrlib.config.BranchConfig for this Branch.
217
This can then be used to get and set configuration options for the
220
:return: A bzrlib.config.BranchConfig.
222
return _mod_config.BranchConfig(self)
224
def get_config_stack(self):
225
"""Get a bzrlib.config.BranchStack for this Branch.
227
This can then be used to get and set configuration options for the
230
:return: A bzrlib.config.BranchStack.
232
return _mod_config.BranchStack(self)
234
def _get_config(self):
235
"""Get the concrete config for just the config in this branch.
237
This is not intended for client use; see Branch.get_config for the
242
:return: An object supporting get_option and set_option.
244
raise NotImplementedError(self._get_config)
246
def _get_fallback_repository(self, url, possible_transports):
247
"""Get the repository we fallback to at url."""
248
url = urlutils.join(self.base, url)
249
a_branch = Branch.open(url, possible_transports=possible_transports)
250
return a_branch.repository
253
def _get_tags_bytes(self):
254
"""Get the bytes of a serialised tags dict.
256
Note that not all branches support tags, nor do all use the same tags
257
logic: this method is specific to BasicTags. Other tag implementations
258
may use the same method name and behave differently, safely, because
259
of the double-dispatch via
260
format.make_tags->tags_instance->get_tags_dict.
262
:return: The bytes of the tags file.
263
:seealso: Branch._set_tags_bytes.
265
if self._tags_bytes is None:
266
self._tags_bytes = self._transport.get_bytes('tags')
267
return self._tags_bytes
269
def _get_nick(self, local=False, possible_transports=None):
270
config = self.get_config()
271
# explicit overrides master, but don't look for master if local is True
272
if not local and not config.has_explicit_nickname():
274
master = self.get_master_branch(possible_transports)
275
if master and self.user_url == master.user_url:
276
raise errors.RecursiveBind(self.user_url)
277
if master is not None:
278
# return the master branch value
280
except errors.RecursiveBind, e:
282
except errors.BzrError, e:
283
# Silently fall back to local implicit nick if the master is
285
mutter("Could not connect to bound branch, "
286
"falling back to local nick.\n " + str(e))
287
return config.get_nickname()
289
def _set_nick(self, nick):
290
self.get_config().set_user_option('nickname', nick, warn_masked=True)
292
nick = property(_get_nick, _set_nick)
295
raise NotImplementedError(self.is_locked)
297
def _lefthand_history(self, revision_id, last_rev=None,
299
if 'evil' in debug.debug_flags:
300
mutter_callsite(4, "_lefthand_history scales with history.")
301
# stop_revision must be a descendant of last_revision
302
graph = self.repository.get_graph()
303
if last_rev is not None:
304
if not graph.is_ancestor(last_rev, revision_id):
305
# our previous tip is not merged into stop_revision
306
raise errors.DivergedBranches(self, other_branch)
307
# make a new revision history from the graph
308
parents_map = graph.get_parent_map([revision_id])
309
if revision_id not in parents_map:
310
raise errors.NoSuchRevision(self, revision_id)
311
current_rev_id = revision_id
313
check_not_reserved_id = _mod_revision.check_not_reserved_id
314
# Do not include ghosts or graph origin in revision_history
315
while (current_rev_id in parents_map and
316
len(parents_map[current_rev_id]) > 0):
317
check_not_reserved_id(current_rev_id)
318
new_history.append(current_rev_id)
319
current_rev_id = parents_map[current_rev_id][0]
320
parents_map = graph.get_parent_map([current_rev_id])
321
new_history.reverse()
324
def lock_write(self, token=None):
325
"""Lock the branch for write operations.
327
:param token: A token to permit reacquiring a previously held and
329
:return: A BranchWriteLockResult.
331
raise NotImplementedError(self.lock_write)
334
"""Lock the branch for read operations.
336
:return: A bzrlib.lock.LogicalLockResult.
338
raise NotImplementedError(self.lock_read)
341
raise NotImplementedError(self.unlock)
343
def peek_lock_mode(self):
344
"""Return lock mode for the Branch: 'r', 'w' or None"""
345
raise NotImplementedError(self.peek_lock_mode)
347
def get_physical_lock_status(self):
348
raise NotImplementedError(self.get_physical_lock_status)
351
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
352
"""Return the revision_id for a dotted revno.
354
:param revno: a tuple like (1,) or (1,1,2)
355
:param _cache_reverse: a private parameter enabling storage
356
of the reverse mapping in a top level cache. (This should
357
only be done in selective circumstances as we want to
358
avoid having the mapping cached multiple times.)
359
:return: the revision_id
360
:raises errors.NoSuchRevision: if the revno doesn't exist
362
rev_id = self._do_dotted_revno_to_revision_id(revno)
364
self._partial_revision_id_to_revno_cache[rev_id] = revno
367
def _do_dotted_revno_to_revision_id(self, revno):
368
"""Worker function for dotted_revno_to_revision_id.
370
Subclasses should override this if they wish to
371
provide a more efficient implementation.
374
return self.get_rev_id(revno[0])
375
revision_id_to_revno = self.get_revision_id_to_revno_map()
376
revision_ids = [revision_id for revision_id, this_revno
377
in revision_id_to_revno.iteritems()
378
if revno == this_revno]
379
if len(revision_ids) == 1:
380
return revision_ids[0]
382
revno_str = '.'.join(map(str, revno))
383
raise errors.NoSuchRevision(self, revno_str)
386
def revision_id_to_dotted_revno(self, revision_id):
387
"""Given a revision id, return its dotted revno.
389
:return: a tuple like (1,) or (400,1,3).
391
return self._do_revision_id_to_dotted_revno(revision_id)
393
def _do_revision_id_to_dotted_revno(self, revision_id):
394
"""Worker function for revision_id_to_revno."""
395
# Try the caches if they are loaded
396
result = self._partial_revision_id_to_revno_cache.get(revision_id)
397
if result is not None:
399
if self._revision_id_to_revno_cache:
400
result = self._revision_id_to_revno_cache.get(revision_id)
402
raise errors.NoSuchRevision(self, revision_id)
403
# Try the mainline as it's optimised
405
revno = self.revision_id_to_revno(revision_id)
407
except errors.NoSuchRevision:
408
# We need to load and use the full revno map after all
409
result = self.get_revision_id_to_revno_map().get(revision_id)
411
raise errors.NoSuchRevision(self, revision_id)
415
def get_revision_id_to_revno_map(self):
416
"""Return the revision_id => dotted revno map.
418
This will be regenerated on demand, but will be cached.
420
:return: A dictionary mapping revision_id => dotted revno.
421
This dictionary should not be modified by the caller.
423
if self._revision_id_to_revno_cache is not None:
424
mapping = self._revision_id_to_revno_cache
426
mapping = self._gen_revno_map()
427
self._cache_revision_id_to_revno(mapping)
428
# TODO: jam 20070417 Since this is being cached, should we be returning
430
# I would rather not, and instead just declare that users should not
431
# modify the return value.
434
def _gen_revno_map(self):
435
"""Create a new mapping from revision ids to dotted revnos.
437
Dotted revnos are generated based on the current tip in the revision
439
This is the worker function for get_revision_id_to_revno_map, which
440
just caches the return value.
442
:return: A dictionary mapping revision_id => dotted revno.
444
revision_id_to_revno = dict((rev_id, revno)
445
for rev_id, depth, revno, end_of_merge
446
in self.iter_merge_sorted_revisions())
447
return revision_id_to_revno
450
def iter_merge_sorted_revisions(self, start_revision_id=None,
451
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
452
"""Walk the revisions for a branch in merge sorted order.
454
Merge sorted order is the output from a merge-aware,
455
topological sort, i.e. all parents come before their
456
children going forward; the opposite for reverse.
458
:param start_revision_id: the revision_id to begin walking from.
459
If None, the branch tip is used.
460
:param stop_revision_id: the revision_id to terminate the walk
461
after. If None, the rest of history is included.
462
:param stop_rule: if stop_revision_id is not None, the precise rule
463
to use for termination:
465
* 'exclude' - leave the stop revision out of the result (default)
466
* 'include' - the stop revision is the last item in the result
467
* 'with-merges' - include the stop revision and all of its
468
merged revisions in the result
469
* 'with-merges-without-common-ancestry' - filter out revisions
470
that are in both ancestries
471
:param direction: either 'reverse' or 'forward':
473
* reverse means return the start_revision_id first, i.e.
474
start at the most recent revision and go backwards in history
475
* forward returns tuples in the opposite order to reverse.
476
Note in particular that forward does *not* do any intelligent
477
ordering w.r.t. depth as some clients of this API may like.
478
(If required, that ought to be done at higher layers.)
480
:return: an iterator over (revision_id, depth, revno, end_of_merge)
483
* revision_id: the unique id of the revision
484
* depth: How many levels of merging deep this node has been
486
* revno_sequence: This field provides a sequence of
487
revision numbers for all revisions. The format is:
488
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
489
branch that the revno is on. From left to right the REVNO numbers
490
are the sequence numbers within that branch of the revision.
491
* end_of_merge: When True the next node (earlier in history) is
492
part of a different merge.
494
# Note: depth and revno values are in the context of the branch so
495
# we need the full graph to get stable numbers, regardless of the
497
if self._merge_sorted_revisions_cache is None:
498
last_revision = self.last_revision()
499
known_graph = self.repository.get_known_graph_ancestry(
501
self._merge_sorted_revisions_cache = known_graph.merge_sort(
503
filtered = self._filter_merge_sorted_revisions(
504
self._merge_sorted_revisions_cache, start_revision_id,
505
stop_revision_id, stop_rule)
506
# Make sure we don't return revisions that are not part of the
507
# start_revision_id ancestry.
508
filtered = self._filter_start_non_ancestors(filtered)
509
if direction == 'reverse':
511
if direction == 'forward':
512
return reversed(list(filtered))
514
raise ValueError('invalid direction %r' % direction)
516
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
517
start_revision_id, stop_revision_id, stop_rule):
518
"""Iterate over an inclusive range of sorted revisions."""
519
rev_iter = iter(merge_sorted_revisions)
520
if start_revision_id is not None:
521
for node in rev_iter:
523
if rev_id != start_revision_id:
526
# The decision to include the start or not
527
# depends on the stop_rule if a stop is provided
528
# so pop this node back into the iterator
529
rev_iter = itertools.chain(iter([node]), rev_iter)
531
if stop_revision_id is None:
533
for node in rev_iter:
535
yield (rev_id, node.merge_depth, node.revno,
537
elif stop_rule == 'exclude':
538
for node in rev_iter:
540
if rev_id == stop_revision_id:
542
yield (rev_id, node.merge_depth, node.revno,
544
elif stop_rule == 'include':
545
for node in rev_iter:
547
yield (rev_id, node.merge_depth, node.revno,
549
if rev_id == stop_revision_id:
551
elif stop_rule == 'with-merges-without-common-ancestry':
552
# We want to exclude all revisions that are already part of the
553
# stop_revision_id ancestry.
554
graph = self.repository.get_graph()
555
ancestors = graph.find_unique_ancestors(start_revision_id,
557
for node in rev_iter:
559
if rev_id not in ancestors:
561
yield (rev_id, node.merge_depth, node.revno,
563
elif stop_rule == 'with-merges':
564
stop_rev = self.repository.get_revision(stop_revision_id)
565
if stop_rev.parent_ids:
566
left_parent = stop_rev.parent_ids[0]
568
left_parent = _mod_revision.NULL_REVISION
569
# left_parent is the actual revision we want to stop logging at,
570
# since we want to show the merged revisions after the stop_rev too
571
reached_stop_revision_id = False
572
revision_id_whitelist = []
573
for node in rev_iter:
575
if rev_id == left_parent:
576
# reached the left parent after the stop_revision
578
if (not reached_stop_revision_id or
579
rev_id in revision_id_whitelist):
580
yield (rev_id, node.merge_depth, node.revno,
582
if reached_stop_revision_id or rev_id == stop_revision_id:
583
# only do the merged revs of rev_id from now on
584
rev = self.repository.get_revision(rev_id)
586
reached_stop_revision_id = True
587
revision_id_whitelist.extend(rev.parent_ids)
589
raise ValueError('invalid stop_rule %r' % stop_rule)
591
def _filter_start_non_ancestors(self, rev_iter):
592
# If we started from a dotted revno, we want to consider it as a tip
593
# and don't want to yield revisions that are not part of its
594
# ancestry. Given the order guaranteed by the merge sort, we will see
595
# uninteresting descendants of the first parent of our tip before the
597
first = rev_iter.next()
598
(rev_id, merge_depth, revno, end_of_merge) = first
601
# We start at a mainline revision so by definition, all others
602
# revisions in rev_iter are ancestors
603
for node in rev_iter:
608
pmap = self.repository.get_parent_map([rev_id])
609
parents = pmap.get(rev_id, [])
611
whitelist.update(parents)
613
# If there is no parents, there is nothing of interest left
615
# FIXME: It's hard to test this scenario here as this code is never
616
# called in that case. -- vila 20100322
619
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
621
if rev_id in whitelist:
622
pmap = self.repository.get_parent_map([rev_id])
623
parents = pmap.get(rev_id, [])
624
whitelist.remove(rev_id)
625
whitelist.update(parents)
627
# We've reached the mainline, there is nothing left to
631
# A revision that is not part of the ancestry of our
634
yield (rev_id, merge_depth, revno, end_of_merge)
636
def leave_lock_in_place(self):
637
"""Tell this branch object not to release the physical lock when this
640
If lock_write doesn't return a token, then this method is not supported.
642
self.control_files.leave_in_place()
644
def dont_leave_lock_in_place(self):
645
"""Tell this branch object to release the physical lock when this
646
object is unlocked, even if it didn't originally acquire it.
648
If lock_write doesn't return a token, then this method is not supported.
650
self.control_files.dont_leave_in_place()
652
def bind(self, other):
653
"""Bind the local branch the other branch.
655
:param other: The branch to bind to
658
raise errors.UpgradeRequired(self.user_url)
660
def get_append_revisions_only(self):
661
"""Whether it is only possible to append revisions to the history.
663
if not self._format.supports_set_append_revisions_only():
665
return self.get_config(
666
).get_user_option_as_bool('append_revisions_only')
668
def set_append_revisions_only(self, enabled):
669
if not self._format.supports_set_append_revisions_only():
670
raise errors.UpgradeRequired(self.user_url)
675
self.get_config().set_user_option('append_revisions_only', value,
678
def set_reference_info(self, file_id, tree_path, branch_location):
679
"""Set the branch location to use for a tree reference."""
680
raise errors.UnsupportedOperation(self.set_reference_info, self)
682
def get_reference_info(self, file_id):
683
"""Get the tree_path and branch_location for a tree reference."""
684
raise errors.UnsupportedOperation(self.get_reference_info, self)
687
def fetch(self, from_branch, last_revision=None, limit=None):
688
"""Copy revisions from from_branch into this branch.
690
:param from_branch: Where to copy from.
691
:param last_revision: What revision to stop at (None for at the end
693
:param limit: Optional rough limit of revisions to fetch
696
return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
698
def get_bound_location(self):
699
"""Return the URL of the branch we are bound to.
701
Older format branches cannot bind, please be sure to use a metadir
706
def get_old_bound_location(self):
707
"""Return the URL of the branch we used to be bound to
709
raise errors.UpgradeRequired(self.user_url)
711
def get_commit_builder(self, parents, config=None, timestamp=None,
712
timezone=None, committer=None, revprops=None,
713
revision_id=None, lossy=False):
714
"""Obtain a CommitBuilder for this branch.
716
:param parents: Revision ids of the parents of the new revision.
717
:param config: Optional configuration to use.
718
:param timestamp: Optional timestamp recorded for commit.
719
:param timezone: Optional timezone for timestamp.
720
:param committer: Optional committer to set for commit.
721
:param revprops: Optional dictionary of revision properties.
722
:param revision_id: Optional revision id.
723
:param lossy: Whether to discard data that can not be natively
724
represented, when pushing to a foreign VCS
728
config = self.get_config()
730
return self.repository.get_commit_builder(self, parents, config,
731
timestamp, timezone, committer, revprops, revision_id,
734
def get_master_branch(self, possible_transports=None):
735
"""Return the branch we are bound to.
737
:return: Either a Branch, or None
741
@deprecated_method(deprecated_in((2, 5, 0)))
742
def get_revision_delta(self, revno):
743
"""Return the delta for one revision.
745
The delta is relative to its mainline predecessor, or the
746
empty tree for revision 1.
749
revid = self.get_rev_id(revno)
750
except errors.NoSuchRevision:
751
raise errors.InvalidRevisionNumber(revno)
752
return self.repository.get_revision_delta(revid)
754
def get_stacked_on_url(self):
755
"""Get the URL this branch is stacked against.
757
:raises NotStacked: If the branch is not stacked.
758
:raises UnstackableBranchFormat: If the branch does not support
761
raise NotImplementedError(self.get_stacked_on_url)
763
def print_file(self, file, revision_id):
764
"""Print `file` to stdout."""
765
raise NotImplementedError(self.print_file)
767
@deprecated_method(deprecated_in((2, 4, 0)))
768
def set_revision_history(self, rev_history):
769
"""See Branch.set_revision_history."""
770
self._set_revision_history(rev_history)
773
def _set_revision_history(self, rev_history):
774
if len(rev_history) == 0:
775
revid = _mod_revision.NULL_REVISION
777
revid = rev_history[-1]
778
if rev_history != self._lefthand_history(revid):
779
raise errors.NotLefthandHistory(rev_history)
780
self.set_last_revision_info(len(rev_history), revid)
781
self._cache_revision_history(rev_history)
782
for hook in Branch.hooks['set_rh']:
783
hook(self, rev_history)
786
def set_last_revision_info(self, revno, revision_id):
787
"""Set the last revision of this branch.
789
The caller is responsible for checking that the revno is correct
790
for this revision id.
792
It may be possible to set the branch last revision to an id not
793
present in the repository. However, branches can also be
794
configured to check constraints on history, in which case this may not
797
raise NotImplementedError(self.set_last_revision_info)
800
def generate_revision_history(self, revision_id, last_rev=None,
802
"""See Branch.generate_revision_history"""
803
graph = self.repository.get_graph()
804
(last_revno, last_revid) = self.last_revision_info()
805
known_revision_ids = [
806
(last_revid, last_revno),
807
(_mod_revision.NULL_REVISION, 0),
809
if last_rev is not None:
810
if not graph.is_ancestor(last_rev, revision_id):
811
# our previous tip is not merged into stop_revision
812
raise errors.DivergedBranches(self, other_branch)
813
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
814
self.set_last_revision_info(revno, revision_id)
817
def set_parent(self, url):
818
"""See Branch.set_parent."""
819
# TODO: Maybe delete old location files?
820
# URLs should never be unicode, even on the local fs,
821
# FIXUP this and get_parent in a future branch format bump:
822
# read and rewrite the file. RBC 20060125
824
if isinstance(url, unicode):
826
url = url.encode('ascii')
827
except UnicodeEncodeError:
828
raise errors.InvalidURL(url,
829
"Urls must be 7-bit ascii, "
830
"use bzrlib.urlutils.escape")
831
url = urlutils.relative_url(self.base, url)
832
self._set_parent_location(url)
835
def set_stacked_on_url(self, url):
836
"""Set the URL this branch is stacked against.
838
:raises UnstackableBranchFormat: If the branch does not support
840
:raises UnstackableRepositoryFormat: If the repository does not support
843
if not self._format.supports_stacking():
844
raise errors.UnstackableBranchFormat(self._format, self.user_url)
845
# XXX: Changing from one fallback repository to another does not check
846
# that all the data you need is present in the new fallback.
847
# Possibly it should.
848
self._check_stackable_repo()
851
old_url = self.get_stacked_on_url()
852
except (errors.NotStacked, errors.UnstackableBranchFormat,
853
errors.UnstackableRepositoryFormat):
857
self._activate_fallback_location(url,
858
possible_transports=[self.bzrdir.root_transport])
859
# write this out after the repository is stacked to avoid setting a
860
# stacked config that doesn't work.
861
self._set_config_location('stacked_on_location', url)
864
"""Change a branch to be unstacked, copying data as needed.
866
Don't call this directly, use set_stacked_on_url(None).
868
pb = ui.ui_factory.nested_progress_bar()
870
pb.update(gettext("Unstacking"))
871
# The basic approach here is to fetch the tip of the branch,
872
# including all available ghosts, from the existing stacked
873
# repository into a new repository object without the fallbacks.
875
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
876
# correct for CHKMap repostiories
877
old_repository = self.repository
878
if len(old_repository._fallback_repositories) != 1:
879
raise AssertionError("can't cope with fallback repositories "
880
"of %r (fallbacks: %r)" % (old_repository,
881
old_repository._fallback_repositories))
882
# Open the new repository object.
883
# Repositories don't offer an interface to remove fallback
884
# repositories today; take the conceptually simpler option and just
885
# reopen it. We reopen it starting from the URL so that we
886
# get a separate connection for RemoteRepositories and can
887
# stream from one of them to the other. This does mean doing
888
# separate SSH connection setup, but unstacking is not a
889
# common operation so it's tolerable.
890
new_bzrdir = controldir.ControlDir.open(
891
self.bzrdir.root_transport.base)
892
new_repository = new_bzrdir.find_repository()
893
if new_repository._fallback_repositories:
894
raise AssertionError("didn't expect %r to have "
895
"fallback_repositories"
896
% (self.repository,))
897
# Replace self.repository with the new repository.
898
# Do our best to transfer the lock state (i.e. lock-tokens and
899
# lock count) of self.repository to the new repository.
900
lock_token = old_repository.lock_write().repository_token
901
self.repository = new_repository
902
if isinstance(self, remote.RemoteBranch):
903
# Remote branches can have a second reference to the old
904
# repository that need to be replaced.
905
if self._real_branch is not None:
906
self._real_branch.repository = new_repository
907
self.repository.lock_write(token=lock_token)
908
if lock_token is not None:
909
old_repository.leave_lock_in_place()
910
old_repository.unlock()
911
if lock_token is not None:
912
# XXX: self.repository.leave_lock_in_place() before this
913
# function will not be preserved. Fortunately that doesn't
914
# affect the current default format (2a), and would be a
915
# corner-case anyway.
916
# - Andrew Bennetts, 2010/06/30
917
self.repository.dont_leave_lock_in_place()
921
old_repository.unlock()
922
except errors.LockNotHeld:
925
if old_lock_count == 0:
926
raise AssertionError(
927
'old_repository should have been locked at least once.')
928
for i in range(old_lock_count-1):
929
self.repository.lock_write()
930
# Fetch from the old repository into the new.
931
old_repository.lock_read()
933
# XXX: If you unstack a branch while it has a working tree
934
# with a pending merge, the pending-merged revisions will no
935
# longer be present. You can (probably) revert and remerge.
937
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
938
except errors.TagsNotSupported:
939
tags_to_fetch = set()
940
fetch_spec = _mod_graph.NotInOtherForRevs(self.repository,
941
old_repository, required_ids=[self.last_revision()],
942
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
943
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
945
old_repository.unlock()
949
def _set_tags_bytes(self, bytes):
950
"""Mirror method for _get_tags_bytes.
952
:seealso: Branch._get_tags_bytes.
954
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
955
op.add_cleanup(self.lock_write().unlock)
956
return op.run_simple(bytes)
958
def _set_tags_bytes_locked(self, bytes):
959
self._tags_bytes = bytes
960
return self._transport.put_bytes('tags', bytes)
962
def _cache_revision_history(self, rev_history):
963
"""Set the cached revision history to rev_history.
965
The revision_history method will use this cache to avoid regenerating
966
the revision history.
968
This API is semi-public; it only for use by subclasses, all other code
969
should consider it to be private.
971
self._revision_history_cache = rev_history
973
def _cache_revision_id_to_revno(self, revision_id_to_revno):
974
"""Set the cached revision_id => revno map to revision_id_to_revno.
976
This API is semi-public; it only for use by subclasses, all other code
977
should consider it to be private.
979
self._revision_id_to_revno_cache = revision_id_to_revno
981
def _clear_cached_state(self):
982
"""Clear any cached data on this branch, e.g. cached revision history.
984
This means the next call to revision_history will need to call
985
_gen_revision_history.
987
This API is semi-public; it only for use by subclasses, all other code
988
should consider it to be private.
990
self._revision_history_cache = None
991
self._revision_id_to_revno_cache = None
992
self._last_revision_info_cache = None
993
self._master_branch_cache = None
994
self._merge_sorted_revisions_cache = None
995
self._partial_revision_history_cache = []
996
self._partial_revision_id_to_revno_cache = {}
997
self._tags_bytes = None
999
def _gen_revision_history(self):
1000
"""Return sequence of revision hashes on to this branch.
1002
Unlike revision_history, this method always regenerates or rereads the
1003
revision history, i.e. it does not cache the result, so repeated calls
1006
Concrete subclasses should override this instead of revision_history so
1007
that subclasses do not need to deal with caching logic.
1009
This API is semi-public; it only for use by subclasses, all other code
1010
should consider it to be private.
1012
raise NotImplementedError(self._gen_revision_history)
1014
@deprecated_method(deprecated_in((2, 5, 0)))
1016
def revision_history(self):
1017
"""Return sequence of revision ids on this branch.
1019
This method will cache the revision history for as long as it is safe to
1022
return self._revision_history()
1024
def _revision_history(self):
1025
if 'evil' in debug.debug_flags:
1026
mutter_callsite(3, "revision_history scales with history.")
1027
if self._revision_history_cache is not None:
1028
history = self._revision_history_cache
1030
history = self._gen_revision_history()
1031
self._cache_revision_history(history)
1032
return list(history)
1035
"""Return current revision number for this branch.
1037
That is equivalent to the number of revisions committed to
1040
return self.last_revision_info()[0]
1043
"""Older format branches cannot bind or unbind."""
1044
raise errors.UpgradeRequired(self.user_url)
1046
def last_revision(self):
1047
"""Return last revision id, or NULL_REVISION."""
1048
return self.last_revision_info()[1]
1051
def last_revision_info(self):
1052
"""Return information about the last revision.
1054
:return: A tuple (revno, revision_id).
1056
if self._last_revision_info_cache is None:
1057
self._last_revision_info_cache = self._read_last_revision_info()
1058
return self._last_revision_info_cache
1060
def _read_last_revision_info(self):
1061
raise NotImplementedError(self._read_last_revision_info)
1063
@deprecated_method(deprecated_in((2, 4, 0)))
1064
def import_last_revision_info(self, source_repo, revno, revid):
1065
"""Set the last revision info, importing from another repo if necessary.
1067
:param source_repo: Source repository to optionally fetch from
1068
:param revno: Revision number of the new tip
1069
:param revid: Revision id of the new tip
1071
if not self.repository.has_same_location(source_repo):
1072
self.repository.fetch(source_repo, revision_id=revid)
1073
self.set_last_revision_info(revno, revid)
1075
def import_last_revision_info_and_tags(self, source, revno, revid,
1077
"""Set the last revision info, importing from another repo if necessary.
1079
This is used by the bound branch code to upload a revision to
1080
the master branch first before updating the tip of the local branch.
1081
Revisions referenced by source's tags are also transferred.
1083
:param source: Source branch to optionally fetch from
1084
:param revno: Revision number of the new tip
1085
:param revid: Revision id of the new tip
1086
:param lossy: Whether to discard metadata that can not be
1087
natively represented
1088
:return: Tuple with the new revision number and revision id
1089
(should only be different from the arguments when lossy=True)
1091
if not self.repository.has_same_location(source.repository):
1092
self.fetch(source, revid)
1093
self.set_last_revision_info(revno, revid)
1094
return (revno, revid)
1096
def revision_id_to_revno(self, revision_id):
1097
"""Given a revision id, return its revno"""
1098
if _mod_revision.is_null(revision_id):
1100
history = self._revision_history()
1102
return history.index(revision_id) + 1
1104
raise errors.NoSuchRevision(self, revision_id)
1107
def get_rev_id(self, revno, history=None):
1108
"""Find the revision id of the specified revno."""
1110
return _mod_revision.NULL_REVISION
1111
last_revno, last_revid = self.last_revision_info()
1112
if revno == last_revno:
1114
if revno <= 0 or revno > last_revno:
1115
raise errors.NoSuchRevision(self, revno)
1116
distance_from_last = last_revno - revno
1117
if len(self._partial_revision_history_cache) <= distance_from_last:
1118
self._extend_partial_history(distance_from_last)
1119
return self._partial_revision_history_cache[distance_from_last]
1121
def pull(self, source, overwrite=False, stop_revision=None,
1122
possible_transports=None, *args, **kwargs):
1123
"""Mirror source into this branch.
1125
This branch is considered to be 'local', having low latency.
1127
:returns: PullResult instance
1129
return InterBranch.get(source, self).pull(overwrite=overwrite,
1130
stop_revision=stop_revision,
1131
possible_transports=possible_transports, *args, **kwargs)
1133
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1135
"""Mirror this branch into target.
1137
This branch is considered to be 'local', having low latency.
1139
return InterBranch.get(self, target).push(overwrite, stop_revision,
1140
lossy, *args, **kwargs)
1142
def basis_tree(self):
1143
"""Return `Tree` object for last revision."""
1144
return self.repository.revision_tree(self.last_revision())
1146
def get_parent(self):
1147
"""Return the parent location of the branch.
1149
This is the default location for pull/missing. The usual
1150
pattern is that the user can override it by specifying a
1153
parent = self._get_parent_location()
1156
# This is an old-format absolute path to a local branch
1157
# turn it into a url
1158
if parent.startswith('/'):
1159
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1161
return urlutils.join(self.base[:-1], parent)
1162
except errors.InvalidURLJoin, e:
1163
raise errors.InaccessibleParent(parent, self.user_url)
1165
def _get_parent_location(self):
1166
raise NotImplementedError(self._get_parent_location)
1168
def _set_config_location(self, name, url, config=None,
1169
make_relative=False):
1171
config = self.get_config()
1175
url = urlutils.relative_url(self.base, url)
1176
config.set_user_option(name, url, warn_masked=True)
1178
def _get_config_location(self, name, config=None):
1180
config = self.get_config()
1181
location = config.get_user_option(name)
1186
def get_child_submit_format(self):
1187
"""Return the preferred format of submissions to this branch."""
1188
return self.get_config().get_user_option("child_submit_format")
1190
def get_submit_branch(self):
1191
"""Return the submit location of the branch.
1193
This is the default location for bundle. The usual
1194
pattern is that the user can override it by specifying a
1197
return self.get_config().get_user_option('submit_branch')
1199
def set_submit_branch(self, location):
1200
"""Return the submit location of the branch.
1202
This is the default location for bundle. The usual
1203
pattern is that the user can override it by specifying a
1206
self.get_config().set_user_option('submit_branch', location,
1209
def get_public_branch(self):
1210
"""Return the public location of the branch.
1212
This is used by merge directives.
1214
return self._get_config_location('public_branch')
1216
def set_public_branch(self, location):
1217
"""Return the submit location of the branch.
1219
This is the default location for bundle. The usual
1220
pattern is that the user can override it by specifying a
1223
self._set_config_location('public_branch', location)
1225
def get_push_location(self):
1226
"""Return the None or the location to push this branch to."""
1227
push_loc = self.get_config().get_user_option('push_location')
1230
def set_push_location(self, location):
1231
"""Set a new push location for this branch."""
1232
raise NotImplementedError(self.set_push_location)
1234
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1235
"""Run the post_change_branch_tip hooks."""
1236
hooks = Branch.hooks['post_change_branch_tip']
1239
new_revno, new_revid = self.last_revision_info()
1240
params = ChangeBranchTipParams(
1241
self, old_revno, new_revno, old_revid, new_revid)
1245
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1246
"""Run the pre_change_branch_tip hooks."""
1247
hooks = Branch.hooks['pre_change_branch_tip']
1250
old_revno, old_revid = self.last_revision_info()
1251
params = ChangeBranchTipParams(
1252
self, old_revno, new_revno, old_revid, new_revid)
1258
"""Synchronise this branch with the master branch if any.
1260
:return: None or the last_revision pivoted out during the update.
1264
def check_revno(self, revno):
1266
Check whether a revno corresponds to any revision.
1267
Zero (the NULL revision) is considered valid.
1270
self.check_real_revno(revno)
1272
def check_real_revno(self, revno):
1274
Check whether a revno corresponds to a real revision.
1275
Zero (the NULL revision) is considered invalid
1277
if revno < 1 or revno > self.revno():
1278
raise errors.InvalidRevisionNumber(revno)
1281
def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
1282
"""Clone this branch into to_bzrdir preserving all semantic values.
1284
Most API users will want 'create_clone_on_transport', which creates a
1285
new bzrdir and branch on the fly.
1287
revision_id: if not None, the revision history in the new branch will
1288
be truncated to end with revision_id.
1290
result = to_bzrdir.create_branch()
1293
if repository_policy is not None:
1294
repository_policy.configure_branch(result)
1295
self.copy_content_into(result, revision_id=revision_id)
1301
def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1303
"""Create a new line of development from the branch, into to_bzrdir.
1305
to_bzrdir controls the branch format.
1307
revision_id: if not None, the revision history in the new branch will
1308
be truncated to end with revision_id.
1310
if (repository_policy is not None and
1311
repository_policy.requires_stacking()):
1312
to_bzrdir._format.require_stacking(_skip_repo=True)
1313
result = to_bzrdir.create_branch(repository=repository)
1316
if repository_policy is not None:
1317
repository_policy.configure_branch(result)
1318
self.copy_content_into(result, revision_id=revision_id)
1319
master_url = self.get_bound_location()
1320
if master_url is None:
1321
result.set_parent(self.bzrdir.root_transport.base)
1323
result.set_parent(master_url)
1328
def _synchronize_history(self, destination, revision_id):
1329
"""Synchronize last revision and revision history between branches.
1331
This version is most efficient when the destination is also a
1332
BzrBranch6, but works for BzrBranch5, as long as the destination's
1333
repository contains all the lefthand ancestors of the intended
1334
last_revision. If not, set_last_revision_info will fail.
1336
:param destination: The branch to copy the history into
1337
:param revision_id: The revision-id to truncate history at. May
1338
be None to copy complete history.
1340
source_revno, source_revision_id = self.last_revision_info()
1341
if revision_id is None:
1342
revno, revision_id = source_revno, source_revision_id
1344
graph = self.repository.get_graph()
1346
revno = graph.find_distance_to_null(revision_id,
1347
[(source_revision_id, source_revno)])
1348
except errors.GhostRevisionsHaveNoRevno:
1349
# Default to 1, if we can't find anything else
1351
destination.set_last_revision_info(revno, revision_id)
1353
def copy_content_into(self, destination, revision_id=None):
1354
"""Copy the content of self into destination.
1356
revision_id: if not None, the revision history in the new branch will
1357
be truncated to end with revision_id.
1359
return InterBranch.get(self, destination).copy_content_into(
1360
revision_id=revision_id)
1362
def update_references(self, target):
1363
if not getattr(self._format, 'supports_reference_locations', False):
1365
reference_dict = self._get_all_reference_info()
1366
if len(reference_dict) == 0:
1368
old_base = self.base
1369
new_base = target.base
1370
target_reference_dict = target._get_all_reference_info()
1371
for file_id, (tree_path, branch_location) in (
1372
reference_dict.items()):
1373
branch_location = urlutils.rebase_url(branch_location,
1375
target_reference_dict.setdefault(
1376
file_id, (tree_path, branch_location))
1377
target._set_all_reference_info(target_reference_dict)
1380
def check(self, refs):
1381
"""Check consistency of the branch.
1383
In particular this checks that revisions given in the revision-history
1384
do actually match up in the revision graph, and that they're all
1385
present in the repository.
1387
Callers will typically also want to check the repository.
1389
:param refs: Calculated refs for this branch as specified by
1390
branch._get_check_refs()
1391
:return: A BranchCheckResult.
1393
result = BranchCheckResult(self)
1394
last_revno, last_revision_id = self.last_revision_info()
1395
actual_revno = refs[('lefthand-distance', last_revision_id)]
1396
if actual_revno != last_revno:
1397
result.errors.append(errors.BzrCheckError(
1398
'revno does not match len(mainline) %s != %s' % (
1399
last_revno, actual_revno)))
1400
# TODO: We should probably also check that self.revision_history
1401
# matches the repository for older branch formats.
1402
# If looking for the code that cross-checks repository parents against
1403
# the Graph.iter_lefthand_ancestry output, that is now a repository
1407
def _get_checkout_format(self, lightweight=False):
1408
"""Return the most suitable metadir for a checkout of this branch.
1409
Weaves are used if this branch's repository uses weaves.
1411
format = self.repository.bzrdir.checkout_metadir()
1412
format.set_branch_format(self._format)
1415
def create_clone_on_transport(self, to_transport, revision_id=None,
1416
stacked_on=None, create_prefix=False, use_existing_dir=False,
1418
"""Create a clone of this branch and its bzrdir.
1420
:param to_transport: The transport to clone onto.
1421
:param revision_id: The revision id to use as tip in the new branch.
1422
If None the tip is obtained from this branch.
1423
:param stacked_on: An optional URL to stack the clone on.
1424
:param create_prefix: Create any missing directories leading up to
1426
:param use_existing_dir: Use an existing directory if one exists.
1428
# XXX: Fix the bzrdir API to allow getting the branch back from the
1429
# clone call. Or something. 20090224 RBC/spiv.
1430
# XXX: Should this perhaps clone colocated branches as well,
1431
# rather than just the default branch? 20100319 JRV
1432
if revision_id is None:
1433
revision_id = self.last_revision()
1434
dir_to = self.bzrdir.clone_on_transport(to_transport,
1435
revision_id=revision_id, stacked_on=stacked_on,
1436
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1438
return dir_to.open_branch()
1440
def create_checkout(self, to_location, revision_id=None,
1441
lightweight=False, accelerator_tree=None,
1443
"""Create a checkout of a branch.
1445
:param to_location: The url to produce the checkout at
1446
:param revision_id: The revision to check out
1447
:param lightweight: If True, produce a lightweight checkout, otherwise,
1448
produce a bound branch (heavyweight checkout)
1449
:param accelerator_tree: A tree which can be used for retrieving file
1450
contents more quickly than the revision tree, i.e. a workingtree.
1451
The revision tree will be used for cases where accelerator_tree's
1452
content is different.
1453
:param hardlink: If true, hard-link files from accelerator_tree,
1455
:return: The tree of the created checkout
1457
t = transport.get_transport(to_location)
1459
format = self._get_checkout_format(lightweight=lightweight)
1461
checkout = format.initialize_on_transport(t)
1462
from_branch = BranchReferenceFormat().initialize(checkout,
1465
checkout_branch = controldir.ControlDir.create_branch_convenience(
1466
to_location, force_new_tree=False, format=format)
1467
checkout = checkout_branch.bzrdir
1468
checkout_branch.bind(self)
1469
# pull up to the specified revision_id to set the initial
1470
# branch tip correctly, and seed it with history.
1471
checkout_branch.pull(self, stop_revision=revision_id)
1473
tree = checkout.create_workingtree(revision_id,
1474
from_branch=from_branch,
1475
accelerator_tree=accelerator_tree,
1477
basis_tree = tree.basis_tree()
1478
basis_tree.lock_read()
1480
for path, file_id in basis_tree.iter_references():
1481
reference_parent = self.reference_parent(file_id, path)
1482
reference_parent.create_checkout(tree.abspath(path),
1483
basis_tree.get_reference_revision(file_id, path),
1490
def reconcile(self, thorough=True):
1491
"""Make sure the data stored in this branch is consistent."""
1492
from bzrlib.reconcile import BranchReconciler
1493
reconciler = BranchReconciler(self, thorough=thorough)
1494
reconciler.reconcile()
1497
def reference_parent(self, file_id, path, possible_transports=None):
1498
"""Return the parent branch for a tree-reference file_id
1500
:param file_id: The file_id of the tree reference
1501
:param path: The path of the file_id in the tree
1502
:return: A branch associated with the file_id
1504
# FIXME should provide multiple branches, based on config
1505
return Branch.open(self.bzrdir.root_transport.clone(path).base,
1506
possible_transports=possible_transports)
1508
def supports_tags(self):
1509
return self._format.supports_tags()
1511
def automatic_tag_name(self, revision_id):
1512
"""Try to automatically find the tag name for a revision.
1514
:param revision_id: Revision id of the revision.
1515
:return: A tag name or None if no tag name could be determined.
1517
for hook in Branch.hooks['automatic_tag_name']:
1518
ret = hook(self, revision_id)
1523
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1525
"""Ensure that revision_b is a descendant of revision_a.
1527
This is a helper function for update_revisions.
1529
:raises: DivergedBranches if revision_b has diverged from revision_a.
1530
:returns: True if revision_b is a descendant of revision_a.
1532
relation = self._revision_relations(revision_a, revision_b, graph)
1533
if relation == 'b_descends_from_a':
1535
elif relation == 'diverged':
1536
raise errors.DivergedBranches(self, other_branch)
1537
elif relation == 'a_descends_from_b':
1540
raise AssertionError("invalid relation: %r" % (relation,))
1542
def _revision_relations(self, revision_a, revision_b, graph):
1543
"""Determine the relationship between two revisions.
1545
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1547
heads = graph.heads([revision_a, revision_b])
1548
if heads == set([revision_b]):
1549
return 'b_descends_from_a'
1550
elif heads == set([revision_a, revision_b]):
1551
# These branches have diverged
1553
elif heads == set([revision_a]):
1554
return 'a_descends_from_b'
1556
raise AssertionError("invalid heads: %r" % (heads,))
1558
def heads_to_fetch(self):
1559
"""Return the heads that must and that should be fetched to copy this
1560
branch into another repo.
1562
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1563
set of heads that must be fetched. if_present_fetch is a set of
1564
heads that must be fetched if present, but no error is necessary if
1565
they are not present.
1567
# For bzr native formats must_fetch is just the tip, and if_present_fetch
1569
must_fetch = set([self.last_revision()])
1570
if_present_fetch = set()
1571
c = self.get_config()
1572
include_tags = c.get_user_option_as_bool('branch.fetch_tags',
1576
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1577
except errors.TagsNotSupported:
1579
must_fetch.discard(_mod_revision.NULL_REVISION)
1580
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1581
return must_fetch, if_present_fetch
1584
class BranchFormat(controldir.ControlComponentFormat):
1585
"""An encapsulation of the initialization and open routines for a format.
1587
Formats provide three things:
1588
* An initialization routine,
1592
Formats are placed in an dict by their format string for reference
1593
during branch opening. It's not required that these be instances, they
1594
can be classes themselves with class methods - it simply depends on
1595
whether state is needed for a given format or not.
1597
Once a format is deprecated, just deprecate the initialize and open
1598
methods on the format class. Do not deprecate the object, as the
1599
object will be created every time regardless.
1602
def __eq__(self, other):
1603
return self.__class__ is other.__class__
1605
def __ne__(self, other):
1606
return not (self == other)
1609
def find_format(klass, controldir, name=None):
1610
"""Return the format for the branch object in controldir."""
1612
transport = controldir.get_branch_transport(None, name=name)
1613
except errors.NoSuchFile:
1614
raise errors.NotBranchError(path=name, bzrdir=controldir)
1616
format_string = transport.get_bytes("format")
1617
return format_registry.get(format_string)
1618
except errors.NoSuchFile:
1619
raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
1621
raise errors.UnknownFormatError(format=format_string, kind='branch')
1624
@deprecated_method(deprecated_in((2, 4, 0)))
1625
def get_default_format(klass):
1626
"""Return the current default format."""
1627
return format_registry.get_default()
1630
@deprecated_method(deprecated_in((2, 4, 0)))
1631
def get_formats(klass):
1632
"""Get all the known formats.
1634
Warning: This triggers a load of all lazy registered formats: do not
1635
use except when that is desireed.
1637
return format_registry._get_all()
1639
def get_reference(self, controldir, name=None):
1640
"""Get the target reference of the branch in controldir.
1642
format probing must have been completed before calling
1643
this method - it is assumed that the format of the branch
1644
in controldir is correct.
1646
:param controldir: The controldir to get the branch data from.
1647
:param name: Name of the colocated branch to fetch
1648
:return: None if the branch is not a reference branch.
1653
def set_reference(self, controldir, name, to_branch):
1654
"""Set the target reference of the branch in controldir.
1656
format probing must have been completed before calling
1657
this method - it is assumed that the format of the branch
1658
in controldir is correct.
1660
:param controldir: The controldir to set the branch reference for.
1661
:param name: Name of colocated branch to set, None for default
1662
:param to_branch: branch that the checkout is to reference
1664
raise NotImplementedError(self.set_reference)
1666
def get_format_string(self):
1667
"""Return the ASCII format string that identifies this format."""
1668
raise NotImplementedError(self.get_format_string)
1670
def get_format_description(self):
1671
"""Return the short format description for this format."""
1672
raise NotImplementedError(self.get_format_description)
1674
def _run_post_branch_init_hooks(self, controldir, name, branch):
1675
hooks = Branch.hooks['post_branch_init']
1678
params = BranchInitHookParams(self, controldir, name, branch)
1682
def initialize(self, controldir, name=None, repository=None,
1683
append_revisions_only=None):
1684
"""Create a branch of this format in controldir.
1686
:param name: Name of the colocated branch to create.
1688
raise NotImplementedError(self.initialize)
1690
def is_supported(self):
1691
"""Is this format supported?
1693
Supported formats can be initialized and opened.
1694
Unsupported formats may not support initialization or committing or
1695
some other features depending on the reason for not being supported.
1699
def make_tags(self, branch):
1700
"""Create a tags object for branch.
1702
This method is on BranchFormat, because BranchFormats are reflected
1703
over the wire via network_name(), whereas full Branch instances require
1704
multiple VFS method calls to operate at all.
1706
The default implementation returns a disabled-tags instance.
1708
Note that it is normal for branch to be a RemoteBranch when using tags
1711
return _mod_tag.DisabledTags(branch)
1713
def network_name(self):
1714
"""A simple byte string uniquely identifying this format for RPC calls.
1716
MetaDir branch formats use their disk format string to identify the
1717
repository over the wire. All in one formats such as bzr < 0.8, and
1718
foreign formats like svn/git and hg should use some marker which is
1719
unique and immutable.
1721
raise NotImplementedError(self.network_name)
1723
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1724
found_repository=None, possible_transports=None):
1725
"""Return the branch object for controldir.
1727
:param controldir: A ControlDir that contains a branch.
1728
:param name: Name of colocated branch to open
1729
:param _found: a private parameter, do not use it. It is used to
1730
indicate if format probing has already be done.
1731
:param ignore_fallbacks: when set, no fallback branches will be opened
1732
(if there are any). Default is to open fallbacks.
1734
raise NotImplementedError(self.open)
1737
@deprecated_method(deprecated_in((2, 4, 0)))
1738
def register_format(klass, format):
1739
"""Register a metadir format.
1741
See MetaDirBranchFormatFactory for the ability to register a format
1742
without loading the code the format needs until it is actually used.
1744
format_registry.register(format)
1747
@deprecated_method(deprecated_in((2, 4, 0)))
1748
def set_default_format(klass, format):
1749
format_registry.set_default(format)
1751
def supports_set_append_revisions_only(self):
1752
"""True if this format supports set_append_revisions_only."""
1755
def supports_stacking(self):
1756
"""True if this format records a stacked-on branch."""
1759
def supports_leaving_lock(self):
1760
"""True if this format supports leaving locks in place."""
1761
return False # by default
1764
@deprecated_method(deprecated_in((2, 4, 0)))
1765
def unregister_format(klass, format):
1766
format_registry.remove(format)
1769
return self.get_format_description().rstrip()
1771
def supports_tags(self):
1772
"""True if this format supports tags stored in the branch"""
1773
return False # by default
1775
def tags_are_versioned(self):
1776
"""Whether the tag container for this branch versions tags."""
1779
def supports_tags_referencing_ghosts(self):
1780
"""True if tags can reference ghost revisions."""
1784
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1785
"""A factory for a BranchFormat object, permitting simple lazy registration.
1787
While none of the built in BranchFormats are lazy registered yet,
1788
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1789
use it, and the bzr-loom plugin uses it as well (see
1790
bzrlib.plugins.loom.formats).
1793
def __init__(self, format_string, module_name, member_name):
1794
"""Create a MetaDirBranchFormatFactory.
1796
:param format_string: The format string the format has.
1797
:param module_name: Module to load the format class from.
1798
:param member_name: Attribute name within the module for the format class.
1800
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1801
self._format_string = format_string
1803
def get_format_string(self):
1804
"""See BranchFormat.get_format_string."""
1805
return self._format_string
1808
"""Used for network_format_registry support."""
1809
return self.get_obj()()
1812
class BranchHooks(Hooks):
1813
"""A dictionary mapping hook name to a list of callables for branch hooks.
1815
e.g. ['set_rh'] Is the list of items to be called when the
1816
set_revision_history function is invoked.
1820
"""Create the default hooks.
1822
These are all empty initially, because by default nothing should get
1825
Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1826
self.add_hook('set_rh',
1827
"Invoked whenever the revision history has been set via "
1828
"set_revision_history. The api signature is (branch, "
1829
"revision_history), and the branch will be write-locked. "
1830
"The set_rh hook can be expensive for bzr to trigger, a better "
1831
"hook to use is Branch.post_change_branch_tip.", (0, 15))
1832
self.add_hook('open',
1833
"Called with the Branch object that has been opened after a "
1834
"branch is opened.", (1, 8))
1835
self.add_hook('post_push',
1836
"Called after a push operation completes. post_push is called "
1837
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1838
"bzr client.", (0, 15))
1839
self.add_hook('post_pull',
1840
"Called after a pull operation completes. post_pull is called "
1841
"with a bzrlib.branch.PullResult object and only runs in the "
1842
"bzr client.", (0, 15))
1843
self.add_hook('pre_commit',
1844
"Called after a commit is calculated but before it is "
1845
"completed. pre_commit is called with (local, master, old_revno, "
1846
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1847
"). old_revid is NULL_REVISION for the first commit to a branch, "
1848
"tree_delta is a TreeDelta object describing changes from the "
1849
"basis revision. hooks MUST NOT modify this delta. "
1850
" future_tree is an in-memory tree obtained from "
1851
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1853
self.add_hook('post_commit',
1854
"Called in the bzr client after a commit has completed. "
1855
"post_commit is called with (local, master, old_revno, old_revid, "
1856
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1857
"commit to a branch.", (0, 15))
1858
self.add_hook('post_uncommit',
1859
"Called in the bzr client after an uncommit completes. "
1860
"post_uncommit is called with (local, master, old_revno, "
1861
"old_revid, new_revno, new_revid) where local is the local branch "
1862
"or None, master is the target branch, and an empty branch "
1863
"receives new_revno of 0, new_revid of None.", (0, 15))
1864
self.add_hook('pre_change_branch_tip',
1865
"Called in bzr client and server before a change to the tip of a "
1866
"branch is made. pre_change_branch_tip is called with a "
1867
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1868
"commit, uncommit will all trigger this hook.", (1, 6))
1869
self.add_hook('post_change_branch_tip',
1870
"Called in bzr client and server after a change to the tip of a "
1871
"branch is made. post_change_branch_tip is called with a "
1872
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1873
"commit, uncommit will all trigger this hook.", (1, 4))
1874
self.add_hook('transform_fallback_location',
1875
"Called when a stacked branch is activating its fallback "
1876
"locations. transform_fallback_location is called with (branch, "
1877
"url), and should return a new url. Returning the same url "
1878
"allows it to be used as-is, returning a different one can be "
1879
"used to cause the branch to stack on a closer copy of that "
1880
"fallback_location. Note that the branch cannot have history "
1881
"accessing methods called on it during this hook because the "
1882
"fallback locations have not been activated. When there are "
1883
"multiple hooks installed for transform_fallback_location, "
1884
"all are called with the url returned from the previous hook."
1885
"The order is however undefined.", (1, 9))
1886
self.add_hook('automatic_tag_name',
1887
"Called to determine an automatic tag name for a revision. "
1888
"automatic_tag_name is called with (branch, revision_id) and "
1889
"should return a tag name or None if no tag name could be "
1890
"determined. The first non-None tag name returned will be used.",
1892
self.add_hook('post_branch_init',
1893
"Called after new branch initialization completes. "
1894
"post_branch_init is called with a "
1895
"bzrlib.branch.BranchInitHookParams. "
1896
"Note that init, branch and checkout (both heavyweight and "
1897
"lightweight) will all trigger this hook.", (2, 2))
1898
self.add_hook('post_switch',
1899
"Called after a checkout switches branch. "
1900
"post_switch is called with a "
1901
"bzrlib.branch.SwitchHookParams.", (2, 2))
1905
# install the default hooks into the Branch class.
1906
Branch.hooks = BranchHooks()
1909
class ChangeBranchTipParams(object):
1910
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1912
There are 5 fields that hooks may wish to access:
1914
:ivar branch: the branch being changed
1915
:ivar old_revno: revision number before the change
1916
:ivar new_revno: revision number after the change
1917
:ivar old_revid: revision id before the change
1918
:ivar new_revid: revision id after the change
1920
The revid fields are strings. The revno fields are integers.
1923
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1924
"""Create a group of ChangeBranchTip parameters.
1926
:param branch: The branch being changed.
1927
:param old_revno: Revision number before the change.
1928
:param new_revno: Revision number after the change.
1929
:param old_revid: Tip revision id before the change.
1930
:param new_revid: Tip revision id after the change.
1932
self.branch = branch
1933
self.old_revno = old_revno
1934
self.new_revno = new_revno
1935
self.old_revid = old_revid
1936
self.new_revid = new_revid
1938
def __eq__(self, other):
1939
return self.__dict__ == other.__dict__
1942
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1943
self.__class__.__name__, self.branch,
1944
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1947
class BranchInitHookParams(object):
1948
"""Object holding parameters passed to `*_branch_init` hooks.
1950
There are 4 fields that hooks may wish to access:
1952
:ivar format: the branch format
1953
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1954
:ivar name: name of colocated branch, if any (or None)
1955
:ivar branch: the branch created
1957
Note that for lightweight checkouts, the bzrdir and format fields refer to
1958
the checkout, hence they are different from the corresponding fields in
1959
branch, which refer to the original branch.
1962
def __init__(self, format, controldir, name, branch):
1963
"""Create a group of BranchInitHook parameters.
1965
:param format: the branch format
1966
:param controldir: the ControlDir where the branch will be/has been
1968
:param name: name of colocated branch, if any (or None)
1969
:param branch: the branch created
1971
Note that for lightweight checkouts, the bzrdir and format fields refer
1972
to the checkout, hence they are different from the corresponding fields
1973
in branch, which refer to the original branch.
1975
self.format = format
1976
self.bzrdir = controldir
1978
self.branch = branch
1980
def __eq__(self, other):
1981
return self.__dict__ == other.__dict__
1984
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1987
class SwitchHookParams(object):
1988
"""Object holding parameters passed to `*_switch` hooks.
1990
There are 4 fields that hooks may wish to access:
1992
:ivar control_dir: ControlDir of the checkout to change
1993
:ivar to_branch: branch that the checkout is to reference
1994
:ivar force: skip the check for local commits in a heavy checkout
1995
:ivar revision_id: revision ID to switch to (or None)
1998
def __init__(self, control_dir, to_branch, force, revision_id):
1999
"""Create a group of SwitchHook parameters.
2001
:param control_dir: ControlDir of the checkout to change
2002
:param to_branch: branch that the checkout is to reference
2003
:param force: skip the check for local commits in a heavy checkout
2004
:param revision_id: revision ID to switch to (or None)
2006
self.control_dir = control_dir
2007
self.to_branch = to_branch
2009
self.revision_id = revision_id
2011
def __eq__(self, other):
2012
return self.__dict__ == other.__dict__
2015
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
2016
self.control_dir, self.to_branch,
2020
class BranchFormatMetadir(BranchFormat):
2021
"""Common logic for meta-dir based branch formats."""
2023
def _branch_class(self):
2024
"""What class to instantiate on open calls."""
2025
raise NotImplementedError(self._branch_class)
2027
def _get_initial_config(self, append_revisions_only=None):
2028
if append_revisions_only:
2029
return "append_revisions_only = True\n"
2031
# Avoid writing anything if append_revisions_only is disabled,
2032
# as that is the default.
2035
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2037
"""Initialize a branch in a bzrdir, with specified files
2039
:param a_bzrdir: The bzrdir to initialize the branch in
2040
:param utf8_files: The files to create as a list of
2041
(filename, content) tuples
2042
:param name: Name of colocated branch to create, if any
2043
:return: a branch in this format
2045
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2046
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2047
control_files = lockable_files.LockableFiles(branch_transport,
2048
'lock', lockdir.LockDir)
2049
control_files.create_lock()
2050
control_files.lock_write()
2052
utf8_files += [('format', self.get_format_string())]
2053
for (filename, content) in utf8_files:
2054
branch_transport.put_bytes(
2056
mode=a_bzrdir._get_file_mode())
2058
control_files.unlock()
2059
branch = self.open(a_bzrdir, name, _found=True,
2060
found_repository=repository)
2061
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2064
def network_name(self):
2065
"""A simple byte string uniquely identifying this format for RPC calls.
2067
Metadir branch formats use their format string.
2069
return self.get_format_string()
2071
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2072
found_repository=None, possible_transports=None):
2073
"""See BranchFormat.open()."""
2075
format = BranchFormat.find_format(a_bzrdir, name=name)
2076
if format.__class__ != self.__class__:
2077
raise AssertionError("wrong format %r found for %r" %
2079
transport = a_bzrdir.get_branch_transport(None, name=name)
2081
control_files = lockable_files.LockableFiles(transport, 'lock',
2083
if found_repository is None:
2084
found_repository = a_bzrdir.find_repository()
2085
return self._branch_class()(_format=self,
2086
_control_files=control_files,
2089
_repository=found_repository,
2090
ignore_fallbacks=ignore_fallbacks,
2091
possible_transports=possible_transports)
2092
except errors.NoSuchFile:
2093
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2096
def _matchingbzrdir(self):
2097
ret = bzrdir.BzrDirMetaFormat1()
2098
ret.set_branch_format(self)
2101
def supports_tags(self):
2104
def supports_leaving_lock(self):
2108
class BzrBranchFormat5(BranchFormatMetadir):
2109
"""Bzr branch format 5.
2112
- a revision-history file.
2114
- a lock dir guarding the branch itself
2115
- all of this stored in a branch/ subdirectory
2116
- works with shared repositories.
2118
This format is new in bzr 0.8.
2121
def _branch_class(self):
2124
def get_format_string(self):
2125
"""See BranchFormat.get_format_string()."""
2126
return "Bazaar-NG branch format 5\n"
2128
def get_format_description(self):
2129
"""See BranchFormat.get_format_description()."""
2130
return "Branch format 5"
2132
def initialize(self, a_bzrdir, name=None, repository=None,
2133
append_revisions_only=None):
2134
"""Create a branch of this format in a_bzrdir."""
2135
if append_revisions_only:
2136
raise errors.UpgradeRequired(a_bzrdir.user_url)
2137
utf8_files = [('revision-history', ''),
2138
('branch-name', ''),
2140
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2142
def supports_tags(self):
2146
class BzrBranchFormat6(BranchFormatMetadir):
2147
"""Branch format with last-revision and tags.
2149
Unlike previous formats, this has no explicit revision history. Instead,
2150
this just stores the last-revision, and the left-hand history leading
2151
up to there is the history.
2153
This format was introduced in bzr 0.15
2154
and became the default in 0.91.
2157
def _branch_class(self):
2160
def get_format_string(self):
2161
"""See BranchFormat.get_format_string()."""
2162
return "Bazaar Branch Format 6 (bzr 0.15)\n"
2164
def get_format_description(self):
2165
"""See BranchFormat.get_format_description()."""
2166
return "Branch format 6"
2168
def initialize(self, a_bzrdir, name=None, repository=None,
2169
append_revisions_only=None):
2170
"""Create a branch of this format in a_bzrdir."""
2171
utf8_files = [('last-revision', '0 null:\n'),
2173
self._get_initial_config(append_revisions_only)),
2176
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2178
def make_tags(self, branch):
2179
"""See bzrlib.branch.BranchFormat.make_tags()."""
2180
return _mod_tag.BasicTags(branch)
2182
def supports_set_append_revisions_only(self):
2186
class BzrBranchFormat8(BranchFormatMetadir):
2187
"""Metadir format supporting storing locations of subtree branches."""
2189
def _branch_class(self):
2192
def get_format_string(self):
2193
"""See BranchFormat.get_format_string()."""
2194
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2196
def get_format_description(self):
2197
"""See BranchFormat.get_format_description()."""
2198
return "Branch format 8"
2200
def initialize(self, a_bzrdir, name=None, repository=None,
2201
append_revisions_only=None):
2202
"""Create a branch of this format in a_bzrdir."""
2203
utf8_files = [('last-revision', '0 null:\n'),
2205
self._get_initial_config(append_revisions_only)),
2209
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2211
def make_tags(self, branch):
2212
"""See bzrlib.branch.BranchFormat.make_tags()."""
2213
return _mod_tag.BasicTags(branch)
2215
def supports_set_append_revisions_only(self):
2218
def supports_stacking(self):
2221
supports_reference_locations = True
2224
class BzrBranchFormat7(BranchFormatMetadir):
2225
"""Branch format with last-revision, tags, and a stacked location pointer.
2227
The stacked location pointer is passed down to the repository and requires
2228
a repository format with supports_external_lookups = True.
2230
This format was introduced in bzr 1.6.
2233
def initialize(self, a_bzrdir, name=None, repository=None,
2234
append_revisions_only=None):
2235
"""Create a branch of this format in a_bzrdir."""
2236
utf8_files = [('last-revision', '0 null:\n'),
2238
self._get_initial_config(append_revisions_only)),
2241
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2243
def _branch_class(self):
2246
def get_format_string(self):
2247
"""See BranchFormat.get_format_string()."""
2248
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2250
def get_format_description(self):
2251
"""See BranchFormat.get_format_description()."""
2252
return "Branch format 7"
2254
def supports_set_append_revisions_only(self):
2257
def supports_stacking(self):
2260
def make_tags(self, branch):
2261
"""See bzrlib.branch.BranchFormat.make_tags()."""
2262
return _mod_tag.BasicTags(branch)
2264
supports_reference_locations = False
2267
class BranchReferenceFormat(BranchFormatMetadir):
2268
"""Bzr branch reference format.
2270
Branch references are used in implementing checkouts, they
2271
act as an alias to the real branch which is at some other url.
2278
def get_format_string(self):
2279
"""See BranchFormat.get_format_string()."""
2280
return "Bazaar-NG Branch Reference Format 1\n"
2282
def get_format_description(self):
2283
"""See BranchFormat.get_format_description()."""
2284
return "Checkout reference format 1"
2286
def get_reference(self, a_bzrdir, name=None):
2287
"""See BranchFormat.get_reference()."""
2288
transport = a_bzrdir.get_branch_transport(None, name=name)
2289
return transport.get_bytes('location')
2291
def set_reference(self, a_bzrdir, name, to_branch):
2292
"""See BranchFormat.set_reference()."""
2293
transport = a_bzrdir.get_branch_transport(None, name=name)
2294
location = transport.put_bytes('location', to_branch.base)
2296
def initialize(self, a_bzrdir, name=None, target_branch=None,
2297
repository=None, append_revisions_only=None):
2298
"""Create a branch of this format in a_bzrdir."""
2299
if target_branch is None:
2300
# this format does not implement branch itself, thus the implicit
2301
# creation contract must see it as uninitializable
2302
raise errors.UninitializableFormat(self)
2303
mutter('creating branch reference in %s', a_bzrdir.user_url)
2304
if a_bzrdir._format.fixed_components:
2305
raise errors.IncompatibleFormat(self, a_bzrdir._format)
2306
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2307
branch_transport.put_bytes('location',
2308
target_branch.user_url)
2309
branch_transport.put_bytes('format', self.get_format_string())
2311
a_bzrdir, name, _found=True,
2312
possible_transports=[target_branch.bzrdir.root_transport])
2313
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2316
def _make_reference_clone_function(format, a_branch):
2317
"""Create a clone() routine for a branch dynamically."""
2318
def clone(to_bzrdir, revision_id=None,
2319
repository_policy=None):
2320
"""See Branch.clone()."""
2321
return format.initialize(to_bzrdir, target_branch=a_branch)
2322
# cannot obey revision_id limits when cloning a reference ...
2323
# FIXME RBC 20060210 either nuke revision_id for clone, or
2324
# emit some sort of warning/error to the caller ?!
2327
def open(self, a_bzrdir, name=None, _found=False, location=None,
2328
possible_transports=None, ignore_fallbacks=False,
2329
found_repository=None):
2330
"""Return the branch that the branch reference in a_bzrdir points at.
2332
:param a_bzrdir: A BzrDir that contains a branch.
2333
:param name: Name of colocated branch to open, if any
2334
:param _found: a private parameter, do not use it. It is used to
2335
indicate if format probing has already be done.
2336
:param ignore_fallbacks: when set, no fallback branches will be opened
2337
(if there are any). Default is to open fallbacks.
2338
:param location: The location of the referenced branch. If
2339
unspecified, this will be determined from the branch reference in
2341
:param possible_transports: An optional reusable transports list.
2344
format = BranchFormat.find_format(a_bzrdir, name=name)
2345
if format.__class__ != self.__class__:
2346
raise AssertionError("wrong format %r found for %r" %
2348
if location is None:
2349
location = self.get_reference(a_bzrdir, name)
2350
real_bzrdir = controldir.ControlDir.open(
2351
location, possible_transports=possible_transports)
2352
result = real_bzrdir.open_branch(name=name,
2353
ignore_fallbacks=ignore_fallbacks,
2354
possible_transports=possible_transports)
2355
# this changes the behaviour of result.clone to create a new reference
2356
# rather than a copy of the content of the branch.
2357
# I did not use a proxy object because that needs much more extensive
2358
# testing, and we are only changing one behaviour at the moment.
2359
# If we decide to alter more behaviours - i.e. the implicit nickname
2360
# then this should be refactored to introduce a tested proxy branch
2361
# and a subclass of that for use in overriding clone() and ....
2363
result.clone = self._make_reference_clone_function(result)
2367
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2368
"""Branch format registry."""
2370
def __init__(self, other_registry=None):
2371
super(BranchFormatRegistry, self).__init__(other_registry)
2372
self._default_format = None
2374
def set_default(self, format):
2375
self._default_format = format
2377
def get_default(self):
2378
return self._default_format
2381
network_format_registry = registry.FormatRegistry()
2382
"""Registry of formats indexed by their network name.
2384
The network name for a branch format is an identifier that can be used when
2385
referring to formats with smart server operations. See
2386
BranchFormat.network_name() for more detail.
2389
format_registry = BranchFormatRegistry(network_format_registry)
2392
# formats which have no format string are not discoverable
2393
# and not independently creatable, so are not registered.
2394
__format5 = BzrBranchFormat5()
2395
__format6 = BzrBranchFormat6()
2396
__format7 = BzrBranchFormat7()
2397
__format8 = BzrBranchFormat8()
2398
format_registry.register(__format5)
2399
format_registry.register(BranchReferenceFormat())
2400
format_registry.register(__format6)
2401
format_registry.register(__format7)
2402
format_registry.register(__format8)
2403
format_registry.set_default(__format7)
2406
class BranchWriteLockResult(LogicalLockResult):
2407
"""The result of write locking a branch.
2409
:ivar branch_token: The token obtained from the underlying branch lock, or
2411
:ivar unlock: A callable which will unlock the lock.
2414
def __init__(self, unlock, branch_token):
2415
LogicalLockResult.__init__(self, unlock)
2416
self.branch_token = branch_token
2419
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2423
class BzrBranch(Branch, _RelockDebugMixin):
2424
"""A branch stored in the actual filesystem.
2426
Note that it's "local" in the context of the filesystem; it doesn't
2427
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2428
it's writable, and can be accessed via the normal filesystem API.
2430
:ivar _transport: Transport for file operations on this branch's
2431
control files, typically pointing to the .bzr/branch directory.
2432
:ivar repository: Repository for this branch.
2433
:ivar base: The url of the base directory for this branch; the one
2434
containing the .bzr directory.
2435
:ivar name: Optional colocated branch name as it exists in the control
2439
def __init__(self, _format=None,
2440
_control_files=None, a_bzrdir=None, name=None,
2441
_repository=None, ignore_fallbacks=False,
2442
possible_transports=None):
2443
"""Create new branch object at a particular location."""
2444
if a_bzrdir is None:
2445
raise ValueError('a_bzrdir must be supplied')
2447
self.bzrdir = a_bzrdir
2448
self._user_transport = self.bzrdir.transport.clone('..')
2449
if name is not None:
2450
self._user_transport.set_segment_parameter(
2451
"branch", urlutils.escape(name))
2452
self._base = self._user_transport.base
2454
self._format = _format
2455
if _control_files is None:
2456
raise ValueError('BzrBranch _control_files is None')
2457
self.control_files = _control_files
2458
self._transport = _control_files._transport
2459
self.repository = _repository
2460
Branch.__init__(self, possible_transports)
2463
return '%s(%s)' % (self.__class__.__name__, self.user_url)
2467
def _get_base(self):
2468
"""Returns the directory containing the control directory."""
2471
base = property(_get_base, doc="The URL for the root of this branch.")
2474
def user_transport(self):
2475
return self._user_transport
2477
def _get_config(self):
2478
return _mod_config.TransportConfig(self._transport, 'branch.conf')
2480
def _get_config_store(self):
2481
return _mod_config.BranchStore(self)
2483
def is_locked(self):
2484
return self.control_files.is_locked()
2486
def lock_write(self, token=None):
2487
"""Lock the branch for write operations.
2489
:param token: A token to permit reacquiring a previously held and
2491
:return: A BranchWriteLockResult.
2493
if not self.is_locked():
2494
self._note_lock('w')
2495
# All-in-one needs to always unlock/lock.
2496
repo_control = getattr(self.repository, 'control_files', None)
2497
if self.control_files == repo_control or not self.is_locked():
2498
self.repository._warn_if_deprecated(self)
2499
self.repository.lock_write()
2504
return BranchWriteLockResult(self.unlock,
2505
self.control_files.lock_write(token=token))
2508
self.repository.unlock()
2511
def lock_read(self):
2512
"""Lock the branch for read operations.
2514
:return: A bzrlib.lock.LogicalLockResult.
2516
if not self.is_locked():
2517
self._note_lock('r')
2518
# All-in-one needs to always unlock/lock.
2519
repo_control = getattr(self.repository, 'control_files', None)
2520
if self.control_files == repo_control or not self.is_locked():
2521
self.repository._warn_if_deprecated(self)
2522
self.repository.lock_read()
2527
self.control_files.lock_read()
2528
return LogicalLockResult(self.unlock)
2531
self.repository.unlock()
2534
@only_raises(errors.LockNotHeld, errors.LockBroken)
2537
self.control_files.unlock()
2539
# All-in-one needs to always unlock/lock.
2540
repo_control = getattr(self.repository, 'control_files', None)
2541
if (self.control_files == repo_control or
2542
not self.control_files.is_locked()):
2543
self.repository.unlock()
2544
if not self.control_files.is_locked():
2545
# we just released the lock
2546
self._clear_cached_state()
2548
def peek_lock_mode(self):
2549
if self.control_files._lock_count == 0:
2552
return self.control_files._lock_mode
2554
def get_physical_lock_status(self):
2555
return self.control_files.get_physical_lock_status()
2558
def print_file(self, file, revision_id):
2559
"""See Branch.print_file."""
2560
return self.repository.print_file(file, revision_id)
2563
def set_last_revision_info(self, revno, revision_id):
2564
if not revision_id or not isinstance(revision_id, basestring):
2565
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2566
revision_id = _mod_revision.ensure_null(revision_id)
2567
old_revno, old_revid = self.last_revision_info()
2568
if self.get_append_revisions_only():
2569
self._check_history_violation(revision_id)
2570
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2571
self._write_last_revision_info(revno, revision_id)
2572
self._clear_cached_state()
2573
self._last_revision_info_cache = revno, revision_id
2574
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2576
def basis_tree(self):
2577
"""See Branch.basis_tree."""
2578
return self.repository.revision_tree(self.last_revision())
2580
def _get_parent_location(self):
2581
_locs = ['parent', 'pull', 'x-pull']
2584
return self._transport.get_bytes(l).strip('\n')
2585
except errors.NoSuchFile:
2589
def get_stacked_on_url(self):
2590
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2592
def set_push_location(self, location):
2593
"""See Branch.set_push_location."""
2594
self.get_config().set_user_option(
2595
'push_location', location,
2596
store=_mod_config.STORE_LOCATION_NORECURSE)
2598
def _set_parent_location(self, url):
2600
self._transport.delete('parent')
2602
self._transport.put_bytes('parent', url + '\n',
2603
mode=self.bzrdir._get_file_mode())
2607
"""If bound, unbind"""
2608
return self.set_bound_location(None)
2611
def bind(self, other):
2612
"""Bind this branch to the branch other.
2614
This does not push or pull data between the branches, though it does
2615
check for divergence to raise an error when the branches are not
2616
either the same, or one a prefix of the other. That behaviour may not
2617
be useful, so that check may be removed in future.
2619
:param other: The branch to bind to
2622
# TODO: jam 20051230 Consider checking if the target is bound
2623
# It is debatable whether you should be able to bind to
2624
# a branch which is itself bound.
2625
# Committing is obviously forbidden,
2626
# but binding itself may not be.
2627
# Since we *have* to check at commit time, we don't
2628
# *need* to check here
2630
# we want to raise diverged if:
2631
# last_rev is not in the other_last_rev history, AND
2632
# other_last_rev is not in our history, and do it without pulling
2634
self.set_bound_location(other.base)
2636
def get_bound_location(self):
2638
return self._transport.get_bytes('bound')[:-1]
2639
except errors.NoSuchFile:
2643
def get_master_branch(self, possible_transports=None):
2644
"""Return the branch we are bound to.
2646
:return: Either a Branch, or None
2648
if self._master_branch_cache is None:
2649
self._master_branch_cache = self._get_master_branch(
2650
possible_transports)
2651
return self._master_branch_cache
2653
def _get_master_branch(self, possible_transports):
2654
bound_loc = self.get_bound_location()
2658
return Branch.open(bound_loc,
2659
possible_transports=possible_transports)
2660
except (errors.NotBranchError, errors.ConnectionError), e:
2661
raise errors.BoundBranchConnectionFailure(
2665
def set_bound_location(self, location):
2666
"""Set the target where this branch is bound to.
2668
:param location: URL to the target branch
2670
self._master_branch_cache = None
2672
self._transport.put_bytes('bound', location+'\n',
2673
mode=self.bzrdir._get_file_mode())
2676
self._transport.delete('bound')
2677
except errors.NoSuchFile:
2682
def update(self, possible_transports=None):
2683
"""Synchronise this branch with the master branch if any.
2685
:return: None or the last_revision that was pivoted out during the
2688
master = self.get_master_branch(possible_transports)
2689
if master is not None:
2690
old_tip = _mod_revision.ensure_null(self.last_revision())
2691
self.pull(master, overwrite=True)
2692
if self.repository.get_graph().is_ancestor(old_tip,
2693
_mod_revision.ensure_null(self.last_revision())):
2698
def _read_last_revision_info(self):
2699
revision_string = self._transport.get_bytes('last-revision')
2700
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2701
revision_id = cache_utf8.get_cached_utf8(revision_id)
2703
return revno, revision_id
2705
def _write_last_revision_info(self, revno, revision_id):
2706
"""Simply write out the revision id, with no checks.
2708
Use set_last_revision_info to perform this safely.
2710
Does not update the revision_history cache.
2712
revision_id = _mod_revision.ensure_null(revision_id)
2713
out_string = '%d %s\n' % (revno, revision_id)
2714
self._transport.put_bytes('last-revision', out_string,
2715
mode=self.bzrdir._get_file_mode())
2718
class FullHistoryBzrBranch(BzrBranch):
2719
"""Bzr branch which contains the full revision history."""
2722
def set_last_revision_info(self, revno, revision_id):
2723
if not revision_id or not isinstance(revision_id, basestring):
2724
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2725
revision_id = _mod_revision.ensure_null(revision_id)
2726
# this old format stores the full history, but this api doesn't
2727
# provide it, so we must generate, and might as well check it's
2729
history = self._lefthand_history(revision_id)
2730
if len(history) != revno:
2731
raise AssertionError('%d != %d' % (len(history), revno))
2732
self._set_revision_history(history)
2734
def _read_last_revision_info(self):
2735
rh = self._revision_history()
2738
return (revno, rh[-1])
2740
return (0, _mod_revision.NULL_REVISION)
2742
@deprecated_method(deprecated_in((2, 4, 0)))
2744
def set_revision_history(self, rev_history):
2745
"""See Branch.set_revision_history."""
2746
self._set_revision_history(rev_history)
2748
def _set_revision_history(self, rev_history):
2749
if 'evil' in debug.debug_flags:
2750
mutter_callsite(3, "set_revision_history scales with history.")
2751
check_not_reserved_id = _mod_revision.check_not_reserved_id
2752
for rev_id in rev_history:
2753
check_not_reserved_id(rev_id)
2754
if Branch.hooks['post_change_branch_tip']:
2755
# Don't calculate the last_revision_info() if there are no hooks
2757
old_revno, old_revid = self.last_revision_info()
2758
if len(rev_history) == 0:
2759
revid = _mod_revision.NULL_REVISION
2761
revid = rev_history[-1]
2762
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2763
self._write_revision_history(rev_history)
2764
self._clear_cached_state()
2765
self._cache_revision_history(rev_history)
2766
for hook in Branch.hooks['set_rh']:
2767
hook(self, rev_history)
2768
if Branch.hooks['post_change_branch_tip']:
2769
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2771
def _write_revision_history(self, history):
2772
"""Factored out of set_revision_history.
2774
This performs the actual writing to disk.
2775
It is intended to be called by set_revision_history."""
2776
self._transport.put_bytes(
2777
'revision-history', '\n'.join(history),
2778
mode=self.bzrdir._get_file_mode())
2780
def _gen_revision_history(self):
2781
history = self._transport.get_bytes('revision-history').split('\n')
2782
if history[-1:] == ['']:
2783
# There shouldn't be a trailing newline, but just in case.
2787
def _synchronize_history(self, destination, revision_id):
2788
if not isinstance(destination, FullHistoryBzrBranch):
2789
super(BzrBranch, self)._synchronize_history(
2790
destination, revision_id)
2792
if revision_id == _mod_revision.NULL_REVISION:
2795
new_history = self._revision_history()
2796
if revision_id is not None and new_history != []:
2798
new_history = new_history[:new_history.index(revision_id) + 1]
2800
rev = self.repository.get_revision(revision_id)
2801
new_history = rev.get_history(self.repository)[1:]
2802
destination._set_revision_history(new_history)
2805
def generate_revision_history(self, revision_id, last_rev=None,
2807
"""Create a new revision history that will finish with revision_id.
2809
:param revision_id: the new tip to use.
2810
:param last_rev: The previous last_revision. If not None, then this
2811
must be a ancestory of revision_id, or DivergedBranches is raised.
2812
:param other_branch: The other branch that DivergedBranches should
2813
raise with respect to.
2815
self._set_revision_history(self._lefthand_history(revision_id,
2816
last_rev, other_branch))
2819
class BzrBranch5(FullHistoryBzrBranch):
2820
"""A format 5 branch. This supports new features over plain branches.
2822
It has support for a master_branch which is the data for bound branches.
2826
class BzrBranch8(BzrBranch):
2827
"""A branch that stores tree-reference locations."""
2829
def _open_hook(self, possible_transports=None):
2830
if self._ignore_fallbacks:
2832
if possible_transports is None:
2833
possible_transports = [self.bzrdir.root_transport]
2835
url = self.get_stacked_on_url()
2836
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2837
errors.UnstackableBranchFormat):
2840
for hook in Branch.hooks['transform_fallback_location']:
2841
url = hook(self, url)
2843
hook_name = Branch.hooks.get_hook_name(hook)
2844
raise AssertionError(
2845
"'transform_fallback_location' hook %s returned "
2846
"None, not a URL." % hook_name)
2847
self._activate_fallback_location(url,
2848
possible_transports=possible_transports)
2850
def __init__(self, *args, **kwargs):
2851
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2852
super(BzrBranch8, self).__init__(*args, **kwargs)
2853
self._last_revision_info_cache = None
2854
self._reference_info = None
2856
def _clear_cached_state(self):
2857
super(BzrBranch8, self)._clear_cached_state()
2858
self._last_revision_info_cache = None
2859
self._reference_info = None
2861
def _check_history_violation(self, revision_id):
2862
current_revid = self.last_revision()
2863
last_revision = _mod_revision.ensure_null(current_revid)
2864
if _mod_revision.is_null(last_revision):
2866
graph = self.repository.get_graph()
2867
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2868
if lh_ancestor == current_revid:
2870
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2872
def _gen_revision_history(self):
2873
"""Generate the revision history from last revision
2875
last_revno, last_revision = self.last_revision_info()
2876
self._extend_partial_history(stop_index=last_revno-1)
2877
return list(reversed(self._partial_revision_history_cache))
2880
def _set_parent_location(self, url):
2881
"""Set the parent branch"""
2882
self._set_config_location('parent_location', url, make_relative=True)
2885
def _get_parent_location(self):
2886
"""Set the parent branch"""
2887
return self._get_config_location('parent_location')
2890
def _set_all_reference_info(self, info_dict):
2891
"""Replace all reference info stored in a branch.
2893
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2896
writer = rio.RioWriter(s)
2897
for key, (tree_path, branch_location) in info_dict.iteritems():
2898
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2899
branch_location=branch_location)
2900
writer.write_stanza(stanza)
2901
self._transport.put_bytes('references', s.getvalue())
2902
self._reference_info = info_dict
2905
def _get_all_reference_info(self):
2906
"""Return all the reference info stored in a branch.
2908
:return: A dict of {file_id: (tree_path, branch_location)}
2910
if self._reference_info is not None:
2911
return self._reference_info
2912
rio_file = self._transport.get('references')
2914
stanzas = rio.read_stanzas(rio_file)
2915
info_dict = dict((s['file_id'], (s['tree_path'],
2916
s['branch_location'])) for s in stanzas)
2919
self._reference_info = info_dict
2922
def set_reference_info(self, file_id, tree_path, branch_location):
2923
"""Set the branch location to use for a tree reference.
2925
:param file_id: The file-id of the tree reference.
2926
:param tree_path: The path of the tree reference in the tree.
2927
:param branch_location: The location of the branch to retrieve tree
2930
info_dict = self._get_all_reference_info()
2931
info_dict[file_id] = (tree_path, branch_location)
2932
if None in (tree_path, branch_location):
2933
if tree_path is not None:
2934
raise ValueError('tree_path must be None when branch_location'
2936
if branch_location is not None:
2937
raise ValueError('branch_location must be None when tree_path'
2939
del info_dict[file_id]
2940
self._set_all_reference_info(info_dict)
2942
def get_reference_info(self, file_id):
2943
"""Get the tree_path and branch_location for a tree reference.
2945
:return: a tuple of (tree_path, branch_location)
2947
return self._get_all_reference_info().get(file_id, (None, None))
2949
def reference_parent(self, file_id, path, possible_transports=None):
2950
"""Return the parent branch for a tree-reference file_id.
2952
:param file_id: The file_id of the tree reference
2953
:param path: The path of the file_id in the tree
2954
:return: A branch associated with the file_id
2956
branch_location = self.get_reference_info(file_id)[1]
2957
if branch_location is None:
2958
return Branch.reference_parent(self, file_id, path,
2959
possible_transports)
2960
branch_location = urlutils.join(self.user_url, branch_location)
2961
return Branch.open(branch_location,
2962
possible_transports=possible_transports)
2964
def set_push_location(self, location):
2965
"""See Branch.set_push_location."""
2966
self._set_config_location('push_location', location)
2968
def set_bound_location(self, location):
2969
"""See Branch.set_push_location."""
2970
self._master_branch_cache = None
2972
config = self.get_config()
2973
if location is None:
2974
if config.get_user_option('bound') != 'True':
2977
config.set_user_option('bound', 'False', warn_masked=True)
2980
self._set_config_location('bound_location', location,
2982
config.set_user_option('bound', 'True', warn_masked=True)
2985
def _get_bound_location(self, bound):
2986
"""Return the bound location in the config file.
2988
Return None if the bound parameter does not match"""
2989
config = self.get_config()
2990
config_bound = (config.get_user_option('bound') == 'True')
2991
if config_bound != bound:
2993
return self._get_config_location('bound_location', config=config)
2995
def get_bound_location(self):
2996
"""See Branch.set_push_location."""
2997
return self._get_bound_location(True)
2999
def get_old_bound_location(self):
3000
"""See Branch.get_old_bound_location"""
3001
return self._get_bound_location(False)
3003
def get_stacked_on_url(self):
3004
# you can always ask for the URL; but you might not be able to use it
3005
# if the repo can't support stacking.
3006
## self._check_stackable_repo()
3007
# stacked_on_location is only ever defined in branch.conf, so don't
3008
# waste effort reading the whole stack of config files.
3009
config = self.get_config()._get_branch_data_config()
3010
stacked_url = self._get_config_location('stacked_on_location',
3012
if stacked_url is None:
3013
raise errors.NotStacked(self)
3017
def get_rev_id(self, revno, history=None):
3018
"""Find the revision id of the specified revno."""
3020
return _mod_revision.NULL_REVISION
3022
last_revno, last_revision_id = self.last_revision_info()
3023
if revno <= 0 or revno > last_revno:
3024
raise errors.NoSuchRevision(self, revno)
3026
if history is not None:
3027
return history[revno - 1]
3029
index = last_revno - revno
3030
if len(self._partial_revision_history_cache) <= index:
3031
self._extend_partial_history(stop_index=index)
3032
if len(self._partial_revision_history_cache) > index:
3033
return self._partial_revision_history_cache[index]
3035
raise errors.NoSuchRevision(self, revno)
3038
def revision_id_to_revno(self, revision_id):
3039
"""Given a revision id, return its revno"""
3040
if _mod_revision.is_null(revision_id):
3043
index = self._partial_revision_history_cache.index(revision_id)
3046
self._extend_partial_history(stop_revision=revision_id)
3047
except errors.RevisionNotPresent, e:
3048
raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
3049
index = len(self._partial_revision_history_cache) - 1
3051
raise errors.NoSuchRevision(self, revision_id)
3052
if self._partial_revision_history_cache[index] != revision_id:
3053
raise errors.NoSuchRevision(self, revision_id)
3054
return self.revno() - index
3057
class BzrBranch7(BzrBranch8):
3058
"""A branch with support for a fallback repository."""
3060
def set_reference_info(self, file_id, tree_path, branch_location):
3061
Branch.set_reference_info(self, file_id, tree_path, branch_location)
3063
def get_reference_info(self, file_id):
3064
Branch.get_reference_info(self, file_id)
3066
def reference_parent(self, file_id, path, possible_transports=None):
3067
return Branch.reference_parent(self, file_id, path,
3068
possible_transports)
3071
class BzrBranch6(BzrBranch7):
3072
"""See BzrBranchFormat6 for the capabilities of this branch.
3074
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
3078
def get_stacked_on_url(self):
3079
raise errors.UnstackableBranchFormat(self._format, self.user_url)
3082
######################################################################
3083
# results of operations
3086
class _Result(object):
3088
def _show_tag_conficts(self, to_file):
3089
if not getattr(self, 'tag_conflicts', None):
3091
to_file.write('Conflicting tags:\n')
3092
for name, value1, value2 in self.tag_conflicts:
3093
to_file.write(' %s\n' % (name, ))
3096
class PullResult(_Result):
3097
"""Result of a Branch.pull operation.
3099
:ivar old_revno: Revision number before pull.
3100
:ivar new_revno: Revision number after pull.
3101
:ivar old_revid: Tip revision id before pull.
3102
:ivar new_revid: Tip revision id after pull.
3103
:ivar source_branch: Source (local) branch object. (read locked)
3104
:ivar master_branch: Master branch of the target, or the target if no
3106
:ivar local_branch: target branch if there is a Master, else None
3107
:ivar target_branch: Target/destination branch object. (write locked)
3108
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3109
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3112
@deprecated_method(deprecated_in((2, 3, 0)))
3114
"""Return the relative change in revno.
3116
:deprecated: Use `new_revno` and `old_revno` instead.
3118
return self.new_revno - self.old_revno
3120
def report(self, to_file):
3121
tag_conflicts = getattr(self, "tag_conflicts", None)
3122
tag_updates = getattr(self, "tag_updates", None)
3124
if self.old_revid != self.new_revid:
3125
to_file.write('Now on revision %d.\n' % self.new_revno)
3127
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3128
if self.old_revid == self.new_revid and not tag_updates:
3129
if not tag_conflicts:
3130
to_file.write('No revisions or tags to pull.\n')
3132
to_file.write('No revisions to pull.\n')
3133
self._show_tag_conficts(to_file)
3136
class BranchPushResult(_Result):
3137
"""Result of a Branch.push operation.
3139
:ivar old_revno: Revision number (eg 10) of the target before push.
3140
:ivar new_revno: Revision number (eg 12) of the target after push.
3141
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
3143
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
3145
:ivar source_branch: Source branch object that the push was from. This is
3146
read locked, and generally is a local (and thus low latency) branch.
3147
:ivar master_branch: If target is a bound branch, the master branch of
3148
target, or target itself. Always write locked.
3149
:ivar target_branch: The direct Branch where data is being sent (write
3151
:ivar local_branch: If the target is a bound branch this will be the
3152
target, otherwise it will be None.
3155
@deprecated_method(deprecated_in((2, 3, 0)))
3157
"""Return the relative change in revno.
3159
:deprecated: Use `new_revno` and `old_revno` instead.
3161
return self.new_revno - self.old_revno
3163
def report(self, to_file):
3164
# TODO: This function gets passed a to_file, but then
3165
# ignores it and calls note() instead. This is also
3166
# inconsistent with PullResult(), which writes to stdout.
3167
# -- JRV20110901, bug #838853
3168
tag_conflicts = getattr(self, "tag_conflicts", None)
3169
tag_updates = getattr(self, "tag_updates", None)
3171
if self.old_revid != self.new_revid:
3172
note(gettext('Pushed up to revision %d.') % self.new_revno)
3174
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3175
if self.old_revid == self.new_revid and not tag_updates:
3176
if not tag_conflicts:
3177
note(gettext('No new revisions or tags to push.'))
3179
note(gettext('No new revisions to push.'))
3180
self._show_tag_conficts(to_file)
3183
class BranchCheckResult(object):
3184
"""Results of checking branch consistency.
3189
def __init__(self, branch):
3190
self.branch = branch
3193
def report_results(self, verbose):
3194
"""Report the check results via trace.note.
3196
:param verbose: Requests more detailed display of what was checked,
3199
note(gettext('checked branch {0} format {1}').format(
3200
self.branch.user_url, self.branch._format))
3201
for error in self.errors:
3202
note(gettext('found error:%s'), error)
3205
class Converter5to6(object):
3206
"""Perform an in-place upgrade of format 5 to format 6"""
3208
def convert(self, branch):
3209
# Data for 5 and 6 can peacefully coexist.
3210
format = BzrBranchFormat6()
3211
new_branch = format.open(branch.bzrdir, _found=True)
3213
# Copy source data into target
3214
new_branch._write_last_revision_info(*branch.last_revision_info())
3215
new_branch.set_parent(branch.get_parent())
3216
new_branch.set_bound_location(branch.get_bound_location())
3217
new_branch.set_push_location(branch.get_push_location())
3219
# New branch has no tags by default
3220
new_branch.tags._set_tag_dict({})
3222
# Copying done; now update target format
3223
new_branch._transport.put_bytes('format',
3224
format.get_format_string(),
3225
mode=new_branch.bzrdir._get_file_mode())
3227
# Clean up old files
3228
new_branch._transport.delete('revision-history')
3230
branch.set_parent(None)
3231
except errors.NoSuchFile:
3233
branch.set_bound_location(None)
3236
class Converter6to7(object):
3237
"""Perform an in-place upgrade of format 6 to format 7"""
3239
def convert(self, branch):
3240
format = BzrBranchFormat7()
3241
branch._set_config_location('stacked_on_location', '')
3242
# update target format
3243
branch._transport.put_bytes('format', format.get_format_string())
3246
class Converter7to8(object):
3247
"""Perform an in-place upgrade of format 7 to format 8"""
3249
def convert(self, branch):
3250
format = BzrBranchFormat8()
3251
branch._transport.put_bytes('references', '')
3252
# update target format
3253
branch._transport.put_bytes('format', format.get_format_string())
3256
class InterBranch(InterObject):
3257
"""This class represents operations taking place between two branches.
3259
Its instances have methods like pull() and push() and contain
3260
references to the source and target repositories these operations
3261
can be carried out on.
3265
"""The available optimised InterBranch types."""
3268
def _get_branch_formats_to_test(klass):
3269
"""Return an iterable of format tuples for testing.
3271
:return: An iterable of (from_format, to_format) to use when testing
3272
this InterBranch class. Each InterBranch class should define this
3275
raise NotImplementedError(klass._get_branch_formats_to_test)
3278
def pull(self, overwrite=False, stop_revision=None,
3279
possible_transports=None, local=False):
3280
"""Mirror source into target branch.
3282
The target branch is considered to be 'local', having low latency.
3284
:returns: PullResult instance
3286
raise NotImplementedError(self.pull)
3289
def push(self, overwrite=False, stop_revision=None, lossy=False,
3290
_override_hook_source_branch=None):
3291
"""Mirror the source branch into the target branch.
3293
The source branch is considered to be 'local', having low latency.
3295
raise NotImplementedError(self.push)
3298
def copy_content_into(self, revision_id=None):
3299
"""Copy the content of source into target
3301
revision_id: if not None, the revision history in the new branch will
3302
be truncated to end with revision_id.
3304
raise NotImplementedError(self.copy_content_into)
3307
def fetch(self, stop_revision=None, limit=None):
3310
:param stop_revision: Last revision to fetch
3311
:param limit: Optional rough limit of revisions to fetch
3313
raise NotImplementedError(self.fetch)
3316
class GenericInterBranch(InterBranch):
3317
"""InterBranch implementation that uses public Branch functions."""
3320
def is_compatible(klass, source, target):
3321
# GenericBranch uses the public API, so always compatible
3325
def _get_branch_formats_to_test(klass):
3326
return [(format_registry.get_default(), format_registry.get_default())]
3329
def unwrap_format(klass, format):
3330
if isinstance(format, remote.RemoteBranchFormat):
3331
format._ensure_real()
3332
return format._custom_format
3336
def copy_content_into(self, revision_id=None):
3337
"""Copy the content of source into target
3339
revision_id: if not None, the revision history in the new branch will
3340
be truncated to end with revision_id.
3342
self.source.update_references(self.target)
3343
self.source._synchronize_history(self.target, revision_id)
3345
parent = self.source.get_parent()
3346
except errors.InaccessibleParent, e:
3347
mutter('parent was not accessible to copy: %s', e)
3350
self.target.set_parent(parent)
3351
if self.source._push_should_merge_tags():
3352
self.source.tags.merge_to(self.target.tags)
3355
def fetch(self, stop_revision=None, limit=None):
3356
if self.target.base == self.source.base:
3358
self.source.lock_read()
3360
fetch_spec_factory = fetch.FetchSpecFactory()
3361
fetch_spec_factory.source_branch = self.source
3362
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3363
fetch_spec_factory.source_repo = self.source.repository
3364
fetch_spec_factory.target_repo = self.target.repository
3365
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3366
fetch_spec_factory.limit = limit
3367
fetch_spec = fetch_spec_factory.make_fetch_spec()
3368
return self.target.repository.fetch(self.source.repository,
3369
fetch_spec=fetch_spec)
3371
self.source.unlock()
3374
def _update_revisions(self, stop_revision=None, overwrite=False,
3376
other_revno, other_last_revision = self.source.last_revision_info()
3377
stop_revno = None # unknown
3378
if stop_revision is None:
3379
stop_revision = other_last_revision
3380
if _mod_revision.is_null(stop_revision):
3381
# if there are no commits, we're done.
3383
stop_revno = other_revno
3385
# what's the current last revision, before we fetch [and change it
3387
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3388
# we fetch here so that we don't process data twice in the common
3389
# case of having something to pull, and so that the check for
3390
# already merged can operate on the just fetched graph, which will
3391
# be cached in memory.
3392
self.fetch(stop_revision=stop_revision)
3393
# Check to see if one is an ancestor of the other
3396
graph = self.target.repository.get_graph()
3397
if self.target._check_if_descendant_or_diverged(
3398
stop_revision, last_rev, graph, self.source):
3399
# stop_revision is a descendant of last_rev, but we aren't
3400
# overwriting, so we're done.
3402
if stop_revno is None:
3404
graph = self.target.repository.get_graph()
3405
this_revno, this_last_revision = \
3406
self.target.last_revision_info()
3407
stop_revno = graph.find_distance_to_null(stop_revision,
3408
[(other_last_revision, other_revno),
3409
(this_last_revision, this_revno)])
3410
self.target.set_last_revision_info(stop_revno, stop_revision)
3413
def pull(self, overwrite=False, stop_revision=None,
3414
possible_transports=None, run_hooks=True,
3415
_override_hook_target=None, local=False):
3416
"""Pull from source into self, updating my master if any.
3418
:param run_hooks: Private parameter - if false, this branch
3419
is being called because it's the master of the primary branch,
3420
so it should not run its hooks.
3422
bound_location = self.target.get_bound_location()
3423
if local and not bound_location:
3424
raise errors.LocalRequiresBoundBranch()
3425
master_branch = None
3426
source_is_master = False
3428
# bound_location comes from a config file, some care has to be
3429
# taken to relate it to source.user_url
3430
normalized = urlutils.normalize_url(bound_location)
3432
relpath = self.source.user_transport.relpath(normalized)
3433
source_is_master = (relpath == '')
3434
except (errors.PathNotChild, errors.InvalidURL):
3435
source_is_master = False
3436
if not local and bound_location and not source_is_master:
3437
# not pulling from master, so we need to update master.
3438
master_branch = self.target.get_master_branch(possible_transports)
3439
master_branch.lock_write()
3442
# pull from source into master.
3443
master_branch.pull(self.source, overwrite, stop_revision,
3445
return self._pull(overwrite,
3446
stop_revision, _hook_master=master_branch,
3447
run_hooks=run_hooks,
3448
_override_hook_target=_override_hook_target,
3449
merge_tags_to_master=not source_is_master)
3452
master_branch.unlock()
3454
def push(self, overwrite=False, stop_revision=None, lossy=False,
3455
_override_hook_source_branch=None):
3456
"""See InterBranch.push.
3458
This is the basic concrete implementation of push()
3460
:param _override_hook_source_branch: If specified, run the hooks
3461
passing this Branch as the source, rather than self. This is for
3462
use of RemoteBranch, where push is delegated to the underlying
3466
raise errors.LossyPushToSameVCS(self.source, self.target)
3467
# TODO: Public option to disable running hooks - should be trivial but
3470
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3471
op.add_cleanup(self.source.lock_read().unlock)
3472
op.add_cleanup(self.target.lock_write().unlock)
3473
return op.run(overwrite, stop_revision,
3474
_override_hook_source_branch=_override_hook_source_branch)
3476
def _basic_push(self, overwrite, stop_revision):
3477
"""Basic implementation of push without bound branches or hooks.
3479
Must be called with source read locked and target write locked.
3481
result = BranchPushResult()
3482
result.source_branch = self.source
3483
result.target_branch = self.target
3484
result.old_revno, result.old_revid = self.target.last_revision_info()
3485
self.source.update_references(self.target)
3486
if result.old_revid != stop_revision:
3487
# We assume that during 'push' this repository is closer than
3489
graph = self.source.repository.get_graph(self.target.repository)
3490
self._update_revisions(stop_revision, overwrite=overwrite,
3492
if self.source._push_should_merge_tags():
3493
result.tag_updates, result.tag_conflicts = (
3494
self.source.tags.merge_to(self.target.tags, overwrite))
3495
result.new_revno, result.new_revid = self.target.last_revision_info()
3498
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3499
_override_hook_source_branch=None):
3500
"""Push from source into target, and into target's master if any.
3503
if _override_hook_source_branch:
3504
result.source_branch = _override_hook_source_branch
3505
for hook in Branch.hooks['post_push']:
3508
bound_location = self.target.get_bound_location()
3509
if bound_location and self.target.base != bound_location:
3510
# there is a master branch.
3512
# XXX: Why the second check? Is it even supported for a branch to
3513
# be bound to itself? -- mbp 20070507
3514
master_branch = self.target.get_master_branch()
3515
master_branch.lock_write()
3516
operation.add_cleanup(master_branch.unlock)
3517
# push into the master from the source branch.
3518
master_inter = InterBranch.get(self.source, master_branch)
3519
master_inter._basic_push(overwrite, stop_revision)
3520
# and push into the target branch from the source. Note that
3521
# we push from the source branch again, because it's considered
3522
# the highest bandwidth repository.
3523
result = self._basic_push(overwrite, stop_revision)
3524
result.master_branch = master_branch
3525
result.local_branch = self.target
3527
master_branch = None
3529
result = self._basic_push(overwrite, stop_revision)
3530
# TODO: Why set master_branch and local_branch if there's no
3531
# binding? Maybe cleaner to just leave them unset? -- mbp
3533
result.master_branch = self.target
3534
result.local_branch = None
3538
def _pull(self, overwrite=False, stop_revision=None,
3539
possible_transports=None, _hook_master=None, run_hooks=True,
3540
_override_hook_target=None, local=False,
3541
merge_tags_to_master=True):
3544
This function is the core worker, used by GenericInterBranch.pull to
3545
avoid duplication when pulling source->master and source->local.
3547
:param _hook_master: Private parameter - set the branch to
3548
be supplied as the master to pull hooks.
3549
:param run_hooks: Private parameter - if false, this branch
3550
is being called because it's the master of the primary branch,
3551
so it should not run its hooks.
3552
is being called because it's the master of the primary branch,
3553
so it should not run its hooks.
3554
:param _override_hook_target: Private parameter - set the branch to be
3555
supplied as the target_branch to pull hooks.
3556
:param local: Only update the local branch, and not the bound branch.
3558
# This type of branch can't be bound.
3560
raise errors.LocalRequiresBoundBranch()
3561
result = PullResult()
3562
result.source_branch = self.source
3563
if _override_hook_target is None:
3564
result.target_branch = self.target
3566
result.target_branch = _override_hook_target
3567
self.source.lock_read()
3569
# We assume that during 'pull' the target repository is closer than
3571
self.source.update_references(self.target)
3572
graph = self.target.repository.get_graph(self.source.repository)
3573
# TODO: Branch formats should have a flag that indicates
3574
# that revno's are expensive, and pull() should honor that flag.
3576
result.old_revno, result.old_revid = \
3577
self.target.last_revision_info()
3578
self._update_revisions(stop_revision, overwrite=overwrite,
3580
# TODO: The old revid should be specified when merging tags,
3581
# so a tags implementation that versions tags can only
3582
# pull in the most recent changes. -- JRV20090506
3583
result.tag_updates, result.tag_conflicts = (
3584
self.source.tags.merge_to(self.target.tags, overwrite,
3585
ignore_master=not merge_tags_to_master))
3586
result.new_revno, result.new_revid = self.target.last_revision_info()
3588
result.master_branch = _hook_master
3589
result.local_branch = result.target_branch
3591
result.master_branch = result.target_branch
3592
result.local_branch = None
3594
for hook in Branch.hooks['post_pull']:
3597
self.source.unlock()
3601
InterBranch.register_optimiser(GenericInterBranch)