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
17
from __future__ import absolute_import
21
from cStringIO import StringIO
23
from bzrlib.lazy_import import lazy_import
24
lazy_import(globals(), """
31
config as _mod_config,
40
revision as _mod_revision,
48
from bzrlib.i18n import gettext, ngettext
54
from bzrlib.decorators import (
59
from bzrlib.hooks import Hooks
60
from bzrlib.inter import InterObject
61
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
62
from bzrlib import registry
63
from bzrlib.symbol_versioning import (
67
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
70
class Branch(controldir.ControlComponent):
71
"""Branch holding a history of revisions.
74
Base directory/url of the branch; using control_url and
75
control_transport is more standardized.
76
:ivar hooks: An instance of BranchHooks.
77
:ivar _master_branch_cache: cached result of get_master_branch, see
80
# this is really an instance variable - FIXME move it there
85
def control_transport(self):
86
return self._transport
89
def user_transport(self):
90
return self.bzrdir.user_transport
92
def __init__(self, possible_transports=None):
93
self.tags = self._format.make_tags(self)
94
self._revision_history_cache = None
95
self._revision_id_to_revno_cache = None
96
self._partial_revision_id_to_revno_cache = {}
97
self._partial_revision_history_cache = []
98
self._tags_bytes = None
99
self._last_revision_info_cache = None
100
self._master_branch_cache = None
101
self._merge_sorted_revisions_cache = None
102
self._open_hook(possible_transports)
103
hooks = Branch.hooks['open']
107
def _open_hook(self, possible_transports):
108
"""Called by init to allow simpler extension of the base class."""
110
def _activate_fallback_location(self, url, possible_transports):
111
"""Activate the branch/repository from url as a fallback repository."""
112
for existing_fallback_repo in self.repository._fallback_repositories:
113
if existing_fallback_repo.user_url == url:
114
# This fallback is already configured. This probably only
115
# happens because ControlDir.sprout is a horrible mess. To avoid
116
# confusing _unstack we don't add this a second time.
117
mutter('duplicate activation of fallback %r on %r', url, self)
119
repo = self._get_fallback_repository(url, possible_transports)
120
if repo.has_same_location(self.repository):
121
raise errors.UnstackableLocationError(self.user_url, url)
122
self.repository.add_fallback_repository(repo)
124
def break_lock(self):
125
"""Break a lock if one is present from another instance.
127
Uses the ui factory to ask for confirmation if the lock may be from
130
This will probe the repository for its lock as well.
132
self.control_files.break_lock()
133
self.repository.break_lock()
134
master = self.get_master_branch()
135
if master is not None:
138
def _check_stackable_repo(self):
139
if not self.repository._format.supports_external_lookups:
140
raise errors.UnstackableRepositoryFormat(self.repository._format,
141
self.repository.base)
143
def _extend_partial_history(self, stop_index=None, stop_revision=None):
144
"""Extend the partial history to include a given index
146
If a stop_index is supplied, stop when that index has been reached.
147
If a stop_revision is supplied, stop when that revision is
148
encountered. Otherwise, stop when the beginning of history is
151
:param stop_index: The index which should be present. When it is
152
present, history extension will stop.
153
:param stop_revision: The revision id which should be present. When
154
it is encountered, history extension will stop.
156
if len(self._partial_revision_history_cache) == 0:
157
self._partial_revision_history_cache = [self.last_revision()]
158
repository._iter_for_revno(
159
self.repository, self._partial_revision_history_cache,
160
stop_index=stop_index, stop_revision=stop_revision)
161
if self._partial_revision_history_cache[-1] == _mod_revision.NULL_REVISION:
162
self._partial_revision_history_cache.pop()
164
def _get_check_refs(self):
165
"""Get the references needed for check().
169
revid = self.last_revision()
170
return [('revision-existence', revid), ('lefthand-distance', revid)]
173
def open(base, _unsupported=False, possible_transports=None):
174
"""Open the branch rooted at base.
176
For instance, if the branch is at URL/.bzr/branch,
177
Branch.open(URL) -> a Branch instance.
179
control = controldir.ControlDir.open(base, _unsupported,
180
possible_transports=possible_transports)
181
return control.open_branch(unsupported=_unsupported,
182
possible_transports=possible_transports)
185
def open_from_transport(transport, name=None, _unsupported=False,
186
possible_transports=None):
187
"""Open the branch rooted at transport"""
188
control = controldir.ControlDir.open_from_transport(transport, _unsupported)
189
return control.open_branch(name=name, unsupported=_unsupported,
190
possible_transports=possible_transports)
193
def open_containing(url, possible_transports=None):
194
"""Open an existing branch which contains url.
196
This probes for a branch at url, and searches upwards from there.
198
Basically we keep looking up until we find the control directory or
199
run into the root. If there isn't one, raises NotBranchError.
200
If there is one and it is either an unrecognised format or an unsupported
201
format, UnknownFormatError or UnsupportedFormatError are raised.
202
If there is one, it is returned, along with the unused portion of url.
204
control, relpath = controldir.ControlDir.open_containing(url,
206
branch = control.open_branch(possible_transports=possible_transports)
207
return (branch, relpath)
209
def _push_should_merge_tags(self):
210
"""Should _basic_push merge this branch's tags into the target?
212
The default implementation returns False if this branch has no tags,
213
and True the rest of the time. Subclasses may override this.
215
return self.supports_tags() and self.tags.get_tag_dict()
217
def get_config(self):
218
"""Get a bzrlib.config.BranchConfig for this Branch.
220
This can then be used to get and set configuration options for the
223
:return: A bzrlib.config.BranchConfig.
225
return _mod_config.BranchConfig(self)
227
def get_config_stack(self):
228
"""Get a bzrlib.config.BranchStack for this Branch.
230
This can then be used to get and set configuration options for the
233
:return: A bzrlib.config.BranchStack.
235
return _mod_config.BranchStack(self)
237
def _get_config(self):
238
"""Get the concrete config for just the config in this branch.
240
This is not intended for client use; see Branch.get_config for the
245
:return: An object supporting get_option and set_option.
247
raise NotImplementedError(self._get_config)
249
def _get_fallback_repository(self, url, possible_transports):
250
"""Get the repository we fallback to at url."""
251
url = urlutils.join(self.base, url)
252
a_branch = Branch.open(url, possible_transports=possible_transports)
253
return a_branch.repository
256
def _get_tags_bytes(self):
257
"""Get the bytes of a serialised tags dict.
259
Note that not all branches support tags, nor do all use the same tags
260
logic: this method is specific to BasicTags. Other tag implementations
261
may use the same method name and behave differently, safely, because
262
of the double-dispatch via
263
format.make_tags->tags_instance->get_tags_dict.
265
:return: The bytes of the tags file.
266
:seealso: Branch._set_tags_bytes.
268
if self._tags_bytes is None:
269
self._tags_bytes = self._transport.get_bytes('tags')
270
return self._tags_bytes
272
def _get_nick(self, local=False, possible_transports=None):
273
config = self.get_config()
274
# explicit overrides master, but don't look for master if local is True
275
if not local and not config.has_explicit_nickname():
277
master = self.get_master_branch(possible_transports)
278
if master and self.user_url == master.user_url:
279
raise errors.RecursiveBind(self.user_url)
280
if master is not None:
281
# return the master branch value
283
except errors.RecursiveBind, e:
285
except errors.BzrError, e:
286
# Silently fall back to local implicit nick if the master is
288
mutter("Could not connect to bound branch, "
289
"falling back to local nick.\n " + str(e))
290
return config.get_nickname()
292
def _set_nick(self, nick):
293
self.get_config().set_user_option('nickname', nick, warn_masked=True)
295
nick = property(_get_nick, _set_nick)
298
raise NotImplementedError(self.is_locked)
300
def _lefthand_history(self, revision_id, last_rev=None,
302
if 'evil' in debug.debug_flags:
303
mutter_callsite(4, "_lefthand_history scales with history.")
304
# stop_revision must be a descendant of last_revision
305
graph = self.repository.get_graph()
306
if last_rev is not None:
307
if not graph.is_ancestor(last_rev, revision_id):
308
# our previous tip is not merged into stop_revision
309
raise errors.DivergedBranches(self, other_branch)
310
# make a new revision history from the graph
311
parents_map = graph.get_parent_map([revision_id])
312
if revision_id not in parents_map:
313
raise errors.NoSuchRevision(self, revision_id)
314
current_rev_id = revision_id
316
check_not_reserved_id = _mod_revision.check_not_reserved_id
317
# Do not include ghosts or graph origin in revision_history
318
while (current_rev_id in parents_map and
319
len(parents_map[current_rev_id]) > 0):
320
check_not_reserved_id(current_rev_id)
321
new_history.append(current_rev_id)
322
current_rev_id = parents_map[current_rev_id][0]
323
parents_map = graph.get_parent_map([current_rev_id])
324
new_history.reverse()
327
def lock_write(self, token=None):
328
"""Lock the branch for write operations.
330
:param token: A token to permit reacquiring a previously held and
332
:return: A BranchWriteLockResult.
334
raise NotImplementedError(self.lock_write)
337
"""Lock the branch for read operations.
339
:return: A bzrlib.lock.LogicalLockResult.
341
raise NotImplementedError(self.lock_read)
344
raise NotImplementedError(self.unlock)
346
def peek_lock_mode(self):
347
"""Return lock mode for the Branch: 'r', 'w' or None"""
348
raise NotImplementedError(self.peek_lock_mode)
350
def get_physical_lock_status(self):
351
raise NotImplementedError(self.get_physical_lock_status)
354
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
355
"""Return the revision_id for a dotted revno.
357
:param revno: a tuple like (1,) or (1,1,2)
358
:param _cache_reverse: a private parameter enabling storage
359
of the reverse mapping in a top level cache. (This should
360
only be done in selective circumstances as we want to
361
avoid having the mapping cached multiple times.)
362
:return: the revision_id
363
:raises errors.NoSuchRevision: if the revno doesn't exist
365
rev_id = self._do_dotted_revno_to_revision_id(revno)
367
self._partial_revision_id_to_revno_cache[rev_id] = revno
370
def _do_dotted_revno_to_revision_id(self, revno):
371
"""Worker function for dotted_revno_to_revision_id.
373
Subclasses should override this if they wish to
374
provide a more efficient implementation.
377
return self.get_rev_id(revno[0])
378
revision_id_to_revno = self.get_revision_id_to_revno_map()
379
revision_ids = [revision_id for revision_id, this_revno
380
in revision_id_to_revno.iteritems()
381
if revno == this_revno]
382
if len(revision_ids) == 1:
383
return revision_ids[0]
385
revno_str = '.'.join(map(str, revno))
386
raise errors.NoSuchRevision(self, revno_str)
389
def revision_id_to_dotted_revno(self, revision_id):
390
"""Given a revision id, return its dotted revno.
392
:return: a tuple like (1,) or (400,1,3).
394
return self._do_revision_id_to_dotted_revno(revision_id)
396
def _do_revision_id_to_dotted_revno(self, revision_id):
397
"""Worker function for revision_id_to_revno."""
398
# Try the caches if they are loaded
399
result = self._partial_revision_id_to_revno_cache.get(revision_id)
400
if result is not None:
402
if self._revision_id_to_revno_cache:
403
result = self._revision_id_to_revno_cache.get(revision_id)
405
raise errors.NoSuchRevision(self, revision_id)
406
# Try the mainline as it's optimised
408
revno = self.revision_id_to_revno(revision_id)
410
except errors.NoSuchRevision:
411
# We need to load and use the full revno map after all
412
result = self.get_revision_id_to_revno_map().get(revision_id)
414
raise errors.NoSuchRevision(self, revision_id)
418
def get_revision_id_to_revno_map(self):
419
"""Return the revision_id => dotted revno map.
421
This will be regenerated on demand, but will be cached.
423
:return: A dictionary mapping revision_id => dotted revno.
424
This dictionary should not be modified by the caller.
426
if self._revision_id_to_revno_cache is not None:
427
mapping = self._revision_id_to_revno_cache
429
mapping = self._gen_revno_map()
430
self._cache_revision_id_to_revno(mapping)
431
# TODO: jam 20070417 Since this is being cached, should we be returning
433
# I would rather not, and instead just declare that users should not
434
# modify the return value.
437
def _gen_revno_map(self):
438
"""Create a new mapping from revision ids to dotted revnos.
440
Dotted revnos are generated based on the current tip in the revision
442
This is the worker function for get_revision_id_to_revno_map, which
443
just caches the return value.
445
:return: A dictionary mapping revision_id => dotted revno.
447
revision_id_to_revno = dict((rev_id, revno)
448
for rev_id, depth, revno, end_of_merge
449
in self.iter_merge_sorted_revisions())
450
return revision_id_to_revno
453
def iter_merge_sorted_revisions(self, start_revision_id=None,
454
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
455
"""Walk the revisions for a branch in merge sorted order.
457
Merge sorted order is the output from a merge-aware,
458
topological sort, i.e. all parents come before their
459
children going forward; the opposite for reverse.
461
:param start_revision_id: the revision_id to begin walking from.
462
If None, the branch tip is used.
463
:param stop_revision_id: the revision_id to terminate the walk
464
after. If None, the rest of history is included.
465
:param stop_rule: if stop_revision_id is not None, the precise rule
466
to use for termination:
468
* 'exclude' - leave the stop revision out of the result (default)
469
* 'include' - the stop revision is the last item in the result
470
* 'with-merges' - include the stop revision and all of its
471
merged revisions in the result
472
* 'with-merges-without-common-ancestry' - filter out revisions
473
that are in both ancestries
474
:param direction: either 'reverse' or 'forward':
476
* reverse means return the start_revision_id first, i.e.
477
start at the most recent revision and go backwards in history
478
* forward returns tuples in the opposite order to reverse.
479
Note in particular that forward does *not* do any intelligent
480
ordering w.r.t. depth as some clients of this API may like.
481
(If required, that ought to be done at higher layers.)
483
:return: an iterator over (revision_id, depth, revno, end_of_merge)
486
* revision_id: the unique id of the revision
487
* depth: How many levels of merging deep this node has been
489
* revno_sequence: This field provides a sequence of
490
revision numbers for all revisions. The format is:
491
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
492
branch that the revno is on. From left to right the REVNO numbers
493
are the sequence numbers within that branch of the revision.
494
* end_of_merge: When True the next node (earlier in history) is
495
part of a different merge.
497
# Note: depth and revno values are in the context of the branch so
498
# we need the full graph to get stable numbers, regardless of the
500
if self._merge_sorted_revisions_cache is None:
501
last_revision = self.last_revision()
502
known_graph = self.repository.get_known_graph_ancestry(
504
self._merge_sorted_revisions_cache = known_graph.merge_sort(
506
filtered = self._filter_merge_sorted_revisions(
507
self._merge_sorted_revisions_cache, start_revision_id,
508
stop_revision_id, stop_rule)
509
# Make sure we don't return revisions that are not part of the
510
# start_revision_id ancestry.
511
filtered = self._filter_start_non_ancestors(filtered)
512
if direction == 'reverse':
514
if direction == 'forward':
515
return reversed(list(filtered))
517
raise ValueError('invalid direction %r' % direction)
519
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
520
start_revision_id, stop_revision_id, stop_rule):
521
"""Iterate over an inclusive range of sorted revisions."""
522
rev_iter = iter(merge_sorted_revisions)
523
if start_revision_id is not None:
524
for node in rev_iter:
526
if rev_id != start_revision_id:
529
# The decision to include the start or not
530
# depends on the stop_rule if a stop is provided
531
# so pop this node back into the iterator
532
rev_iter = itertools.chain(iter([node]), rev_iter)
534
if stop_revision_id is None:
536
for node in rev_iter:
538
yield (rev_id, node.merge_depth, node.revno,
540
elif stop_rule == 'exclude':
541
for node in rev_iter:
543
if rev_id == stop_revision_id:
545
yield (rev_id, node.merge_depth, node.revno,
547
elif stop_rule == 'include':
548
for node in rev_iter:
550
yield (rev_id, node.merge_depth, node.revno,
552
if rev_id == stop_revision_id:
554
elif stop_rule == 'with-merges-without-common-ancestry':
555
# We want to exclude all revisions that are already part of the
556
# stop_revision_id ancestry.
557
graph = self.repository.get_graph()
558
ancestors = graph.find_unique_ancestors(start_revision_id,
560
for node in rev_iter:
562
if rev_id not in ancestors:
564
yield (rev_id, node.merge_depth, node.revno,
566
elif stop_rule == 'with-merges':
567
stop_rev = self.repository.get_revision(stop_revision_id)
568
if stop_rev.parent_ids:
569
left_parent = stop_rev.parent_ids[0]
571
left_parent = _mod_revision.NULL_REVISION
572
# left_parent is the actual revision we want to stop logging at,
573
# since we want to show the merged revisions after the stop_rev too
574
reached_stop_revision_id = False
575
revision_id_whitelist = []
576
for node in rev_iter:
578
if rev_id == left_parent:
579
# reached the left parent after the stop_revision
581
if (not reached_stop_revision_id or
582
rev_id in revision_id_whitelist):
583
yield (rev_id, node.merge_depth, node.revno,
585
if reached_stop_revision_id or rev_id == stop_revision_id:
586
# only do the merged revs of rev_id from now on
587
rev = self.repository.get_revision(rev_id)
589
reached_stop_revision_id = True
590
revision_id_whitelist.extend(rev.parent_ids)
592
raise ValueError('invalid stop_rule %r' % stop_rule)
594
def _filter_start_non_ancestors(self, rev_iter):
595
# If we started from a dotted revno, we want to consider it as a tip
596
# and don't want to yield revisions that are not part of its
597
# ancestry. Given the order guaranteed by the merge sort, we will see
598
# uninteresting descendants of the first parent of our tip before the
600
first = rev_iter.next()
601
(rev_id, merge_depth, revno, end_of_merge) = first
604
# We start at a mainline revision so by definition, all others
605
# revisions in rev_iter are ancestors
606
for node in rev_iter:
611
pmap = self.repository.get_parent_map([rev_id])
612
parents = pmap.get(rev_id, [])
614
whitelist.update(parents)
616
# If there is no parents, there is nothing of interest left
618
# FIXME: It's hard to test this scenario here as this code is never
619
# called in that case. -- vila 20100322
622
for (rev_id, merge_depth, revno, end_of_merge) in rev_iter:
624
if rev_id in whitelist:
625
pmap = self.repository.get_parent_map([rev_id])
626
parents = pmap.get(rev_id, [])
627
whitelist.remove(rev_id)
628
whitelist.update(parents)
630
# We've reached the mainline, there is nothing left to
634
# A revision that is not part of the ancestry of our
637
yield (rev_id, merge_depth, revno, end_of_merge)
639
def leave_lock_in_place(self):
640
"""Tell this branch object not to release the physical lock when this
643
If lock_write doesn't return a token, then this method is not supported.
645
self.control_files.leave_in_place()
647
def dont_leave_lock_in_place(self):
648
"""Tell this branch object to release the physical lock when this
649
object is unlocked, even if it didn't originally acquire it.
651
If lock_write doesn't return a token, then this method is not supported.
653
self.control_files.dont_leave_in_place()
655
def bind(self, other):
656
"""Bind the local branch the other branch.
658
:param other: The branch to bind to
661
raise errors.UpgradeRequired(self.user_url)
663
def get_append_revisions_only(self):
664
"""Whether it is only possible to append revisions to the history.
666
if not self._format.supports_set_append_revisions_only():
668
return self.get_config_stack().get('append_revisions_only')
670
def set_append_revisions_only(self, enabled):
671
if not self._format.supports_set_append_revisions_only():
672
raise errors.UpgradeRequired(self.user_url)
673
self.get_config_stack().set('append_revisions_only', enabled)
675
def set_reference_info(self, file_id, tree_path, branch_location):
676
"""Set the branch location to use for a tree reference."""
677
raise errors.UnsupportedOperation(self.set_reference_info, self)
679
def get_reference_info(self, file_id):
680
"""Get the tree_path and branch_location for a tree reference."""
681
raise errors.UnsupportedOperation(self.get_reference_info, self)
684
def fetch(self, from_branch, last_revision=None, limit=None):
685
"""Copy revisions from from_branch into this branch.
687
:param from_branch: Where to copy from.
688
:param last_revision: What revision to stop at (None for at the end
690
:param limit: Optional rough limit of revisions to fetch
693
return InterBranch.get(from_branch, self).fetch(last_revision, limit=limit)
695
def get_bound_location(self):
696
"""Return the URL of the branch we are bound to.
698
Older format branches cannot bind, please be sure to use a metadir
703
def get_old_bound_location(self):
704
"""Return the URL of the branch we used to be bound to
706
raise errors.UpgradeRequired(self.user_url)
708
def get_commit_builder(self, parents, config_stack=None, timestamp=None,
709
timezone=None, committer=None, revprops=None,
710
revision_id=None, lossy=False):
711
"""Obtain a CommitBuilder for this branch.
713
:param parents: Revision ids of the parents of the new revision.
714
:param config: Optional configuration to use.
715
:param timestamp: Optional timestamp recorded for commit.
716
:param timezone: Optional timezone for timestamp.
717
:param committer: Optional committer to set for commit.
718
:param revprops: Optional dictionary of revision properties.
719
:param revision_id: Optional revision id.
720
:param lossy: Whether to discard data that can not be natively
721
represented, when pushing to a foreign VCS
724
if config_stack is None:
725
config_stack = self.get_config_stack()
727
return self.repository.get_commit_builder(self, parents, config_stack,
728
timestamp, timezone, committer, revprops, revision_id,
731
def get_master_branch(self, possible_transports=None):
732
"""Return the branch we are bound to.
734
:return: Either a Branch, or None
738
@deprecated_method(deprecated_in((2, 5, 0)))
739
def get_revision_delta(self, revno):
740
"""Return the delta for one revision.
742
The delta is relative to its mainline predecessor, or the
743
empty tree for revision 1.
746
revid = self.get_rev_id(revno)
747
except errors.NoSuchRevision:
748
raise errors.InvalidRevisionNumber(revno)
749
return self.repository.get_revision_delta(revid)
751
def get_stacked_on_url(self):
752
"""Get the URL this branch is stacked against.
754
:raises NotStacked: If the branch is not stacked.
755
:raises UnstackableBranchFormat: If the branch does not support
758
raise NotImplementedError(self.get_stacked_on_url)
760
def print_file(self, file, revision_id):
761
"""Print `file` to stdout."""
762
raise NotImplementedError(self.print_file)
764
@deprecated_method(deprecated_in((2, 4, 0)))
765
def set_revision_history(self, rev_history):
766
"""See Branch.set_revision_history."""
767
self._set_revision_history(rev_history)
770
def _set_revision_history(self, rev_history):
771
if len(rev_history) == 0:
772
revid = _mod_revision.NULL_REVISION
774
revid = rev_history[-1]
775
if rev_history != self._lefthand_history(revid):
776
raise errors.NotLefthandHistory(rev_history)
777
self.set_last_revision_info(len(rev_history), revid)
778
self._cache_revision_history(rev_history)
779
for hook in Branch.hooks['set_rh']:
780
hook(self, rev_history)
783
def set_last_revision_info(self, revno, revision_id):
784
"""Set the last revision of this branch.
786
The caller is responsible for checking that the revno is correct
787
for this revision id.
789
It may be possible to set the branch last revision to an id not
790
present in the repository. However, branches can also be
791
configured to check constraints on history, in which case this may not
794
raise NotImplementedError(self.set_last_revision_info)
797
def generate_revision_history(self, revision_id, last_rev=None,
799
"""See Branch.generate_revision_history"""
800
graph = self.repository.get_graph()
801
(last_revno, last_revid) = self.last_revision_info()
802
known_revision_ids = [
803
(last_revid, last_revno),
804
(_mod_revision.NULL_REVISION, 0),
806
if last_rev is not None:
807
if not graph.is_ancestor(last_rev, revision_id):
808
# our previous tip is not merged into stop_revision
809
raise errors.DivergedBranches(self, other_branch)
810
revno = graph.find_distance_to_null(revision_id, known_revision_ids)
811
self.set_last_revision_info(revno, revision_id)
814
def set_parent(self, url):
815
"""See Branch.set_parent."""
816
# TODO: Maybe delete old location files?
817
# URLs should never be unicode, even on the local fs,
818
# FIXUP this and get_parent in a future branch format bump:
819
# read and rewrite the file. RBC 20060125
821
if isinstance(url, unicode):
823
url = url.encode('ascii')
824
except UnicodeEncodeError:
825
raise errors.InvalidURL(url,
826
"Urls must be 7-bit ascii, "
827
"use bzrlib.urlutils.escape")
828
url = urlutils.relative_url(self.base, url)
829
self._set_parent_location(url)
832
def set_stacked_on_url(self, url):
833
"""Set the URL this branch is stacked against.
835
:raises UnstackableBranchFormat: If the branch does not support
837
:raises UnstackableRepositoryFormat: If the repository does not support
840
if not self._format.supports_stacking():
841
raise errors.UnstackableBranchFormat(self._format, self.user_url)
842
# XXX: Changing from one fallback repository to another does not check
843
# that all the data you need is present in the new fallback.
844
# Possibly it should.
845
self._check_stackable_repo()
848
old_url = self.get_stacked_on_url()
849
except (errors.NotStacked, errors.UnstackableBranchFormat,
850
errors.UnstackableRepositoryFormat):
854
self._activate_fallback_location(url,
855
possible_transports=[self.bzrdir.root_transport])
856
# write this out after the repository is stacked to avoid setting a
857
# stacked config that doesn't work.
858
self._set_config_location('stacked_on_location', url)
861
"""Change a branch to be unstacked, copying data as needed.
863
Don't call this directly, use set_stacked_on_url(None).
865
pb = ui.ui_factory.nested_progress_bar()
867
pb.update(gettext("Unstacking"))
868
# The basic approach here is to fetch the tip of the branch,
869
# including all available ghosts, from the existing stacked
870
# repository into a new repository object without the fallbacks.
872
# XXX: See <https://launchpad.net/bugs/397286> - this may not be
873
# correct for CHKMap repostiories
874
old_repository = self.repository
875
if len(old_repository._fallback_repositories) != 1:
876
raise AssertionError("can't cope with fallback repositories "
877
"of %r (fallbacks: %r)" % (old_repository,
878
old_repository._fallback_repositories))
879
# Open the new repository object.
880
# Repositories don't offer an interface to remove fallback
881
# repositories today; take the conceptually simpler option and just
882
# reopen it. We reopen it starting from the URL so that we
883
# get a separate connection for RemoteRepositories and can
884
# stream from one of them to the other. This does mean doing
885
# separate SSH connection setup, but unstacking is not a
886
# common operation so it's tolerable.
887
new_bzrdir = controldir.ControlDir.open(
888
self.bzrdir.root_transport.base)
889
new_repository = new_bzrdir.find_repository()
890
if new_repository._fallback_repositories:
891
raise AssertionError("didn't expect %r to have "
892
"fallback_repositories"
893
% (self.repository,))
894
# Replace self.repository with the new repository.
895
# Do our best to transfer the lock state (i.e. lock-tokens and
896
# lock count) of self.repository to the new repository.
897
lock_token = old_repository.lock_write().repository_token
898
self.repository = new_repository
899
if isinstance(self, remote.RemoteBranch):
900
# Remote branches can have a second reference to the old
901
# repository that need to be replaced.
902
if self._real_branch is not None:
903
self._real_branch.repository = new_repository
904
self.repository.lock_write(token=lock_token)
905
if lock_token is not None:
906
old_repository.leave_lock_in_place()
907
old_repository.unlock()
908
if lock_token is not None:
909
# XXX: self.repository.leave_lock_in_place() before this
910
# function will not be preserved. Fortunately that doesn't
911
# affect the current default format (2a), and would be a
912
# corner-case anyway.
913
# - Andrew Bennetts, 2010/06/30
914
self.repository.dont_leave_lock_in_place()
918
old_repository.unlock()
919
except errors.LockNotHeld:
922
if old_lock_count == 0:
923
raise AssertionError(
924
'old_repository should have been locked at least once.')
925
for i in range(old_lock_count-1):
926
self.repository.lock_write()
927
# Fetch from the old repository into the new.
928
old_repository.lock_read()
930
# XXX: If you unstack a branch while it has a working tree
931
# with a pending merge, the pending-merged revisions will no
932
# longer be present. You can (probably) revert and remerge.
934
tags_to_fetch = set(self.tags.get_reverse_tag_dict())
935
except errors.TagsNotSupported:
936
tags_to_fetch = set()
937
fetch_spec = vf_search.NotInOtherForRevs(self.repository,
938
old_repository, required_ids=[self.last_revision()],
939
if_present_ids=tags_to_fetch, find_ghosts=True).execute()
940
self.repository.fetch(old_repository, fetch_spec=fetch_spec)
942
old_repository.unlock()
946
def _set_tags_bytes(self, bytes):
947
"""Mirror method for _get_tags_bytes.
949
:seealso: Branch._get_tags_bytes.
951
op = cleanup.OperationWithCleanups(self._set_tags_bytes_locked)
952
op.add_cleanup(self.lock_write().unlock)
953
return op.run_simple(bytes)
955
def _set_tags_bytes_locked(self, bytes):
956
self._tags_bytes = bytes
957
return self._transport.put_bytes('tags', bytes)
959
def _cache_revision_history(self, rev_history):
960
"""Set the cached revision history to rev_history.
962
The revision_history method will use this cache to avoid regenerating
963
the revision history.
965
This API is semi-public; it only for use by subclasses, all other code
966
should consider it to be private.
968
self._revision_history_cache = rev_history
970
def _cache_revision_id_to_revno(self, revision_id_to_revno):
971
"""Set the cached revision_id => revno map to revision_id_to_revno.
973
This API is semi-public; it only for use by subclasses, all other code
974
should consider it to be private.
976
self._revision_id_to_revno_cache = revision_id_to_revno
978
def _clear_cached_state(self):
979
"""Clear any cached data on this branch, e.g. cached revision history.
981
This means the next call to revision_history will need to call
982
_gen_revision_history.
984
This API is semi-public; it only for use by subclasses, all other code
985
should consider it to be private.
987
self._revision_history_cache = None
988
self._revision_id_to_revno_cache = None
989
self._last_revision_info_cache = None
990
self._master_branch_cache = None
991
self._merge_sorted_revisions_cache = None
992
self._partial_revision_history_cache = []
993
self._partial_revision_id_to_revno_cache = {}
994
self._tags_bytes = None
996
def _gen_revision_history(self):
997
"""Return sequence of revision hashes on to this branch.
999
Unlike revision_history, this method always regenerates or rereads the
1000
revision history, i.e. it does not cache the result, so repeated calls
1003
Concrete subclasses should override this instead of revision_history so
1004
that subclasses do not need to deal with caching logic.
1006
This API is semi-public; it only for use by subclasses, all other code
1007
should consider it to be private.
1009
raise NotImplementedError(self._gen_revision_history)
1011
@deprecated_method(deprecated_in((2, 5, 0)))
1013
def revision_history(self):
1014
"""Return sequence of revision ids on this branch.
1016
This method will cache the revision history for as long as it is safe to
1019
return self._revision_history()
1021
def _revision_history(self):
1022
if 'evil' in debug.debug_flags:
1023
mutter_callsite(3, "revision_history scales with history.")
1024
if self._revision_history_cache is not None:
1025
history = self._revision_history_cache
1027
history = self._gen_revision_history()
1028
self._cache_revision_history(history)
1029
return list(history)
1032
"""Return current revision number for this branch.
1034
That is equivalent to the number of revisions committed to
1037
return self.last_revision_info()[0]
1040
"""Older format branches cannot bind or unbind."""
1041
raise errors.UpgradeRequired(self.user_url)
1043
def last_revision(self):
1044
"""Return last revision id, or NULL_REVISION."""
1045
return self.last_revision_info()[1]
1048
def last_revision_info(self):
1049
"""Return information about the last revision.
1051
:return: A tuple (revno, revision_id).
1053
if self._last_revision_info_cache is None:
1054
self._last_revision_info_cache = self._read_last_revision_info()
1055
return self._last_revision_info_cache
1057
def _read_last_revision_info(self):
1058
raise NotImplementedError(self._read_last_revision_info)
1060
@deprecated_method(deprecated_in((2, 4, 0)))
1061
def import_last_revision_info(self, source_repo, revno, revid):
1062
"""Set the last revision info, importing from another repo if necessary.
1064
:param source_repo: Source repository to optionally fetch from
1065
:param revno: Revision number of the new tip
1066
:param revid: Revision id of the new tip
1068
if not self.repository.has_same_location(source_repo):
1069
self.repository.fetch(source_repo, revision_id=revid)
1070
self.set_last_revision_info(revno, revid)
1072
def import_last_revision_info_and_tags(self, source, revno, revid,
1074
"""Set the last revision info, importing from another repo if necessary.
1076
This is used by the bound branch code to upload a revision to
1077
the master branch first before updating the tip of the local branch.
1078
Revisions referenced by source's tags are also transferred.
1080
:param source: Source branch to optionally fetch from
1081
:param revno: Revision number of the new tip
1082
:param revid: Revision id of the new tip
1083
:param lossy: Whether to discard metadata that can not be
1084
natively represented
1085
:return: Tuple with the new revision number and revision id
1086
(should only be different from the arguments when lossy=True)
1088
if not self.repository.has_same_location(source.repository):
1089
self.fetch(source, revid)
1090
self.set_last_revision_info(revno, revid)
1091
return (revno, revid)
1093
def revision_id_to_revno(self, revision_id):
1094
"""Given a revision id, return its revno"""
1095
if _mod_revision.is_null(revision_id):
1097
history = self._revision_history()
1099
return history.index(revision_id) + 1
1101
raise errors.NoSuchRevision(self, revision_id)
1104
def get_rev_id(self, revno, history=None):
1105
"""Find the revision id of the specified revno."""
1107
return _mod_revision.NULL_REVISION
1108
last_revno, last_revid = self.last_revision_info()
1109
if revno == last_revno:
1111
if revno <= 0 or revno > last_revno:
1112
raise errors.NoSuchRevision(self, revno)
1113
distance_from_last = last_revno - revno
1114
if len(self._partial_revision_history_cache) <= distance_from_last:
1115
self._extend_partial_history(distance_from_last)
1116
return self._partial_revision_history_cache[distance_from_last]
1118
def pull(self, source, overwrite=False, stop_revision=None,
1119
possible_transports=None, *args, **kwargs):
1120
"""Mirror source into this branch.
1122
This branch is considered to be 'local', having low latency.
1124
:returns: PullResult instance
1126
return InterBranch.get(source, self).pull(overwrite=overwrite,
1127
stop_revision=stop_revision,
1128
possible_transports=possible_transports, *args, **kwargs)
1130
def push(self, target, overwrite=False, stop_revision=None, lossy=False,
1132
"""Mirror this branch into target.
1134
This branch is considered to be 'local', having low latency.
1136
return InterBranch.get(self, target).push(overwrite, stop_revision,
1137
lossy, *args, **kwargs)
1139
def basis_tree(self):
1140
"""Return `Tree` object for last revision."""
1141
return self.repository.revision_tree(self.last_revision())
1143
def get_parent(self):
1144
"""Return the parent location of the branch.
1146
This is the default location for pull/missing. The usual
1147
pattern is that the user can override it by specifying a
1150
parent = self._get_parent_location()
1153
# This is an old-format absolute path to a local branch
1154
# turn it into a url
1155
if parent.startswith('/'):
1156
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1158
return urlutils.join(self.base[:-1], parent)
1159
except errors.InvalidURLJoin, e:
1160
raise errors.InaccessibleParent(parent, self.user_url)
1162
def _get_parent_location(self):
1163
raise NotImplementedError(self._get_parent_location)
1165
def _set_config_location(self, name, url, config=None,
1166
make_relative=False):
1168
config = self.get_config()
1172
url = urlutils.relative_url(self.base, url)
1173
config.set_user_option(name, url, warn_masked=True)
1175
def _get_config_location(self, name, config=None):
1177
config = self.get_config()
1178
location = config.get_user_option(name)
1183
def get_child_submit_format(self):
1184
"""Return the preferred format of submissions to this branch."""
1185
return self.get_config().get_user_option("child_submit_format")
1187
def get_submit_branch(self):
1188
"""Return the submit location of the branch.
1190
This is the default location for bundle. The usual
1191
pattern is that the user can override it by specifying a
1194
return self.get_config().get_user_option('submit_branch')
1196
def set_submit_branch(self, location):
1197
"""Return the submit location of the branch.
1199
This is the default location for bundle. The usual
1200
pattern is that the user can override it by specifying a
1203
self.get_config().set_user_option('submit_branch', location,
1206
def get_public_branch(self):
1207
"""Return the public location of the branch.
1209
This is used by merge directives.
1211
return self._get_config_location('public_branch')
1213
def set_public_branch(self, location):
1214
"""Return the submit location of the branch.
1216
This is the default location for bundle. The usual
1217
pattern is that the user can override it by specifying a
1220
self._set_config_location('public_branch', location)
1222
def get_push_location(self):
1223
"""Return the None or the location to push this branch to."""
1224
push_loc = self.get_config().get_user_option('push_location')
1227
def set_push_location(self, location):
1228
"""Set a new push location for this branch."""
1229
raise NotImplementedError(self.set_push_location)
1231
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1232
"""Run the post_change_branch_tip hooks."""
1233
hooks = Branch.hooks['post_change_branch_tip']
1236
new_revno, new_revid = self.last_revision_info()
1237
params = ChangeBranchTipParams(
1238
self, old_revno, new_revno, old_revid, new_revid)
1242
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1243
"""Run the pre_change_branch_tip hooks."""
1244
hooks = Branch.hooks['pre_change_branch_tip']
1247
old_revno, old_revid = self.last_revision_info()
1248
params = ChangeBranchTipParams(
1249
self, old_revno, new_revno, old_revid, new_revid)
1255
"""Synchronise this branch with the master branch if any.
1257
:return: None or the last_revision pivoted out during the update.
1261
def check_revno(self, revno):
1263
Check whether a revno corresponds to any revision.
1264
Zero (the NULL revision) is considered valid.
1267
self.check_real_revno(revno)
1269
def check_real_revno(self, revno):
1271
Check whether a revno corresponds to a real revision.
1272
Zero (the NULL revision) is considered invalid
1274
if revno < 1 or revno > self.revno():
1275
raise errors.InvalidRevisionNumber(revno)
1278
def clone(self, to_bzrdir, revision_id=None, repository_policy=None):
1279
"""Clone this branch into to_bzrdir preserving all semantic values.
1281
Most API users will want 'create_clone_on_transport', which creates a
1282
new bzrdir and branch on the fly.
1284
revision_id: if not None, the revision history in the new branch will
1285
be truncated to end with revision_id.
1287
result = to_bzrdir.create_branch()
1290
if repository_policy is not None:
1291
repository_policy.configure_branch(result)
1292
self.copy_content_into(result, revision_id=revision_id)
1298
def sprout(self, to_bzrdir, revision_id=None, repository_policy=None,
1300
"""Create a new line of development from the branch, into to_bzrdir.
1302
to_bzrdir controls the branch format.
1304
revision_id: if not None, the revision history in the new branch will
1305
be truncated to end with revision_id.
1307
if (repository_policy is not None and
1308
repository_policy.requires_stacking()):
1309
to_bzrdir._format.require_stacking(_skip_repo=True)
1310
result = to_bzrdir.create_branch(repository=repository)
1313
if repository_policy is not None:
1314
repository_policy.configure_branch(result)
1315
self.copy_content_into(result, revision_id=revision_id)
1316
master_url = self.get_bound_location()
1317
if master_url is None:
1318
result.set_parent(self.bzrdir.root_transport.base)
1320
result.set_parent(master_url)
1325
def _synchronize_history(self, destination, revision_id):
1326
"""Synchronize last revision and revision history between branches.
1328
This version is most efficient when the destination is also a
1329
BzrBranch6, but works for BzrBranch5, as long as the destination's
1330
repository contains all the lefthand ancestors of the intended
1331
last_revision. If not, set_last_revision_info will fail.
1333
:param destination: The branch to copy the history into
1334
:param revision_id: The revision-id to truncate history at. May
1335
be None to copy complete history.
1337
source_revno, source_revision_id = self.last_revision_info()
1338
if revision_id is None:
1339
revno, revision_id = source_revno, source_revision_id
1341
graph = self.repository.get_graph()
1343
revno = graph.find_distance_to_null(revision_id,
1344
[(source_revision_id, source_revno)])
1345
except errors.GhostRevisionsHaveNoRevno:
1346
# Default to 1, if we can't find anything else
1348
destination.set_last_revision_info(revno, revision_id)
1350
def copy_content_into(self, destination, revision_id=None):
1351
"""Copy the content of self into destination.
1353
revision_id: if not None, the revision history in the new branch will
1354
be truncated to end with revision_id.
1356
return InterBranch.get(self, destination).copy_content_into(
1357
revision_id=revision_id)
1359
def update_references(self, target):
1360
if not getattr(self._format, 'supports_reference_locations', False):
1362
reference_dict = self._get_all_reference_info()
1363
if len(reference_dict) == 0:
1365
old_base = self.base
1366
new_base = target.base
1367
target_reference_dict = target._get_all_reference_info()
1368
for file_id, (tree_path, branch_location) in (
1369
reference_dict.items()):
1370
branch_location = urlutils.rebase_url(branch_location,
1372
target_reference_dict.setdefault(
1373
file_id, (tree_path, branch_location))
1374
target._set_all_reference_info(target_reference_dict)
1377
def check(self, refs):
1378
"""Check consistency of the branch.
1380
In particular this checks that revisions given in the revision-history
1381
do actually match up in the revision graph, and that they're all
1382
present in the repository.
1384
Callers will typically also want to check the repository.
1386
:param refs: Calculated refs for this branch as specified by
1387
branch._get_check_refs()
1388
:return: A BranchCheckResult.
1390
result = BranchCheckResult(self)
1391
last_revno, last_revision_id = self.last_revision_info()
1392
actual_revno = refs[('lefthand-distance', last_revision_id)]
1393
if actual_revno != last_revno:
1394
result.errors.append(errors.BzrCheckError(
1395
'revno does not match len(mainline) %s != %s' % (
1396
last_revno, actual_revno)))
1397
# TODO: We should probably also check that self.revision_history
1398
# matches the repository for older branch formats.
1399
# If looking for the code that cross-checks repository parents against
1400
# the Graph.iter_lefthand_ancestry output, that is now a repository
1404
def _get_checkout_format(self, lightweight=False):
1405
"""Return the most suitable metadir for a checkout of this branch.
1406
Weaves are used if this branch's repository uses weaves.
1408
format = self.repository.bzrdir.checkout_metadir()
1409
format.set_branch_format(self._format)
1412
def create_clone_on_transport(self, to_transport, revision_id=None,
1413
stacked_on=None, create_prefix=False, use_existing_dir=False,
1415
"""Create a clone of this branch and its bzrdir.
1417
:param to_transport: The transport to clone onto.
1418
:param revision_id: The revision id to use as tip in the new branch.
1419
If None the tip is obtained from this branch.
1420
:param stacked_on: An optional URL to stack the clone on.
1421
:param create_prefix: Create any missing directories leading up to
1423
:param use_existing_dir: Use an existing directory if one exists.
1425
# XXX: Fix the bzrdir API to allow getting the branch back from the
1426
# clone call. Or something. 20090224 RBC/spiv.
1427
# XXX: Should this perhaps clone colocated branches as well,
1428
# rather than just the default branch? 20100319 JRV
1429
if revision_id is None:
1430
revision_id = self.last_revision()
1431
dir_to = self.bzrdir.clone_on_transport(to_transport,
1432
revision_id=revision_id, stacked_on=stacked_on,
1433
create_prefix=create_prefix, use_existing_dir=use_existing_dir,
1435
return dir_to.open_branch()
1437
def create_checkout(self, to_location, revision_id=None,
1438
lightweight=False, accelerator_tree=None,
1440
"""Create a checkout of a branch.
1442
:param to_location: The url to produce the checkout at
1443
:param revision_id: The revision to check out
1444
:param lightweight: If True, produce a lightweight checkout, otherwise,
1445
produce a bound branch (heavyweight checkout)
1446
:param accelerator_tree: A tree which can be used for retrieving file
1447
contents more quickly than the revision tree, i.e. a workingtree.
1448
The revision tree will be used for cases where accelerator_tree's
1449
content is different.
1450
:param hardlink: If true, hard-link files from accelerator_tree,
1452
:return: The tree of the created checkout
1454
t = transport.get_transport(to_location)
1456
format = self._get_checkout_format(lightweight=lightweight)
1458
checkout = format.initialize_on_transport(t)
1459
from_branch = BranchReferenceFormat().initialize(checkout,
1462
checkout_branch = controldir.ControlDir.create_branch_convenience(
1463
to_location, force_new_tree=False, format=format)
1464
checkout = checkout_branch.bzrdir
1465
checkout_branch.bind(self)
1466
# pull up to the specified revision_id to set the initial
1467
# branch tip correctly, and seed it with history.
1468
checkout_branch.pull(self, stop_revision=revision_id)
1470
tree = checkout.create_workingtree(revision_id,
1471
from_branch=from_branch,
1472
accelerator_tree=accelerator_tree,
1474
basis_tree = tree.basis_tree()
1475
basis_tree.lock_read()
1477
for path, file_id in basis_tree.iter_references():
1478
reference_parent = self.reference_parent(file_id, path)
1479
reference_parent.create_checkout(tree.abspath(path),
1480
basis_tree.get_reference_revision(file_id, path),
1487
def reconcile(self, thorough=True):
1488
"""Make sure the data stored in this branch is consistent."""
1489
from bzrlib.reconcile import BranchReconciler
1490
reconciler = BranchReconciler(self, thorough=thorough)
1491
reconciler.reconcile()
1494
def reference_parent(self, file_id, path, possible_transports=None):
1495
"""Return the parent branch for a tree-reference file_id
1497
:param file_id: The file_id of the tree reference
1498
:param path: The path of the file_id in the tree
1499
:return: A branch associated with the file_id
1501
# FIXME should provide multiple branches, based on config
1502
return Branch.open(self.bzrdir.root_transport.clone(path).base,
1503
possible_transports=possible_transports)
1505
def supports_tags(self):
1506
return self._format.supports_tags()
1508
def automatic_tag_name(self, revision_id):
1509
"""Try to automatically find the tag name for a revision.
1511
:param revision_id: Revision id of the revision.
1512
:return: A tag name or None if no tag name could be determined.
1514
for hook in Branch.hooks['automatic_tag_name']:
1515
ret = hook(self, revision_id)
1520
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1522
"""Ensure that revision_b is a descendant of revision_a.
1524
This is a helper function for update_revisions.
1526
:raises: DivergedBranches if revision_b has diverged from revision_a.
1527
:returns: True if revision_b is a descendant of revision_a.
1529
relation = self._revision_relations(revision_a, revision_b, graph)
1530
if relation == 'b_descends_from_a':
1532
elif relation == 'diverged':
1533
raise errors.DivergedBranches(self, other_branch)
1534
elif relation == 'a_descends_from_b':
1537
raise AssertionError("invalid relation: %r" % (relation,))
1539
def _revision_relations(self, revision_a, revision_b, graph):
1540
"""Determine the relationship between two revisions.
1542
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1544
heads = graph.heads([revision_a, revision_b])
1545
if heads == set([revision_b]):
1546
return 'b_descends_from_a'
1547
elif heads == set([revision_a, revision_b]):
1548
# These branches have diverged
1550
elif heads == set([revision_a]):
1551
return 'a_descends_from_b'
1553
raise AssertionError("invalid heads: %r" % (heads,))
1555
def heads_to_fetch(self):
1556
"""Return the heads that must and that should be fetched to copy this
1557
branch into another repo.
1559
:returns: a 2-tuple of (must_fetch, if_present_fetch). must_fetch is a
1560
set of heads that must be fetched. if_present_fetch is a set of
1561
heads that must be fetched if present, but no error is necessary if
1562
they are not present.
1564
# For bzr native formats must_fetch is just the tip, and if_present_fetch
1566
must_fetch = set([self.last_revision()])
1567
if_present_fetch = set()
1568
c = self.get_config()
1569
include_tags = c.get_user_option_as_bool('branch.fetch_tags',
1573
if_present_fetch = set(self.tags.get_reverse_tag_dict())
1574
except errors.TagsNotSupported:
1576
must_fetch.discard(_mod_revision.NULL_REVISION)
1577
if_present_fetch.discard(_mod_revision.NULL_REVISION)
1578
return must_fetch, if_present_fetch
1581
class BranchFormat(controldir.ControlComponentFormat):
1582
"""An encapsulation of the initialization and open routines for a format.
1584
Formats provide three things:
1585
* An initialization routine,
1589
Formats are placed in an dict by their format string for reference
1590
during branch opening. It's not required that these be instances, they
1591
can be classes themselves with class methods - it simply depends on
1592
whether state is needed for a given format or not.
1594
Once a format is deprecated, just deprecate the initialize and open
1595
methods on the format class. Do not deprecate the object, as the
1596
object will be created every time regardless.
1599
def __eq__(self, other):
1600
return self.__class__ is other.__class__
1602
def __ne__(self, other):
1603
return not (self == other)
1606
@deprecated_method(deprecated_in((2, 4, 0)))
1607
def get_default_format(klass):
1608
"""Return the current default format."""
1609
return format_registry.get_default()
1612
@deprecated_method(deprecated_in((2, 4, 0)))
1613
def get_formats(klass):
1614
"""Get all the known formats.
1616
Warning: This triggers a load of all lazy registered formats: do not
1617
use except when that is desireed.
1619
return format_registry._get_all()
1621
def get_reference(self, controldir, name=None):
1622
"""Get the target reference of the branch in controldir.
1624
format probing must have been completed before calling
1625
this method - it is assumed that the format of the branch
1626
in controldir is correct.
1628
:param controldir: The controldir to get the branch data from.
1629
:param name: Name of the colocated branch to fetch
1630
:return: None if the branch is not a reference branch.
1635
def set_reference(self, controldir, name, to_branch):
1636
"""Set the target reference of the branch in controldir.
1638
format probing must have been completed before calling
1639
this method - it is assumed that the format of the branch
1640
in controldir is correct.
1642
:param controldir: The controldir to set the branch reference for.
1643
:param name: Name of colocated branch to set, None for default
1644
:param to_branch: branch that the checkout is to reference
1646
raise NotImplementedError(self.set_reference)
1648
def get_format_description(self):
1649
"""Return the short format description for this format."""
1650
raise NotImplementedError(self.get_format_description)
1652
def _run_post_branch_init_hooks(self, controldir, name, branch):
1653
hooks = Branch.hooks['post_branch_init']
1656
params = BranchInitHookParams(self, controldir, name, branch)
1660
def initialize(self, controldir, name=None, repository=None,
1661
append_revisions_only=None):
1662
"""Create a branch of this format in controldir.
1664
:param name: Name of the colocated branch to create.
1666
raise NotImplementedError(self.initialize)
1668
def is_supported(self):
1669
"""Is this format supported?
1671
Supported formats can be initialized and opened.
1672
Unsupported formats may not support initialization or committing or
1673
some other features depending on the reason for not being supported.
1677
def make_tags(self, branch):
1678
"""Create a tags object for branch.
1680
This method is on BranchFormat, because BranchFormats are reflected
1681
over the wire via network_name(), whereas full Branch instances require
1682
multiple VFS method calls to operate at all.
1684
The default implementation returns a disabled-tags instance.
1686
Note that it is normal for branch to be a RemoteBranch when using tags
1689
return _mod_tag.DisabledTags(branch)
1691
def network_name(self):
1692
"""A simple byte string uniquely identifying this format for RPC calls.
1694
MetaDir branch formats use their disk format string to identify the
1695
repository over the wire. All in one formats such as bzr < 0.8, and
1696
foreign formats like svn/git and hg should use some marker which is
1697
unique and immutable.
1699
raise NotImplementedError(self.network_name)
1701
def open(self, controldir, name=None, _found=False, ignore_fallbacks=False,
1702
found_repository=None, possible_transports=None):
1703
"""Return the branch object for controldir.
1705
:param controldir: A ControlDir that contains a branch.
1706
:param name: Name of colocated branch to open
1707
:param _found: a private parameter, do not use it. It is used to
1708
indicate if format probing has already be done.
1709
:param ignore_fallbacks: when set, no fallback branches will be opened
1710
(if there are any). Default is to open fallbacks.
1712
raise NotImplementedError(self.open)
1715
@deprecated_method(deprecated_in((2, 4, 0)))
1716
def register_format(klass, format):
1717
"""Register a metadir format.
1719
See MetaDirBranchFormatFactory for the ability to register a format
1720
without loading the code the format needs until it is actually used.
1722
format_registry.register(format)
1725
@deprecated_method(deprecated_in((2, 4, 0)))
1726
def set_default_format(klass, format):
1727
format_registry.set_default(format)
1729
def supports_set_append_revisions_only(self):
1730
"""True if this format supports set_append_revisions_only."""
1733
def supports_stacking(self):
1734
"""True if this format records a stacked-on branch."""
1737
def supports_leaving_lock(self):
1738
"""True if this format supports leaving locks in place."""
1739
return False # by default
1742
@deprecated_method(deprecated_in((2, 4, 0)))
1743
def unregister_format(klass, format):
1744
format_registry.remove(format)
1747
return self.get_format_description().rstrip()
1749
def supports_tags(self):
1750
"""True if this format supports tags stored in the branch"""
1751
return False # by default
1753
def tags_are_versioned(self):
1754
"""Whether the tag container for this branch versions tags."""
1757
def supports_tags_referencing_ghosts(self):
1758
"""True if tags can reference ghost revisions."""
1762
class MetaDirBranchFormatFactory(registry._LazyObjectGetter):
1763
"""A factory for a BranchFormat object, permitting simple lazy registration.
1765
While none of the built in BranchFormats are lazy registered yet,
1766
bzrlib.tests.test_branch.TestMetaDirBranchFormatFactory demonstrates how to
1767
use it, and the bzr-loom plugin uses it as well (see
1768
bzrlib.plugins.loom.formats).
1771
def __init__(self, format_string, module_name, member_name):
1772
"""Create a MetaDirBranchFormatFactory.
1774
:param format_string: The format string the format has.
1775
:param module_name: Module to load the format class from.
1776
:param member_name: Attribute name within the module for the format class.
1778
registry._LazyObjectGetter.__init__(self, module_name, member_name)
1779
self._format_string = format_string
1781
def get_format_string(self):
1782
"""See BranchFormat.get_format_string."""
1783
return self._format_string
1786
"""Used for network_format_registry support."""
1787
return self.get_obj()()
1790
class BranchHooks(Hooks):
1791
"""A dictionary mapping hook name to a list of callables for branch hooks.
1793
e.g. ['set_rh'] Is the list of items to be called when the
1794
set_revision_history function is invoked.
1798
"""Create the default hooks.
1800
These are all empty initially, because by default nothing should get
1803
Hooks.__init__(self, "bzrlib.branch", "Branch.hooks")
1804
self.add_hook('set_rh',
1805
"Invoked whenever the revision history has been set via "
1806
"set_revision_history. The api signature is (branch, "
1807
"revision_history), and the branch will be write-locked. "
1808
"The set_rh hook can be expensive for bzr to trigger, a better "
1809
"hook to use is Branch.post_change_branch_tip.", (0, 15))
1810
self.add_hook('open',
1811
"Called with the Branch object that has been opened after a "
1812
"branch is opened.", (1, 8))
1813
self.add_hook('post_push',
1814
"Called after a push operation completes. post_push is called "
1815
"with a bzrlib.branch.BranchPushResult object and only runs in the "
1816
"bzr client.", (0, 15))
1817
self.add_hook('post_pull',
1818
"Called after a pull operation completes. post_pull is called "
1819
"with a bzrlib.branch.PullResult object and only runs in the "
1820
"bzr client.", (0, 15))
1821
self.add_hook('pre_commit',
1822
"Called after a commit is calculated but before it is "
1823
"completed. pre_commit is called with (local, master, old_revno, "
1824
"old_revid, future_revno, future_revid, tree_delta, future_tree"
1825
"). old_revid is NULL_REVISION for the first commit to a branch, "
1826
"tree_delta is a TreeDelta object describing changes from the "
1827
"basis revision. hooks MUST NOT modify this delta. "
1828
" future_tree is an in-memory tree obtained from "
1829
"CommitBuilder.revision_tree() and hooks MUST NOT modify this "
1831
self.add_hook('post_commit',
1832
"Called in the bzr client after a commit has completed. "
1833
"post_commit is called with (local, master, old_revno, old_revid, "
1834
"new_revno, new_revid). old_revid is NULL_REVISION for the first "
1835
"commit to a branch.", (0, 15))
1836
self.add_hook('post_uncommit',
1837
"Called in the bzr client after an uncommit completes. "
1838
"post_uncommit is called with (local, master, old_revno, "
1839
"old_revid, new_revno, new_revid) where local is the local branch "
1840
"or None, master is the target branch, and an empty branch "
1841
"receives new_revno of 0, new_revid of None.", (0, 15))
1842
self.add_hook('pre_change_branch_tip',
1843
"Called in bzr client and server before a change to the tip of a "
1844
"branch is made. pre_change_branch_tip is called with a "
1845
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1846
"commit, uncommit will all trigger this hook.", (1, 6))
1847
self.add_hook('post_change_branch_tip',
1848
"Called in bzr client and server after a change to the tip of a "
1849
"branch is made. post_change_branch_tip is called with a "
1850
"bzrlib.branch.ChangeBranchTipParams. Note that push, pull, "
1851
"commit, uncommit will all trigger this hook.", (1, 4))
1852
self.add_hook('transform_fallback_location',
1853
"Called when a stacked branch is activating its fallback "
1854
"locations. transform_fallback_location is called with (branch, "
1855
"url), and should return a new url. Returning the same url "
1856
"allows it to be used as-is, returning a different one can be "
1857
"used to cause the branch to stack on a closer copy of that "
1858
"fallback_location. Note that the branch cannot have history "
1859
"accessing methods called on it during this hook because the "
1860
"fallback locations have not been activated. When there are "
1861
"multiple hooks installed for transform_fallback_location, "
1862
"all are called with the url returned from the previous hook."
1863
"The order is however undefined.", (1, 9))
1864
self.add_hook('automatic_tag_name',
1865
"Called to determine an automatic tag name for a revision. "
1866
"automatic_tag_name is called with (branch, revision_id) and "
1867
"should return a tag name or None if no tag name could be "
1868
"determined. The first non-None tag name returned will be used.",
1870
self.add_hook('post_branch_init',
1871
"Called after new branch initialization completes. "
1872
"post_branch_init is called with a "
1873
"bzrlib.branch.BranchInitHookParams. "
1874
"Note that init, branch and checkout (both heavyweight and "
1875
"lightweight) will all trigger this hook.", (2, 2))
1876
self.add_hook('post_switch',
1877
"Called after a checkout switches branch. "
1878
"post_switch is called with a "
1879
"bzrlib.branch.SwitchHookParams.", (2, 2))
1883
# install the default hooks into the Branch class.
1884
Branch.hooks = BranchHooks()
1887
class ChangeBranchTipParams(object):
1888
"""Object holding parameters passed to `*_change_branch_tip` hooks.
1890
There are 5 fields that hooks may wish to access:
1892
:ivar branch: the branch being changed
1893
:ivar old_revno: revision number before the change
1894
:ivar new_revno: revision number after the change
1895
:ivar old_revid: revision id before the change
1896
:ivar new_revid: revision id after the change
1898
The revid fields are strings. The revno fields are integers.
1901
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1902
"""Create a group of ChangeBranchTip parameters.
1904
:param branch: The branch being changed.
1905
:param old_revno: Revision number before the change.
1906
:param new_revno: Revision number after the change.
1907
:param old_revid: Tip revision id before the change.
1908
:param new_revid: Tip revision id after the change.
1910
self.branch = branch
1911
self.old_revno = old_revno
1912
self.new_revno = new_revno
1913
self.old_revid = old_revid
1914
self.new_revid = new_revid
1916
def __eq__(self, other):
1917
return self.__dict__ == other.__dict__
1920
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1921
self.__class__.__name__, self.branch,
1922
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1925
class BranchInitHookParams(object):
1926
"""Object holding parameters passed to `*_branch_init` hooks.
1928
There are 4 fields that hooks may wish to access:
1930
:ivar format: the branch format
1931
:ivar bzrdir: the ControlDir where the branch will be/has been initialized
1932
:ivar name: name of colocated branch, if any (or None)
1933
:ivar branch: the branch created
1935
Note that for lightweight checkouts, the bzrdir and format fields refer to
1936
the checkout, hence they are different from the corresponding fields in
1937
branch, which refer to the original branch.
1940
def __init__(self, format, controldir, name, branch):
1941
"""Create a group of BranchInitHook parameters.
1943
:param format: the branch format
1944
:param controldir: the ControlDir where the branch will be/has been
1946
:param name: name of colocated branch, if any (or None)
1947
:param branch: the branch created
1949
Note that for lightweight checkouts, the bzrdir and format fields refer
1950
to the checkout, hence they are different from the corresponding fields
1951
in branch, which refer to the original branch.
1953
self.format = format
1954
self.bzrdir = controldir
1956
self.branch = branch
1958
def __eq__(self, other):
1959
return self.__dict__ == other.__dict__
1962
return "<%s of %s>" % (self.__class__.__name__, self.branch)
1965
class SwitchHookParams(object):
1966
"""Object holding parameters passed to `*_switch` hooks.
1968
There are 4 fields that hooks may wish to access:
1970
:ivar control_dir: ControlDir of the checkout to change
1971
:ivar to_branch: branch that the checkout is to reference
1972
:ivar force: skip the check for local commits in a heavy checkout
1973
:ivar revision_id: revision ID to switch to (or None)
1976
def __init__(self, control_dir, to_branch, force, revision_id):
1977
"""Create a group of SwitchHook parameters.
1979
:param control_dir: ControlDir of the checkout to change
1980
:param to_branch: branch that the checkout is to reference
1981
:param force: skip the check for local commits in a heavy checkout
1982
:param revision_id: revision ID to switch to (or None)
1984
self.control_dir = control_dir
1985
self.to_branch = to_branch
1987
self.revision_id = revision_id
1989
def __eq__(self, other):
1990
return self.__dict__ == other.__dict__
1993
return "<%s for %s to (%s, %s)>" % (self.__class__.__name__,
1994
self.control_dir, self.to_branch,
1998
class BranchFormatMetadir(bzrdir.BzrDirMetaComponentFormat, BranchFormat):
1999
"""Base class for branch formats that live in meta directories.
2003
BranchFormat.__init__(self)
2004
bzrdir.BzrDirMetaComponentFormat.__init__(self)
2007
def find_format(klass, controldir, name=None):
2008
"""Return the format for the branch object in controldir."""
2010
transport = controldir.get_branch_transport(None, name=name)
2011
except errors.NoSuchFile:
2012
raise errors.NotBranchError(path=name, bzrdir=controldir)
2014
format_string = transport.get_bytes("format")
2015
except errors.NoSuchFile:
2016
raise errors.NotBranchError(path=transport.base, bzrdir=controldir)
2017
return klass._find_format(format_registry, 'branch', format_string)
2019
def _branch_class(self):
2020
"""What class to instantiate on open calls."""
2021
raise NotImplementedError(self._branch_class)
2023
def _get_initial_config(self, append_revisions_only=None):
2024
if append_revisions_only:
2025
return "append_revisions_only = True\n"
2027
# Avoid writing anything if append_revisions_only is disabled,
2028
# as that is the default.
2031
def _initialize_helper(self, a_bzrdir, utf8_files, name=None,
2033
"""Initialize a branch in a bzrdir, with specified files
2035
:param a_bzrdir: The bzrdir to initialize the branch in
2036
:param utf8_files: The files to create as a list of
2037
(filename, content) tuples
2038
:param name: Name of colocated branch to create, if any
2039
:return: a branch in this format
2041
mutter('creating branch %r in %s', self, a_bzrdir.user_url)
2042
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2043
control_files = lockable_files.LockableFiles(branch_transport,
2044
'lock', lockdir.LockDir)
2045
control_files.create_lock()
2046
control_files.lock_write()
2048
utf8_files += [('format', self.get_format_string())]
2049
for (filename, content) in utf8_files:
2050
branch_transport.put_bytes(
2052
mode=a_bzrdir._get_file_mode())
2054
control_files.unlock()
2055
branch = self.open(a_bzrdir, name, _found=True,
2056
found_repository=repository)
2057
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2060
def open(self, a_bzrdir, name=None, _found=False, ignore_fallbacks=False,
2061
found_repository=None, possible_transports=None):
2062
"""See BranchFormat.open()."""
2064
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2065
if format.__class__ != self.__class__:
2066
raise AssertionError("wrong format %r found for %r" %
2068
transport = a_bzrdir.get_branch_transport(None, name=name)
2070
control_files = lockable_files.LockableFiles(transport, 'lock',
2072
if found_repository is None:
2073
found_repository = a_bzrdir.find_repository()
2074
return self._branch_class()(_format=self,
2075
_control_files=control_files,
2078
_repository=found_repository,
2079
ignore_fallbacks=ignore_fallbacks,
2080
possible_transports=possible_transports)
2081
except errors.NoSuchFile:
2082
raise errors.NotBranchError(path=transport.base, bzrdir=a_bzrdir)
2085
def _matchingbzrdir(self):
2086
ret = bzrdir.BzrDirMetaFormat1()
2087
ret.set_branch_format(self)
2090
def supports_tags(self):
2093
def supports_leaving_lock(self):
2097
class BzrBranchFormat5(BranchFormatMetadir):
2098
"""Bzr branch format 5.
2101
- a revision-history file.
2103
- a lock dir guarding the branch itself
2104
- all of this stored in a branch/ subdirectory
2105
- works with shared repositories.
2107
This format is new in bzr 0.8.
2110
def _branch_class(self):
2114
def get_format_string(cls):
2115
"""See BranchFormat.get_format_string()."""
2116
return "Bazaar-NG branch format 5\n"
2118
def get_format_description(self):
2119
"""See BranchFormat.get_format_description()."""
2120
return "Branch format 5"
2122
def initialize(self, a_bzrdir, name=None, repository=None,
2123
append_revisions_only=None):
2124
"""Create a branch of this format in a_bzrdir."""
2125
if append_revisions_only:
2126
raise errors.UpgradeRequired(a_bzrdir.user_url)
2127
utf8_files = [('revision-history', ''),
2128
('branch-name', ''),
2130
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2132
def supports_tags(self):
2136
class BzrBranchFormat6(BranchFormatMetadir):
2137
"""Branch format with last-revision and tags.
2139
Unlike previous formats, this has no explicit revision history. Instead,
2140
this just stores the last-revision, and the left-hand history leading
2141
up to there is the history.
2143
This format was introduced in bzr 0.15
2144
and became the default in 0.91.
2147
def _branch_class(self):
2151
def get_format_string(cls):
2152
"""See BranchFormat.get_format_string()."""
2153
return "Bazaar Branch Format 6 (bzr 0.15)\n"
2155
def get_format_description(self):
2156
"""See BranchFormat.get_format_description()."""
2157
return "Branch format 6"
2159
def initialize(self, a_bzrdir, name=None, repository=None,
2160
append_revisions_only=None):
2161
"""Create a branch of this format in a_bzrdir."""
2162
utf8_files = [('last-revision', '0 null:\n'),
2164
self._get_initial_config(append_revisions_only)),
2167
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2169
def make_tags(self, branch):
2170
"""See bzrlib.branch.BranchFormat.make_tags()."""
2171
return _mod_tag.BasicTags(branch)
2173
def supports_set_append_revisions_only(self):
2177
class BzrBranchFormat8(BranchFormatMetadir):
2178
"""Metadir format supporting storing locations of subtree branches."""
2180
def _branch_class(self):
2184
def get_format_string(cls):
2185
"""See BranchFormat.get_format_string()."""
2186
return "Bazaar Branch Format 8 (needs bzr 1.15)\n"
2188
def get_format_description(self):
2189
"""See BranchFormat.get_format_description()."""
2190
return "Branch format 8"
2192
def initialize(self, a_bzrdir, name=None, repository=None,
2193
append_revisions_only=None):
2194
"""Create a branch of this format in a_bzrdir."""
2195
utf8_files = [('last-revision', '0 null:\n'),
2197
self._get_initial_config(append_revisions_only)),
2201
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2203
def make_tags(self, branch):
2204
"""See bzrlib.branch.BranchFormat.make_tags()."""
2205
return _mod_tag.BasicTags(branch)
2207
def supports_set_append_revisions_only(self):
2210
def supports_stacking(self):
2213
supports_reference_locations = True
2216
class BzrBranchFormat7(BranchFormatMetadir):
2217
"""Branch format with last-revision, tags, and a stacked location pointer.
2219
The stacked location pointer is passed down to the repository and requires
2220
a repository format with supports_external_lookups = True.
2222
This format was introduced in bzr 1.6.
2225
def initialize(self, a_bzrdir, name=None, repository=None,
2226
append_revisions_only=None):
2227
"""Create a branch of this format in a_bzrdir."""
2228
utf8_files = [('last-revision', '0 null:\n'),
2230
self._get_initial_config(append_revisions_only)),
2233
return self._initialize_helper(a_bzrdir, utf8_files, name, repository)
2235
def _branch_class(self):
2239
def get_format_string(cls):
2240
"""See BranchFormat.get_format_string()."""
2241
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
2243
def get_format_description(self):
2244
"""See BranchFormat.get_format_description()."""
2245
return "Branch format 7"
2247
def supports_set_append_revisions_only(self):
2250
def supports_stacking(self):
2253
def make_tags(self, branch):
2254
"""See bzrlib.branch.BranchFormat.make_tags()."""
2255
return _mod_tag.BasicTags(branch)
2257
supports_reference_locations = False
2260
class BranchReferenceFormat(BranchFormatMetadir):
2261
"""Bzr branch reference format.
2263
Branch references are used in implementing checkouts, they
2264
act as an alias to the real branch which is at some other url.
2272
def get_format_string(cls):
2273
"""See BranchFormat.get_format_string()."""
2274
return "Bazaar-NG Branch Reference Format 1\n"
2276
def get_format_description(self):
2277
"""See BranchFormat.get_format_description()."""
2278
return "Checkout reference format 1"
2280
def get_reference(self, a_bzrdir, name=None):
2281
"""See BranchFormat.get_reference()."""
2282
transport = a_bzrdir.get_branch_transport(None, name=name)
2283
return transport.get_bytes('location')
2285
def set_reference(self, a_bzrdir, name, to_branch):
2286
"""See BranchFormat.set_reference()."""
2287
transport = a_bzrdir.get_branch_transport(None, name=name)
2288
location = transport.put_bytes('location', to_branch.base)
2290
def initialize(self, a_bzrdir, name=None, target_branch=None,
2291
repository=None, append_revisions_only=None):
2292
"""Create a branch of this format in a_bzrdir."""
2293
if target_branch is None:
2294
# this format does not implement branch itself, thus the implicit
2295
# creation contract must see it as uninitializable
2296
raise errors.UninitializableFormat(self)
2297
mutter('creating branch reference in %s', a_bzrdir.user_url)
2298
if a_bzrdir._format.fixed_components:
2299
raise errors.IncompatibleFormat(self, a_bzrdir._format)
2300
branch_transport = a_bzrdir.get_branch_transport(self, name=name)
2301
branch_transport.put_bytes('location',
2302
target_branch.user_url)
2303
branch_transport.put_bytes('format', self.get_format_string())
2305
a_bzrdir, name, _found=True,
2306
possible_transports=[target_branch.bzrdir.root_transport])
2307
self._run_post_branch_init_hooks(a_bzrdir, name, branch)
2310
def _make_reference_clone_function(format, a_branch):
2311
"""Create a clone() routine for a branch dynamically."""
2312
def clone(to_bzrdir, revision_id=None,
2313
repository_policy=None):
2314
"""See Branch.clone()."""
2315
return format.initialize(to_bzrdir, target_branch=a_branch)
2316
# cannot obey revision_id limits when cloning a reference ...
2317
# FIXME RBC 20060210 either nuke revision_id for clone, or
2318
# emit some sort of warning/error to the caller ?!
2321
def open(self, a_bzrdir, name=None, _found=False, location=None,
2322
possible_transports=None, ignore_fallbacks=False,
2323
found_repository=None):
2324
"""Return the branch that the branch reference in a_bzrdir points at.
2326
:param a_bzrdir: A BzrDir that contains a branch.
2327
:param name: Name of colocated branch to open, if any
2328
:param _found: a private parameter, do not use it. It is used to
2329
indicate if format probing has already be done.
2330
:param ignore_fallbacks: when set, no fallback branches will be opened
2331
(if there are any). Default is to open fallbacks.
2332
:param location: The location of the referenced branch. If
2333
unspecified, this will be determined from the branch reference in
2335
:param possible_transports: An optional reusable transports list.
2338
format = BranchFormatMetadir.find_format(a_bzrdir, name=name)
2339
if format.__class__ != self.__class__:
2340
raise AssertionError("wrong format %r found for %r" %
2342
if location is None:
2343
location = self.get_reference(a_bzrdir, name)
2344
real_bzrdir = controldir.ControlDir.open(
2345
location, possible_transports=possible_transports)
2346
result = real_bzrdir.open_branch(name=name,
2347
ignore_fallbacks=ignore_fallbacks,
2348
possible_transports=possible_transports)
2349
# this changes the behaviour of result.clone to create a new reference
2350
# rather than a copy of the content of the branch.
2351
# I did not use a proxy object because that needs much more extensive
2352
# testing, and we are only changing one behaviour at the moment.
2353
# If we decide to alter more behaviours - i.e. the implicit nickname
2354
# then this should be refactored to introduce a tested proxy branch
2355
# and a subclass of that for use in overriding clone() and ....
2357
result.clone = self._make_reference_clone_function(result)
2361
class BranchFormatRegistry(controldir.ControlComponentFormatRegistry):
2362
"""Branch format registry."""
2364
def __init__(self, other_registry=None):
2365
super(BranchFormatRegistry, self).__init__(other_registry)
2366
self._default_format = None
2368
def set_default(self, format):
2369
self._default_format = format
2371
def get_default(self):
2372
return self._default_format
2375
network_format_registry = registry.FormatRegistry()
2376
"""Registry of formats indexed by their network name.
2378
The network name for a branch format is an identifier that can be used when
2379
referring to formats with smart server operations. See
2380
BranchFormat.network_name() for more detail.
2383
format_registry = BranchFormatRegistry(network_format_registry)
2386
# formats which have no format string are not discoverable
2387
# and not independently creatable, so are not registered.
2388
__format5 = BzrBranchFormat5()
2389
__format6 = BzrBranchFormat6()
2390
__format7 = BzrBranchFormat7()
2391
__format8 = BzrBranchFormat8()
2392
format_registry.register(__format5)
2393
format_registry.register(BranchReferenceFormat())
2394
format_registry.register(__format6)
2395
format_registry.register(__format7)
2396
format_registry.register(__format8)
2397
format_registry.set_default(__format7)
2400
class BranchWriteLockResult(LogicalLockResult):
2401
"""The result of write locking a branch.
2403
:ivar branch_token: The token obtained from the underlying branch lock, or
2405
:ivar unlock: A callable which will unlock the lock.
2408
def __init__(self, unlock, branch_token):
2409
LogicalLockResult.__init__(self, unlock)
2410
self.branch_token = branch_token
2413
return "BranchWriteLockResult(%s, %s)" % (self.branch_token,
2417
class BzrBranch(Branch, _RelockDebugMixin):
2418
"""A branch stored in the actual filesystem.
2420
Note that it's "local" in the context of the filesystem; it doesn't
2421
really matter if it's on an nfs/smb/afs/coda/... share, as long as
2422
it's writable, and can be accessed via the normal filesystem API.
2424
:ivar _transport: Transport for file operations on this branch's
2425
control files, typically pointing to the .bzr/branch directory.
2426
:ivar repository: Repository for this branch.
2427
:ivar base: The url of the base directory for this branch; the one
2428
containing the .bzr directory.
2429
:ivar name: Optional colocated branch name as it exists in the control
2433
def __init__(self, _format=None,
2434
_control_files=None, a_bzrdir=None, name=None,
2435
_repository=None, ignore_fallbacks=False,
2436
possible_transports=None):
2437
"""Create new branch object at a particular location."""
2438
if a_bzrdir is None:
2439
raise ValueError('a_bzrdir must be supplied')
2441
self.bzrdir = a_bzrdir
2442
self._user_transport = self.bzrdir.transport.clone('..')
2443
if name is not None:
2444
self._user_transport.set_segment_parameter(
2445
"branch", urlutils.escape(name))
2446
self._base = self._user_transport.base
2448
self._format = _format
2449
if _control_files is None:
2450
raise ValueError('BzrBranch _control_files is None')
2451
self.control_files = _control_files
2452
self._transport = _control_files._transport
2453
self.repository = _repository
2454
Branch.__init__(self, possible_transports)
2457
return '%s(%s)' % (self.__class__.__name__, self.user_url)
2461
def _get_base(self):
2462
"""Returns the directory containing the control directory."""
2465
base = property(_get_base, doc="The URL for the root of this branch.")
2468
def user_transport(self):
2469
return self._user_transport
2471
def _get_config(self):
2472
return _mod_config.TransportConfig(self._transport, 'branch.conf')
2474
def _get_config_store(self):
2475
return _mod_config.BranchStore(self)
2477
def is_locked(self):
2478
return self.control_files.is_locked()
2480
def lock_write(self, token=None):
2481
"""Lock the branch for write operations.
2483
:param token: A token to permit reacquiring a previously held and
2485
:return: A BranchWriteLockResult.
2487
if not self.is_locked():
2488
self._note_lock('w')
2489
# All-in-one needs to always unlock/lock.
2490
repo_control = getattr(self.repository, 'control_files', None)
2491
if self.control_files == repo_control or not self.is_locked():
2492
self.repository._warn_if_deprecated(self)
2493
self.repository.lock_write()
2498
return BranchWriteLockResult(self.unlock,
2499
self.control_files.lock_write(token=token))
2502
self.repository.unlock()
2505
def lock_read(self):
2506
"""Lock the branch for read operations.
2508
:return: A bzrlib.lock.LogicalLockResult.
2510
if not self.is_locked():
2511
self._note_lock('r')
2512
# All-in-one needs to always unlock/lock.
2513
repo_control = getattr(self.repository, 'control_files', None)
2514
if self.control_files == repo_control or not self.is_locked():
2515
self.repository._warn_if_deprecated(self)
2516
self.repository.lock_read()
2521
self.control_files.lock_read()
2522
return LogicalLockResult(self.unlock)
2525
self.repository.unlock()
2528
@only_raises(errors.LockNotHeld, errors.LockBroken)
2531
self.control_files.unlock()
2533
# All-in-one needs to always unlock/lock.
2534
repo_control = getattr(self.repository, 'control_files', None)
2535
if (self.control_files == repo_control or
2536
not self.control_files.is_locked()):
2537
self.repository.unlock()
2538
if not self.control_files.is_locked():
2539
# we just released the lock
2540
self._clear_cached_state()
2542
def peek_lock_mode(self):
2543
if self.control_files._lock_count == 0:
2546
return self.control_files._lock_mode
2548
def get_physical_lock_status(self):
2549
return self.control_files.get_physical_lock_status()
2552
def print_file(self, file, revision_id):
2553
"""See Branch.print_file."""
2554
return self.repository.print_file(file, revision_id)
2557
def set_last_revision_info(self, revno, revision_id):
2558
if not revision_id or not isinstance(revision_id, basestring):
2559
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2560
revision_id = _mod_revision.ensure_null(revision_id)
2561
old_revno, old_revid = self.last_revision_info()
2562
if self.get_append_revisions_only():
2563
self._check_history_violation(revision_id)
2564
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2565
self._write_last_revision_info(revno, revision_id)
2566
self._clear_cached_state()
2567
self._last_revision_info_cache = revno, revision_id
2568
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2570
def basis_tree(self):
2571
"""See Branch.basis_tree."""
2572
return self.repository.revision_tree(self.last_revision())
2574
def _get_parent_location(self):
2575
_locs = ['parent', 'pull', 'x-pull']
2578
return self._transport.get_bytes(l).strip('\n')
2579
except errors.NoSuchFile:
2583
def get_stacked_on_url(self):
2584
raise errors.UnstackableBranchFormat(self._format, self.user_url)
2586
def set_push_location(self, location):
2587
"""See Branch.set_push_location."""
2588
self.get_config().set_user_option(
2589
'push_location', location,
2590
store=_mod_config.STORE_LOCATION_NORECURSE)
2592
def _set_parent_location(self, url):
2594
self._transport.delete('parent')
2596
self._transport.put_bytes('parent', url + '\n',
2597
mode=self.bzrdir._get_file_mode())
2601
"""If bound, unbind"""
2602
return self.set_bound_location(None)
2605
def bind(self, other):
2606
"""Bind this branch to the branch other.
2608
This does not push or pull data between the branches, though it does
2609
check for divergence to raise an error when the branches are not
2610
either the same, or one a prefix of the other. That behaviour may not
2611
be useful, so that check may be removed in future.
2613
:param other: The branch to bind to
2616
# TODO: jam 20051230 Consider checking if the target is bound
2617
# It is debatable whether you should be able to bind to
2618
# a branch which is itself bound.
2619
# Committing is obviously forbidden,
2620
# but binding itself may not be.
2621
# Since we *have* to check at commit time, we don't
2622
# *need* to check here
2624
# we want to raise diverged if:
2625
# last_rev is not in the other_last_rev history, AND
2626
# other_last_rev is not in our history, and do it without pulling
2628
self.set_bound_location(other.base)
2630
def get_bound_location(self):
2632
return self._transport.get_bytes('bound')[:-1]
2633
except errors.NoSuchFile:
2637
def get_master_branch(self, possible_transports=None):
2638
"""Return the branch we are bound to.
2640
:return: Either a Branch, or None
2642
if self._master_branch_cache is None:
2643
self._master_branch_cache = self._get_master_branch(
2644
possible_transports)
2645
return self._master_branch_cache
2647
def _get_master_branch(self, possible_transports):
2648
bound_loc = self.get_bound_location()
2652
return Branch.open(bound_loc,
2653
possible_transports=possible_transports)
2654
except (errors.NotBranchError, errors.ConnectionError), e:
2655
raise errors.BoundBranchConnectionFailure(
2659
def set_bound_location(self, location):
2660
"""Set the target where this branch is bound to.
2662
:param location: URL to the target branch
2664
self._master_branch_cache = None
2666
self._transport.put_bytes('bound', location+'\n',
2667
mode=self.bzrdir._get_file_mode())
2670
self._transport.delete('bound')
2671
except errors.NoSuchFile:
2676
def update(self, possible_transports=None):
2677
"""Synchronise this branch with the master branch if any.
2679
:return: None or the last_revision that was pivoted out during the
2682
master = self.get_master_branch(possible_transports)
2683
if master is not None:
2684
old_tip = _mod_revision.ensure_null(self.last_revision())
2685
self.pull(master, overwrite=True)
2686
if self.repository.get_graph().is_ancestor(old_tip,
2687
_mod_revision.ensure_null(self.last_revision())):
2692
def _read_last_revision_info(self):
2693
revision_string = self._transport.get_bytes('last-revision')
2694
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2695
revision_id = cache_utf8.get_cached_utf8(revision_id)
2697
return revno, revision_id
2699
def _write_last_revision_info(self, revno, revision_id):
2700
"""Simply write out the revision id, with no checks.
2702
Use set_last_revision_info to perform this safely.
2704
Does not update the revision_history cache.
2706
revision_id = _mod_revision.ensure_null(revision_id)
2707
out_string = '%d %s\n' % (revno, revision_id)
2708
self._transport.put_bytes('last-revision', out_string,
2709
mode=self.bzrdir._get_file_mode())
2712
class FullHistoryBzrBranch(BzrBranch):
2713
"""Bzr branch which contains the full revision history."""
2716
def set_last_revision_info(self, revno, revision_id):
2717
if not revision_id or not isinstance(revision_id, basestring):
2718
raise errors.InvalidRevisionId(revision_id=revision_id, branch=self)
2719
revision_id = _mod_revision.ensure_null(revision_id)
2720
# this old format stores the full history, but this api doesn't
2721
# provide it, so we must generate, and might as well check it's
2723
history = self._lefthand_history(revision_id)
2724
if len(history) != revno:
2725
raise AssertionError('%d != %d' % (len(history), revno))
2726
self._set_revision_history(history)
2728
def _read_last_revision_info(self):
2729
rh = self._revision_history()
2732
return (revno, rh[-1])
2734
return (0, _mod_revision.NULL_REVISION)
2736
@deprecated_method(deprecated_in((2, 4, 0)))
2738
def set_revision_history(self, rev_history):
2739
"""See Branch.set_revision_history."""
2740
self._set_revision_history(rev_history)
2742
def _set_revision_history(self, rev_history):
2743
if 'evil' in debug.debug_flags:
2744
mutter_callsite(3, "set_revision_history scales with history.")
2745
check_not_reserved_id = _mod_revision.check_not_reserved_id
2746
for rev_id in rev_history:
2747
check_not_reserved_id(rev_id)
2748
if Branch.hooks['post_change_branch_tip']:
2749
# Don't calculate the last_revision_info() if there are no hooks
2751
old_revno, old_revid = self.last_revision_info()
2752
if len(rev_history) == 0:
2753
revid = _mod_revision.NULL_REVISION
2755
revid = rev_history[-1]
2756
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
2757
self._write_revision_history(rev_history)
2758
self._clear_cached_state()
2759
self._cache_revision_history(rev_history)
2760
for hook in Branch.hooks['set_rh']:
2761
hook(self, rev_history)
2762
if Branch.hooks['post_change_branch_tip']:
2763
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2765
def _write_revision_history(self, history):
2766
"""Factored out of set_revision_history.
2768
This performs the actual writing to disk.
2769
It is intended to be called by set_revision_history."""
2770
self._transport.put_bytes(
2771
'revision-history', '\n'.join(history),
2772
mode=self.bzrdir._get_file_mode())
2774
def _gen_revision_history(self):
2775
history = self._transport.get_bytes('revision-history').split('\n')
2776
if history[-1:] == ['']:
2777
# There shouldn't be a trailing newline, but just in case.
2781
def _synchronize_history(self, destination, revision_id):
2782
if not isinstance(destination, FullHistoryBzrBranch):
2783
super(BzrBranch, self)._synchronize_history(
2784
destination, revision_id)
2786
if revision_id == _mod_revision.NULL_REVISION:
2789
new_history = self._revision_history()
2790
if revision_id is not None and new_history != []:
2792
new_history = new_history[:new_history.index(revision_id) + 1]
2794
rev = self.repository.get_revision(revision_id)
2795
new_history = rev.get_history(self.repository)[1:]
2796
destination._set_revision_history(new_history)
2799
def generate_revision_history(self, revision_id, last_rev=None,
2801
"""Create a new revision history that will finish with revision_id.
2803
:param revision_id: the new tip to use.
2804
:param last_rev: The previous last_revision. If not None, then this
2805
must be a ancestory of revision_id, or DivergedBranches is raised.
2806
:param other_branch: The other branch that DivergedBranches should
2807
raise with respect to.
2809
self._set_revision_history(self._lefthand_history(revision_id,
2810
last_rev, other_branch))
2813
class BzrBranch5(FullHistoryBzrBranch):
2814
"""A format 5 branch. This supports new features over plain branches.
2816
It has support for a master_branch which is the data for bound branches.
2820
class BzrBranch8(BzrBranch):
2821
"""A branch that stores tree-reference locations."""
2823
def _open_hook(self, possible_transports=None):
2824
if self._ignore_fallbacks:
2826
if possible_transports is None:
2827
possible_transports = [self.bzrdir.root_transport]
2829
url = self.get_stacked_on_url()
2830
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2831
errors.UnstackableBranchFormat):
2834
for hook in Branch.hooks['transform_fallback_location']:
2835
url = hook(self, url)
2837
hook_name = Branch.hooks.get_hook_name(hook)
2838
raise AssertionError(
2839
"'transform_fallback_location' hook %s returned "
2840
"None, not a URL." % hook_name)
2841
self._activate_fallback_location(url,
2842
possible_transports=possible_transports)
2844
def __init__(self, *args, **kwargs):
2845
self._ignore_fallbacks = kwargs.get('ignore_fallbacks', False)
2846
super(BzrBranch8, self).__init__(*args, **kwargs)
2847
self._last_revision_info_cache = None
2848
self._reference_info = None
2850
def _clear_cached_state(self):
2851
super(BzrBranch8, self)._clear_cached_state()
2852
self._last_revision_info_cache = None
2853
self._reference_info = None
2855
def _check_history_violation(self, revision_id):
2856
current_revid = self.last_revision()
2857
last_revision = _mod_revision.ensure_null(current_revid)
2858
if _mod_revision.is_null(last_revision):
2860
graph = self.repository.get_graph()
2861
for lh_ancestor in graph.iter_lefthand_ancestry(revision_id):
2862
if lh_ancestor == current_revid:
2864
raise errors.AppendRevisionsOnlyViolation(self.user_url)
2866
def _gen_revision_history(self):
2867
"""Generate the revision history from last revision
2869
last_revno, last_revision = self.last_revision_info()
2870
self._extend_partial_history(stop_index=last_revno-1)
2871
return list(reversed(self._partial_revision_history_cache))
2874
def _set_parent_location(self, url):
2875
"""Set the parent branch"""
2876
self._set_config_location('parent_location', url, make_relative=True)
2879
def _get_parent_location(self):
2880
"""Set the parent branch"""
2881
return self._get_config_location('parent_location')
2884
def _set_all_reference_info(self, info_dict):
2885
"""Replace all reference info stored in a branch.
2887
:param info_dict: A dict of {file_id: (tree_path, branch_location)}
2890
writer = rio.RioWriter(s)
2891
for key, (tree_path, branch_location) in info_dict.iteritems():
2892
stanza = rio.Stanza(file_id=key, tree_path=tree_path,
2893
branch_location=branch_location)
2894
writer.write_stanza(stanza)
2895
self._transport.put_bytes('references', s.getvalue())
2896
self._reference_info = info_dict
2899
def _get_all_reference_info(self):
2900
"""Return all the reference info stored in a branch.
2902
:return: A dict of {file_id: (tree_path, branch_location)}
2904
if self._reference_info is not None:
2905
return self._reference_info
2906
rio_file = self._transport.get('references')
2908
stanzas = rio.read_stanzas(rio_file)
2909
info_dict = dict((s['file_id'], (s['tree_path'],
2910
s['branch_location'])) for s in stanzas)
2913
self._reference_info = info_dict
2916
def set_reference_info(self, file_id, tree_path, branch_location):
2917
"""Set the branch location to use for a tree reference.
2919
:param file_id: The file-id of the tree reference.
2920
:param tree_path: The path of the tree reference in the tree.
2921
:param branch_location: The location of the branch to retrieve tree
2924
info_dict = self._get_all_reference_info()
2925
info_dict[file_id] = (tree_path, branch_location)
2926
if None in (tree_path, branch_location):
2927
if tree_path is not None:
2928
raise ValueError('tree_path must be None when branch_location'
2930
if branch_location is not None:
2931
raise ValueError('branch_location must be None when tree_path'
2933
del info_dict[file_id]
2934
self._set_all_reference_info(info_dict)
2936
def get_reference_info(self, file_id):
2937
"""Get the tree_path and branch_location for a tree reference.
2939
:return: a tuple of (tree_path, branch_location)
2941
return self._get_all_reference_info().get(file_id, (None, None))
2943
def reference_parent(self, file_id, path, possible_transports=None):
2944
"""Return the parent branch for a tree-reference file_id.
2946
:param file_id: The file_id of the tree reference
2947
:param path: The path of the file_id in the tree
2948
:return: A branch associated with the file_id
2950
branch_location = self.get_reference_info(file_id)[1]
2951
if branch_location is None:
2952
return Branch.reference_parent(self, file_id, path,
2953
possible_transports)
2954
branch_location = urlutils.join(self.user_url, branch_location)
2955
return Branch.open(branch_location,
2956
possible_transports=possible_transports)
2958
def set_push_location(self, location):
2959
"""See Branch.set_push_location."""
2960
self._set_config_location('push_location', location)
2962
def set_bound_location(self, location):
2963
"""See Branch.set_push_location."""
2964
self._master_branch_cache = None
2966
config = self.get_config()
2967
if location is None:
2968
if config.get_user_option('bound') != 'True':
2971
config.set_user_option('bound', 'False', warn_masked=True)
2974
self._set_config_location('bound_location', location,
2976
config.set_user_option('bound', 'True', warn_masked=True)
2979
def _get_bound_location(self, bound):
2980
"""Return the bound location in the config file.
2982
Return None if the bound parameter does not match"""
2983
config = self.get_config()
2984
config_bound = (config.get_user_option('bound') == 'True')
2985
if config_bound != bound:
2987
return self._get_config_location('bound_location', config=config)
2989
def get_bound_location(self):
2990
"""See Branch.set_push_location."""
2991
return self._get_bound_location(True)
2993
def get_old_bound_location(self):
2994
"""See Branch.get_old_bound_location"""
2995
return self._get_bound_location(False)
2997
def get_stacked_on_url(self):
2998
# you can always ask for the URL; but you might not be able to use it
2999
# if the repo can't support stacking.
3000
## self._check_stackable_repo()
3001
# stacked_on_location is only ever defined in branch.conf, so don't
3002
# waste effort reading the whole stack of config files.
3003
config = self.get_config()._get_branch_data_config()
3004
stacked_url = self._get_config_location('stacked_on_location',
3006
if stacked_url is None:
3007
raise errors.NotStacked(self)
3011
def get_rev_id(self, revno, history=None):
3012
"""Find the revision id of the specified revno."""
3014
return _mod_revision.NULL_REVISION
3016
last_revno, last_revision_id = self.last_revision_info()
3017
if revno <= 0 or revno > last_revno:
3018
raise errors.NoSuchRevision(self, revno)
3020
if history is not None:
3021
return history[revno - 1]
3023
index = last_revno - revno
3024
if len(self._partial_revision_history_cache) <= index:
3025
self._extend_partial_history(stop_index=index)
3026
if len(self._partial_revision_history_cache) > index:
3027
return self._partial_revision_history_cache[index]
3029
raise errors.NoSuchRevision(self, revno)
3032
def revision_id_to_revno(self, revision_id):
3033
"""Given a revision id, return its revno"""
3034
if _mod_revision.is_null(revision_id):
3037
index = self._partial_revision_history_cache.index(revision_id)
3040
self._extend_partial_history(stop_revision=revision_id)
3041
except errors.RevisionNotPresent, e:
3042
raise errors.GhostRevisionsHaveNoRevno(revision_id, e.revision_id)
3043
index = len(self._partial_revision_history_cache) - 1
3045
raise errors.NoSuchRevision(self, revision_id)
3046
if self._partial_revision_history_cache[index] != revision_id:
3047
raise errors.NoSuchRevision(self, revision_id)
3048
return self.revno() - index
3051
class BzrBranch7(BzrBranch8):
3052
"""A branch with support for a fallback repository."""
3054
def set_reference_info(self, file_id, tree_path, branch_location):
3055
Branch.set_reference_info(self, file_id, tree_path, branch_location)
3057
def get_reference_info(self, file_id):
3058
Branch.get_reference_info(self, file_id)
3060
def reference_parent(self, file_id, path, possible_transports=None):
3061
return Branch.reference_parent(self, file_id, path,
3062
possible_transports)
3065
class BzrBranch6(BzrBranch7):
3066
"""See BzrBranchFormat6 for the capabilities of this branch.
3068
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
3072
def get_stacked_on_url(self):
3073
raise errors.UnstackableBranchFormat(self._format, self.user_url)
3076
######################################################################
3077
# results of operations
3080
class _Result(object):
3082
def _show_tag_conficts(self, to_file):
3083
if not getattr(self, 'tag_conflicts', None):
3085
to_file.write('Conflicting tags:\n')
3086
for name, value1, value2 in self.tag_conflicts:
3087
to_file.write(' %s\n' % (name, ))
3090
class PullResult(_Result):
3091
"""Result of a Branch.pull operation.
3093
:ivar old_revno: Revision number before pull.
3094
:ivar new_revno: Revision number after pull.
3095
:ivar old_revid: Tip revision id before pull.
3096
:ivar new_revid: Tip revision id after pull.
3097
:ivar source_branch: Source (local) branch object. (read locked)
3098
:ivar master_branch: Master branch of the target, or the target if no
3100
:ivar local_branch: target branch if there is a Master, else None
3101
:ivar target_branch: Target/destination branch object. (write locked)
3102
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
3103
:ivar tag_updates: A dict with new tags, see BasicTags.merge_to
3106
@deprecated_method(deprecated_in((2, 3, 0)))
3108
"""Return the relative change in revno.
3110
:deprecated: Use `new_revno` and `old_revno` instead.
3112
return self.new_revno - self.old_revno
3114
def report(self, to_file):
3115
tag_conflicts = getattr(self, "tag_conflicts", None)
3116
tag_updates = getattr(self, "tag_updates", None)
3118
if self.old_revid != self.new_revid:
3119
to_file.write('Now on revision %d.\n' % self.new_revno)
3121
to_file.write('%d tag(s) updated.\n' % len(tag_updates))
3122
if self.old_revid == self.new_revid and not tag_updates:
3123
if not tag_conflicts:
3124
to_file.write('No revisions or tags to pull.\n')
3126
to_file.write('No revisions to pull.\n')
3127
self._show_tag_conficts(to_file)
3130
class BranchPushResult(_Result):
3131
"""Result of a Branch.push operation.
3133
:ivar old_revno: Revision number (eg 10) of the target before push.
3134
:ivar new_revno: Revision number (eg 12) of the target after push.
3135
:ivar old_revid: Tip revision id (eg joe@foo.com-1234234-aoeua34) of target
3137
:ivar new_revid: Tip revision id (eg joe@foo.com-5676566-boa234a) of target
3139
:ivar source_branch: Source branch object that the push was from. This is
3140
read locked, and generally is a local (and thus low latency) branch.
3141
:ivar master_branch: If target is a bound branch, the master branch of
3142
target, or target itself. Always write locked.
3143
:ivar target_branch: The direct Branch where data is being sent (write
3145
:ivar local_branch: If the target is a bound branch this will be the
3146
target, otherwise it will be None.
3149
@deprecated_method(deprecated_in((2, 3, 0)))
3151
"""Return the relative change in revno.
3153
:deprecated: Use `new_revno` and `old_revno` instead.
3155
return self.new_revno - self.old_revno
3157
def report(self, to_file):
3158
# TODO: This function gets passed a to_file, but then
3159
# ignores it and calls note() instead. This is also
3160
# inconsistent with PullResult(), which writes to stdout.
3161
# -- JRV20110901, bug #838853
3162
tag_conflicts = getattr(self, "tag_conflicts", None)
3163
tag_updates = getattr(self, "tag_updates", None)
3165
if self.old_revid != self.new_revid:
3166
note(gettext('Pushed up to revision %d.') % self.new_revno)
3168
note(ngettext('%d tag updated.', '%d tags updated.', len(tag_updates)) % len(tag_updates))
3169
if self.old_revid == self.new_revid and not tag_updates:
3170
if not tag_conflicts:
3171
note(gettext('No new revisions or tags to push.'))
3173
note(gettext('No new revisions to push.'))
3174
self._show_tag_conficts(to_file)
3177
class BranchCheckResult(object):
3178
"""Results of checking branch consistency.
3183
def __init__(self, branch):
3184
self.branch = branch
3187
def report_results(self, verbose):
3188
"""Report the check results via trace.note.
3190
:param verbose: Requests more detailed display of what was checked,
3193
note(gettext('checked branch {0} format {1}').format(
3194
self.branch.user_url, self.branch._format))
3195
for error in self.errors:
3196
note(gettext('found error:%s'), error)
3199
class Converter5to6(object):
3200
"""Perform an in-place upgrade of format 5 to format 6"""
3202
def convert(self, branch):
3203
# Data for 5 and 6 can peacefully coexist.
3204
format = BzrBranchFormat6()
3205
new_branch = format.open(branch.bzrdir, _found=True)
3207
# Copy source data into target
3208
new_branch._write_last_revision_info(*branch.last_revision_info())
3209
new_branch.set_parent(branch.get_parent())
3210
new_branch.set_bound_location(branch.get_bound_location())
3211
new_branch.set_push_location(branch.get_push_location())
3213
# New branch has no tags by default
3214
new_branch.tags._set_tag_dict({})
3216
# Copying done; now update target format
3217
new_branch._transport.put_bytes('format',
3218
format.get_format_string(),
3219
mode=new_branch.bzrdir._get_file_mode())
3221
# Clean up old files
3222
new_branch._transport.delete('revision-history')
3224
branch.set_parent(None)
3225
except errors.NoSuchFile:
3227
branch.set_bound_location(None)
3230
class Converter6to7(object):
3231
"""Perform an in-place upgrade of format 6 to format 7"""
3233
def convert(self, branch):
3234
format = BzrBranchFormat7()
3235
branch._set_config_location('stacked_on_location', '')
3236
# update target format
3237
branch._transport.put_bytes('format', format.get_format_string())
3240
class Converter7to8(object):
3241
"""Perform an in-place upgrade of format 7 to format 8"""
3243
def convert(self, branch):
3244
format = BzrBranchFormat8()
3245
branch._transport.put_bytes('references', '')
3246
# update target format
3247
branch._transport.put_bytes('format', format.get_format_string())
3250
class InterBranch(InterObject):
3251
"""This class represents operations taking place between two branches.
3253
Its instances have methods like pull() and push() and contain
3254
references to the source and target repositories these operations
3255
can be carried out on.
3259
"""The available optimised InterBranch types."""
3262
def _get_branch_formats_to_test(klass):
3263
"""Return an iterable of format tuples for testing.
3265
:return: An iterable of (from_format, to_format) to use when testing
3266
this InterBranch class. Each InterBranch class should define this
3269
raise NotImplementedError(klass._get_branch_formats_to_test)
3272
def pull(self, overwrite=False, stop_revision=None,
3273
possible_transports=None, local=False):
3274
"""Mirror source into target branch.
3276
The target branch is considered to be 'local', having low latency.
3278
:returns: PullResult instance
3280
raise NotImplementedError(self.pull)
3283
def push(self, overwrite=False, stop_revision=None, lossy=False,
3284
_override_hook_source_branch=None):
3285
"""Mirror the source branch into the target branch.
3287
The source branch is considered to be 'local', having low latency.
3289
raise NotImplementedError(self.push)
3292
def copy_content_into(self, revision_id=None):
3293
"""Copy the content of source into target
3295
revision_id: if not None, the revision history in the new branch will
3296
be truncated to end with revision_id.
3298
raise NotImplementedError(self.copy_content_into)
3301
def fetch(self, stop_revision=None, limit=None):
3304
:param stop_revision: Last revision to fetch
3305
:param limit: Optional rough limit of revisions to fetch
3307
raise NotImplementedError(self.fetch)
3310
class GenericInterBranch(InterBranch):
3311
"""InterBranch implementation that uses public Branch functions."""
3314
def is_compatible(klass, source, target):
3315
# GenericBranch uses the public API, so always compatible
3319
def _get_branch_formats_to_test(klass):
3320
return [(format_registry.get_default(), format_registry.get_default())]
3323
def unwrap_format(klass, format):
3324
if isinstance(format, remote.RemoteBranchFormat):
3325
format._ensure_real()
3326
return format._custom_format
3330
def copy_content_into(self, revision_id=None):
3331
"""Copy the content of source into target
3333
revision_id: if not None, the revision history in the new branch will
3334
be truncated to end with revision_id.
3336
self.source.update_references(self.target)
3337
self.source._synchronize_history(self.target, revision_id)
3339
parent = self.source.get_parent()
3340
except errors.InaccessibleParent, e:
3341
mutter('parent was not accessible to copy: %s', e)
3344
self.target.set_parent(parent)
3345
if self.source._push_should_merge_tags():
3346
self.source.tags.merge_to(self.target.tags)
3349
def fetch(self, stop_revision=None, limit=None):
3350
if self.target.base == self.source.base:
3352
self.source.lock_read()
3354
fetch_spec_factory = fetch.FetchSpecFactory()
3355
fetch_spec_factory.source_branch = self.source
3356
fetch_spec_factory.source_branch_stop_revision_id = stop_revision
3357
fetch_spec_factory.source_repo = self.source.repository
3358
fetch_spec_factory.target_repo = self.target.repository
3359
fetch_spec_factory.target_repo_kind = fetch.TargetRepoKinds.PREEXISTING
3360
fetch_spec_factory.limit = limit
3361
fetch_spec = fetch_spec_factory.make_fetch_spec()
3362
return self.target.repository.fetch(self.source.repository,
3363
fetch_spec=fetch_spec)
3365
self.source.unlock()
3368
def _update_revisions(self, stop_revision=None, overwrite=False,
3370
other_revno, other_last_revision = self.source.last_revision_info()
3371
stop_revno = None # unknown
3372
if stop_revision is None:
3373
stop_revision = other_last_revision
3374
if _mod_revision.is_null(stop_revision):
3375
# if there are no commits, we're done.
3377
stop_revno = other_revno
3379
# what's the current last revision, before we fetch [and change it
3381
last_rev = _mod_revision.ensure_null(self.target.last_revision())
3382
# we fetch here so that we don't process data twice in the common
3383
# case of having something to pull, and so that the check for
3384
# already merged can operate on the just fetched graph, which will
3385
# be cached in memory.
3386
self.fetch(stop_revision=stop_revision)
3387
# Check to see if one is an ancestor of the other
3390
graph = self.target.repository.get_graph()
3391
if self.target._check_if_descendant_or_diverged(
3392
stop_revision, last_rev, graph, self.source):
3393
# stop_revision is a descendant of last_rev, but we aren't
3394
# overwriting, so we're done.
3396
if stop_revno is None:
3398
graph = self.target.repository.get_graph()
3399
this_revno, this_last_revision = \
3400
self.target.last_revision_info()
3401
stop_revno = graph.find_distance_to_null(stop_revision,
3402
[(other_last_revision, other_revno),
3403
(this_last_revision, this_revno)])
3404
self.target.set_last_revision_info(stop_revno, stop_revision)
3407
def pull(self, overwrite=False, stop_revision=None,
3408
possible_transports=None, run_hooks=True,
3409
_override_hook_target=None, local=False):
3410
"""Pull from source into self, updating my master if any.
3412
:param run_hooks: Private parameter - if false, this branch
3413
is being called because it's the master of the primary branch,
3414
so it should not run its hooks.
3416
bound_location = self.target.get_bound_location()
3417
if local and not bound_location:
3418
raise errors.LocalRequiresBoundBranch()
3419
master_branch = None
3420
source_is_master = False
3422
# bound_location comes from a config file, some care has to be
3423
# taken to relate it to source.user_url
3424
normalized = urlutils.normalize_url(bound_location)
3426
relpath = self.source.user_transport.relpath(normalized)
3427
source_is_master = (relpath == '')
3428
except (errors.PathNotChild, errors.InvalidURL):
3429
source_is_master = False
3430
if not local and bound_location and not source_is_master:
3431
# not pulling from master, so we need to update master.
3432
master_branch = self.target.get_master_branch(possible_transports)
3433
master_branch.lock_write()
3436
# pull from source into master.
3437
master_branch.pull(self.source, overwrite, stop_revision,
3439
return self._pull(overwrite,
3440
stop_revision, _hook_master=master_branch,
3441
run_hooks=run_hooks,
3442
_override_hook_target=_override_hook_target,
3443
merge_tags_to_master=not source_is_master)
3446
master_branch.unlock()
3448
def push(self, overwrite=False, stop_revision=None, lossy=False,
3449
_override_hook_source_branch=None):
3450
"""See InterBranch.push.
3452
This is the basic concrete implementation of push()
3454
:param _override_hook_source_branch: If specified, run the hooks
3455
passing this Branch as the source, rather than self. This is for
3456
use of RemoteBranch, where push is delegated to the underlying
3460
raise errors.LossyPushToSameVCS(self.source, self.target)
3461
# TODO: Public option to disable running hooks - should be trivial but
3464
op = cleanup.OperationWithCleanups(self._push_with_bound_branches)
3465
op.add_cleanup(self.source.lock_read().unlock)
3466
op.add_cleanup(self.target.lock_write().unlock)
3467
return op.run(overwrite, stop_revision,
3468
_override_hook_source_branch=_override_hook_source_branch)
3470
def _basic_push(self, overwrite, stop_revision):
3471
"""Basic implementation of push without bound branches or hooks.
3473
Must be called with source read locked and target write locked.
3475
result = BranchPushResult()
3476
result.source_branch = self.source
3477
result.target_branch = self.target
3478
result.old_revno, result.old_revid = self.target.last_revision_info()
3479
self.source.update_references(self.target)
3480
if result.old_revid != stop_revision:
3481
# We assume that during 'push' this repository is closer than
3483
graph = self.source.repository.get_graph(self.target.repository)
3484
self._update_revisions(stop_revision, overwrite=overwrite,
3486
if self.source._push_should_merge_tags():
3487
result.tag_updates, result.tag_conflicts = (
3488
self.source.tags.merge_to(self.target.tags, overwrite))
3489
result.new_revno, result.new_revid = self.target.last_revision_info()
3492
def _push_with_bound_branches(self, operation, overwrite, stop_revision,
3493
_override_hook_source_branch=None):
3494
"""Push from source into target, and into target's master if any.
3497
if _override_hook_source_branch:
3498
result.source_branch = _override_hook_source_branch
3499
for hook in Branch.hooks['post_push']:
3502
bound_location = self.target.get_bound_location()
3503
if bound_location and self.target.base != bound_location:
3504
# there is a master branch.
3506
# XXX: Why the second check? Is it even supported for a branch to
3507
# be bound to itself? -- mbp 20070507
3508
master_branch = self.target.get_master_branch()
3509
master_branch.lock_write()
3510
operation.add_cleanup(master_branch.unlock)
3511
# push into the master from the source branch.
3512
master_inter = InterBranch.get(self.source, master_branch)
3513
master_inter._basic_push(overwrite, stop_revision)
3514
# and push into the target branch from the source. Note that
3515
# we push from the source branch again, because it's considered
3516
# the highest bandwidth repository.
3517
result = self._basic_push(overwrite, stop_revision)
3518
result.master_branch = master_branch
3519
result.local_branch = self.target
3521
master_branch = None
3523
result = self._basic_push(overwrite, stop_revision)
3524
# TODO: Why set master_branch and local_branch if there's no
3525
# binding? Maybe cleaner to just leave them unset? -- mbp
3527
result.master_branch = self.target
3528
result.local_branch = None
3532
def _pull(self, overwrite=False, stop_revision=None,
3533
possible_transports=None, _hook_master=None, run_hooks=True,
3534
_override_hook_target=None, local=False,
3535
merge_tags_to_master=True):
3538
This function is the core worker, used by GenericInterBranch.pull to
3539
avoid duplication when pulling source->master and source->local.
3541
:param _hook_master: Private parameter - set the branch to
3542
be supplied as the master to pull hooks.
3543
:param run_hooks: Private parameter - if false, this branch
3544
is being called because it's the master of the primary branch,
3545
so it should not run its hooks.
3546
is being called because it's the master of the primary branch,
3547
so it should not run its hooks.
3548
:param _override_hook_target: Private parameter - set the branch to be
3549
supplied as the target_branch to pull hooks.
3550
:param local: Only update the local branch, and not the bound branch.
3552
# This type of branch can't be bound.
3554
raise errors.LocalRequiresBoundBranch()
3555
result = PullResult()
3556
result.source_branch = self.source
3557
if _override_hook_target is None:
3558
result.target_branch = self.target
3560
result.target_branch = _override_hook_target
3561
self.source.lock_read()
3563
# We assume that during 'pull' the target repository is closer than
3565
self.source.update_references(self.target)
3566
graph = self.target.repository.get_graph(self.source.repository)
3567
# TODO: Branch formats should have a flag that indicates
3568
# that revno's are expensive, and pull() should honor that flag.
3570
result.old_revno, result.old_revid = \
3571
self.target.last_revision_info()
3572
self._update_revisions(stop_revision, overwrite=overwrite,
3574
# TODO: The old revid should be specified when merging tags,
3575
# so a tags implementation that versions tags can only
3576
# pull in the most recent changes. -- JRV20090506
3577
result.tag_updates, result.tag_conflicts = (
3578
self.source.tags.merge_to(self.target.tags, overwrite,
3579
ignore_master=not merge_tags_to_master))
3580
result.new_revno, result.new_revid = self.target.last_revision_info()
3582
result.master_branch = _hook_master
3583
result.local_branch = result.target_branch
3585
result.master_branch = result.target_branch
3586
result.local_branch = None
3588
for hook in Branch.hooks['post_pull']:
3591
self.source.unlock()
3595
InterBranch.register_optimiser(GenericInterBranch)