1
# Copyright (C) 2005, 2006, 2007, 2008 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20
from bzrlib.lazy_import import lazy_import
21
lazy_import(globals(), """
22
from itertools import chain
26
config as _mod_config,
32
revision as _mod_revision,
38
from bzrlib.config import BranchConfig
39
from bzrlib.repofmt.pack_repo import RepositoryFormatKnitPack5RichRoot
40
from bzrlib.tag import (
46
from bzrlib.decorators import needs_read_lock, needs_write_lock
47
from bzrlib.hooks import Hooks
48
from bzrlib.inter import InterObject
49
from bzrlib.symbol_versioning import (
53
from bzrlib.trace import mutter, mutter_callsite, note, is_quiet
56
BZR_BRANCH_FORMAT_4 = "Bazaar-NG branch, format 0.0.4\n"
57
BZR_BRANCH_FORMAT_5 = "Bazaar-NG branch, format 5\n"
58
BZR_BRANCH_FORMAT_6 = "Bazaar Branch Format 6 (bzr 0.15)\n"
61
# TODO: Maybe include checks for common corruption of newlines, etc?
63
# TODO: Some operations like log might retrieve the same revisions
64
# repeatedly to calculate deltas. We could perhaps have a weakref
65
# cache in memory to make this faster. In general anything can be
66
# cached in memory between lock and unlock operations. .. nb thats
67
# what the transaction identity map provides
70
######################################################################
74
"""Branch holding a history of revisions.
77
Base directory/url of the branch.
79
hooks: An instance of BranchHooks.
81
# this is really an instance variable - FIXME move it there
85
# override this to set the strategy for storing tags
87
return DisabledTags(self)
89
def __init__(self, *ignored, **ignored_too):
90
self.tags = self._make_tags()
91
self._revision_history_cache = None
92
self._revision_id_to_revno_cache = None
93
self._partial_revision_id_to_revno_cache = {}
94
self._last_revision_info_cache = None
95
self._merge_sorted_revisions_cache = None
97
hooks = Branch.hooks['open']
101
def _open_hook(self):
102
"""Called by init to allow simpler extension of the base class."""
104
def break_lock(self):
105
"""Break a lock if one is present from another instance.
107
Uses the ui factory to ask for confirmation if the lock may be from
110
This will probe the repository for its lock as well.
112
self.control_files.break_lock()
113
self.repository.break_lock()
114
master = self.get_master_branch()
115
if master is not None:
119
def open(base, _unsupported=False, possible_transports=None):
120
"""Open the branch rooted at base.
122
For instance, if the branch is at URL/.bzr/branch,
123
Branch.open(URL) -> a Branch instance.
125
control = bzrdir.BzrDir.open(base, _unsupported,
126
possible_transports=possible_transports)
127
return control.open_branch(_unsupported)
130
def open_from_transport(transport, _unsupported=False):
131
"""Open the branch rooted at transport"""
132
control = bzrdir.BzrDir.open_from_transport(transport, _unsupported)
133
return control.open_branch(_unsupported)
136
def open_containing(url, possible_transports=None):
137
"""Open an existing branch which contains url.
139
This probes for a branch at url, and searches upwards from there.
141
Basically we keep looking up until we find the control directory or
142
run into the root. If there isn't one, raises NotBranchError.
143
If there is one and it is either an unrecognised format or an unsupported
144
format, UnknownFormatError or UnsupportedFormatError are raised.
145
If there is one, it is returned, along with the unused portion of url.
147
control, relpath = bzrdir.BzrDir.open_containing(url,
149
return control.open_branch(), relpath
151
def get_config(self):
152
return BranchConfig(self)
154
def _get_nick(self, local=False, possible_transports=None):
155
config = self.get_config()
156
# explicit overrides master, but don't look for master if local is True
157
if not local and not config.has_explicit_nickname():
159
master = self.get_master_branch(possible_transports)
160
if master is not None:
161
# return the master branch value
163
except errors.BzrError, e:
164
# Silently fall back to local implicit nick if the master is
166
mutter("Could not connect to bound branch, "
167
"falling back to local nick.\n " + str(e))
168
return config.get_nickname()
170
def _set_nick(self, nick):
171
self.get_config().set_user_option('nickname', nick, warn_masked=True)
173
nick = property(_get_nick, _set_nick)
176
raise NotImplementedError(self.is_locked)
178
def _lefthand_history(self, revision_id, last_rev=None,
180
if 'evil' in debug.debug_flags:
181
mutter_callsite(4, "_lefthand_history scales with history.")
182
# stop_revision must be a descendant of last_revision
183
graph = self.repository.get_graph()
184
if last_rev is not None:
185
if not graph.is_ancestor(last_rev, revision_id):
186
# our previous tip is not merged into stop_revision
187
raise errors.DivergedBranches(self, other_branch)
188
# make a new revision history from the graph
189
parents_map = graph.get_parent_map([revision_id])
190
if revision_id not in parents_map:
191
raise errors.NoSuchRevision(self, revision_id)
192
current_rev_id = revision_id
194
check_not_reserved_id = _mod_revision.check_not_reserved_id
195
# Do not include ghosts or graph origin in revision_history
196
while (current_rev_id in parents_map and
197
len(parents_map[current_rev_id]) > 0):
198
check_not_reserved_id(current_rev_id)
199
new_history.append(current_rev_id)
200
current_rev_id = parents_map[current_rev_id][0]
201
parents_map = graph.get_parent_map([current_rev_id])
202
new_history.reverse()
205
def lock_write(self):
206
raise NotImplementedError(self.lock_write)
209
raise NotImplementedError(self.lock_read)
212
raise NotImplementedError(self.unlock)
214
def peek_lock_mode(self):
215
"""Return lock mode for the Branch: 'r', 'w' or None"""
216
raise NotImplementedError(self.peek_lock_mode)
218
def get_physical_lock_status(self):
219
raise NotImplementedError(self.get_physical_lock_status)
222
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
223
"""Return the revision_id for a dotted revno.
225
:param revno: a tuple like (1,) or (1,1,2)
226
:param _cache_reverse: a private parameter enabling storage
227
of the reverse mapping in a top level cache. (This should
228
only be done in selective circumstances as we want to
229
avoid having the mapping cached multiple times.)
230
:return: the revision_id
231
:raises errors.NoSuchRevision: if the revno doesn't exist
233
rev_id = self._do_dotted_revno_to_revision_id(revno)
235
self._partial_revision_id_to_revno_cache[rev_id] = revno
238
def _do_dotted_revno_to_revision_id(self, revno):
239
"""Worker function for dotted_revno_to_revision_id.
241
Subclasses should override this if they wish to
242
provide a more efficient implementation.
245
return self.get_rev_id(revno[0])
246
revision_id_to_revno = self.get_revision_id_to_revno_map()
247
revision_ids = [revision_id for revision_id, this_revno
248
in revision_id_to_revno.iteritems()
249
if revno == this_revno]
250
if len(revision_ids) == 1:
251
return revision_ids[0]
253
revno_str = '.'.join(map(str, revno))
254
raise errors.NoSuchRevision(self, revno_str)
257
def revision_id_to_dotted_revno(self, revision_id):
258
"""Given a revision id, return its dotted revno.
260
:return: a tuple like (1,) or (400,1,3).
262
return self._do_revision_id_to_dotted_revno(revision_id)
264
def _do_revision_id_to_dotted_revno(self, revision_id):
265
"""Worker function for revision_id_to_revno."""
266
# Try the caches if they are loaded
267
result = self._partial_revision_id_to_revno_cache.get(revision_id)
268
if result is not None:
270
if self._revision_id_to_revno_cache:
271
result = self._revision_id_to_revno_cache.get(revision_id)
273
raise errors.NoSuchRevision(self, revision_id)
274
# Try the mainline as it's optimised
276
revno = self.revision_id_to_revno(revision_id)
278
except errors.NoSuchRevision:
279
# We need to load and use the full revno map after all
280
result = self.get_revision_id_to_revno_map().get(revision_id)
282
raise errors.NoSuchRevision(self, revision_id)
286
def get_revision_id_to_revno_map(self):
287
"""Return the revision_id => dotted revno map.
289
This will be regenerated on demand, but will be cached.
291
:return: A dictionary mapping revision_id => dotted revno.
292
This dictionary should not be modified by the caller.
294
if self._revision_id_to_revno_cache is not None:
295
mapping = self._revision_id_to_revno_cache
297
mapping = self._gen_revno_map()
298
self._cache_revision_id_to_revno(mapping)
299
# TODO: jam 20070417 Since this is being cached, should we be returning
301
# I would rather not, and instead just declare that users should not
302
# modify the return value.
305
def _gen_revno_map(self):
306
"""Create a new mapping from revision ids to dotted revnos.
308
Dotted revnos are generated based on the current tip in the revision
310
This is the worker function for get_revision_id_to_revno_map, which
311
just caches the return value.
313
:return: A dictionary mapping revision_id => dotted revno.
315
revision_id_to_revno = dict((rev_id, revno)
316
for rev_id, depth, revno, end_of_merge
317
in self.iter_merge_sorted_revisions())
318
return revision_id_to_revno
321
def iter_merge_sorted_revisions(self, start_revision_id=None,
322
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
323
"""Walk the revisions for a branch in merge sorted order.
325
Merge sorted order is the output from a merge-aware,
326
topological sort, i.e. all parents come before their
327
children going forward; the opposite for reverse.
329
:param start_revision_id: the revision_id to begin walking from.
330
If None, the branch tip is used.
331
:param stop_revision_id: the revision_id to terminate the walk
332
after. If None, the rest of history is included.
333
:param stop_rule: if stop_revision_id is not None, the precise rule
334
to use for termination:
335
* 'exclude' - leave the stop revision out of the result (default)
336
* 'include' - the stop revision is the last item in the result
337
* 'with-merges' - include the stop revision and all of its
338
merged revisions in the result
339
:param direction: either 'reverse' or 'forward':
340
* reverse means return the start_revision_id first, i.e.
341
start at the most recent revision and go backwards in history
342
* forward returns tuples in the opposite order to reverse.
343
Note in particular that forward does *not* do any intelligent
344
ordering w.r.t. depth as some clients of this API may like.
345
(If required, that ought to be done at higher layers.)
347
:return: an iterator over (revision_id, depth, revno, end_of_merge)
350
* revision_id: the unique id of the revision
351
* depth: How many levels of merging deep this node has been
353
* revno_sequence: This field provides a sequence of
354
revision numbers for all revisions. The format is:
355
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
356
branch that the revno is on. From left to right the REVNO numbers
357
are the sequence numbers within that branch of the revision.
358
* end_of_merge: When True the next node (earlier in history) is
359
part of a different merge.
361
# Note: depth and revno values are in the context of the branch so
362
# we need the full graph to get stable numbers, regardless of the
364
if self._merge_sorted_revisions_cache is None:
365
last_revision = self.last_revision()
366
graph = self.repository.get_graph()
367
parent_map = dict(((key, value) for key, value in
368
graph.iter_ancestry([last_revision]) if value is not None))
369
revision_graph = repository._strip_NULL_ghosts(parent_map)
370
revs = tsort.merge_sort(revision_graph, last_revision, None,
372
# Drop the sequence # before caching
373
self._merge_sorted_revisions_cache = [r[1:] for r in revs]
375
filtered = self._filter_merge_sorted_revisions(
376
self._merge_sorted_revisions_cache, start_revision_id,
377
stop_revision_id, stop_rule)
378
if direction == 'reverse':
380
if direction == 'forward':
381
return reversed(list(filtered))
383
raise ValueError('invalid direction %r' % direction)
385
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
386
start_revision_id, stop_revision_id, stop_rule):
387
"""Iterate over an inclusive range of sorted revisions."""
388
rev_iter = iter(merge_sorted_revisions)
389
if start_revision_id is not None:
390
for rev_id, depth, revno, end_of_merge in rev_iter:
391
if rev_id != start_revision_id:
394
# The decision to include the start or not
395
# depends on the stop_rule if a stop is provided
397
iter([(rev_id, depth, revno, end_of_merge)]),
400
if stop_revision_id is None:
401
for rev_id, depth, revno, end_of_merge in rev_iter:
402
yield rev_id, depth, revno, end_of_merge
403
elif stop_rule == 'exclude':
404
for rev_id, depth, revno, end_of_merge in rev_iter:
405
if rev_id == stop_revision_id:
407
yield rev_id, depth, revno, end_of_merge
408
elif stop_rule == 'include':
409
for rev_id, depth, revno, end_of_merge in rev_iter:
410
yield rev_id, depth, revno, end_of_merge
411
if rev_id == stop_revision_id:
413
elif stop_rule == 'with-merges':
414
stop_rev = self.repository.get_revision(stop_revision_id)
415
if stop_rev.parent_ids:
416
left_parent = stop_rev.parent_ids[0]
418
left_parent = _mod_revision.NULL_REVISION
419
for rev_id, depth, revno, end_of_merge in rev_iter:
420
if rev_id == left_parent:
422
yield rev_id, depth, revno, end_of_merge
424
raise ValueError('invalid stop_rule %r' % stop_rule)
426
def leave_lock_in_place(self):
427
"""Tell this branch object not to release the physical lock when this
430
If lock_write doesn't return a token, then this method is not supported.
432
self.control_files.leave_in_place()
434
def dont_leave_lock_in_place(self):
435
"""Tell this branch object to release the physical lock when this
436
object is unlocked, even if it didn't originally acquire it.
438
If lock_write doesn't return a token, then this method is not supported.
440
self.control_files.dont_leave_in_place()
442
def bind(self, other):
443
"""Bind the local branch the other branch.
445
:param other: The branch to bind to
448
raise errors.UpgradeRequired(self.base)
451
def fetch(self, from_branch, last_revision=None, pb=None):
452
"""Copy revisions from from_branch into this branch.
454
:param from_branch: Where to copy from.
455
:param last_revision: What revision to stop at (None for at the end
457
:param pb: An optional progress bar to use.
459
Returns the copied revision count and the failed revisions in a tuple:
462
if self.base == from_branch.base:
465
nested_pb = ui.ui_factory.nested_progress_bar()
470
from_branch.lock_read()
472
if last_revision is None:
473
pb.update('get source history')
474
last_revision = from_branch.last_revision()
475
last_revision = _mod_revision.ensure_null(last_revision)
476
return self.repository.fetch(from_branch.repository,
477
revision_id=last_revision,
480
if nested_pb is not None:
484
def get_bound_location(self):
485
"""Return the URL of the branch we are bound to.
487
Older format branches cannot bind, please be sure to use a metadir
492
def get_old_bound_location(self):
493
"""Return the URL of the branch we used to be bound to
495
raise errors.UpgradeRequired(self.base)
497
def get_commit_builder(self, parents, config=None, timestamp=None,
498
timezone=None, committer=None, revprops=None,
500
"""Obtain a CommitBuilder for this branch.
502
:param parents: Revision ids of the parents of the new revision.
503
:param config: Optional configuration to use.
504
:param timestamp: Optional timestamp recorded for commit.
505
:param timezone: Optional timezone for timestamp.
506
:param committer: Optional committer to set for commit.
507
:param revprops: Optional dictionary of revision properties.
508
:param revision_id: Optional revision id.
512
config = self.get_config()
514
return self.repository.get_commit_builder(self, parents, config,
515
timestamp, timezone, committer, revprops, revision_id)
517
def get_master_branch(self, possible_transports=None):
518
"""Return the branch we are bound to.
520
:return: Either a Branch, or None
524
def get_revision_delta(self, revno):
525
"""Return the delta for one revision.
527
The delta is relative to its mainline predecessor, or the
528
empty tree for revision 1.
530
rh = self.revision_history()
531
if not (1 <= revno <= len(rh)):
532
raise errors.InvalidRevisionNumber(revno)
533
return self.repository.get_revision_delta(rh[revno-1])
535
def get_stacked_on_url(self):
536
"""Get the URL this branch is stacked against.
538
:raises NotStacked: If the branch is not stacked.
539
:raises UnstackableBranchFormat: If the branch does not support
542
raise NotImplementedError(self.get_stacked_on_url)
544
def print_file(self, file, revision_id):
545
"""Print `file` to stdout."""
546
raise NotImplementedError(self.print_file)
548
def set_revision_history(self, rev_history):
549
raise NotImplementedError(self.set_revision_history)
551
def set_stacked_on_url(self, url):
552
"""Set the URL this branch is stacked against.
554
:raises UnstackableBranchFormat: If the branch does not support
556
:raises UnstackableRepositoryFormat: If the repository does not support
559
raise NotImplementedError(self.set_stacked_on_url)
561
def _cache_revision_history(self, rev_history):
562
"""Set the cached revision history to rev_history.
564
The revision_history method will use this cache to avoid regenerating
565
the revision history.
567
This API is semi-public; it only for use by subclasses, all other code
568
should consider it to be private.
570
self._revision_history_cache = rev_history
572
def _cache_revision_id_to_revno(self, revision_id_to_revno):
573
"""Set the cached revision_id => revno map to revision_id_to_revno.
575
This API is semi-public; it only for use by subclasses, all other code
576
should consider it to be private.
578
self._revision_id_to_revno_cache = revision_id_to_revno
580
def _clear_cached_state(self):
581
"""Clear any cached data on this branch, e.g. cached revision history.
583
This means the next call to revision_history will need to call
584
_gen_revision_history.
586
This API is semi-public; it only for use by subclasses, all other code
587
should consider it to be private.
589
self._revision_history_cache = None
590
self._revision_id_to_revno_cache = None
591
self._last_revision_info_cache = None
592
self._merge_sorted_revisions_cache = None
594
def _gen_revision_history(self):
595
"""Return sequence of revision hashes on to this branch.
597
Unlike revision_history, this method always regenerates or rereads the
598
revision history, i.e. it does not cache the result, so repeated calls
601
Concrete subclasses should override this instead of revision_history so
602
that subclasses do not need to deal with caching logic.
604
This API is semi-public; it only for use by subclasses, all other code
605
should consider it to be private.
607
raise NotImplementedError(self._gen_revision_history)
610
def revision_history(self):
611
"""Return sequence of revision ids on this branch.
613
This method will cache the revision history for as long as it is safe to
616
if 'evil' in debug.debug_flags:
617
mutter_callsite(3, "revision_history scales with history.")
618
if self._revision_history_cache is not None:
619
history = self._revision_history_cache
621
history = self._gen_revision_history()
622
self._cache_revision_history(history)
626
"""Return current revision number for this branch.
628
That is equivalent to the number of revisions committed to
631
return self.last_revision_info()[0]
634
"""Older format branches cannot bind or unbind."""
635
raise errors.UpgradeRequired(self.base)
637
def set_append_revisions_only(self, enabled):
638
"""Older format branches are never restricted to append-only"""
639
raise errors.UpgradeRequired(self.base)
641
def last_revision(self):
642
"""Return last revision id, or NULL_REVISION."""
643
return self.last_revision_info()[1]
646
def last_revision_info(self):
647
"""Return information about the last revision.
649
:return: A tuple (revno, revision_id).
651
if self._last_revision_info_cache is None:
652
self._last_revision_info_cache = self._last_revision_info()
653
return self._last_revision_info_cache
655
def _last_revision_info(self):
656
rh = self.revision_history()
659
return (revno, rh[-1])
661
return (0, _mod_revision.NULL_REVISION)
663
@deprecated_method(deprecated_in((1, 6, 0)))
664
def missing_revisions(self, other, stop_revision=None):
665
"""Return a list of new revisions that would perfectly fit.
667
If self and other have not diverged, return a list of the revisions
668
present in other, but missing from self.
670
self_history = self.revision_history()
671
self_len = len(self_history)
672
other_history = other.revision_history()
673
other_len = len(other_history)
674
common_index = min(self_len, other_len) -1
675
if common_index >= 0 and \
676
self_history[common_index] != other_history[common_index]:
677
raise errors.DivergedBranches(self, other)
679
if stop_revision is None:
680
stop_revision = other_len
682
if stop_revision > other_len:
683
raise errors.NoSuchRevision(self, stop_revision)
684
return other_history[self_len:stop_revision]
687
def update_revisions(self, other, stop_revision=None, overwrite=False,
689
"""Pull in new perfect-fit revisions.
691
:param other: Another Branch to pull from
692
:param stop_revision: Updated until the given revision
693
:param overwrite: Always set the branch pointer, rather than checking
694
to see if it is a proper descendant.
695
:param graph: A Graph object that can be used to query history
696
information. This can be None.
699
return InterBranch.get(other, self).update_revisions(stop_revision,
702
def revision_id_to_revno(self, revision_id):
703
"""Given a revision id, return its revno"""
704
if _mod_revision.is_null(revision_id):
706
history = self.revision_history()
708
return history.index(revision_id) + 1
710
raise errors.NoSuchRevision(self, revision_id)
712
def get_rev_id(self, revno, history=None):
713
"""Find the revision id of the specified revno."""
715
return _mod_revision.NULL_REVISION
717
history = self.revision_history()
718
if revno <= 0 or revno > len(history):
719
raise errors.NoSuchRevision(self, revno)
720
return history[revno - 1]
722
def pull(self, source, overwrite=False, stop_revision=None,
723
possible_transports=None, _override_hook_target=None):
724
"""Mirror source into this branch.
726
This branch is considered to be 'local', having low latency.
728
:returns: PullResult instance
730
raise NotImplementedError(self.pull)
732
def push(self, target, overwrite=False, stop_revision=None):
733
"""Mirror this branch into target.
735
This branch is considered to be 'local', having low latency.
737
raise NotImplementedError(self.push)
739
def basis_tree(self):
740
"""Return `Tree` object for last revision."""
741
return self.repository.revision_tree(self.last_revision())
743
def get_parent(self):
744
"""Return the parent location of the branch.
746
This is the default location for pull/missing. The usual
747
pattern is that the user can override it by specifying a
750
raise NotImplementedError(self.get_parent)
752
def _set_config_location(self, name, url, config=None,
753
make_relative=False):
755
config = self.get_config()
759
url = urlutils.relative_url(self.base, url)
760
config.set_user_option(name, url, warn_masked=True)
762
def _get_config_location(self, name, config=None):
764
config = self.get_config()
765
location = config.get_user_option(name)
770
def get_submit_branch(self):
771
"""Return the submit location of the branch.
773
This is the default location for bundle. The usual
774
pattern is that the user can override it by specifying a
777
return self.get_config().get_user_option('submit_branch')
779
def set_submit_branch(self, location):
780
"""Return the submit location of the branch.
782
This is the default location for bundle. The usual
783
pattern is that the user can override it by specifying a
786
self.get_config().set_user_option('submit_branch', location,
789
def get_public_branch(self):
790
"""Return the public location of the branch.
792
This is is used by merge directives.
794
return self._get_config_location('public_branch')
796
def set_public_branch(self, location):
797
"""Return the submit location of the branch.
799
This is the default location for bundle. The usual
800
pattern is that the user can override it by specifying a
803
self._set_config_location('public_branch', location)
805
def get_push_location(self):
806
"""Return the None or the location to push this branch to."""
807
push_loc = self.get_config().get_user_option('push_location')
810
def set_push_location(self, location):
811
"""Set a new push location for this branch."""
812
raise NotImplementedError(self.set_push_location)
814
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
815
"""Run the post_change_branch_tip hooks."""
816
hooks = Branch.hooks['post_change_branch_tip']
819
new_revno, new_revid = self.last_revision_info()
820
params = ChangeBranchTipParams(
821
self, old_revno, new_revno, old_revid, new_revid)
825
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
826
"""Run the pre_change_branch_tip hooks."""
827
hooks = Branch.hooks['pre_change_branch_tip']
830
old_revno, old_revid = self.last_revision_info()
831
params = ChangeBranchTipParams(
832
self, old_revno, new_revno, old_revid, new_revid)
836
except errors.TipChangeRejected:
839
exc_info = sys.exc_info()
840
hook_name = Branch.hooks.get_hook_name(hook)
841
raise errors.HookFailed(
842
'pre_change_branch_tip', hook_name, exc_info)
844
def set_parent(self, url):
845
raise NotImplementedError(self.set_parent)
849
"""Synchronise this branch with the master branch if any.
851
:return: None or the last_revision pivoted out during the update.
855
def check_revno(self, revno):
857
Check whether a revno corresponds to any revision.
858
Zero (the NULL revision) is considered valid.
861
self.check_real_revno(revno)
863
def check_real_revno(self, revno):
865
Check whether a revno corresponds to a real revision.
866
Zero (the NULL revision) is considered invalid
868
if revno < 1 or revno > self.revno():
869
raise errors.InvalidRevisionNumber(revno)
872
def clone(self, to_bzrdir, revision_id=None):
873
"""Clone this branch into to_bzrdir preserving all semantic values.
875
revision_id: if not None, the revision history in the new branch will
876
be truncated to end with revision_id.
878
result = to_bzrdir.create_branch()
879
self.copy_content_into(result, revision_id=revision_id)
883
def sprout(self, to_bzrdir, revision_id=None):
884
"""Create a new line of development from the branch, into to_bzrdir.
886
to_bzrdir controls the branch format.
888
revision_id: if not None, the revision history in the new branch will
889
be truncated to end with revision_id.
891
result = to_bzrdir.create_branch()
892
self.copy_content_into(result, revision_id=revision_id)
893
result.set_parent(self.bzrdir.root_transport.base)
896
def _synchronize_history(self, destination, revision_id):
897
"""Synchronize last revision and revision history between branches.
899
This version is most efficient when the destination is also a
900
BzrBranch6, but works for BzrBranch5, as long as the destination's
901
repository contains all the lefthand ancestors of the intended
902
last_revision. If not, set_last_revision_info will fail.
904
:param destination: The branch to copy the history into
905
:param revision_id: The revision-id to truncate history at. May
906
be None to copy complete history.
908
source_revno, source_revision_id = self.last_revision_info()
909
if revision_id is None:
910
revno, revision_id = source_revno, source_revision_id
911
elif source_revision_id == revision_id:
912
# we know the revno without needing to walk all of history
915
# To figure out the revno for a random revision, we need to build
916
# the revision history, and count its length.
917
# We don't care about the order, just how long it is.
918
# Alternatively, we could start at the current location, and count
919
# backwards. But there is no guarantee that we will find it since
920
# it may be a merged revision.
921
revno = len(list(self.repository.iter_reverse_revision_history(
923
destination.set_last_revision_info(revno, revision_id)
926
def copy_content_into(self, destination, revision_id=None):
927
"""Copy the content of self into destination.
929
revision_id: if not None, the revision history in the new branch will
930
be truncated to end with revision_id.
932
self._synchronize_history(destination, revision_id)
934
parent = self.get_parent()
935
except errors.InaccessibleParent, e:
936
mutter('parent was not accessible to copy: %s', e)
939
destination.set_parent(parent)
940
self.tags.merge_to(destination.tags)
944
"""Check consistency of the branch.
946
In particular this checks that revisions given in the revision-history
947
do actually match up in the revision graph, and that they're all
948
present in the repository.
950
Callers will typically also want to check the repository.
952
:return: A BranchCheckResult.
954
mainline_parent_id = None
955
last_revno, last_revision_id = self.last_revision_info()
956
real_rev_history = list(self.repository.iter_reverse_revision_history(
958
real_rev_history.reverse()
959
if len(real_rev_history) != last_revno:
960
raise errors.BzrCheckError('revno does not match len(mainline)'
961
' %s != %s' % (last_revno, len(real_rev_history)))
962
# TODO: We should probably also check that real_rev_history actually
963
# matches self.revision_history()
964
for revision_id in real_rev_history:
966
revision = self.repository.get_revision(revision_id)
967
except errors.NoSuchRevision, e:
968
raise errors.BzrCheckError("mainline revision {%s} not in repository"
970
# In general the first entry on the revision history has no parents.
971
# But it's not illegal for it to have parents listed; this can happen
972
# in imports from Arch when the parents weren't reachable.
973
if mainline_parent_id is not None:
974
if mainline_parent_id not in revision.parent_ids:
975
raise errors.BzrCheckError("previous revision {%s} not listed among "
977
% (mainline_parent_id, revision_id))
978
mainline_parent_id = revision_id
979
return BranchCheckResult(self)
981
def _get_checkout_format(self):
982
"""Return the most suitable metadir for a checkout of this branch.
983
Weaves are used if this branch's repository uses weaves.
985
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
986
from bzrlib.repofmt import weaverepo
987
format = bzrdir.BzrDirMetaFormat1()
988
format.repository_format = weaverepo.RepositoryFormat7()
990
format = self.repository.bzrdir.checkout_metadir()
991
format.set_branch_format(self._format)
994
def create_checkout(self, to_location, revision_id=None,
995
lightweight=False, accelerator_tree=None,
997
"""Create a checkout of a branch.
999
:param to_location: The url to produce the checkout at
1000
:param revision_id: The revision to check out
1001
:param lightweight: If True, produce a lightweight checkout, otherwise,
1002
produce a bound branch (heavyweight checkout)
1003
:param accelerator_tree: A tree which can be used for retrieving file
1004
contents more quickly than the revision tree, i.e. a workingtree.
1005
The revision tree will be used for cases where accelerator_tree's
1006
content is different.
1007
:param hardlink: If true, hard-link files from accelerator_tree,
1009
:return: The tree of the created checkout
1011
t = transport.get_transport(to_location)
1014
format = self._get_checkout_format()
1015
checkout = format.initialize_on_transport(t)
1016
from_branch = BranchReferenceFormat().initialize(checkout, self)
1018
format = self._get_checkout_format()
1019
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1020
to_location, force_new_tree=False, format=format)
1021
checkout = checkout_branch.bzrdir
1022
checkout_branch.bind(self)
1023
# pull up to the specified revision_id to set the initial
1024
# branch tip correctly, and seed it with history.
1025
checkout_branch.pull(self, stop_revision=revision_id)
1027
tree = checkout.create_workingtree(revision_id,
1028
from_branch=from_branch,
1029
accelerator_tree=accelerator_tree,
1031
basis_tree = tree.basis_tree()
1032
basis_tree.lock_read()
1034
for path, file_id in basis_tree.iter_references():
1035
reference_parent = self.reference_parent(file_id, path)
1036
reference_parent.create_checkout(tree.abspath(path),
1037
basis_tree.get_reference_revision(file_id, path),
1044
def reconcile(self, thorough=True):
1045
"""Make sure the data stored in this branch is consistent."""
1046
from bzrlib.reconcile import BranchReconciler
1047
reconciler = BranchReconciler(self, thorough=thorough)
1048
reconciler.reconcile()
1051
def reference_parent(self, file_id, path):
1052
"""Return the parent branch for a tree-reference file_id
1053
:param file_id: The file_id of the tree reference
1054
:param path: The path of the file_id in the tree
1055
:return: A branch associated with the file_id
1057
# FIXME should provide multiple branches, based on config
1058
return Branch.open(self.bzrdir.root_transport.clone(path).base)
1060
def supports_tags(self):
1061
return self._format.supports_tags()
1063
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1065
"""Ensure that revision_b is a descendant of revision_a.
1067
This is a helper function for update_revisions.
1069
:raises: DivergedBranches if revision_b has diverged from revision_a.
1070
:returns: True if revision_b is a descendant of revision_a.
1072
relation = self._revision_relations(revision_a, revision_b, graph)
1073
if relation == 'b_descends_from_a':
1075
elif relation == 'diverged':
1076
raise errors.DivergedBranches(self, other_branch)
1077
elif relation == 'a_descends_from_b':
1080
raise AssertionError("invalid relation: %r" % (relation,))
1082
def _revision_relations(self, revision_a, revision_b, graph):
1083
"""Determine the relationship between two revisions.
1085
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1087
heads = graph.heads([revision_a, revision_b])
1088
if heads == set([revision_b]):
1089
return 'b_descends_from_a'
1090
elif heads == set([revision_a, revision_b]):
1091
# These branches have diverged
1093
elif heads == set([revision_a]):
1094
return 'a_descends_from_b'
1096
raise AssertionError("invalid heads: %r" % (heads,))
1099
class BranchFormat(object):
1100
"""An encapsulation of the initialization and open routines for a format.
1102
Formats provide three things:
1103
* An initialization routine,
1107
Formats are placed in an dict by their format string for reference
1108
during branch opening. Its not required that these be instances, they
1109
can be classes themselves with class methods - it simply depends on
1110
whether state is needed for a given format or not.
1112
Once a format is deprecated, just deprecate the initialize and open
1113
methods on the format class. Do not deprecate the object, as the
1114
object will be created every time regardless.
1117
_default_format = None
1118
"""The default format used for new branches."""
1121
"""The known formats."""
1123
def __eq__(self, other):
1124
return self.__class__ is other.__class__
1126
def __ne__(self, other):
1127
return not (self == other)
1130
def find_format(klass, a_bzrdir):
1131
"""Return the format for the branch object in a_bzrdir."""
1133
transport = a_bzrdir.get_branch_transport(None)
1134
format_string = transport.get("format").read()
1135
return klass._formats[format_string]
1136
except errors.NoSuchFile:
1137
raise errors.NotBranchError(path=transport.base)
1139
raise errors.UnknownFormatError(format=format_string, kind='branch')
1142
def get_default_format(klass):
1143
"""Return the current default format."""
1144
return klass._default_format
1146
def get_reference(self, a_bzrdir):
1147
"""Get the target reference of the branch in a_bzrdir.
1149
format probing must have been completed before calling
1150
this method - it is assumed that the format of the branch
1151
in a_bzrdir is correct.
1153
:param a_bzrdir: The bzrdir to get the branch data from.
1154
:return: None if the branch is not a reference branch.
1159
def set_reference(self, a_bzrdir, to_branch):
1160
"""Set the target reference of the branch in a_bzrdir.
1162
format probing must have been completed before calling
1163
this method - it is assumed that the format of the branch
1164
in a_bzrdir is correct.
1166
:param a_bzrdir: The bzrdir to set the branch reference for.
1167
:param to_branch: branch that the checkout is to reference
1169
raise NotImplementedError(self.set_reference)
1171
def get_format_string(self):
1172
"""Return the ASCII format string that identifies this format."""
1173
raise NotImplementedError(self.get_format_string)
1175
def get_format_description(self):
1176
"""Return the short format description for this format."""
1177
raise NotImplementedError(self.get_format_description)
1179
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1181
"""Initialize a branch in a bzrdir, with specified files
1183
:param a_bzrdir: The bzrdir to initialize the branch in
1184
:param utf8_files: The files to create as a list of
1185
(filename, content) tuples
1186
:param set_format: If True, set the format with
1187
self.get_format_string. (BzrBranch4 has its format set
1189
:return: a branch in this format
1191
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1192
branch_transport = a_bzrdir.get_branch_transport(self)
1194
'metadir': ('lock', lockdir.LockDir),
1195
'branch4': ('branch-lock', lockable_files.TransportLock),
1197
lock_name, lock_class = lock_map[lock_type]
1198
control_files = lockable_files.LockableFiles(branch_transport,
1199
lock_name, lock_class)
1200
control_files.create_lock()
1201
control_files.lock_write()
1203
utf8_files += [('format', self.get_format_string())]
1205
for (filename, content) in utf8_files:
1206
branch_transport.put_bytes(
1208
mode=a_bzrdir._get_file_mode())
1210
control_files.unlock()
1211
return self.open(a_bzrdir, _found=True)
1213
def initialize(self, a_bzrdir):
1214
"""Create a branch of this format in a_bzrdir."""
1215
raise NotImplementedError(self.initialize)
1217
def is_supported(self):
1218
"""Is this format supported?
1220
Supported formats can be initialized and opened.
1221
Unsupported formats may not support initialization or committing or
1222
some other features depending on the reason for not being supported.
1226
def open(self, a_bzrdir, _found=False):
1227
"""Return the branch object for a_bzrdir
1229
_found is a private parameter, do not use it. It is used to indicate
1230
if format probing has already be done.
1232
raise NotImplementedError(self.open)
1235
def register_format(klass, format):
1236
klass._formats[format.get_format_string()] = format
1239
def set_default_format(klass, format):
1240
klass._default_format = format
1242
def supports_stacking(self):
1243
"""True if this format records a stacked-on branch."""
1247
def unregister_format(klass, format):
1248
del klass._formats[format.get_format_string()]
1251
return self.get_format_string().rstrip()
1253
def supports_tags(self):
1254
"""True if this format supports tags stored in the branch"""
1255
return False # by default
1258
class BranchHooks(Hooks):
1259
"""A dictionary mapping hook name to a list of callables for branch hooks.
1261
e.g. ['set_rh'] Is the list of items to be called when the
1262
set_revision_history function is invoked.
1266
"""Create the default hooks.
1268
These are all empty initially, because by default nothing should get
1271
Hooks.__init__(self)
1272
# Introduced in 0.15:
1273
# invoked whenever the revision history has been set
1274
# with set_revision_history. The api signature is
1275
# (branch, revision_history), and the branch will
1278
# Invoked after a branch is opened. The api signature is (branch).
1280
# invoked after a push operation completes.
1281
# the api signature is
1283
# containing the members
1284
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1285
# where local is the local target branch or None, master is the target
1286
# master branch, and the rest should be self explanatory. The source
1287
# is read locked and the target branches write locked. Source will
1288
# be the local low-latency branch.
1289
self['post_push'] = []
1290
# invoked after a pull operation completes.
1291
# the api signature is
1293
# containing the members
1294
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1295
# where local is the local branch or None, master is the target
1296
# master branch, and the rest should be self explanatory. The source
1297
# is read locked and the target branches write locked. The local
1298
# branch is the low-latency branch.
1299
self['post_pull'] = []
1300
# invoked before a commit operation takes place.
1301
# the api signature is
1302
# (local, master, old_revno, old_revid, future_revno, future_revid,
1303
# tree_delta, future_tree).
1304
# old_revid is NULL_REVISION for the first commit to a branch
1305
# tree_delta is a TreeDelta object describing changes from the basis
1306
# revision, hooks MUST NOT modify this delta
1307
# future_tree is an in-memory tree obtained from
1308
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1309
self['pre_commit'] = []
1310
# invoked after a commit operation completes.
1311
# the api signature is
1312
# (local, master, old_revno, old_revid, new_revno, new_revid)
1313
# old_revid is NULL_REVISION for the first commit to a branch.
1314
self['post_commit'] = []
1315
# invoked after a uncommit operation completes.
1316
# the api signature is
1317
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1318
# local is the local branch or None, master is the target branch,
1319
# and an empty branch recieves new_revno of 0, new_revid of None.
1320
self['post_uncommit'] = []
1322
# Invoked before the tip of a branch changes.
1323
# the api signature is
1324
# (params) where params is a ChangeBranchTipParams with the members
1325
# (branch, old_revno, new_revno, old_revid, new_revid)
1326
self['pre_change_branch_tip'] = []
1328
# Invoked after the tip of a branch changes.
1329
# the api signature is
1330
# (params) where params is a ChangeBranchTipParams with the members
1331
# (branch, old_revno, new_revno, old_revid, new_revid)
1332
self['post_change_branch_tip'] = []
1334
# Invoked when a stacked branch activates its fallback locations and
1335
# allows the transformation of the url of said location.
1336
# the api signature is
1337
# (branch, url) where branch is the branch having its fallback
1338
# location activated and url is the url for the fallback location.
1339
# The hook should return a url.
1340
self['transform_fallback_location'] = []
1343
# install the default hooks into the Branch class.
1344
Branch.hooks = BranchHooks()
1347
class ChangeBranchTipParams(object):
1348
"""Object holding parameters passed to *_change_branch_tip hooks.
1350
There are 5 fields that hooks may wish to access:
1352
:ivar branch: the branch being changed
1353
:ivar old_revno: revision number before the change
1354
:ivar new_revno: revision number after the change
1355
:ivar old_revid: revision id before the change
1356
:ivar new_revid: revision id after the change
1358
The revid fields are strings. The revno fields are integers.
1361
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1362
"""Create a group of ChangeBranchTip parameters.
1364
:param branch: The branch being changed.
1365
:param old_revno: Revision number before the change.
1366
:param new_revno: Revision number after the change.
1367
:param old_revid: Tip revision id before the change.
1368
:param new_revid: Tip revision id after the change.
1370
self.branch = branch
1371
self.old_revno = old_revno
1372
self.new_revno = new_revno
1373
self.old_revid = old_revid
1374
self.new_revid = new_revid
1376
def __eq__(self, other):
1377
return self.__dict__ == other.__dict__
1380
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1381
self.__class__.__name__, self.branch,
1382
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1385
class BzrBranchFormat4(BranchFormat):
1386
"""Bzr branch format 4.
1389
- a revision-history file.
1390
- a branch-lock lock file [ to be shared with the bzrdir ]
1393
def get_format_description(self):
1394
"""See BranchFormat.get_format_description()."""
1395
return "Branch format 4"
1397
def initialize(self, a_bzrdir):
1398
"""Create a branch of this format in a_bzrdir."""
1399
utf8_files = [('revision-history', ''),
1400
('branch-name', ''),
1402
return self._initialize_helper(a_bzrdir, utf8_files,
1403
lock_type='branch4', set_format=False)
1406
super(BzrBranchFormat4, self).__init__()
1407
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1409
def open(self, a_bzrdir, _found=False):
1410
"""Return the branch object for a_bzrdir
1412
_found is a private parameter, do not use it. It is used to indicate
1413
if format probing has already be done.
1416
# we are being called directly and must probe.
1417
raise NotImplementedError
1418
return BzrBranch(_format=self,
1419
_control_files=a_bzrdir._control_files,
1421
_repository=a_bzrdir.open_repository())
1424
return "Bazaar-NG branch format 4"
1427
class BranchFormatMetadir(BranchFormat):
1428
"""Common logic for meta-dir based branch formats."""
1430
def _branch_class(self):
1431
"""What class to instantiate on open calls."""
1432
raise NotImplementedError(self._branch_class)
1434
def open(self, a_bzrdir, _found=False):
1435
"""Return the branch object for a_bzrdir.
1437
_found is a private parameter, do not use it. It is used to indicate
1438
if format probing has already be done.
1441
format = BranchFormat.find_format(a_bzrdir)
1442
if format.__class__ != self.__class__:
1443
raise AssertionError("wrong format %r found for %r" %
1446
transport = a_bzrdir.get_branch_transport(None)
1447
control_files = lockable_files.LockableFiles(transport, 'lock',
1449
return self._branch_class()(_format=self,
1450
_control_files=control_files,
1452
_repository=a_bzrdir.find_repository())
1453
except errors.NoSuchFile:
1454
raise errors.NotBranchError(path=transport.base)
1457
super(BranchFormatMetadir, self).__init__()
1458
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1459
self._matchingbzrdir.set_branch_format(self)
1461
def supports_tags(self):
1465
class BzrBranchFormat5(BranchFormatMetadir):
1466
"""Bzr branch format 5.
1469
- a revision-history file.
1471
- a lock dir guarding the branch itself
1472
- all of this stored in a branch/ subdirectory
1473
- works with shared repositories.
1475
This format is new in bzr 0.8.
1478
def _branch_class(self):
1481
def get_format_string(self):
1482
"""See BranchFormat.get_format_string()."""
1483
return "Bazaar-NG branch format 5\n"
1485
def get_format_description(self):
1486
"""See BranchFormat.get_format_description()."""
1487
return "Branch format 5"
1489
def initialize(self, a_bzrdir):
1490
"""Create a branch of this format in a_bzrdir."""
1491
utf8_files = [('revision-history', ''),
1492
('branch-name', ''),
1494
return self._initialize_helper(a_bzrdir, utf8_files)
1496
def supports_tags(self):
1500
class BzrBranchFormat6(BranchFormatMetadir):
1501
"""Branch format with last-revision and tags.
1503
Unlike previous formats, this has no explicit revision history. Instead,
1504
this just stores the last-revision, and the left-hand history leading
1505
up to there is the history.
1507
This format was introduced in bzr 0.15
1508
and became the default in 0.91.
1511
def _branch_class(self):
1514
def get_format_string(self):
1515
"""See BranchFormat.get_format_string()."""
1516
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1518
def get_format_description(self):
1519
"""See BranchFormat.get_format_description()."""
1520
return "Branch format 6"
1522
def initialize(self, a_bzrdir):
1523
"""Create a branch of this format in a_bzrdir."""
1524
utf8_files = [('last-revision', '0 null:\n'),
1525
('branch.conf', ''),
1528
return self._initialize_helper(a_bzrdir, utf8_files)
1531
class BzrBranchFormat7(BranchFormatMetadir):
1532
"""Branch format with last-revision, tags, and a stacked location pointer.
1534
The stacked location pointer is passed down to the repository and requires
1535
a repository format with supports_external_lookups = True.
1537
This format was introduced in bzr 1.6.
1540
def _branch_class(self):
1543
def get_format_string(self):
1544
"""See BranchFormat.get_format_string()."""
1545
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
1547
def get_format_description(self):
1548
"""See BranchFormat.get_format_description()."""
1549
return "Branch format 7"
1551
def initialize(self, a_bzrdir):
1552
"""Create a branch of this format in a_bzrdir."""
1553
utf8_files = [('last-revision', '0 null:\n'),
1554
('branch.conf', ''),
1557
return self._initialize_helper(a_bzrdir, utf8_files)
1560
super(BzrBranchFormat7, self).__init__()
1561
self._matchingbzrdir.repository_format = \
1562
RepositoryFormatKnitPack5RichRoot()
1564
def supports_stacking(self):
1568
class BranchReferenceFormat(BranchFormat):
1569
"""Bzr branch reference format.
1571
Branch references are used in implementing checkouts, they
1572
act as an alias to the real branch which is at some other url.
1579
def get_format_string(self):
1580
"""See BranchFormat.get_format_string()."""
1581
return "Bazaar-NG Branch Reference Format 1\n"
1583
def get_format_description(self):
1584
"""See BranchFormat.get_format_description()."""
1585
return "Checkout reference format 1"
1587
def get_reference(self, a_bzrdir):
1588
"""See BranchFormat.get_reference()."""
1589
transport = a_bzrdir.get_branch_transport(None)
1590
return transport.get('location').read()
1592
def set_reference(self, a_bzrdir, to_branch):
1593
"""See BranchFormat.set_reference()."""
1594
transport = a_bzrdir.get_branch_transport(None)
1595
location = transport.put_bytes('location', to_branch.base)
1597
def initialize(self, a_bzrdir, target_branch=None):
1598
"""Create a branch of this format in a_bzrdir."""
1599
if target_branch is None:
1600
# this format does not implement branch itself, thus the implicit
1601
# creation contract must see it as uninitializable
1602
raise errors.UninitializableFormat(self)
1603
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1604
branch_transport = a_bzrdir.get_branch_transport(self)
1605
branch_transport.put_bytes('location',
1606
target_branch.bzrdir.root_transport.base)
1607
branch_transport.put_bytes('format', self.get_format_string())
1609
a_bzrdir, _found=True,
1610
possible_transports=[target_branch.bzrdir.root_transport])
1613
super(BranchReferenceFormat, self).__init__()
1614
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1615
self._matchingbzrdir.set_branch_format(self)
1617
def _make_reference_clone_function(format, a_branch):
1618
"""Create a clone() routine for a branch dynamically."""
1619
def clone(to_bzrdir, revision_id=None):
1620
"""See Branch.clone()."""
1621
return format.initialize(to_bzrdir, a_branch)
1622
# cannot obey revision_id limits when cloning a reference ...
1623
# FIXME RBC 20060210 either nuke revision_id for clone, or
1624
# emit some sort of warning/error to the caller ?!
1627
def open(self, a_bzrdir, _found=False, location=None,
1628
possible_transports=None):
1629
"""Return the branch that the branch reference in a_bzrdir points at.
1631
_found is a private parameter, do not use it. It is used to indicate
1632
if format probing has already be done.
1635
format = BranchFormat.find_format(a_bzrdir)
1636
if format.__class__ != self.__class__:
1637
raise AssertionError("wrong format %r found for %r" %
1639
if location is None:
1640
location = self.get_reference(a_bzrdir)
1641
real_bzrdir = bzrdir.BzrDir.open(
1642
location, possible_transports=possible_transports)
1643
result = real_bzrdir.open_branch()
1644
# this changes the behaviour of result.clone to create a new reference
1645
# rather than a copy of the content of the branch.
1646
# I did not use a proxy object because that needs much more extensive
1647
# testing, and we are only changing one behaviour at the moment.
1648
# If we decide to alter more behaviours - i.e. the implicit nickname
1649
# then this should be refactored to introduce a tested proxy branch
1650
# and a subclass of that for use in overriding clone() and ....
1652
result.clone = self._make_reference_clone_function(result)
1656
# formats which have no format string are not discoverable
1657
# and not independently creatable, so are not registered.
1658
__format5 = BzrBranchFormat5()
1659
__format6 = BzrBranchFormat6()
1660
__format7 = BzrBranchFormat7()
1661
BranchFormat.register_format(__format5)
1662
BranchFormat.register_format(BranchReferenceFormat())
1663
BranchFormat.register_format(__format6)
1664
BranchFormat.register_format(__format7)
1665
BranchFormat.set_default_format(__format6)
1666
_legacy_formats = [BzrBranchFormat4(),
1669
class BzrBranch(Branch):
1670
"""A branch stored in the actual filesystem.
1672
Note that it's "local" in the context of the filesystem; it doesn't
1673
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1674
it's writable, and can be accessed via the normal filesystem API.
1676
:ivar _transport: Transport for file operations on this branch's
1677
control files, typically pointing to the .bzr/branch directory.
1678
:ivar repository: Repository for this branch.
1679
:ivar base: The url of the base directory for this branch; the one
1680
containing the .bzr directory.
1683
def __init__(self, _format=None,
1684
_control_files=None, a_bzrdir=None, _repository=None):
1685
"""Create new branch object at a particular location."""
1686
if a_bzrdir is None:
1687
raise ValueError('a_bzrdir must be supplied')
1689
self.bzrdir = a_bzrdir
1690
self._base = self.bzrdir.transport.clone('..').base
1691
# XXX: We should be able to just do
1692
# self.base = self.bzrdir.root_transport.base
1693
# but this does not quite work yet -- mbp 20080522
1694
self._format = _format
1695
if _control_files is None:
1696
raise ValueError('BzrBranch _control_files is None')
1697
self.control_files = _control_files
1698
self._transport = _control_files._transport
1699
self.repository = _repository
1700
Branch.__init__(self)
1703
return '%s(%r)' % (self.__class__.__name__, self.base)
1707
def _get_base(self):
1708
"""Returns the directory containing the control directory."""
1711
base = property(_get_base, doc="The URL for the root of this branch.")
1713
def is_locked(self):
1714
return self.control_files.is_locked()
1716
def lock_write(self, token=None):
1717
repo_token = self.repository.lock_write()
1719
token = self.control_files.lock_write(token=token)
1721
self.repository.unlock()
1725
def lock_read(self):
1726
self.repository.lock_read()
1728
self.control_files.lock_read()
1730
self.repository.unlock()
1734
# TODO: test for failed two phase locks. This is known broken.
1736
self.control_files.unlock()
1738
self.repository.unlock()
1739
if not self.control_files.is_locked():
1740
# we just released the lock
1741
self._clear_cached_state()
1743
def peek_lock_mode(self):
1744
if self.control_files._lock_count == 0:
1747
return self.control_files._lock_mode
1749
def get_physical_lock_status(self):
1750
return self.control_files.get_physical_lock_status()
1753
def print_file(self, file, revision_id):
1754
"""See Branch.print_file."""
1755
return self.repository.print_file(file, revision_id)
1757
def _write_revision_history(self, history):
1758
"""Factored out of set_revision_history.
1760
This performs the actual writing to disk.
1761
It is intended to be called by BzrBranch5.set_revision_history."""
1762
self._transport.put_bytes(
1763
'revision-history', '\n'.join(history),
1764
mode=self.bzrdir._get_file_mode())
1767
def set_revision_history(self, rev_history):
1768
"""See Branch.set_revision_history."""
1769
if 'evil' in debug.debug_flags:
1770
mutter_callsite(3, "set_revision_history scales with history.")
1771
check_not_reserved_id = _mod_revision.check_not_reserved_id
1772
for rev_id in rev_history:
1773
check_not_reserved_id(rev_id)
1774
if Branch.hooks['post_change_branch_tip']:
1775
# Don't calculate the last_revision_info() if there are no hooks
1777
old_revno, old_revid = self.last_revision_info()
1778
if len(rev_history) == 0:
1779
revid = _mod_revision.NULL_REVISION
1781
revid = rev_history[-1]
1782
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1783
self._write_revision_history(rev_history)
1784
self._clear_cached_state()
1785
self._cache_revision_history(rev_history)
1786
for hook in Branch.hooks['set_rh']:
1787
hook(self, rev_history)
1788
if Branch.hooks['post_change_branch_tip']:
1789
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1791
def _synchronize_history(self, destination, revision_id):
1792
"""Synchronize last revision and revision history between branches.
1794
This version is most efficient when the destination is also a
1795
BzrBranch5, but works for BzrBranch6 as long as the revision
1796
history is the true lefthand parent history, and all of the revisions
1797
are in the destination's repository. If not, set_revision_history
1800
:param destination: The branch to copy the history into
1801
:param revision_id: The revision-id to truncate history at. May
1802
be None to copy complete history.
1804
if not isinstance(destination._format, BzrBranchFormat5):
1805
super(BzrBranch, self)._synchronize_history(
1806
destination, revision_id)
1808
if revision_id == _mod_revision.NULL_REVISION:
1811
new_history = self.revision_history()
1812
if revision_id is not None and new_history != []:
1814
new_history = new_history[:new_history.index(revision_id) + 1]
1816
rev = self.repository.get_revision(revision_id)
1817
new_history = rev.get_history(self.repository)[1:]
1818
destination.set_revision_history(new_history)
1821
def set_last_revision_info(self, revno, revision_id):
1822
"""Set the last revision of this branch.
1824
The caller is responsible for checking that the revno is correct
1825
for this revision id.
1827
It may be possible to set the branch last revision to an id not
1828
present in the repository. However, branches can also be
1829
configured to check constraints on history, in which case this may not
1832
revision_id = _mod_revision.ensure_null(revision_id)
1833
# this old format stores the full history, but this api doesn't
1834
# provide it, so we must generate, and might as well check it's
1836
history = self._lefthand_history(revision_id)
1837
if len(history) != revno:
1838
raise AssertionError('%d != %d' % (len(history), revno))
1839
self.set_revision_history(history)
1841
def _gen_revision_history(self):
1842
history = self._transport.get_bytes('revision-history').split('\n')
1843
if history[-1:] == ['']:
1844
# There shouldn't be a trailing newline, but just in case.
1849
def generate_revision_history(self, revision_id, last_rev=None,
1851
"""Create a new revision history that will finish with revision_id.
1853
:param revision_id: the new tip to use.
1854
:param last_rev: The previous last_revision. If not None, then this
1855
must be a ancestory of revision_id, or DivergedBranches is raised.
1856
:param other_branch: The other branch that DivergedBranches should
1857
raise with respect to.
1859
self.set_revision_history(self._lefthand_history(revision_id,
1860
last_rev, other_branch))
1862
def basis_tree(self):
1863
"""See Branch.basis_tree."""
1864
return self.repository.revision_tree(self.last_revision())
1867
def pull(self, source, overwrite=False, stop_revision=None,
1868
_hook_master=None, run_hooks=True, possible_transports=None,
1869
_override_hook_target=None):
1872
:param _hook_master: Private parameter - set the branch to
1873
be supplied as the master to pull hooks.
1874
:param run_hooks: Private parameter - if false, this branch
1875
is being called because it's the master of the primary branch,
1876
so it should not run its hooks.
1877
:param _override_hook_target: Private parameter - set the branch to be
1878
supplied as the target_branch to pull hooks.
1880
result = PullResult()
1881
result.source_branch = source
1882
if _override_hook_target is None:
1883
result.target_branch = self
1885
result.target_branch = _override_hook_target
1888
# We assume that during 'pull' the local repository is closer than
1890
graph = self.repository.get_graph(source.repository)
1891
result.old_revno, result.old_revid = self.last_revision_info()
1892
self.update_revisions(source, stop_revision, overwrite=overwrite,
1894
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1895
result.new_revno, result.new_revid = self.last_revision_info()
1897
result.master_branch = _hook_master
1898
result.local_branch = result.target_branch
1900
result.master_branch = result.target_branch
1901
result.local_branch = None
1903
for hook in Branch.hooks['post_pull']:
1909
def _get_parent_location(self):
1910
_locs = ['parent', 'pull', 'x-pull']
1913
return self._transport.get_bytes(l).strip('\n')
1914
except errors.NoSuchFile:
1919
def push(self, target, overwrite=False, stop_revision=None,
1920
_override_hook_source_branch=None):
1923
This is the basic concrete implementation of push()
1925
:param _override_hook_source_branch: If specified, run
1926
the hooks passing this Branch as the source, rather than self.
1927
This is for use of RemoteBranch, where push is delegated to the
1928
underlying vfs-based Branch.
1930
# TODO: Public option to disable running hooks - should be trivial but
1932
return _run_with_write_locked_target(
1933
target, self._push_with_bound_branches, target, overwrite,
1935
_override_hook_source_branch=_override_hook_source_branch)
1937
def _push_with_bound_branches(self, target, overwrite,
1939
_override_hook_source_branch=None):
1940
"""Push from self into target, and into target's master if any.
1942
This is on the base BzrBranch class even though it doesn't support
1943
bound branches because the *target* might be bound.
1946
if _override_hook_source_branch:
1947
result.source_branch = _override_hook_source_branch
1948
for hook in Branch.hooks['post_push']:
1951
bound_location = target.get_bound_location()
1952
if bound_location and target.base != bound_location:
1953
# there is a master branch.
1955
# XXX: Why the second check? Is it even supported for a branch to
1956
# be bound to itself? -- mbp 20070507
1957
master_branch = target.get_master_branch()
1958
master_branch.lock_write()
1960
# push into the master from this branch.
1961
self._basic_push(master_branch, overwrite, stop_revision)
1962
# and push into the target branch from this. Note that we push from
1963
# this branch again, because its considered the highest bandwidth
1965
result = self._basic_push(target, overwrite, stop_revision)
1966
result.master_branch = master_branch
1967
result.local_branch = target
1971
master_branch.unlock()
1974
result = self._basic_push(target, overwrite, stop_revision)
1975
# TODO: Why set master_branch and local_branch if there's no
1976
# binding? Maybe cleaner to just leave them unset? -- mbp
1978
result.master_branch = target
1979
result.local_branch = None
1983
def _basic_push(self, target, overwrite, stop_revision):
1984
"""Basic implementation of push without bound branches or hooks.
1986
Must be called with self read locked and target write locked.
1988
result = PushResult()
1989
result.source_branch = self
1990
result.target_branch = target
1991
result.old_revno, result.old_revid = target.last_revision_info()
1992
if result.old_revid != self.last_revision():
1993
# We assume that during 'push' this repository is closer than
1995
graph = self.repository.get_graph(target.repository)
1996
target.update_revisions(self, stop_revision, overwrite=overwrite,
1998
if self._push_should_merge_tags():
1999
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2000
result.new_revno, result.new_revid = target.last_revision_info()
2003
def _push_should_merge_tags(self):
2004
"""Should _basic_push merge this branch's tags into the target?
2006
The default implementation returns False if this branch has no tags,
2007
and True the rest of the time. Subclasses may override this.
2009
return self.tags.supports_tags() and self.tags.get_tag_dict()
2011
def get_parent(self):
2012
"""See Branch.get_parent."""
2013
parent = self._get_parent_location()
2016
# This is an old-format absolute path to a local branch
2017
# turn it into a url
2018
if parent.startswith('/'):
2019
parent = urlutils.local_path_to_url(parent.decode('utf8'))
2021
return urlutils.join(self.base[:-1], parent)
2022
except errors.InvalidURLJoin, e:
2023
raise errors.InaccessibleParent(parent, self.base)
2025
def get_stacked_on_url(self):
2026
raise errors.UnstackableBranchFormat(self._format, self.base)
2028
def set_push_location(self, location):
2029
"""See Branch.set_push_location."""
2030
self.get_config().set_user_option(
2031
'push_location', location,
2032
store=_mod_config.STORE_LOCATION_NORECURSE)
2035
def set_parent(self, url):
2036
"""See Branch.set_parent."""
2037
# TODO: Maybe delete old location files?
2038
# URLs should never be unicode, even on the local fs,
2039
# FIXUP this and get_parent in a future branch format bump:
2040
# read and rewrite the file. RBC 20060125
2042
if isinstance(url, unicode):
2044
url = url.encode('ascii')
2045
except UnicodeEncodeError:
2046
raise errors.InvalidURL(url,
2047
"Urls must be 7-bit ascii, "
2048
"use bzrlib.urlutils.escape")
2049
url = urlutils.relative_url(self.base, url)
2050
self._set_parent_location(url)
2052
def _set_parent_location(self, url):
2054
self._transport.delete('parent')
2056
self._transport.put_bytes('parent', url + '\n',
2057
mode=self.bzrdir._get_file_mode())
2059
def set_stacked_on_url(self, url):
2060
raise errors.UnstackableBranchFormat(self._format, self.base)
2063
class BzrBranch5(BzrBranch):
2064
"""A format 5 branch. This supports new features over plain branches.
2066
It has support for a master_branch which is the data for bound branches.
2070
def pull(self, source, overwrite=False, stop_revision=None,
2071
run_hooks=True, possible_transports=None,
2072
_override_hook_target=None):
2073
"""Pull from source into self, updating my master if any.
2075
:param run_hooks: Private parameter - if false, this branch
2076
is being called because it's the master of the primary branch,
2077
so it should not run its hooks.
2079
bound_location = self.get_bound_location()
2080
master_branch = None
2081
if bound_location and source.base != bound_location:
2082
# not pulling from master, so we need to update master.
2083
master_branch = self.get_master_branch(possible_transports)
2084
master_branch.lock_write()
2087
# pull from source into master.
2088
master_branch.pull(source, overwrite, stop_revision,
2090
return super(BzrBranch5, self).pull(source, overwrite,
2091
stop_revision, _hook_master=master_branch,
2092
run_hooks=run_hooks,
2093
_override_hook_target=_override_hook_target)
2096
master_branch.unlock()
2098
def get_bound_location(self):
2100
return self._transport.get_bytes('bound')[:-1]
2101
except errors.NoSuchFile:
2105
def get_master_branch(self, possible_transports=None):
2106
"""Return the branch we are bound to.
2108
:return: Either a Branch, or None
2110
This could memoise the branch, but if thats done
2111
it must be revalidated on each new lock.
2112
So for now we just don't memoise it.
2113
# RBC 20060304 review this decision.
2115
bound_loc = self.get_bound_location()
2119
return Branch.open(bound_loc,
2120
possible_transports=possible_transports)
2121
except (errors.NotBranchError, errors.ConnectionError), e:
2122
raise errors.BoundBranchConnectionFailure(
2126
def set_bound_location(self, location):
2127
"""Set the target where this branch is bound to.
2129
:param location: URL to the target branch
2132
self._transport.put_bytes('bound', location+'\n',
2133
mode=self.bzrdir._get_file_mode())
2136
self._transport.delete('bound')
2137
except errors.NoSuchFile:
2142
def bind(self, other):
2143
"""Bind this branch to the branch other.
2145
This does not push or pull data between the branches, though it does
2146
check for divergence to raise an error when the branches are not
2147
either the same, or one a prefix of the other. That behaviour may not
2148
be useful, so that check may be removed in future.
2150
:param other: The branch to bind to
2153
# TODO: jam 20051230 Consider checking if the target is bound
2154
# It is debatable whether you should be able to bind to
2155
# a branch which is itself bound.
2156
# Committing is obviously forbidden,
2157
# but binding itself may not be.
2158
# Since we *have* to check at commit time, we don't
2159
# *need* to check here
2161
# we want to raise diverged if:
2162
# last_rev is not in the other_last_rev history, AND
2163
# other_last_rev is not in our history, and do it without pulling
2165
self.set_bound_location(other.base)
2169
"""If bound, unbind"""
2170
return self.set_bound_location(None)
2173
def update(self, possible_transports=None):
2174
"""Synchronise this branch with the master branch if any.
2176
:return: None or the last_revision that was pivoted out during the
2179
master = self.get_master_branch(possible_transports)
2180
if master is not None:
2181
old_tip = _mod_revision.ensure_null(self.last_revision())
2182
self.pull(master, overwrite=True)
2183
if self.repository.get_graph().is_ancestor(old_tip,
2184
_mod_revision.ensure_null(self.last_revision())):
2190
class BzrBranch7(BzrBranch5):
2191
"""A branch with support for a fallback repository."""
2193
def _get_fallback_repository(self, url):
2194
"""Get the repository we fallback to at url."""
2195
url = urlutils.join(self.base, url)
2196
a_bzrdir = bzrdir.BzrDir.open(url,
2197
possible_transports=[self._transport])
2198
return a_bzrdir.open_branch().repository
2200
def _activate_fallback_location(self, url):
2201
"""Activate the branch/repository from url as a fallback repository."""
2202
self.repository.add_fallback_repository(
2203
self._get_fallback_repository(url))
2205
def _open_hook(self):
2207
url = self.get_stacked_on_url()
2208
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2209
errors.UnstackableBranchFormat):
2212
for hook in Branch.hooks['transform_fallback_location']:
2213
url = hook(self, url)
2215
hook_name = Branch.hooks.get_hook_name(hook)
2216
raise AssertionError(
2217
"'transform_fallback_location' hook %s returned "
2218
"None, not a URL." % hook_name)
2219
self._activate_fallback_location(url)
2221
def _check_stackable_repo(self):
2222
if not self.repository._format.supports_external_lookups:
2223
raise errors.UnstackableRepositoryFormat(self.repository._format,
2224
self.repository.base)
2226
def __init__(self, *args, **kwargs):
2227
super(BzrBranch7, self).__init__(*args, **kwargs)
2228
self._last_revision_info_cache = None
2229
self._partial_revision_history_cache = []
2231
def _clear_cached_state(self):
2232
super(BzrBranch7, self)._clear_cached_state()
2233
self._last_revision_info_cache = None
2234
self._partial_revision_history_cache = []
2236
def _last_revision_info(self):
2237
revision_string = self._transport.get_bytes('last-revision')
2238
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2239
revision_id = cache_utf8.get_cached_utf8(revision_id)
2241
return revno, revision_id
2243
def _write_last_revision_info(self, revno, revision_id):
2244
"""Simply write out the revision id, with no checks.
2246
Use set_last_revision_info to perform this safely.
2248
Does not update the revision_history cache.
2249
Intended to be called by set_last_revision_info and
2250
_write_revision_history.
2252
revision_id = _mod_revision.ensure_null(revision_id)
2253
out_string = '%d %s\n' % (revno, revision_id)
2254
self._transport.put_bytes('last-revision', out_string,
2255
mode=self.bzrdir._get_file_mode())
2258
def set_last_revision_info(self, revno, revision_id):
2259
revision_id = _mod_revision.ensure_null(revision_id)
2260
old_revno, old_revid = self.last_revision_info()
2261
if self._get_append_revisions_only():
2262
self._check_history_violation(revision_id)
2263
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2264
self._write_last_revision_info(revno, revision_id)
2265
self._clear_cached_state()
2266
self._last_revision_info_cache = revno, revision_id
2267
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2269
def _synchronize_history(self, destination, revision_id):
2270
"""Synchronize last revision and revision history between branches.
2272
:see: Branch._synchronize_history
2274
# XXX: The base Branch has a fast implementation of this method based
2275
# on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2276
# that uses set_revision_history. This class inherits from BzrBranch5,
2277
# but wants the fast implementation, so it calls
2278
# Branch._synchronize_history directly.
2279
Branch._synchronize_history(self, destination, revision_id)
2281
def _check_history_violation(self, revision_id):
2282
last_revision = _mod_revision.ensure_null(self.last_revision())
2283
if _mod_revision.is_null(last_revision):
2285
if last_revision not in self._lefthand_history(revision_id):
2286
raise errors.AppendRevisionsOnlyViolation(self.base)
2288
def _gen_revision_history(self):
2289
"""Generate the revision history from last revision
2291
last_revno, last_revision = self.last_revision_info()
2292
self._extend_partial_history(stop_index=last_revno-1)
2293
return list(reversed(self._partial_revision_history_cache))
2295
def _extend_partial_history(self, stop_index=None, stop_revision=None):
2296
"""Extend the partial history to include a given index
2298
If a stop_index is supplied, stop when that index has been reached.
2299
If a stop_revision is supplied, stop when that revision is
2300
encountered. Otherwise, stop when the beginning of history is
2303
:param stop_index: The index which should be present. When it is
2304
present, history extension will stop.
2305
:param revision_id: The revision id which should be present. When
2306
it is encountered, history extension will stop.
2308
repo = self.repository
2309
if len(self._partial_revision_history_cache) == 0:
2310
iterator = repo.iter_reverse_revision_history(self.last_revision())
2312
start_revision = self._partial_revision_history_cache[-1]
2313
iterator = repo.iter_reverse_revision_history(start_revision)
2314
#skip the last revision in the list
2315
next_revision = iterator.next()
2316
for revision_id in iterator:
2317
self._partial_revision_history_cache.append(revision_id)
2318
if (stop_index is not None and
2319
len(self._partial_revision_history_cache) > stop_index):
2321
if revision_id == stop_revision:
2324
def _write_revision_history(self, history):
2325
"""Factored out of set_revision_history.
2327
This performs the actual writing to disk, with format-specific checks.
2328
It is intended to be called by BzrBranch5.set_revision_history.
2330
if len(history) == 0:
2331
last_revision = 'null:'
2333
if history != self._lefthand_history(history[-1]):
2334
raise errors.NotLefthandHistory(history)
2335
last_revision = history[-1]
2336
if self._get_append_revisions_only():
2337
self._check_history_violation(last_revision)
2338
self._write_last_revision_info(len(history), last_revision)
2341
def _set_parent_location(self, url):
2342
"""Set the parent branch"""
2343
self._set_config_location('parent_location', url, make_relative=True)
2346
def _get_parent_location(self):
2347
"""Set the parent branch"""
2348
return self._get_config_location('parent_location')
2350
def set_push_location(self, location):
2351
"""See Branch.set_push_location."""
2352
self._set_config_location('push_location', location)
2354
def set_bound_location(self, location):
2355
"""See Branch.set_push_location."""
2357
config = self.get_config()
2358
if location is None:
2359
if config.get_user_option('bound') != 'True':
2362
config.set_user_option('bound', 'False', warn_masked=True)
2365
self._set_config_location('bound_location', location,
2367
config.set_user_option('bound', 'True', warn_masked=True)
2370
def _get_bound_location(self, bound):
2371
"""Return the bound location in the config file.
2373
Return None if the bound parameter does not match"""
2374
config = self.get_config()
2375
config_bound = (config.get_user_option('bound') == 'True')
2376
if config_bound != bound:
2378
return self._get_config_location('bound_location', config=config)
2380
def get_bound_location(self):
2381
"""See Branch.set_push_location."""
2382
return self._get_bound_location(True)
2384
def get_old_bound_location(self):
2385
"""See Branch.get_old_bound_location"""
2386
return self._get_bound_location(False)
2388
def get_stacked_on_url(self):
2389
# you can always ask for the URL; but you might not be able to use it
2390
# if the repo can't support stacking.
2391
## self._check_stackable_repo()
2392
stacked_url = self._get_config_location('stacked_on_location')
2393
if stacked_url is None:
2394
raise errors.NotStacked(self)
2397
def set_append_revisions_only(self, enabled):
2402
self.get_config().set_user_option('append_revisions_only', value,
2405
def set_stacked_on_url(self, url):
2406
self._check_stackable_repo()
2409
old_url = self.get_stacked_on_url()
2410
except (errors.NotStacked, errors.UnstackableBranchFormat,
2411
errors.UnstackableRepositoryFormat):
2414
# repositories don't offer an interface to remove fallback
2415
# repositories today; take the conceptually simpler option and just
2417
self.repository = self.bzrdir.find_repository()
2418
# for every revision reference the branch has, ensure it is pulled
2420
source_repository = self._get_fallback_repository(old_url)
2421
for revision_id in chain([self.last_revision()],
2422
self.tags.get_reverse_tag_dict()):
2423
self.repository.fetch(source_repository, revision_id,
2426
self._activate_fallback_location(url)
2427
# write this out after the repository is stacked to avoid setting a
2428
# stacked config that doesn't work.
2429
self._set_config_location('stacked_on_location', url)
2431
def _get_append_revisions_only(self):
2432
value = self.get_config().get_user_option('append_revisions_only')
2433
return value == 'True'
2435
def _make_tags(self):
2436
return BasicTags(self)
2439
def generate_revision_history(self, revision_id, last_rev=None,
2441
"""See BzrBranch5.generate_revision_history"""
2442
history = self._lefthand_history(revision_id, last_rev, other_branch)
2443
revno = len(history)
2444
self.set_last_revision_info(revno, revision_id)
2447
def get_rev_id(self, revno, history=None):
2448
"""Find the revision id of the specified revno."""
2450
return _mod_revision.NULL_REVISION
2452
last_revno, last_revision_id = self.last_revision_info()
2453
if revno <= 0 or revno > last_revno:
2454
raise errors.NoSuchRevision(self, revno)
2456
if history is not None:
2457
return history[revno - 1]
2459
index = last_revno - revno
2460
if len(self._partial_revision_history_cache) <= index:
2461
self._extend_partial_history(stop_index=index)
2462
if len(self._partial_revision_history_cache) > index:
2463
return self._partial_revision_history_cache[index]
2465
raise errors.NoSuchRevision(self, revno)
2468
def revision_id_to_revno(self, revision_id):
2469
"""Given a revision id, return its revno"""
2470
if _mod_revision.is_null(revision_id):
2473
index = self._partial_revision_history_cache.index(revision_id)
2475
self._extend_partial_history(stop_revision=revision_id)
2476
index = len(self._partial_revision_history_cache) - 1
2477
if self._partial_revision_history_cache[index] != revision_id:
2478
raise errors.NoSuchRevision(self, revision_id)
2479
return self.revno() - index
2482
class BzrBranch6(BzrBranch7):
2483
"""See BzrBranchFormat6 for the capabilities of this branch.
2485
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2489
def get_stacked_on_url(self):
2490
raise errors.UnstackableBranchFormat(self._format, self.base)
2492
def set_stacked_on_url(self, url):
2493
raise errors.UnstackableBranchFormat(self._format, self.base)
2496
######################################################################
2497
# results of operations
2500
class _Result(object):
2502
def _show_tag_conficts(self, to_file):
2503
if not getattr(self, 'tag_conflicts', None):
2505
to_file.write('Conflicting tags:\n')
2506
for name, value1, value2 in self.tag_conflicts:
2507
to_file.write(' %s\n' % (name, ))
2510
class PullResult(_Result):
2511
"""Result of a Branch.pull operation.
2513
:ivar old_revno: Revision number before pull.
2514
:ivar new_revno: Revision number after pull.
2515
:ivar old_revid: Tip revision id before pull.
2516
:ivar new_revid: Tip revision id after pull.
2517
:ivar source_branch: Source (local) branch object.
2518
:ivar master_branch: Master branch of the target, or the target if no
2520
:ivar local_branch: target branch if there is a Master, else None
2521
:ivar target_branch: Target/destination branch object.
2522
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2526
# DEPRECATED: pull used to return the change in revno
2527
return self.new_revno - self.old_revno
2529
def report(self, to_file):
2531
if self.old_revid == self.new_revid:
2532
to_file.write('No revisions to pull.\n')
2534
to_file.write('Now on revision %d.\n' % self.new_revno)
2535
self._show_tag_conficts(to_file)
2538
class PushResult(_Result):
2539
"""Result of a Branch.push operation.
2541
:ivar old_revno: Revision number before push.
2542
:ivar new_revno: Revision number after push.
2543
:ivar old_revid: Tip revision id before push.
2544
:ivar new_revid: Tip revision id after push.
2545
:ivar source_branch: Source branch object.
2546
:ivar master_branch: Master branch of the target, or None.
2547
:ivar target_branch: Target/destination branch object.
2551
# DEPRECATED: push used to return the change in revno
2552
return self.new_revno - self.old_revno
2554
def report(self, to_file):
2555
"""Write a human-readable description of the result."""
2556
if self.old_revid == self.new_revid:
2557
to_file.write('No new revisions to push.\n')
2559
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2560
self._show_tag_conficts(to_file)
2563
class BranchCheckResult(object):
2564
"""Results of checking branch consistency.
2569
def __init__(self, branch):
2570
self.branch = branch
2572
def report_results(self, verbose):
2573
"""Report the check results via trace.note.
2575
:param verbose: Requests more detailed display of what was checked,
2578
note('checked branch %s format %s',
2580
self.branch._format)
2583
class Converter5to6(object):
2584
"""Perform an in-place upgrade of format 5 to format 6"""
2586
def convert(self, branch):
2587
# Data for 5 and 6 can peacefully coexist.
2588
format = BzrBranchFormat6()
2589
new_branch = format.open(branch.bzrdir, _found=True)
2591
# Copy source data into target
2592
new_branch._write_last_revision_info(*branch.last_revision_info())
2593
new_branch.set_parent(branch.get_parent())
2594
new_branch.set_bound_location(branch.get_bound_location())
2595
new_branch.set_push_location(branch.get_push_location())
2597
# New branch has no tags by default
2598
new_branch.tags._set_tag_dict({})
2600
# Copying done; now update target format
2601
new_branch._transport.put_bytes('format',
2602
format.get_format_string(),
2603
mode=new_branch.bzrdir._get_file_mode())
2605
# Clean up old files
2606
new_branch._transport.delete('revision-history')
2608
branch.set_parent(None)
2609
except errors.NoSuchFile:
2611
branch.set_bound_location(None)
2614
class Converter6to7(object):
2615
"""Perform an in-place upgrade of format 6 to format 7"""
2617
def convert(self, branch):
2618
format = BzrBranchFormat7()
2619
branch._set_config_location('stacked_on_location', '')
2620
# update target format
2621
branch._transport.put_bytes('format', format.get_format_string())
2625
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2626
"""Run ``callable(*args, **kwargs)``, write-locking target for the
2629
_run_with_write_locked_target will attempt to release the lock it acquires.
2631
If an exception is raised by callable, then that exception *will* be
2632
propagated, even if the unlock attempt raises its own error. Thus
2633
_run_with_write_locked_target should be preferred to simply doing::
2637
return callable(*args, **kwargs)
2642
# This is very similar to bzrlib.decorators.needs_write_lock. Perhaps they
2643
# should share code?
2646
result = callable(*args, **kwargs)
2648
exc_info = sys.exc_info()
2652
raise exc_info[0], exc_info[1], exc_info[2]
2658
class InterBranch(InterObject):
2659
"""This class represents operations taking place between two branches.
2661
Its instances have methods like pull() and push() and contain
2662
references to the source and target repositories these operations
2663
can be carried out on.
2667
"""The available optimised InterBranch types."""
2670
def _get_branch_format_to_test():
2671
"""Return the Branch format to use when testing this InterBranch."""
2672
raise NotImplementedError(self._get_branch_format_to_test)
2674
def update_revisions(self, stop_revision=None, overwrite=False,
2676
"""Pull in new perfect-fit revisions.
2678
:param stop_revision: Updated until the given revision
2679
:param overwrite: Always set the branch pointer, rather than checking
2680
to see if it is a proper descendant.
2681
:param graph: A Graph object that can be used to query history
2682
information. This can be None.
2685
raise NotImplementedError(self.update_revisions)
2688
class GenericInterBranch(InterBranch):
2689
"""InterBranch implementation that uses public Branch functions.
2693
def _get_branch_format_to_test():
2694
return BranchFormat._default_format
2696
def update_revisions(self, stop_revision=None, overwrite=False,
2698
"""See InterBranch.update_revisions()."""
2699
self.source.lock_read()
2701
other_revno, other_last_revision = self.source.last_revision_info()
2702
stop_revno = None # unknown
2703
if stop_revision is None:
2704
stop_revision = other_last_revision
2705
if _mod_revision.is_null(stop_revision):
2706
# if there are no commits, we're done.
2708
stop_revno = other_revno
2710
# what's the current last revision, before we fetch [and change it
2712
last_rev = _mod_revision.ensure_null(self.target.last_revision())
2713
# we fetch here so that we don't process data twice in the common
2714
# case of having something to pull, and so that the check for
2715
# already merged can operate on the just fetched graph, which will
2716
# be cached in memory.
2717
self.target.fetch(self.source, stop_revision)
2718
# Check to see if one is an ancestor of the other
2721
graph = self.target.repository.get_graph()
2722
if self.target._check_if_descendant_or_diverged(
2723
stop_revision, last_rev, graph, self.source):
2724
# stop_revision is a descendant of last_rev, but we aren't
2725
# overwriting, so we're done.
2727
if stop_revno is None:
2729
graph = self.target.repository.get_graph()
2730
this_revno, this_last_revision = \
2731
self.target.last_revision_info()
2732
stop_revno = graph.find_distance_to_null(stop_revision,
2733
[(other_last_revision, other_revno),
2734
(this_last_revision, this_revno)])
2735
self.target.set_last_revision_info(stop_revno, stop_revision)
2737
self.source.unlock()
2740
def is_compatible(self, source, target):
2741
# GenericBranch uses the public API, so always compatible
2745
InterBranch.register_optimiser(GenericInterBranch)