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 import registry
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.
701
other_revno, other_last_revision = other.last_revision_info()
702
stop_revno = None # unknown
703
if stop_revision is None:
704
stop_revision = other_last_revision
705
if _mod_revision.is_null(stop_revision):
706
# if there are no commits, we're done.
708
stop_revno = other_revno
710
# what's the current last revision, before we fetch [and change it
712
last_rev = _mod_revision.ensure_null(self.last_revision())
713
# we fetch here so that we don't process data twice in the common
714
# case of having something to pull, and so that the check for
715
# already merged can operate on the just fetched graph, which will
716
# be cached in memory.
717
self.fetch(other, stop_revision)
718
# Check to see if one is an ancestor of the other
721
graph = self.repository.get_graph()
722
if self._check_if_descendant_or_diverged(
723
stop_revision, last_rev, graph, other):
724
# stop_revision is a descendant of last_rev, but we aren't
725
# overwriting, so we're done.
727
if stop_revno is None:
729
graph = self.repository.get_graph()
730
this_revno, this_last_revision = self.last_revision_info()
731
stop_revno = graph.find_distance_to_null(stop_revision,
732
[(other_last_revision, other_revno),
733
(this_last_revision, this_revno)])
734
self.set_last_revision_info(stop_revno, stop_revision)
738
def revision_id_to_revno(self, revision_id):
739
"""Given a revision id, return its revno"""
740
if _mod_revision.is_null(revision_id):
742
history = self.revision_history()
744
return history.index(revision_id) + 1
746
raise errors.NoSuchRevision(self, revision_id)
748
def get_rev_id(self, revno, history=None):
749
"""Find the revision id of the specified revno."""
751
return _mod_revision.NULL_REVISION
753
history = self.revision_history()
754
if revno <= 0 or revno > len(history):
755
raise errors.NoSuchRevision(self, revno)
756
return history[revno - 1]
758
def pull(self, source, overwrite=False, stop_revision=None,
759
possible_transports=None, _override_hook_target=None):
760
"""Mirror source into this branch.
762
This branch is considered to be 'local', having low latency.
764
:returns: PullResult instance
766
raise NotImplementedError(self.pull)
768
def push(self, target, overwrite=False, stop_revision=None):
769
"""Mirror this branch into target.
771
This branch is considered to be 'local', having low latency.
773
raise NotImplementedError(self.push)
775
def basis_tree(self):
776
"""Return `Tree` object for last revision."""
777
return self.repository.revision_tree(self.last_revision())
779
def get_parent(self):
780
"""Return the parent location of the branch.
782
This is the default location for pull/missing. The usual
783
pattern is that the user can override it by specifying a
786
raise NotImplementedError(self.get_parent)
788
def _set_config_location(self, name, url, config=None,
789
make_relative=False):
791
config = self.get_config()
795
url = urlutils.relative_url(self.base, url)
796
config.set_user_option(name, url, warn_masked=True)
798
def _get_config_location(self, name, config=None):
800
config = self.get_config()
801
location = config.get_user_option(name)
806
def get_submit_branch(self):
807
"""Return the submit location of the branch.
809
This is the default location for bundle. The usual
810
pattern is that the user can override it by specifying a
813
return self.get_config().get_user_option('submit_branch')
815
def set_submit_branch(self, location):
816
"""Return the submit location of the branch.
818
This is the default location for bundle. The usual
819
pattern is that the user can override it by specifying a
822
self.get_config().set_user_option('submit_branch', location,
825
def get_public_branch(self):
826
"""Return the public location of the branch.
828
This is is used by merge directives.
830
return self._get_config_location('public_branch')
832
def set_public_branch(self, location):
833
"""Return the submit location of the branch.
835
This is the default location for bundle. The usual
836
pattern is that the user can override it by specifying a
839
self._set_config_location('public_branch', location)
841
def get_push_location(self):
842
"""Return the None or the location to push this branch to."""
843
push_loc = self.get_config().get_user_option('push_location')
846
def set_push_location(self, location):
847
"""Set a new push location for this branch."""
848
raise NotImplementedError(self.set_push_location)
850
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
851
"""Run the post_change_branch_tip hooks."""
852
hooks = Branch.hooks['post_change_branch_tip']
855
new_revno, new_revid = self.last_revision_info()
856
params = ChangeBranchTipParams(
857
self, old_revno, new_revno, old_revid, new_revid)
861
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
862
"""Run the pre_change_branch_tip hooks."""
863
hooks = Branch.hooks['pre_change_branch_tip']
866
old_revno, old_revid = self.last_revision_info()
867
params = ChangeBranchTipParams(
868
self, old_revno, new_revno, old_revid, new_revid)
872
except errors.TipChangeRejected:
875
exc_info = sys.exc_info()
876
hook_name = Branch.hooks.get_hook_name(hook)
877
raise errors.HookFailed(
878
'pre_change_branch_tip', hook_name, exc_info)
880
def set_parent(self, url):
881
raise NotImplementedError(self.set_parent)
885
"""Synchronise this branch with the master branch if any.
887
:return: None or the last_revision pivoted out during the update.
891
def check_revno(self, revno):
893
Check whether a revno corresponds to any revision.
894
Zero (the NULL revision) is considered valid.
897
self.check_real_revno(revno)
899
def check_real_revno(self, revno):
901
Check whether a revno corresponds to a real revision.
902
Zero (the NULL revision) is considered invalid
904
if revno < 1 or revno > self.revno():
905
raise errors.InvalidRevisionNumber(revno)
908
def clone(self, to_bzrdir, revision_id=None):
909
"""Clone this branch into to_bzrdir preserving all semantic values.
911
revision_id: if not None, the revision history in the new branch will
912
be truncated to end with revision_id.
914
result = to_bzrdir.create_branch()
915
self.copy_content_into(result, revision_id=revision_id)
919
def sprout(self, to_bzrdir, revision_id=None):
920
"""Create a new line of development from the branch, into to_bzrdir.
922
to_bzrdir controls the branch format.
924
revision_id: if not None, the revision history in the new branch will
925
be truncated to end with revision_id.
927
result = to_bzrdir.create_branch()
928
self.copy_content_into(result, revision_id=revision_id)
929
result.set_parent(self.bzrdir.root_transport.base)
932
def _synchronize_history(self, destination, revision_id):
933
"""Synchronize last revision and revision history between branches.
935
This version is most efficient when the destination is also a
936
BzrBranch6, but works for BzrBranch5, as long as the destination's
937
repository contains all the lefthand ancestors of the intended
938
last_revision. If not, set_last_revision_info will fail.
940
:param destination: The branch to copy the history into
941
:param revision_id: The revision-id to truncate history at. May
942
be None to copy complete history.
944
source_revno, source_revision_id = self.last_revision_info()
945
if revision_id is None:
946
revno, revision_id = source_revno, source_revision_id
947
elif source_revision_id == revision_id:
948
# we know the revno without needing to walk all of history
951
# To figure out the revno for a random revision, we need to build
952
# the revision history, and count its length.
953
# We don't care about the order, just how long it is.
954
# Alternatively, we could start at the current location, and count
955
# backwards. But there is no guarantee that we will find it since
956
# it may be a merged revision.
957
revno = len(list(self.repository.iter_reverse_revision_history(
959
destination.set_last_revision_info(revno, revision_id)
962
def copy_content_into(self, destination, revision_id=None):
963
"""Copy the content of self into destination.
965
revision_id: if not None, the revision history in the new branch will
966
be truncated to end with revision_id.
968
self._synchronize_history(destination, revision_id)
970
parent = self.get_parent()
971
except errors.InaccessibleParent, e:
972
mutter('parent was not accessible to copy: %s', e)
975
destination.set_parent(parent)
976
if self._push_should_merge_tags():
977
self.tags.merge_to(destination.tags)
981
"""Check consistency of the branch.
983
In particular this checks that revisions given in the revision-history
984
do actually match up in the revision graph, and that they're all
985
present in the repository.
987
Callers will typically also want to check the repository.
989
:return: A BranchCheckResult.
991
mainline_parent_id = None
992
last_revno, last_revision_id = self.last_revision_info()
993
real_rev_history = list(self.repository.iter_reverse_revision_history(
995
real_rev_history.reverse()
996
if len(real_rev_history) != last_revno:
997
raise errors.BzrCheckError('revno does not match len(mainline)'
998
' %s != %s' % (last_revno, len(real_rev_history)))
999
# TODO: We should probably also check that real_rev_history actually
1000
# matches self.revision_history()
1001
for revision_id in real_rev_history:
1003
revision = self.repository.get_revision(revision_id)
1004
except errors.NoSuchRevision, e:
1005
raise errors.BzrCheckError("mainline revision {%s} not in repository"
1007
# In general the first entry on the revision history has no parents.
1008
# But it's not illegal for it to have parents listed; this can happen
1009
# in imports from Arch when the parents weren't reachable.
1010
if mainline_parent_id is not None:
1011
if mainline_parent_id not in revision.parent_ids:
1012
raise errors.BzrCheckError("previous revision {%s} not listed among "
1014
% (mainline_parent_id, revision_id))
1015
mainline_parent_id = revision_id
1016
return BranchCheckResult(self)
1018
def _get_checkout_format(self):
1019
"""Return the most suitable metadir for a checkout of this branch.
1020
Weaves are used if this branch's repository uses weaves.
1022
if isinstance(self.bzrdir, bzrdir.BzrDirPreSplitOut):
1023
from bzrlib.repofmt import weaverepo
1024
format = bzrdir.BzrDirMetaFormat1()
1025
format.repository_format = weaverepo.RepositoryFormat7()
1027
format = self.repository.bzrdir.checkout_metadir()
1028
format.set_branch_format(self._format)
1031
def create_checkout(self, to_location, revision_id=None,
1032
lightweight=False, accelerator_tree=None,
1034
"""Create a checkout of a branch.
1036
:param to_location: The url to produce the checkout at
1037
:param revision_id: The revision to check out
1038
:param lightweight: If True, produce a lightweight checkout, otherwise,
1039
produce a bound branch (heavyweight checkout)
1040
:param accelerator_tree: A tree which can be used for retrieving file
1041
contents more quickly than the revision tree, i.e. a workingtree.
1042
The revision tree will be used for cases where accelerator_tree's
1043
content is different.
1044
:param hardlink: If true, hard-link files from accelerator_tree,
1046
:return: The tree of the created checkout
1048
t = transport.get_transport(to_location)
1051
format = self._get_checkout_format()
1052
checkout = format.initialize_on_transport(t)
1053
from_branch = BranchReferenceFormat().initialize(checkout, self)
1055
format = self._get_checkout_format()
1056
checkout_branch = bzrdir.BzrDir.create_branch_convenience(
1057
to_location, force_new_tree=False, format=format)
1058
checkout = checkout_branch.bzrdir
1059
checkout_branch.bind(self)
1060
# pull up to the specified revision_id to set the initial
1061
# branch tip correctly, and seed it with history.
1062
checkout_branch.pull(self, stop_revision=revision_id)
1064
tree = checkout.create_workingtree(revision_id,
1065
from_branch=from_branch,
1066
accelerator_tree=accelerator_tree,
1068
basis_tree = tree.basis_tree()
1069
basis_tree.lock_read()
1071
for path, file_id in basis_tree.iter_references():
1072
reference_parent = self.reference_parent(file_id, path)
1073
reference_parent.create_checkout(tree.abspath(path),
1074
basis_tree.get_reference_revision(file_id, path),
1081
def reconcile(self, thorough=True):
1082
"""Make sure the data stored in this branch is consistent."""
1083
from bzrlib.reconcile import BranchReconciler
1084
reconciler = BranchReconciler(self, thorough=thorough)
1085
reconciler.reconcile()
1088
def reference_parent(self, file_id, path):
1089
"""Return the parent branch for a tree-reference file_id
1090
:param file_id: The file_id of the tree reference
1091
:param path: The path of the file_id in the tree
1092
:return: A branch associated with the file_id
1094
# FIXME should provide multiple branches, based on config
1095
return Branch.open(self.bzrdir.root_transport.clone(path).base)
1097
def supports_tags(self):
1098
return self._format.supports_tags()
1100
def _check_if_descendant_or_diverged(self, revision_a, revision_b, graph,
1102
"""Ensure that revision_b is a descendant of revision_a.
1104
This is a helper function for update_revisions.
1106
:raises: DivergedBranches if revision_b has diverged from revision_a.
1107
:returns: True if revision_b is a descendant of revision_a.
1109
relation = self._revision_relations(revision_a, revision_b, graph)
1110
if relation == 'b_descends_from_a':
1112
elif relation == 'diverged':
1113
raise errors.DivergedBranches(self, other_branch)
1114
elif relation == 'a_descends_from_b':
1117
raise AssertionError("invalid relation: %r" % (relation,))
1119
def _revision_relations(self, revision_a, revision_b, graph):
1120
"""Determine the relationship between two revisions.
1122
:returns: One of: 'a_descends_from_b', 'b_descends_from_a', 'diverged'
1124
heads = graph.heads([revision_a, revision_b])
1125
if heads == set([revision_b]):
1126
return 'b_descends_from_a'
1127
elif heads == set([revision_a, revision_b]):
1128
# These branches have diverged
1130
elif heads == set([revision_a]):
1131
return 'a_descends_from_b'
1133
raise AssertionError("invalid heads: %r" % (heads,))
1136
class BranchFormat(object):
1137
"""An encapsulation of the initialization and open routines for a format.
1139
Formats provide three things:
1140
* An initialization routine,
1144
Formats are placed in an dict by their format string for reference
1145
during branch opening. Its not required that these be instances, they
1146
can be classes themselves with class methods - it simply depends on
1147
whether state is needed for a given format or not.
1149
Once a format is deprecated, just deprecate the initialize and open
1150
methods on the format class. Do not deprecate the object, as the
1151
object will be created every time regardless.
1154
_default_format = None
1155
"""The default format used for new branches."""
1158
"""The known formats."""
1160
def __eq__(self, other):
1161
return self.__class__ is other.__class__
1163
def __ne__(self, other):
1164
return not (self == other)
1167
def find_format(klass, a_bzrdir):
1168
"""Return the format for the branch object in a_bzrdir."""
1170
transport = a_bzrdir.get_branch_transport(None)
1171
format_string = transport.get("format").read()
1172
return klass._formats[format_string]
1173
except errors.NoSuchFile:
1174
raise errors.NotBranchError(path=transport.base)
1176
raise errors.UnknownFormatError(format=format_string, kind='branch')
1179
def get_default_format(klass):
1180
"""Return the current default format."""
1181
return klass._default_format
1183
def get_reference(self, a_bzrdir):
1184
"""Get the target reference of the branch in a_bzrdir.
1186
format probing must have been completed before calling
1187
this method - it is assumed that the format of the branch
1188
in a_bzrdir is correct.
1190
:param a_bzrdir: The bzrdir to get the branch data from.
1191
:return: None if the branch is not a reference branch.
1196
def set_reference(self, a_bzrdir, to_branch):
1197
"""Set the target reference of the branch in a_bzrdir.
1199
format probing must have been completed before calling
1200
this method - it is assumed that the format of the branch
1201
in a_bzrdir is correct.
1203
:param a_bzrdir: The bzrdir to set the branch reference for.
1204
:param to_branch: branch that the checkout is to reference
1206
raise NotImplementedError(self.set_reference)
1208
def get_format_string(self):
1209
"""Return the ASCII format string that identifies this format."""
1210
raise NotImplementedError(self.get_format_string)
1212
def get_format_description(self):
1213
"""Return the short format description for this format."""
1214
raise NotImplementedError(self.get_format_description)
1216
def _initialize_helper(self, a_bzrdir, utf8_files, lock_type='metadir',
1218
"""Initialize a branch in a bzrdir, with specified files
1220
:param a_bzrdir: The bzrdir to initialize the branch in
1221
:param utf8_files: The files to create as a list of
1222
(filename, content) tuples
1223
:param set_format: If True, set the format with
1224
self.get_format_string. (BzrBranch4 has its format set
1226
:return: a branch in this format
1228
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
1229
branch_transport = a_bzrdir.get_branch_transport(self)
1231
'metadir': ('lock', lockdir.LockDir),
1232
'branch4': ('branch-lock', lockable_files.TransportLock),
1234
lock_name, lock_class = lock_map[lock_type]
1235
control_files = lockable_files.LockableFiles(branch_transport,
1236
lock_name, lock_class)
1237
control_files.create_lock()
1238
control_files.lock_write()
1240
utf8_files += [('format', self.get_format_string())]
1242
for (filename, content) in utf8_files:
1243
branch_transport.put_bytes(
1245
mode=a_bzrdir._get_file_mode())
1247
control_files.unlock()
1248
return self.open(a_bzrdir, _found=True)
1250
def initialize(self, a_bzrdir):
1251
"""Create a branch of this format in a_bzrdir."""
1252
raise NotImplementedError(self.initialize)
1254
def is_supported(self):
1255
"""Is this format supported?
1257
Supported formats can be initialized and opened.
1258
Unsupported formats may not support initialization or committing or
1259
some other features depending on the reason for not being supported.
1263
def network_name(self):
1264
"""A simple byte string uniquely identifying this format for RPC calls.
1266
MetaDir branch formats use their disk format string to identify the
1267
repository over the wire. All in one formats such as bzr < 0.8, and
1268
foreign formats like svn/git and hg should use some marker which is
1269
unique and immutable.
1271
raise NotImplementedError(self.network_name)
1273
def open(self, a_bzrdir, _found=False):
1274
"""Return the branch object for a_bzrdir
1276
_found is a private parameter, do not use it. It is used to indicate
1277
if format probing has already be done.
1279
raise NotImplementedError(self.open)
1282
def register_format(klass, format):
1283
"""Register a metadir format."""
1284
klass._formats[format.get_format_string()] = format
1285
# Metadir formats have a network name of their format string.
1286
network_format_registry.register(format.get_format_string(), format)
1289
def set_default_format(klass, format):
1290
klass._default_format = format
1292
def supports_stacking(self):
1293
"""True if this format records a stacked-on branch."""
1297
def unregister_format(klass, format):
1298
del klass._formats[format.get_format_string()]
1301
return self.get_format_description().rstrip()
1303
def supports_tags(self):
1304
"""True if this format supports tags stored in the branch"""
1305
return False # by default
1308
class BranchHooks(Hooks):
1309
"""A dictionary mapping hook name to a list of callables for branch hooks.
1311
e.g. ['set_rh'] Is the list of items to be called when the
1312
set_revision_history function is invoked.
1316
"""Create the default hooks.
1318
These are all empty initially, because by default nothing should get
1321
Hooks.__init__(self)
1322
# Introduced in 0.15:
1323
# invoked whenever the revision history has been set
1324
# with set_revision_history. The api signature is
1325
# (branch, revision_history), and the branch will
1328
# Invoked after a branch is opened. The api signature is (branch).
1330
# invoked after a push operation completes.
1331
# the api signature is
1333
# containing the members
1334
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1335
# where local is the local target branch or None, master is the target
1336
# master branch, and the rest should be self explanatory. The source
1337
# is read locked and the target branches write locked. Source will
1338
# be the local low-latency branch.
1339
self['post_push'] = []
1340
# invoked after a pull operation completes.
1341
# the api signature is
1343
# containing the members
1344
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1345
# where local is the local branch or None, master is the target
1346
# master branch, and the rest should be self explanatory. The source
1347
# is read locked and the target branches write locked. The local
1348
# branch is the low-latency branch.
1349
self['post_pull'] = []
1350
# invoked before a commit operation takes place.
1351
# the api signature is
1352
# (local, master, old_revno, old_revid, future_revno, future_revid,
1353
# tree_delta, future_tree).
1354
# old_revid is NULL_REVISION for the first commit to a branch
1355
# tree_delta is a TreeDelta object describing changes from the basis
1356
# revision, hooks MUST NOT modify this delta
1357
# future_tree is an in-memory tree obtained from
1358
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1359
self['pre_commit'] = []
1360
# invoked after a commit operation completes.
1361
# the api signature is
1362
# (local, master, old_revno, old_revid, new_revno, new_revid)
1363
# old_revid is NULL_REVISION for the first commit to a branch.
1364
self['post_commit'] = []
1365
# invoked after a uncommit operation completes.
1366
# the api signature is
1367
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1368
# local is the local branch or None, master is the target branch,
1369
# and an empty branch recieves new_revno of 0, new_revid of None.
1370
self['post_uncommit'] = []
1372
# Invoked before the tip of a branch changes.
1373
# the api signature is
1374
# (params) where params is a ChangeBranchTipParams with the members
1375
# (branch, old_revno, new_revno, old_revid, new_revid)
1376
self['pre_change_branch_tip'] = []
1378
# Invoked after the tip of a branch changes.
1379
# the api signature is
1380
# (params) where params is a ChangeBranchTipParams with the members
1381
# (branch, old_revno, new_revno, old_revid, new_revid)
1382
self['post_change_branch_tip'] = []
1384
# Invoked when a stacked branch activates its fallback locations and
1385
# allows the transformation of the url of said location.
1386
# the api signature is
1387
# (branch, url) where branch is the branch having its fallback
1388
# location activated and url is the url for the fallback location.
1389
# The hook should return a url.
1390
self['transform_fallback_location'] = []
1393
# install the default hooks into the Branch class.
1394
Branch.hooks = BranchHooks()
1397
class ChangeBranchTipParams(object):
1398
"""Object holding parameters passed to *_change_branch_tip hooks.
1400
There are 5 fields that hooks may wish to access:
1402
:ivar branch: the branch being changed
1403
:ivar old_revno: revision number before the change
1404
:ivar new_revno: revision number after the change
1405
:ivar old_revid: revision id before the change
1406
:ivar new_revid: revision id after the change
1408
The revid fields are strings. The revno fields are integers.
1411
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1412
"""Create a group of ChangeBranchTip parameters.
1414
:param branch: The branch being changed.
1415
:param old_revno: Revision number before the change.
1416
:param new_revno: Revision number after the change.
1417
:param old_revid: Tip revision id before the change.
1418
:param new_revid: Tip revision id after the change.
1420
self.branch = branch
1421
self.old_revno = old_revno
1422
self.new_revno = new_revno
1423
self.old_revid = old_revid
1424
self.new_revid = new_revid
1426
def __eq__(self, other):
1427
return self.__dict__ == other.__dict__
1430
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1431
self.__class__.__name__, self.branch,
1432
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1435
class BzrBranchFormat4(BranchFormat):
1436
"""Bzr branch format 4.
1439
- a revision-history file.
1440
- a branch-lock lock file [ to be shared with the bzrdir ]
1443
def get_format_description(self):
1444
"""See BranchFormat.get_format_description()."""
1445
return "Branch format 4"
1447
def initialize(self, a_bzrdir):
1448
"""Create a branch of this format in a_bzrdir."""
1449
utf8_files = [('revision-history', ''),
1450
('branch-name', ''),
1452
return self._initialize_helper(a_bzrdir, utf8_files,
1453
lock_type='branch4', set_format=False)
1456
super(BzrBranchFormat4, self).__init__()
1457
self._matchingbzrdir = bzrdir.BzrDirFormat6()
1459
def network_name(self):
1460
"""The network name for this format is the control dirs disk label."""
1461
return self._matchingbzrdir.get_format_string()
1463
def open(self, a_bzrdir, _found=False):
1464
"""Return the branch object for a_bzrdir
1466
_found is a private parameter, do not use it. It is used to indicate
1467
if format probing has already be done.
1470
# we are being called directly and must probe.
1471
raise NotImplementedError
1472
return BzrBranch(_format=self,
1473
_control_files=a_bzrdir._control_files,
1475
_repository=a_bzrdir.open_repository())
1478
return "Bazaar-NG branch format 4"
1481
class BranchFormatMetadir(BranchFormat):
1482
"""Common logic for meta-dir based branch formats."""
1484
def _branch_class(self):
1485
"""What class to instantiate on open calls."""
1486
raise NotImplementedError(self._branch_class)
1488
def network_name(self):
1489
"""A simple byte string uniquely identifying this format for RPC calls.
1491
Metadir branch formats use their format string.
1493
return self.get_format_string()
1495
def open(self, a_bzrdir, _found=False):
1496
"""Return the branch object for a_bzrdir.
1498
_found is a private parameter, do not use it. It is used to indicate
1499
if format probing has already be done.
1502
format = BranchFormat.find_format(a_bzrdir)
1503
if format.__class__ != self.__class__:
1504
raise AssertionError("wrong format %r found for %r" %
1507
transport = a_bzrdir.get_branch_transport(None)
1508
control_files = lockable_files.LockableFiles(transport, 'lock',
1510
return self._branch_class()(_format=self,
1511
_control_files=control_files,
1513
_repository=a_bzrdir.find_repository())
1514
except errors.NoSuchFile:
1515
raise errors.NotBranchError(path=transport.base)
1518
super(BranchFormatMetadir, self).__init__()
1519
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1520
self._matchingbzrdir.set_branch_format(self)
1522
def supports_tags(self):
1526
class BzrBranchFormat5(BranchFormatMetadir):
1527
"""Bzr branch format 5.
1530
- a revision-history file.
1532
- a lock dir guarding the branch itself
1533
- all of this stored in a branch/ subdirectory
1534
- works with shared repositories.
1536
This format is new in bzr 0.8.
1539
def _branch_class(self):
1542
def get_format_string(self):
1543
"""See BranchFormat.get_format_string()."""
1544
return "Bazaar-NG branch format 5\n"
1546
def get_format_description(self):
1547
"""See BranchFormat.get_format_description()."""
1548
return "Branch format 5"
1550
def initialize(self, a_bzrdir):
1551
"""Create a branch of this format in a_bzrdir."""
1552
utf8_files = [('revision-history', ''),
1553
('branch-name', ''),
1555
return self._initialize_helper(a_bzrdir, utf8_files)
1557
def supports_tags(self):
1561
class BzrBranchFormat6(BranchFormatMetadir):
1562
"""Branch format with last-revision and tags.
1564
Unlike previous formats, this has no explicit revision history. Instead,
1565
this just stores the last-revision, and the left-hand history leading
1566
up to there is the history.
1568
This format was introduced in bzr 0.15
1569
and became the default in 0.91.
1572
def _branch_class(self):
1575
def get_format_string(self):
1576
"""See BranchFormat.get_format_string()."""
1577
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1579
def get_format_description(self):
1580
"""See BranchFormat.get_format_description()."""
1581
return "Branch format 6"
1583
def initialize(self, a_bzrdir):
1584
"""Create a branch of this format in a_bzrdir."""
1585
utf8_files = [('last-revision', '0 null:\n'),
1586
('branch.conf', ''),
1589
return self._initialize_helper(a_bzrdir, utf8_files)
1592
class BzrBranchFormat7(BranchFormatMetadir):
1593
"""Branch format with last-revision, tags, and a stacked location pointer.
1595
The stacked location pointer is passed down to the repository and requires
1596
a repository format with supports_external_lookups = True.
1598
This format was introduced in bzr 1.6.
1601
def _branch_class(self):
1604
def get_format_string(self):
1605
"""See BranchFormat.get_format_string()."""
1606
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
1608
def get_format_description(self):
1609
"""See BranchFormat.get_format_description()."""
1610
return "Branch format 7"
1612
def initialize(self, a_bzrdir):
1613
"""Create a branch of this format in a_bzrdir."""
1614
utf8_files = [('last-revision', '0 null:\n'),
1615
('branch.conf', ''),
1618
return self._initialize_helper(a_bzrdir, utf8_files)
1621
super(BzrBranchFormat7, self).__init__()
1622
self._matchingbzrdir.repository_format = \
1623
RepositoryFormatKnitPack5RichRoot()
1625
def supports_stacking(self):
1629
class BranchReferenceFormat(BranchFormat):
1630
"""Bzr branch reference format.
1632
Branch references are used in implementing checkouts, they
1633
act as an alias to the real branch which is at some other url.
1640
def get_format_string(self):
1641
"""See BranchFormat.get_format_string()."""
1642
return "Bazaar-NG Branch Reference Format 1\n"
1644
def get_format_description(self):
1645
"""See BranchFormat.get_format_description()."""
1646
return "Checkout reference format 1"
1648
def get_reference(self, a_bzrdir):
1649
"""See BranchFormat.get_reference()."""
1650
transport = a_bzrdir.get_branch_transport(None)
1651
return transport.get('location').read()
1653
def set_reference(self, a_bzrdir, to_branch):
1654
"""See BranchFormat.set_reference()."""
1655
transport = a_bzrdir.get_branch_transport(None)
1656
location = transport.put_bytes('location', to_branch.base)
1658
def initialize(self, a_bzrdir, target_branch=None):
1659
"""Create a branch of this format in a_bzrdir."""
1660
if target_branch is None:
1661
# this format does not implement branch itself, thus the implicit
1662
# creation contract must see it as uninitializable
1663
raise errors.UninitializableFormat(self)
1664
mutter('creating branch reference in %s', a_bzrdir.transport.base)
1665
branch_transport = a_bzrdir.get_branch_transport(self)
1666
branch_transport.put_bytes('location',
1667
target_branch.bzrdir.root_transport.base)
1668
branch_transport.put_bytes('format', self.get_format_string())
1670
a_bzrdir, _found=True,
1671
possible_transports=[target_branch.bzrdir.root_transport])
1674
super(BranchReferenceFormat, self).__init__()
1675
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
1676
self._matchingbzrdir.set_branch_format(self)
1678
def _make_reference_clone_function(format, a_branch):
1679
"""Create a clone() routine for a branch dynamically."""
1680
def clone(to_bzrdir, revision_id=None):
1681
"""See Branch.clone()."""
1682
return format.initialize(to_bzrdir, a_branch)
1683
# cannot obey revision_id limits when cloning a reference ...
1684
# FIXME RBC 20060210 either nuke revision_id for clone, or
1685
# emit some sort of warning/error to the caller ?!
1688
def open(self, a_bzrdir, _found=False, location=None,
1689
possible_transports=None):
1690
"""Return the branch that the branch reference in a_bzrdir points at.
1692
_found is a private parameter, do not use it. It is used to indicate
1693
if format probing has already be done.
1696
format = BranchFormat.find_format(a_bzrdir)
1697
if format.__class__ != self.__class__:
1698
raise AssertionError("wrong format %r found for %r" %
1700
if location is None:
1701
location = self.get_reference(a_bzrdir)
1702
real_bzrdir = bzrdir.BzrDir.open(
1703
location, possible_transports=possible_transports)
1704
result = real_bzrdir.open_branch()
1705
# this changes the behaviour of result.clone to create a new reference
1706
# rather than a copy of the content of the branch.
1707
# I did not use a proxy object because that needs much more extensive
1708
# testing, and we are only changing one behaviour at the moment.
1709
# If we decide to alter more behaviours - i.e. the implicit nickname
1710
# then this should be refactored to introduce a tested proxy branch
1711
# and a subclass of that for use in overriding clone() and ....
1713
result.clone = self._make_reference_clone_function(result)
1717
network_format_registry = registry.FormatRegistry()
1718
"""Registry of formats indexed by their network name.
1720
The network name for a repository format is an identifier that can be used when
1721
referring to formats with smart server operations. See
1722
BranchFormat.network_name() for more detail.
1726
# formats which have no format string are not discoverable
1727
# and not independently creatable, so are not registered.
1728
__format5 = BzrBranchFormat5()
1729
__format6 = BzrBranchFormat6()
1730
__format7 = BzrBranchFormat7()
1731
BranchFormat.register_format(__format5)
1732
BranchFormat.register_format(BranchReferenceFormat())
1733
BranchFormat.register_format(__format6)
1734
BranchFormat.register_format(__format7)
1735
BranchFormat.set_default_format(__format6)
1736
_legacy_formats = [BzrBranchFormat4(),
1738
network_format_registry.register(
1739
_legacy_formats[0].network_name(), _legacy_formats[0])
1742
class BzrBranch(Branch):
1743
"""A branch stored in the actual filesystem.
1745
Note that it's "local" in the context of the filesystem; it doesn't
1746
really matter if it's on an nfs/smb/afs/coda/... share, as long as
1747
it's writable, and can be accessed via the normal filesystem API.
1749
:ivar _transport: Transport for file operations on this branch's
1750
control files, typically pointing to the .bzr/branch directory.
1751
:ivar repository: Repository for this branch.
1752
:ivar base: The url of the base directory for this branch; the one
1753
containing the .bzr directory.
1756
def __init__(self, _format=None,
1757
_control_files=None, a_bzrdir=None, _repository=None):
1758
"""Create new branch object at a particular location."""
1759
if a_bzrdir is None:
1760
raise ValueError('a_bzrdir must be supplied')
1762
self.bzrdir = a_bzrdir
1763
self._base = self.bzrdir.transport.clone('..').base
1764
# XXX: We should be able to just do
1765
# self.base = self.bzrdir.root_transport.base
1766
# but this does not quite work yet -- mbp 20080522
1767
self._format = _format
1768
if _control_files is None:
1769
raise ValueError('BzrBranch _control_files is None')
1770
self.control_files = _control_files
1771
self._transport = _control_files._transport
1772
self.repository = _repository
1773
Branch.__init__(self)
1776
return '%s(%r)' % (self.__class__.__name__, self.base)
1780
def _get_base(self):
1781
"""Returns the directory containing the control directory."""
1784
base = property(_get_base, doc="The URL for the root of this branch.")
1786
def is_locked(self):
1787
return self.control_files.is_locked()
1789
def lock_write(self, token=None):
1790
repo_token = self.repository.lock_write()
1792
token = self.control_files.lock_write(token=token)
1794
self.repository.unlock()
1798
def lock_read(self):
1799
self.repository.lock_read()
1801
self.control_files.lock_read()
1803
self.repository.unlock()
1807
# TODO: test for failed two phase locks. This is known broken.
1809
self.control_files.unlock()
1811
self.repository.unlock()
1812
if not self.control_files.is_locked():
1813
# we just released the lock
1814
self._clear_cached_state()
1816
def peek_lock_mode(self):
1817
if self.control_files._lock_count == 0:
1820
return self.control_files._lock_mode
1822
def get_physical_lock_status(self):
1823
return self.control_files.get_physical_lock_status()
1826
def print_file(self, file, revision_id):
1827
"""See Branch.print_file."""
1828
return self.repository.print_file(file, revision_id)
1830
def _write_revision_history(self, history):
1831
"""Factored out of set_revision_history.
1833
This performs the actual writing to disk.
1834
It is intended to be called by BzrBranch5.set_revision_history."""
1835
self._transport.put_bytes(
1836
'revision-history', '\n'.join(history),
1837
mode=self.bzrdir._get_file_mode())
1840
def set_revision_history(self, rev_history):
1841
"""See Branch.set_revision_history."""
1842
if 'evil' in debug.debug_flags:
1843
mutter_callsite(3, "set_revision_history scales with history.")
1844
check_not_reserved_id = _mod_revision.check_not_reserved_id
1845
for rev_id in rev_history:
1846
check_not_reserved_id(rev_id)
1847
if Branch.hooks['post_change_branch_tip']:
1848
# Don't calculate the last_revision_info() if there are no hooks
1850
old_revno, old_revid = self.last_revision_info()
1851
if len(rev_history) == 0:
1852
revid = _mod_revision.NULL_REVISION
1854
revid = rev_history[-1]
1855
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1856
self._write_revision_history(rev_history)
1857
self._clear_cached_state()
1858
self._cache_revision_history(rev_history)
1859
for hook in Branch.hooks['set_rh']:
1860
hook(self, rev_history)
1861
if Branch.hooks['post_change_branch_tip']:
1862
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1864
def _synchronize_history(self, destination, revision_id):
1865
"""Synchronize last revision and revision history between branches.
1867
This version is most efficient when the destination is also a
1868
BzrBranch5, but works for BzrBranch6 as long as the revision
1869
history is the true lefthand parent history, and all of the revisions
1870
are in the destination's repository. If not, set_revision_history
1873
:param destination: The branch to copy the history into
1874
:param revision_id: The revision-id to truncate history at. May
1875
be None to copy complete history.
1877
if not isinstance(destination._format, BzrBranchFormat5):
1878
super(BzrBranch, self)._synchronize_history(
1879
destination, revision_id)
1881
if revision_id == _mod_revision.NULL_REVISION:
1884
new_history = self.revision_history()
1885
if revision_id is not None and new_history != []:
1887
new_history = new_history[:new_history.index(revision_id) + 1]
1889
rev = self.repository.get_revision(revision_id)
1890
new_history = rev.get_history(self.repository)[1:]
1891
destination.set_revision_history(new_history)
1894
def set_last_revision_info(self, revno, revision_id):
1895
"""Set the last revision of this branch.
1897
The caller is responsible for checking that the revno is correct
1898
for this revision id.
1900
It may be possible to set the branch last revision to an id not
1901
present in the repository. However, branches can also be
1902
configured to check constraints on history, in which case this may not
1905
revision_id = _mod_revision.ensure_null(revision_id)
1906
# this old format stores the full history, but this api doesn't
1907
# provide it, so we must generate, and might as well check it's
1909
history = self._lefthand_history(revision_id)
1910
if len(history) != revno:
1911
raise AssertionError('%d != %d' % (len(history), revno))
1912
self.set_revision_history(history)
1914
def _gen_revision_history(self):
1915
history = self._transport.get_bytes('revision-history').split('\n')
1916
if history[-1:] == ['']:
1917
# There shouldn't be a trailing newline, but just in case.
1922
def generate_revision_history(self, revision_id, last_rev=None,
1924
"""Create a new revision history that will finish with revision_id.
1926
:param revision_id: the new tip to use.
1927
:param last_rev: The previous last_revision. If not None, then this
1928
must be a ancestory of revision_id, or DivergedBranches is raised.
1929
:param other_branch: The other branch that DivergedBranches should
1930
raise with respect to.
1932
self.set_revision_history(self._lefthand_history(revision_id,
1933
last_rev, other_branch))
1935
def basis_tree(self):
1936
"""See Branch.basis_tree."""
1937
return self.repository.revision_tree(self.last_revision())
1940
def pull(self, source, overwrite=False, stop_revision=None,
1941
_hook_master=None, run_hooks=True, possible_transports=None,
1942
_override_hook_target=None):
1945
:param _hook_master: Private parameter - set the branch to
1946
be supplied as the master to pull hooks.
1947
:param run_hooks: Private parameter - if false, this branch
1948
is being called because it's the master of the primary branch,
1949
so it should not run its hooks.
1950
:param _override_hook_target: Private parameter - set the branch to be
1951
supplied as the target_branch to pull hooks.
1953
result = PullResult()
1954
result.source_branch = source
1955
if _override_hook_target is None:
1956
result.target_branch = self
1958
result.target_branch = _override_hook_target
1961
# We assume that during 'pull' the local repository is closer than
1963
graph = self.repository.get_graph(source.repository)
1964
result.old_revno, result.old_revid = self.last_revision_info()
1965
self.update_revisions(source, stop_revision, overwrite=overwrite,
1967
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1968
result.new_revno, result.new_revid = self.last_revision_info()
1970
result.master_branch = _hook_master
1971
result.local_branch = result.target_branch
1973
result.master_branch = result.target_branch
1974
result.local_branch = None
1976
for hook in Branch.hooks['post_pull']:
1982
def _get_parent_location(self):
1983
_locs = ['parent', 'pull', 'x-pull']
1986
return self._transport.get_bytes(l).strip('\n')
1987
except errors.NoSuchFile:
1992
def push(self, target, overwrite=False, stop_revision=None,
1993
_override_hook_source_branch=None):
1996
This is the basic concrete implementation of push()
1998
:param _override_hook_source_branch: If specified, run
1999
the hooks passing this Branch as the source, rather than self.
2000
This is for use of RemoteBranch, where push is delegated to the
2001
underlying vfs-based Branch.
2003
# TODO: Public option to disable running hooks - should be trivial but
2005
return _run_with_write_locked_target(
2006
target, self._push_with_bound_branches, target, overwrite,
2008
_override_hook_source_branch=_override_hook_source_branch)
2010
def _push_with_bound_branches(self, target, overwrite,
2012
_override_hook_source_branch=None):
2013
"""Push from self into target, and into target's master if any.
2015
This is on the base BzrBranch class even though it doesn't support
2016
bound branches because the *target* might be bound.
2019
if _override_hook_source_branch:
2020
result.source_branch = _override_hook_source_branch
2021
for hook in Branch.hooks['post_push']:
2024
bound_location = target.get_bound_location()
2025
if bound_location and target.base != bound_location:
2026
# there is a master branch.
2028
# XXX: Why the second check? Is it even supported for a branch to
2029
# be bound to itself? -- mbp 20070507
2030
master_branch = target.get_master_branch()
2031
master_branch.lock_write()
2033
# push into the master from this branch.
2034
self._basic_push(master_branch, overwrite, stop_revision)
2035
# and push into the target branch from this. Note that we push from
2036
# this branch again, because its considered the highest bandwidth
2038
result = self._basic_push(target, overwrite, stop_revision)
2039
result.master_branch = master_branch
2040
result.local_branch = target
2044
master_branch.unlock()
2047
result = self._basic_push(target, overwrite, stop_revision)
2048
# TODO: Why set master_branch and local_branch if there's no
2049
# binding? Maybe cleaner to just leave them unset? -- mbp
2051
result.master_branch = target
2052
result.local_branch = None
2056
def _basic_push(self, target, overwrite, stop_revision):
2057
"""Basic implementation of push without bound branches or hooks.
2059
Must be called with self read locked and target write locked.
2061
result = PushResult()
2062
result.source_branch = self
2063
result.target_branch = target
2064
result.old_revno, result.old_revid = target.last_revision_info()
2065
if result.old_revid != self.last_revision():
2066
# We assume that during 'push' this repository is closer than
2068
graph = self.repository.get_graph(target.repository)
2069
target.update_revisions(self, stop_revision, overwrite=overwrite,
2071
if self._push_should_merge_tags():
2072
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2073
result.new_revno, result.new_revid = target.last_revision_info()
2076
def _push_should_merge_tags(self):
2077
"""Should _basic_push merge this branch's tags into the target?
2079
The default implementation returns False if this branch has no tags,
2080
and True the rest of the time. Subclasses may override this.
2082
return self.tags.supports_tags() and self.tags.get_tag_dict()
2084
def get_parent(self):
2085
"""See Branch.get_parent."""
2086
parent = self._get_parent_location()
2089
# This is an old-format absolute path to a local branch
2090
# turn it into a url
2091
if parent.startswith('/'):
2092
parent = urlutils.local_path_to_url(parent.decode('utf8'))
2094
return urlutils.join(self.base[:-1], parent)
2095
except errors.InvalidURLJoin, e:
2096
raise errors.InaccessibleParent(parent, self.base)
2098
def get_stacked_on_url(self):
2099
raise errors.UnstackableBranchFormat(self._format, self.base)
2101
def set_push_location(self, location):
2102
"""See Branch.set_push_location."""
2103
self.get_config().set_user_option(
2104
'push_location', location,
2105
store=_mod_config.STORE_LOCATION_NORECURSE)
2108
def set_parent(self, url):
2109
"""See Branch.set_parent."""
2110
# TODO: Maybe delete old location files?
2111
# URLs should never be unicode, even on the local fs,
2112
# FIXUP this and get_parent in a future branch format bump:
2113
# read and rewrite the file. RBC 20060125
2115
if isinstance(url, unicode):
2117
url = url.encode('ascii')
2118
except UnicodeEncodeError:
2119
raise errors.InvalidURL(url,
2120
"Urls must be 7-bit ascii, "
2121
"use bzrlib.urlutils.escape")
2122
url = urlutils.relative_url(self.base, url)
2123
self._set_parent_location(url)
2125
def _set_parent_location(self, url):
2127
self._transport.delete('parent')
2129
self._transport.put_bytes('parent', url + '\n',
2130
mode=self.bzrdir._get_file_mode())
2132
def set_stacked_on_url(self, url):
2133
raise errors.UnstackableBranchFormat(self._format, self.base)
2136
class BzrBranch5(BzrBranch):
2137
"""A format 5 branch. This supports new features over plain branches.
2139
It has support for a master_branch which is the data for bound branches.
2143
def pull(self, source, overwrite=False, stop_revision=None,
2144
run_hooks=True, possible_transports=None,
2145
_override_hook_target=None):
2146
"""Pull from source into self, updating my master if any.
2148
:param run_hooks: Private parameter - if false, this branch
2149
is being called because it's the master of the primary branch,
2150
so it should not run its hooks.
2152
bound_location = self.get_bound_location()
2153
master_branch = None
2154
if bound_location and source.base != bound_location:
2155
# not pulling from master, so we need to update master.
2156
master_branch = self.get_master_branch(possible_transports)
2157
master_branch.lock_write()
2160
# pull from source into master.
2161
master_branch.pull(source, overwrite, stop_revision,
2163
return super(BzrBranch5, self).pull(source, overwrite,
2164
stop_revision, _hook_master=master_branch,
2165
run_hooks=run_hooks,
2166
_override_hook_target=_override_hook_target)
2169
master_branch.unlock()
2171
def get_bound_location(self):
2173
return self._transport.get_bytes('bound')[:-1]
2174
except errors.NoSuchFile:
2178
def get_master_branch(self, possible_transports=None):
2179
"""Return the branch we are bound to.
2181
:return: Either a Branch, or None
2183
This could memoise the branch, but if thats done
2184
it must be revalidated on each new lock.
2185
So for now we just don't memoise it.
2186
# RBC 20060304 review this decision.
2188
bound_loc = self.get_bound_location()
2192
return Branch.open(bound_loc,
2193
possible_transports=possible_transports)
2194
except (errors.NotBranchError, errors.ConnectionError), e:
2195
raise errors.BoundBranchConnectionFailure(
2199
def set_bound_location(self, location):
2200
"""Set the target where this branch is bound to.
2202
:param location: URL to the target branch
2205
self._transport.put_bytes('bound', location+'\n',
2206
mode=self.bzrdir._get_file_mode())
2209
self._transport.delete('bound')
2210
except errors.NoSuchFile:
2215
def bind(self, other):
2216
"""Bind this branch to the branch other.
2218
This does not push or pull data between the branches, though it does
2219
check for divergence to raise an error when the branches are not
2220
either the same, or one a prefix of the other. That behaviour may not
2221
be useful, so that check may be removed in future.
2223
:param other: The branch to bind to
2226
# TODO: jam 20051230 Consider checking if the target is bound
2227
# It is debatable whether you should be able to bind to
2228
# a branch which is itself bound.
2229
# Committing is obviously forbidden,
2230
# but binding itself may not be.
2231
# Since we *have* to check at commit time, we don't
2232
# *need* to check here
2234
# we want to raise diverged if:
2235
# last_rev is not in the other_last_rev history, AND
2236
# other_last_rev is not in our history, and do it without pulling
2238
self.set_bound_location(other.base)
2242
"""If bound, unbind"""
2243
return self.set_bound_location(None)
2246
def update(self, possible_transports=None):
2247
"""Synchronise this branch with the master branch if any.
2249
:return: None or the last_revision that was pivoted out during the
2252
master = self.get_master_branch(possible_transports)
2253
if master is not None:
2254
old_tip = _mod_revision.ensure_null(self.last_revision())
2255
self.pull(master, overwrite=True)
2256
if self.repository.get_graph().is_ancestor(old_tip,
2257
_mod_revision.ensure_null(self.last_revision())):
2263
class BzrBranch7(BzrBranch5):
2264
"""A branch with support for a fallback repository."""
2266
def _get_fallback_repository(self, url):
2267
"""Get the repository we fallback to at url."""
2268
url = urlutils.join(self.base, url)
2269
a_bzrdir = bzrdir.BzrDir.open(url,
2270
possible_transports=[self._transport])
2271
return a_bzrdir.open_branch().repository
2273
def _activate_fallback_location(self, url):
2274
"""Activate the branch/repository from url as a fallback repository."""
2275
self.repository.add_fallback_repository(
2276
self._get_fallback_repository(url))
2278
def _open_hook(self):
2280
url = self.get_stacked_on_url()
2281
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2282
errors.UnstackableBranchFormat):
2285
for hook in Branch.hooks['transform_fallback_location']:
2286
url = hook(self, url)
2288
hook_name = Branch.hooks.get_hook_name(hook)
2289
raise AssertionError(
2290
"'transform_fallback_location' hook %s returned "
2291
"None, not a URL." % hook_name)
2292
self._activate_fallback_location(url)
2294
def _check_stackable_repo(self):
2295
if not self.repository._format.supports_external_lookups:
2296
raise errors.UnstackableRepositoryFormat(self.repository._format,
2297
self.repository.base)
2299
def __init__(self, *args, **kwargs):
2300
super(BzrBranch7, self).__init__(*args, **kwargs)
2301
self._last_revision_info_cache = None
2302
self._partial_revision_history_cache = []
2304
def _clear_cached_state(self):
2305
super(BzrBranch7, self)._clear_cached_state()
2306
self._last_revision_info_cache = None
2307
self._partial_revision_history_cache = []
2309
def _last_revision_info(self):
2310
revision_string = self._transport.get_bytes('last-revision')
2311
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2312
revision_id = cache_utf8.get_cached_utf8(revision_id)
2314
return revno, revision_id
2316
def _write_last_revision_info(self, revno, revision_id):
2317
"""Simply write out the revision id, with no checks.
2319
Use set_last_revision_info to perform this safely.
2321
Does not update the revision_history cache.
2322
Intended to be called by set_last_revision_info and
2323
_write_revision_history.
2325
revision_id = _mod_revision.ensure_null(revision_id)
2326
out_string = '%d %s\n' % (revno, revision_id)
2327
self._transport.put_bytes('last-revision', out_string,
2328
mode=self.bzrdir._get_file_mode())
2331
def set_last_revision_info(self, revno, revision_id):
2332
revision_id = _mod_revision.ensure_null(revision_id)
2333
old_revno, old_revid = self.last_revision_info()
2334
if self._get_append_revisions_only():
2335
self._check_history_violation(revision_id)
2336
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2337
self._write_last_revision_info(revno, revision_id)
2338
self._clear_cached_state()
2339
self._last_revision_info_cache = revno, revision_id
2340
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2342
def _synchronize_history(self, destination, revision_id):
2343
"""Synchronize last revision and revision history between branches.
2345
:see: Branch._synchronize_history
2347
# XXX: The base Branch has a fast implementation of this method based
2348
# on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2349
# that uses set_revision_history. This class inherits from BzrBranch5,
2350
# but wants the fast implementation, so it calls
2351
# Branch._synchronize_history directly.
2352
Branch._synchronize_history(self, destination, revision_id)
2354
def _check_history_violation(self, revision_id):
2355
last_revision = _mod_revision.ensure_null(self.last_revision())
2356
if _mod_revision.is_null(last_revision):
2358
if last_revision not in self._lefthand_history(revision_id):
2359
raise errors.AppendRevisionsOnlyViolation(self.base)
2361
def _gen_revision_history(self):
2362
"""Generate the revision history from last revision
2364
last_revno, last_revision = self.last_revision_info()
2365
self._extend_partial_history(stop_index=last_revno-1)
2366
return list(reversed(self._partial_revision_history_cache))
2368
def _extend_partial_history(self, stop_index=None, stop_revision=None):
2369
"""Extend the partial history to include a given index
2371
If a stop_index is supplied, stop when that index has been reached.
2372
If a stop_revision is supplied, stop when that revision is
2373
encountered. Otherwise, stop when the beginning of history is
2376
:param stop_index: The index which should be present. When it is
2377
present, history extension will stop.
2378
:param revision_id: The revision id which should be present. When
2379
it is encountered, history extension will stop.
2381
repo = self.repository
2382
if len(self._partial_revision_history_cache) == 0:
2383
iterator = repo.iter_reverse_revision_history(self.last_revision())
2385
start_revision = self._partial_revision_history_cache[-1]
2386
iterator = repo.iter_reverse_revision_history(start_revision)
2387
#skip the last revision in the list
2388
next_revision = iterator.next()
2389
for revision_id in iterator:
2390
self._partial_revision_history_cache.append(revision_id)
2391
if (stop_index is not None and
2392
len(self._partial_revision_history_cache) > stop_index):
2394
if revision_id == stop_revision:
2397
def _write_revision_history(self, history):
2398
"""Factored out of set_revision_history.
2400
This performs the actual writing to disk, with format-specific checks.
2401
It is intended to be called by BzrBranch5.set_revision_history.
2403
if len(history) == 0:
2404
last_revision = 'null:'
2406
if history != self._lefthand_history(history[-1]):
2407
raise errors.NotLefthandHistory(history)
2408
last_revision = history[-1]
2409
if self._get_append_revisions_only():
2410
self._check_history_violation(last_revision)
2411
self._write_last_revision_info(len(history), last_revision)
2414
def _set_parent_location(self, url):
2415
"""Set the parent branch"""
2416
self._set_config_location('parent_location', url, make_relative=True)
2419
def _get_parent_location(self):
2420
"""Set the parent branch"""
2421
return self._get_config_location('parent_location')
2423
def set_push_location(self, location):
2424
"""See Branch.set_push_location."""
2425
self._set_config_location('push_location', location)
2427
def set_bound_location(self, location):
2428
"""See Branch.set_push_location."""
2430
config = self.get_config()
2431
if location is None:
2432
if config.get_user_option('bound') != 'True':
2435
config.set_user_option('bound', 'False', warn_masked=True)
2438
self._set_config_location('bound_location', location,
2440
config.set_user_option('bound', 'True', warn_masked=True)
2443
def _get_bound_location(self, bound):
2444
"""Return the bound location in the config file.
2446
Return None if the bound parameter does not match"""
2447
config = self.get_config()
2448
config_bound = (config.get_user_option('bound') == 'True')
2449
if config_bound != bound:
2451
return self._get_config_location('bound_location', config=config)
2453
def get_bound_location(self):
2454
"""See Branch.set_push_location."""
2455
return self._get_bound_location(True)
2457
def get_old_bound_location(self):
2458
"""See Branch.get_old_bound_location"""
2459
return self._get_bound_location(False)
2461
def get_stacked_on_url(self):
2462
# you can always ask for the URL; but you might not be able to use it
2463
# if the repo can't support stacking.
2464
## self._check_stackable_repo()
2465
stacked_url = self._get_config_location('stacked_on_location')
2466
if stacked_url is None:
2467
raise errors.NotStacked(self)
2470
def set_append_revisions_only(self, enabled):
2475
self.get_config().set_user_option('append_revisions_only', value,
2478
def set_stacked_on_url(self, url):
2479
self._check_stackable_repo()
2482
old_url = self.get_stacked_on_url()
2483
except (errors.NotStacked, errors.UnstackableBranchFormat,
2484
errors.UnstackableRepositoryFormat):
2487
# repositories don't offer an interface to remove fallback
2488
# repositories today; take the conceptually simpler option and just
2490
self.repository = self.bzrdir.find_repository()
2491
# for every revision reference the branch has, ensure it is pulled
2493
source_repository = self._get_fallback_repository(old_url)
2494
for revision_id in chain([self.last_revision()],
2495
self.tags.get_reverse_tag_dict()):
2496
self.repository.fetch(source_repository, revision_id,
2499
self._activate_fallback_location(url)
2500
# write this out after the repository is stacked to avoid setting a
2501
# stacked config that doesn't work.
2502
self._set_config_location('stacked_on_location', url)
2504
def _get_append_revisions_only(self):
2505
value = self.get_config().get_user_option('append_revisions_only')
2506
return value == 'True'
2508
def _make_tags(self):
2509
return BasicTags(self)
2512
def generate_revision_history(self, revision_id, last_rev=None,
2514
"""See BzrBranch5.generate_revision_history"""
2515
history = self._lefthand_history(revision_id, last_rev, other_branch)
2516
revno = len(history)
2517
self.set_last_revision_info(revno, revision_id)
2520
def get_rev_id(self, revno, history=None):
2521
"""Find the revision id of the specified revno."""
2523
return _mod_revision.NULL_REVISION
2525
last_revno, last_revision_id = self.last_revision_info()
2526
if revno <= 0 or revno > last_revno:
2527
raise errors.NoSuchRevision(self, revno)
2529
if history is not None:
2530
return history[revno - 1]
2532
index = last_revno - revno
2533
if len(self._partial_revision_history_cache) <= index:
2534
self._extend_partial_history(stop_index=index)
2535
if len(self._partial_revision_history_cache) > index:
2536
return self._partial_revision_history_cache[index]
2538
raise errors.NoSuchRevision(self, revno)
2541
def revision_id_to_revno(self, revision_id):
2542
"""Given a revision id, return its revno"""
2543
if _mod_revision.is_null(revision_id):
2546
index = self._partial_revision_history_cache.index(revision_id)
2548
self._extend_partial_history(stop_revision=revision_id)
2549
index = len(self._partial_revision_history_cache) - 1
2550
if self._partial_revision_history_cache[index] != revision_id:
2551
raise errors.NoSuchRevision(self, revision_id)
2552
return self.revno() - index
2555
class BzrBranch6(BzrBranch7):
2556
"""See BzrBranchFormat6 for the capabilities of this branch.
2558
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2562
def get_stacked_on_url(self):
2563
raise errors.UnstackableBranchFormat(self._format, self.base)
2565
def set_stacked_on_url(self, url):
2566
raise errors.UnstackableBranchFormat(self._format, self.base)
2569
######################################################################
2570
# results of operations
2573
class _Result(object):
2575
def _show_tag_conficts(self, to_file):
2576
if not getattr(self, 'tag_conflicts', None):
2578
to_file.write('Conflicting tags:\n')
2579
for name, value1, value2 in self.tag_conflicts:
2580
to_file.write(' %s\n' % (name, ))
2583
class PullResult(_Result):
2584
"""Result of a Branch.pull operation.
2586
:ivar old_revno: Revision number before pull.
2587
:ivar new_revno: Revision number after pull.
2588
:ivar old_revid: Tip revision id before pull.
2589
:ivar new_revid: Tip revision id after pull.
2590
:ivar source_branch: Source (local) branch object.
2591
:ivar master_branch: Master branch of the target, or the target if no
2593
:ivar local_branch: target branch if there is a Master, else None
2594
:ivar target_branch: Target/destination branch object.
2595
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2599
# DEPRECATED: pull used to return the change in revno
2600
return self.new_revno - self.old_revno
2602
def report(self, to_file):
2604
if self.old_revid == self.new_revid:
2605
to_file.write('No revisions to pull.\n')
2607
to_file.write('Now on revision %d.\n' % self.new_revno)
2608
self._show_tag_conficts(to_file)
2611
class PushResult(_Result):
2612
"""Result of a Branch.push operation.
2614
:ivar old_revno: Revision number before push.
2615
:ivar new_revno: Revision number after push.
2616
:ivar old_revid: Tip revision id before push.
2617
:ivar new_revid: Tip revision id after push.
2618
:ivar source_branch: Source branch object.
2619
:ivar master_branch: Master branch of the target, or None.
2620
:ivar target_branch: Target/destination branch object.
2624
# DEPRECATED: push used to return the change in revno
2625
return self.new_revno - self.old_revno
2627
def report(self, to_file):
2628
"""Write a human-readable description of the result."""
2629
if self.old_revid == self.new_revid:
2630
to_file.write('No new revisions to push.\n')
2632
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2633
self._show_tag_conficts(to_file)
2636
class BranchCheckResult(object):
2637
"""Results of checking branch consistency.
2642
def __init__(self, branch):
2643
self.branch = branch
2645
def report_results(self, verbose):
2646
"""Report the check results via trace.note.
2648
:param verbose: Requests more detailed display of what was checked,
2651
note('checked branch %s format %s',
2653
self.branch._format)
2656
class Converter5to6(object):
2657
"""Perform an in-place upgrade of format 5 to format 6"""
2659
def convert(self, branch):
2660
# Data for 5 and 6 can peacefully coexist.
2661
format = BzrBranchFormat6()
2662
new_branch = format.open(branch.bzrdir, _found=True)
2664
# Copy source data into target
2665
new_branch._write_last_revision_info(*branch.last_revision_info())
2666
new_branch.set_parent(branch.get_parent())
2667
new_branch.set_bound_location(branch.get_bound_location())
2668
new_branch.set_push_location(branch.get_push_location())
2670
# New branch has no tags by default
2671
new_branch.tags._set_tag_dict({})
2673
# Copying done; now update target format
2674
new_branch._transport.put_bytes('format',
2675
format.get_format_string(),
2676
mode=new_branch.bzrdir._get_file_mode())
2678
# Clean up old files
2679
new_branch._transport.delete('revision-history')
2681
branch.set_parent(None)
2682
except errors.NoSuchFile:
2684
branch.set_bound_location(None)
2687
class Converter6to7(object):
2688
"""Perform an in-place upgrade of format 6 to format 7"""
2690
def convert(self, branch):
2691
format = BzrBranchFormat7()
2692
branch._set_config_location('stacked_on_location', '')
2693
# update target format
2694
branch._transport.put_bytes('format', format.get_format_string())
2698
def _run_with_write_locked_target(target, callable, *args, **kwargs):
2699
"""Run ``callable(*args, **kwargs)``, write-locking target for the
2702
_run_with_write_locked_target will attempt to release the lock it acquires.
2704
If an exception is raised by callable, then that exception *will* be
2705
propagated, even if the unlock attempt raises its own error. Thus
2706
_run_with_write_locked_target should be preferred to simply doing::
2710
return callable(*args, **kwargs)
2715
# This is very similar to bzrlib.decorators.needs_write_lock. Perhaps they
2716
# should share code?
2719
result = callable(*args, **kwargs)
2721
exc_info = sys.exc_info()
2725
raise exc_info[0], exc_info[1], exc_info[2]