190
185
def get_physical_lock_status(self):
191
186
raise NotImplementedError(self.get_physical_lock_status)
194
def dotted_revno_to_revision_id(self, revno, _cache_reverse=False):
195
"""Return the revision_id for a dotted revno.
197
:param revno: a tuple like (1,) or (1,1,2)
198
:param _cache_reverse: a private parameter enabling storage
199
of the reverse mapping in a top level cache. (This should
200
only be done in selective circumstances as we want to
201
avoid having the mapping cached multiple times.)
202
:return: the revision_id
203
:raises errors.NoSuchRevision: if the revno doesn't exist
205
rev_id = self._do_dotted_revno_to_revision_id(revno)
207
self._partial_revision_id_to_revno_cache[rev_id] = revno
210
def _do_dotted_revno_to_revision_id(self, revno):
211
"""Worker function for dotted_revno_to_revision_id.
213
Subclasses should override this if they wish to
214
provide a more efficient implementation.
217
return self.get_rev_id(revno[0])
218
revision_id_to_revno = self.get_revision_id_to_revno_map()
219
revision_ids = [revision_id for revision_id, this_revno
220
in revision_id_to_revno.iteritems()
221
if revno == this_revno]
222
if len(revision_ids) == 1:
223
return revision_ids[0]
225
revno_str = '.'.join(map(str, revno))
226
raise errors.NoSuchRevision(self, revno_str)
229
def revision_id_to_dotted_revno(self, revision_id):
230
"""Given a revision id, return its dotted revno.
232
:return: a tuple like (1,) or (400,1,3).
234
return self._do_revision_id_to_dotted_revno(revision_id)
236
def _do_revision_id_to_dotted_revno(self, revision_id):
237
"""Worker function for revision_id_to_revno."""
238
# Try the caches if they are loaded
239
result = self._partial_revision_id_to_revno_cache.get(revision_id)
240
if result is not None:
242
if self._revision_id_to_revno_cache:
243
result = self._revision_id_to_revno_cache.get(revision_id)
245
raise errors.NoSuchRevision(self, revision_id)
246
# Try the mainline as it's optimised
248
revno = self.revision_id_to_revno(revision_id)
250
except errors.NoSuchRevision:
251
# We need to load and use the full revno map after all
252
result = self.get_revision_id_to_revno_map().get(revision_id)
254
raise errors.NoSuchRevision(self, revision_id)
258
def get_revision_id_to_revno_map(self):
259
"""Return the revision_id => dotted revno map.
261
This will be regenerated on demand, but will be cached.
263
:return: A dictionary mapping revision_id => dotted revno.
264
This dictionary should not be modified by the caller.
266
if self._revision_id_to_revno_cache is not None:
267
mapping = self._revision_id_to_revno_cache
269
mapping = self._gen_revno_map()
270
self._cache_revision_id_to_revno(mapping)
271
# TODO: jam 20070417 Since this is being cached, should we be returning
273
# I would rather not, and instead just declare that users should not
274
# modify the return value.
277
def _gen_revno_map(self):
278
"""Create a new mapping from revision ids to dotted revnos.
280
Dotted revnos are generated based on the current tip in the revision
282
This is the worker function for get_revision_id_to_revno_map, which
283
just caches the return value.
285
:return: A dictionary mapping revision_id => dotted revno.
287
revision_id_to_revno = dict((rev_id, revno)
288
for rev_id, depth, revno, end_of_merge
289
in self.iter_merge_sorted_revisions())
290
return revision_id_to_revno
293
def iter_merge_sorted_revisions(self, start_revision_id=None,
294
stop_revision_id=None, stop_rule='exclude', direction='reverse'):
295
"""Walk the revisions for a branch in merge sorted order.
297
Merge sorted order is the output from a merge-aware,
298
topological sort, i.e. all parents come before their
299
children going forward; the opposite for reverse.
301
:param start_revision_id: the revision_id to begin walking from.
302
If None, the branch tip is used.
303
:param stop_revision_id: the revision_id to terminate the walk
304
after. If None, the rest of history is included.
305
:param stop_rule: if stop_revision_id is not None, the precise rule
306
to use for termination:
307
* 'exclude' - leave the stop revision out of the result (default)
308
* 'include' - the stop revision is the last item in the result
309
* 'with-merges' - include the stop revision and all of its
310
merged revisions in the result
311
:param direction: either 'reverse' or 'forward':
312
* reverse means return the start_revision_id first, i.e.
313
start at the most recent revision and go backwards in history
314
* forward returns tuples in the opposite order to reverse.
315
Note in particular that forward does *not* do any intelligent
316
ordering w.r.t. depth as some clients of this API may like.
317
(If required, that ought to be done at higher layers.)
319
:return: an iterator over (revision_id, depth, revno, end_of_merge)
322
* revision_id: the unique id of the revision
323
* depth: How many levels of merging deep this node has been
325
* revno_sequence: This field provides a sequence of
326
revision numbers for all revisions. The format is:
327
(REVNO, BRANCHNUM, BRANCHREVNO). BRANCHNUM is the number of the
328
branch that the revno is on. From left to right the REVNO numbers
329
are the sequence numbers within that branch of the revision.
330
* end_of_merge: When True the next node (earlier in history) is
331
part of a different merge.
333
# Note: depth and revno values are in the context of the branch so
334
# we need the full graph to get stable numbers, regardless of the
336
if self._merge_sorted_revisions_cache is None:
337
last_revision = self.last_revision()
338
graph = self.repository.get_graph()
339
parent_map = dict(((key, value) for key, value in
340
graph.iter_ancestry([last_revision]) if value is not None))
341
revision_graph = repository._strip_NULL_ghosts(parent_map)
342
revs = tsort.merge_sort(revision_graph, last_revision, None,
344
# Drop the sequence # before caching
345
self._merge_sorted_revisions_cache = [r[1:] for r in revs]
347
filtered = self._filter_merge_sorted_revisions(
348
self._merge_sorted_revisions_cache, start_revision_id,
349
stop_revision_id, stop_rule)
350
if direction == 'reverse':
352
if direction == 'forward':
353
return reversed(list(filtered))
355
raise ValueError('invalid direction %r' % direction)
357
def _filter_merge_sorted_revisions(self, merge_sorted_revisions,
358
start_revision_id, stop_revision_id, stop_rule):
359
"""Iterate over an inclusive range of sorted revisions."""
360
rev_iter = iter(merge_sorted_revisions)
361
if start_revision_id is not None:
362
for rev_id, depth, revno, end_of_merge in rev_iter:
363
if rev_id != start_revision_id:
366
# The decision to include the start or not
367
# depends on the stop_rule if a stop is provided
369
iter([(rev_id, depth, revno, end_of_merge)]),
372
if stop_revision_id is None:
373
for rev_id, depth, revno, end_of_merge in rev_iter:
374
yield rev_id, depth, revno, end_of_merge
375
elif stop_rule == 'exclude':
376
for rev_id, depth, revno, end_of_merge in rev_iter:
377
if rev_id == stop_revision_id:
379
yield rev_id, depth, revno, end_of_merge
380
elif stop_rule == 'include':
381
for rev_id, depth, revno, end_of_merge in rev_iter:
382
yield rev_id, depth, revno, end_of_merge
383
if rev_id == stop_revision_id:
385
elif stop_rule == 'with-merges':
386
stop_rev = self.repository.get_revision(stop_revision_id)
387
if stop_rev.parent_ids:
388
left_parent = stop_rev.parent_ids[0]
390
left_parent = _mod_revision.NULL_REVISION
391
for rev_id, depth, revno, end_of_merge in rev_iter:
392
if rev_id == left_parent:
394
yield rev_id, depth, revno, end_of_merge
396
raise ValueError('invalid stop_rule %r' % stop_rule)
398
def leave_lock_in_place(self):
399
"""Tell this branch object not to release the physical lock when this
402
If lock_write doesn't return a token, then this method is not supported.
404
self.control_files.leave_in_place()
406
def dont_leave_lock_in_place(self):
407
"""Tell this branch object to release the physical lock when this
408
object is unlocked, even if it didn't originally acquire it.
410
If lock_write doesn't return a token, then this method is not supported.
412
self.control_files.dont_leave_in_place()
188
def abspath(self, name):
189
"""Return absolute filename for something in the branch
191
XXX: Robert Collins 20051017 what is this used for? why is it a branch
192
method and not a tree method.
194
raise NotImplementedError(self.abspath)
414
196
def bind(self, other):
415
197
"""Bind the local branch the other branch.
499
280
The delta is relative to its mainline predecessor, or the
500
281
empty tree for revision 1.
283
assert isinstance(revno, int)
502
284
rh = self.revision_history()
503
285
if not (1 <= revno <= len(rh)):
504
raise errors.InvalidRevisionNumber(revno)
286
raise InvalidRevisionNumber(revno)
505
287
return self.repository.get_revision_delta(rh[revno-1])
507
def get_stacked_on_url(self):
508
"""Get the URL this branch is stacked against.
510
:raises NotStacked: If the branch is not stacked.
511
:raises UnstackableBranchFormat: If the branch does not support
514
raise NotImplementedError(self.get_stacked_on_url)
289
def get_root_id(self):
290
"""Return the id of this branches root"""
291
raise NotImplementedError(self.get_root_id)
516
293
def print_file(self, file, revision_id):
517
294
"""Print `file` to stdout."""
518
295
raise NotImplementedError(self.print_file)
297
def append_revision(self, *revision_ids):
298
raise NotImplementedError(self.append_revision)
520
300
def set_revision_history(self, rev_history):
521
301
raise NotImplementedError(self.set_revision_history)
523
def set_stacked_on_url(self, url):
524
"""Set the URL this branch is stacked against.
526
:raises UnstackableBranchFormat: If the branch does not support
528
:raises UnstackableRepositoryFormat: If the repository does not support
531
raise NotImplementedError(self.set_stacked_on_url)
533
def _cache_revision_history(self, rev_history):
534
"""Set the cached revision history to rev_history.
536
The revision_history method will use this cache to avoid regenerating
537
the revision history.
539
This API is semi-public; it only for use by subclasses, all other code
540
should consider it to be private.
542
self._revision_history_cache = rev_history
544
def _cache_revision_id_to_revno(self, revision_id_to_revno):
545
"""Set the cached revision_id => revno map to revision_id_to_revno.
547
This API is semi-public; it only for use by subclasses, all other code
548
should consider it to be private.
550
self._revision_id_to_revno_cache = revision_id_to_revno
552
def _clear_cached_state(self):
553
"""Clear any cached data on this branch, e.g. cached revision history.
555
This means the next call to revision_history will need to call
556
_gen_revision_history.
558
This API is semi-public; it only for use by subclasses, all other code
559
should consider it to be private.
561
self._revision_history_cache = None
562
self._revision_id_to_revno_cache = None
563
self._last_revision_info_cache = None
564
self._merge_sorted_revisions_cache = None
566
def _gen_revision_history(self):
567
"""Return sequence of revision hashes on to this branch.
569
Unlike revision_history, this method always regenerates or rereads the
570
revision history, i.e. it does not cache the result, so repeated calls
573
Concrete subclasses should override this instead of revision_history so
574
that subclasses do not need to deal with caching logic.
576
This API is semi-public; it only for use by subclasses, all other code
577
should consider it to be private.
579
raise NotImplementedError(self._gen_revision_history)
582
303
def revision_history(self):
583
"""Return sequence of revision ids on this branch.
585
This method will cache the revision history for as long as it is safe to
588
if 'evil' in debug.debug_flags:
589
mutter_callsite(3, "revision_history scales with history.")
590
if self._revision_history_cache is not None:
591
history = self._revision_history_cache
593
history = self._gen_revision_history()
594
self._cache_revision_history(history)
304
"""Return sequence of revision hashes on to this branch."""
305
raise NotImplementedError(self.revision_history)
598
308
"""Return current revision number for this branch.
646
337
common_index = min(self_len, other_len) -1
647
338
if common_index >= 0 and \
648
339
self_history[common_index] != other_history[common_index]:
649
raise errors.DivergedBranches(self, other)
340
raise DivergedBranches(self, other)
651
342
if stop_revision is None:
652
343
stop_revision = other_len
345
assert isinstance(stop_revision, int)
654
346
if stop_revision > other_len:
655
347
raise errors.NoSuchRevision(self, stop_revision)
656
348
return other_history[self_len:stop_revision]
659
def update_revisions(self, other, stop_revision=None, overwrite=False,
350
def update_revisions(self, other, stop_revision=None):
661
351
"""Pull in new perfect-fit revisions.
663
353
:param other: Another Branch to pull from
664
354
:param stop_revision: Updated until the given revision
665
:param overwrite: Always set the branch pointer, rather than checking
666
to see if it is a proper descendant.
667
:param graph: A Graph object that can be used to query history
668
information. This can be None.
673
other_revno, other_last_revision = other.last_revision_info()
674
stop_revno = None # unknown
675
if stop_revision is None:
676
stop_revision = other_last_revision
677
if _mod_revision.is_null(stop_revision):
678
# if there are no commits, we're done.
680
stop_revno = other_revno
682
# what's the current last revision, before we fetch [and change it
684
last_rev = _mod_revision.ensure_null(self.last_revision())
685
# we fetch here so that we don't process data twice in the common
686
# case of having something to pull, and so that the check for
687
# already merged can operate on the just fetched graph, which will
688
# be cached in memory.
689
self.fetch(other, stop_revision)
690
# Check to see if one is an ancestor of the other
693
graph = self.repository.get_graph()
694
if self._check_if_descendant_or_diverged(
695
stop_revision, last_rev, graph, other):
696
# stop_revision is a descendant of last_rev, but we aren't
697
# overwriting, so we're done.
699
if stop_revno is None:
701
graph = self.repository.get_graph()
702
this_revno, this_last_revision = self.last_revision_info()
703
stop_revno = graph.find_distance_to_null(stop_revision,
704
[(other_last_revision, other_revno),
705
(this_last_revision, this_revno)])
706
self.set_last_revision_info(stop_revno, stop_revision)
357
raise NotImplementedError(self.update_revisions)
710
359
def revision_id_to_revno(self, revision_id):
711
360
"""Given a revision id, return its revno"""
712
if _mod_revision.is_null(revision_id):
361
if revision_id is None:
714
363
history = self.revision_history()
716
365
return history.index(revision_id) + 1
717
366
except ValueError:
718
raise errors.NoSuchRevision(self, revision_id)
367
raise bzrlib.errors.NoSuchRevision(self, revision_id)
720
369
def get_rev_id(self, revno, history=None):
721
370
"""Find the revision id of the specified revno."""
723
return _mod_revision.NULL_REVISION
724
373
if history is None:
725
374
history = self.revision_history()
726
375
if revno <= 0 or revno > len(history):
727
raise errors.NoSuchRevision(self, revno)
376
raise bzrlib.errors.NoSuchRevision(self, revno)
728
377
return history[revno - 1]
730
def pull(self, source, overwrite=False, stop_revision=None,
731
possible_transports=None, _override_hook_target=None):
379
def pull(self, source, overwrite=False, stop_revision=None):
732
380
"""Mirror source into this branch.
734
382
This branch is considered to be 'local', having low latency.
736
:returns: PullResult instance
738
384
raise NotImplementedError(self.pull)
844
477
Zero (the NULL revision) is considered invalid
846
479
if revno < 1 or revno > self.revno():
847
raise errors.InvalidRevisionNumber(revno)
480
raise InvalidRevisionNumber(revno)
850
def clone(self, to_bzrdir, revision_id=None):
483
def clone(self, *args, **kwargs):
851
484
"""Clone this branch into to_bzrdir preserving all semantic values.
853
486
revision_id: if not None, the revision history in the new branch will
854
487
be truncated to end with revision_id.
856
result = to_bzrdir.create_branch()
489
# for API compatibility, until 0.8 releases we provide the old api:
490
# def clone(self, to_location, revision=None, basis_branch=None, to_branch_format=None):
491
# after 0.8 releases, the *args and **kwargs should be changed:
492
# def clone(self, to_bzrdir, revision_id=None):
493
if (kwargs.get('to_location', None) or
494
kwargs.get('revision', None) or
495
kwargs.get('basis_branch', None) or
496
(len(args) and isinstance(args[0], basestring))):
497
# backwards compatibility api:
498
warn("Branch.clone() has been deprecated for BzrDir.clone() from"
499
" bzrlib 0.8.", DeprecationWarning, stacklevel=3)
502
basis_branch = args[2]
504
basis_branch = kwargs.get('basis_branch', None)
506
basis = basis_branch.bzrdir
511
revision_id = args[1]
513
revision_id = kwargs.get('revision', None)
518
# no default to raise if not provided.
519
url = kwargs.get('to_location')
520
return self.bzrdir.clone(url,
521
revision_id=revision_id,
522
basis=basis).open_branch()
524
# generate args by hand
526
revision_id = args[1]
528
revision_id = kwargs.get('revision_id', None)
532
# no default to raise if not provided.
533
to_bzrdir = kwargs.get('to_bzrdir')
534
result = self._format.initialize(to_bzrdir)
857
535
self.copy_content_into(result, revision_id=revision_id)
861
539
def sprout(self, to_bzrdir, revision_id=None):
862
540
"""Create a new line of development from the branch, into to_bzrdir.
864
to_bzrdir controls the branch format.
866
542
revision_id: if not None, the revision history in the new branch will
867
543
be truncated to end with revision_id.
869
result = to_bzrdir.create_branch()
545
result = self._format.initialize(to_bzrdir)
870
546
self.copy_content_into(result, revision_id=revision_id)
871
547
result.set_parent(self.bzrdir.root_transport.base)
874
def _synchronize_history(self, destination, revision_id):
875
"""Synchronize last revision and revision history between branches.
877
This version is most efficient when the destination is also a
878
BzrBranch6, but works for BzrBranch5, as long as the destination's
879
repository contains all the lefthand ancestors of the intended
880
last_revision. If not, set_last_revision_info will fail.
882
:param destination: The branch to copy the history into
883
:param revision_id: The revision-id to truncate history at. May
884
be None to copy complete history.
886
source_revno, source_revision_id = self.last_revision_info()
887
if revision_id is None:
888
revno, revision_id = source_revno, source_revision_id
889
elif source_revision_id == revision_id:
890
# we know the revno without needing to walk all of history
893
# To figure out the revno for a random revision, we need to build
894
# the revision history, and count its length.
895
# We don't care about the order, just how long it is.
896
# Alternatively, we could start at the current location, and count
897
# backwards. But there is no guarantee that we will find it since
898
# it may be a merged revision.
899
revno = len(list(self.repository.iter_reverse_revision_history(
901
destination.set_last_revision_info(revno, revision_id)
904
551
def copy_content_into(self, destination, revision_id=None):
905
552
"""Copy the content of self into destination.
1246
742
These are all empty initially, because by default nothing should get
1249
Hooks.__init__(self)
1250
# Introduced in 0.15:
1251
746
# invoked whenever the revision history has been set
1252
747
# with set_revision_history. The api signature is
1253
748
# (branch, revision_history), and the branch will
749
# be write-locked. Introduced in 0.15.
1255
750
self['set_rh'] = []
1256
# Invoked after a branch is opened. The api signature is (branch).
1258
# invoked after a push operation completes.
1259
# the api signature is
1261
# containing the members
1262
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1263
# where local is the local target branch or None, master is the target
1264
# master branch, and the rest should be self explanatory. The source
1265
# is read locked and the target branches write locked. Source will
1266
# be the local low-latency branch.
1267
self['post_push'] = []
1268
# invoked after a pull operation completes.
1269
# the api signature is
1271
# containing the members
1272
# (source, local, master, old_revno, old_revid, new_revno, new_revid)
1273
# where local is the local branch or None, master is the target
1274
# master branch, and the rest should be self explanatory. The source
1275
# is read locked and the target branches write locked. The local
1276
# branch is the low-latency branch.
1277
self['post_pull'] = []
1278
# invoked before a commit operation takes place.
1279
# the api signature is
1280
# (local, master, old_revno, old_revid, future_revno, future_revid,
1281
# tree_delta, future_tree).
1282
# old_revid is NULL_REVISION for the first commit to a branch
1283
# tree_delta is a TreeDelta object describing changes from the basis
1284
# revision, hooks MUST NOT modify this delta
1285
# future_tree is an in-memory tree obtained from
1286
# CommitBuilder.revision_tree() and hooks MUST NOT modify this tree
1287
self['pre_commit'] = []
1288
# invoked after a commit operation completes.
1289
# the api signature is
1290
# (local, master, old_revno, old_revid, new_revno, new_revid)
1291
# old_revid is NULL_REVISION for the first commit to a branch.
1292
self['post_commit'] = []
1293
# invoked after a uncommit operation completes.
1294
# the api signature is
1295
# (local, master, old_revno, old_revid, new_revno, new_revid) where
1296
# local is the local branch or None, master is the target branch,
1297
# and an empty branch recieves new_revno of 0, new_revid of None.
1298
self['post_uncommit'] = []
1300
# Invoked before the tip of a branch changes.
1301
# the api signature is
1302
# (params) where params is a ChangeBranchTipParams with the members
1303
# (branch, old_revno, new_revno, old_revid, new_revid)
1304
self['pre_change_branch_tip'] = []
1306
# Invoked after the tip of a branch changes.
1307
# the api signature is
1308
# (params) where params is a ChangeBranchTipParams with the members
1309
# (branch, old_revno, new_revno, old_revid, new_revid)
1310
self['post_change_branch_tip'] = []
1312
# Invoked when a stacked branch activates its fallback locations and
1313
# allows the transformation of the url of said location.
1314
# the api signature is
1315
# (branch, url) where branch is the branch having its fallback
1316
# location activated and url is the url for the fallback location.
1317
# The hook should return a url.
1318
self['transform_fallback_location'] = []
752
def install_hook(self, hook_name, a_callable):
753
"""Install a_callable in to the hook hook_name.
755
:param hook_name: A hook name. See the __init__ method of BranchHooks
756
for the complete list of hooks.
757
:param a_callable: The callable to be invoked when the hook triggers.
758
The exact signature will depend on the hook - see the __init__
759
method of BranchHooks for details on each hook.
762
self[hook_name].append(a_callable)
764
raise errors.UnknownHook('branch', hook_name)
1321
767
# install the default hooks into the Branch class.
1322
768
Branch.hooks = BranchHooks()
1325
class ChangeBranchTipParams(object):
1326
"""Object holding parameters passed to *_change_branch_tip hooks.
1328
There are 5 fields that hooks may wish to access:
1330
:ivar branch: the branch being changed
1331
:ivar old_revno: revision number before the change
1332
:ivar new_revno: revision number after the change
1333
:ivar old_revid: revision id before the change
1334
:ivar new_revid: revision id after the change
1336
The revid fields are strings. The revno fields are integers.
1339
def __init__(self, branch, old_revno, new_revno, old_revid, new_revid):
1340
"""Create a group of ChangeBranchTip parameters.
1342
:param branch: The branch being changed.
1343
:param old_revno: Revision number before the change.
1344
:param new_revno: Revision number after the change.
1345
:param old_revid: Tip revision id before the change.
1346
:param new_revid: Tip revision id after the change.
1348
self.branch = branch
1349
self.old_revno = old_revno
1350
self.new_revno = new_revno
1351
self.old_revid = old_revid
1352
self.new_revid = new_revid
1354
def __eq__(self, other):
1355
return self.__dict__ == other.__dict__
1358
return "<%s of %s from (%s, %s) to (%s, %s)>" % (
1359
self.__class__.__name__, self.branch,
1360
self.old_revno, self.old_revid, self.new_revno, self.new_revid)
1363
771
class BzrBranchFormat4(BranchFormat):
1364
772
"""Bzr branch format 4.
1467
844
def initialize(self, a_bzrdir):
1468
845
"""Create a branch of this format in a_bzrdir."""
846
mutter('creating branch %r in %s', self, a_bzrdir.transport.base)
847
branch_transport = a_bzrdir.get_branch_transport(self)
1469
848
utf8_files = [('revision-history', ''),
1470
849
('branch-name', ''),
1472
return self._initialize_helper(a_bzrdir, utf8_files)
1474
def supports_tags(self):
1478
class BzrBranchFormat6(BranchFormatMetadir):
1479
"""Branch format with last-revision and tags.
1481
Unlike previous formats, this has no explicit revision history. Instead,
1482
this just stores the last-revision, and the left-hand history leading
1483
up to there is the history.
1485
This format was introduced in bzr 0.15
1486
and became the default in 0.91.
1489
def _branch_class(self):
1492
def get_format_string(self):
1493
"""See BranchFormat.get_format_string()."""
1494
return "Bazaar Branch Format 6 (bzr 0.15)\n"
1496
def get_format_description(self):
1497
"""See BranchFormat.get_format_description()."""
1498
return "Branch format 6"
1500
def initialize(self, a_bzrdir):
1501
"""Create a branch of this format in a_bzrdir."""
1502
utf8_files = [('last-revision', '0 null:\n'),
1503
('branch.conf', ''),
1506
return self._initialize_helper(a_bzrdir, utf8_files)
1509
class BzrBranchFormat7(BranchFormatMetadir):
1510
"""Branch format with last-revision, tags, and a stacked location pointer.
1512
The stacked location pointer is passed down to the repository and requires
1513
a repository format with supports_external_lookups = True.
1515
This format was introduced in bzr 1.6.
1518
def _branch_class(self):
1521
def get_format_string(self):
1522
"""See BranchFormat.get_format_string()."""
1523
return "Bazaar Branch Format 7 (needs bzr 1.6)\n"
1525
def get_format_description(self):
1526
"""See BranchFormat.get_format_description()."""
1527
return "Branch format 7"
1529
def initialize(self, a_bzrdir):
1530
"""Create a branch of this format in a_bzrdir."""
1531
utf8_files = [('last-revision', '0 null:\n'),
1532
('branch.conf', ''),
1535
return self._initialize_helper(a_bzrdir, utf8_files)
851
control_files = lockable_files.LockableFiles(branch_transport, 'lock',
853
control_files.create_lock()
854
control_files.lock_write()
855
control_files.put_utf8('format', self.get_format_string())
857
for file, content in utf8_files:
858
control_files.put_utf8(file, content)
860
control_files.unlock()
861
return self.open(a_bzrdir, _found=True, )
1537
863
def __init__(self):
1538
super(BzrBranchFormat7, self).__init__()
1539
self._matchingbzrdir.repository_format = \
1540
RepositoryFormatKnitPack5RichRoot()
1542
def supports_stacking(self):
864
super(BzrBranchFormat5, self).__init__()
865
self._matchingbzrdir = bzrdir.BzrDirMetaFormat1()
867
def open(self, a_bzrdir, _found=False):
868
"""Return the branch object for a_bzrdir
870
_found is a private parameter, do not use it. It is used to indicate
871
if format probing has already be done.
874
format = BranchFormat.find_format(a_bzrdir)
875
assert format.__class__ == self.__class__
876
transport = a_bzrdir.get_branch_transport(None)
877
control_files = lockable_files.LockableFiles(transport, 'lock',
879
return BzrBranch5(_format=self,
880
_control_files=control_files,
882
_repository=a_bzrdir.find_repository())
885
return "Bazaar-NG Metadir branch format 5"
1546
888
class BranchReferenceFormat(BranchFormat):
1732
1125
"""See Branch.print_file."""
1733
1126
return self.repository.print_file(file, revision_id)
1735
def _write_revision_history(self, history):
1736
"""Factored out of set_revision_history.
1738
This performs the actual writing to disk.
1739
It is intended to be called by BzrBranch5.set_revision_history."""
1740
self._transport.put_bytes(
1741
'revision-history', '\n'.join(history),
1742
mode=self.bzrdir._get_file_mode())
1129
def append_revision(self, *revision_ids):
1130
"""See Branch.append_revision."""
1131
for revision_id in revision_ids:
1132
_mod_revision.check_not_reserved_id(revision_id)
1133
mutter("add {%s} to revision-history" % revision_id)
1134
rev_history = self.revision_history()
1135
rev_history.extend(revision_ids)
1136
self.set_revision_history(rev_history)
1744
1138
@needs_write_lock
1745
1139
def set_revision_history(self, rev_history):
1746
1140
"""See Branch.set_revision_history."""
1747
if 'evil' in debug.debug_flags:
1748
mutter_callsite(3, "set_revision_history scales with history.")
1749
check_not_reserved_id = _mod_revision.check_not_reserved_id
1750
for rev_id in rev_history:
1751
check_not_reserved_id(rev_id)
1752
if Branch.hooks['post_change_branch_tip']:
1753
# Don't calculate the last_revision_info() if there are no hooks
1755
old_revno, old_revid = self.last_revision_info()
1756
if len(rev_history) == 0:
1757
revid = _mod_revision.NULL_REVISION
1141
self.control_files.put_utf8(
1142
'revision-history', '\n'.join(rev_history))
1143
transaction = self.get_transaction()
1144
history = transaction.map.find_revision_history()
1145
if history is not None:
1146
# update the revision history in the identity map.
1147
history[:] = list(rev_history)
1148
# this call is disabled because revision_history is
1149
# not really an object yet, and the transaction is for objects.
1150
# transaction.register_dirty(history)
1759
revid = rev_history[-1]
1760
self._run_pre_change_branch_tip_hooks(len(rev_history), revid)
1761
self._write_revision_history(rev_history)
1762
self._clear_cached_state()
1763
self._cache_revision_history(rev_history)
1152
transaction.map.add_revision_history(rev_history)
1153
# this call is disabled because revision_history is
1154
# not really an object yet, and the transaction is for objects.
1155
# transaction.register_clean(history)
1764
1156
for hook in Branch.hooks['set_rh']:
1765
1157
hook(self, rev_history)
1766
if Branch.hooks['post_change_branch_tip']:
1767
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
1769
def _synchronize_history(self, destination, revision_id):
1770
"""Synchronize last revision and revision history between branches.
1772
This version is most efficient when the destination is also a
1773
BzrBranch5, but works for BzrBranch6 as long as the revision
1774
history is the true lefthand parent history, and all of the revisions
1775
are in the destination's repository. If not, set_revision_history
1778
:param destination: The branch to copy the history into
1779
:param revision_id: The revision-id to truncate history at. May
1780
be None to copy complete history.
1782
if not isinstance(destination._format, BzrBranchFormat5):
1783
super(BzrBranch, self)._synchronize_history(
1784
destination, revision_id)
1786
if revision_id == _mod_revision.NULL_REVISION:
1789
new_history = self.revision_history()
1790
if revision_id is not None and new_history != []:
1792
new_history = new_history[:new_history.index(revision_id) + 1]
1794
rev = self.repository.get_revision(revision_id)
1795
new_history = rev.get_history(self.repository)[1:]
1796
destination.set_revision_history(new_history)
1798
def _run_pre_change_branch_tip_hooks(self, new_revno, new_revid):
1799
"""Run the pre_change_branch_tip hooks."""
1800
hooks = Branch.hooks['pre_change_branch_tip']
1803
old_revno, old_revid = self.last_revision_info()
1804
params = ChangeBranchTipParams(
1805
self, old_revno, new_revno, old_revid, new_revid)
1809
except errors.TipChangeRejected:
1812
exc_info = sys.exc_info()
1813
hook_name = Branch.hooks.get_hook_name(hook)
1814
raise errors.HookFailed(
1815
'pre_change_branch_tip', hook_name, exc_info)
1817
def _run_post_change_branch_tip_hooks(self, old_revno, old_revid):
1818
"""Run the post_change_branch_tip hooks."""
1819
hooks = Branch.hooks['post_change_branch_tip']
1822
new_revno, new_revid = self.last_revision_info()
1823
params = ChangeBranchTipParams(
1824
self, old_revno, new_revno, old_revid, new_revid)
1829
def set_last_revision_info(self, revno, revision_id):
1830
"""Set the last revision of this branch.
1832
The caller is responsible for checking that the revno is correct
1833
for this revision id.
1835
It may be possible to set the branch last revision to an id not
1836
present in the repository. However, branches can also be
1837
configured to check constraints on history, in which case this may not
1840
revision_id = _mod_revision.ensure_null(revision_id)
1841
# this old format stores the full history, but this api doesn't
1842
# provide it, so we must generate, and might as well check it's
1844
history = self._lefthand_history(revision_id)
1845
if len(history) != revno:
1846
raise AssertionError('%d != %d' % (len(history), revno))
1847
self.set_revision_history(history)
1849
def _gen_revision_history(self):
1850
history = self._transport.get_bytes('revision-history').split('\n')
1851
if history[-1:] == ['']:
1852
# There shouldn't be a trailing newline, but just in case.
1856
def _lefthand_history(self, revision_id, last_rev=None,
1858
if 'evil' in debug.debug_flags:
1859
mutter_callsite(4, "_lefthand_history scales with history.")
1860
# stop_revision must be a descendant of last_revision
1861
graph = self.repository.get_graph()
1862
if last_rev is not None:
1863
if not graph.is_ancestor(last_rev, revision_id):
1864
# our previous tip is not merged into stop_revision
1865
raise errors.DivergedBranches(self, other_branch)
1866
# make a new revision history from the graph
1867
parents_map = graph.get_parent_map([revision_id])
1868
if revision_id not in parents_map:
1869
raise errors.NoSuchRevision(self, revision_id)
1870
current_rev_id = revision_id
1872
check_not_reserved_id = _mod_revision.check_not_reserved_id
1873
# Do not include ghosts or graph origin in revision_history
1874
while (current_rev_id in parents_map and
1875
len(parents_map[current_rev_id]) > 0):
1876
check_not_reserved_id(current_rev_id)
1877
new_history.append(current_rev_id)
1878
current_rev_id = parents_map[current_rev_id][0]
1879
parents_map = graph.get_parent_map([current_rev_id])
1880
new_history.reverse()
1884
def generate_revision_history(self, revision_id, last_rev=None,
1160
def revision_history(self):
1161
"""See Branch.revision_history."""
1162
transaction = self.get_transaction()
1163
history = transaction.map.find_revision_history()
1164
if history is not None:
1165
# mutter("cache hit for revision-history in %s", self)
1166
return list(history)
1167
decode_utf8 = cache_utf8.decode
1168
history = [decode_utf8(l.rstrip('\r\n')) for l in
1169
self.control_files.get('revision-history').readlines()]
1170
transaction.map.add_revision_history(history)
1171
# this call is disabled because revision_history is
1172
# not really an object yet, and the transaction is for objects.
1173
# transaction.register_clean(history, precious=True)
1174
return list(history)
1177
def generate_revision_history(self, revision_id, last_rev=None,
1885
1178
other_branch=None):
1886
1179
"""Create a new revision history that will finish with revision_id.
1888
1181
:param revision_id: the new tip to use.
1889
1182
:param last_rev: The previous last_revision. If not None, then this
1890
1183
must be a ancestory of revision_id, or DivergedBranches is raised.
1891
1184
:param other_branch: The other branch that DivergedBranches should
1892
1185
raise with respect to.
1894
self.set_revision_history(self._lefthand_history(revision_id,
1895
last_rev, other_branch))
1187
# stop_revision must be a descendant of last_revision
1188
stop_graph = self.repository.get_revision_graph(revision_id)
1189
if last_rev is not None and last_rev not in stop_graph:
1190
# our previous tip is not merged into stop_revision
1191
raise errors.DivergedBranches(self, other_branch)
1192
# make a new revision history from the graph
1193
current_rev_id = revision_id
1195
while current_rev_id not in (None, _mod_revision.NULL_REVISION):
1196
new_history.append(current_rev_id)
1197
current_rev_id_parents = stop_graph[current_rev_id]
1199
current_rev_id = current_rev_id_parents[0]
1201
current_rev_id = None
1202
new_history.reverse()
1203
self.set_revision_history(new_history)
1206
def update_revisions(self, other, stop_revision=None):
1207
"""See Branch.update_revisions."""
1210
if stop_revision is None:
1211
stop_revision = other.last_revision()
1212
if stop_revision is None:
1213
# if there are no commits, we're done.
1215
# whats the current last revision, before we fetch [and change it
1217
last_rev = self.last_revision()
1218
# we fetch here regardless of whether we need to so that we pickup
1220
self.fetch(other, stop_revision)
1221
my_ancestry = self.repository.get_ancestry(last_rev)
1222
if stop_revision in my_ancestry:
1223
# last_revision is a descendant of stop_revision
1225
self.generate_revision_history(stop_revision, last_rev=last_rev,
1897
1230
def basis_tree(self):
1898
1231
"""See Branch.basis_tree."""
1899
1232
return self.repository.revision_tree(self.last_revision())
1234
@deprecated_method(zero_eight)
1235
def working_tree(self):
1236
"""Create a Working tree object for this branch."""
1238
from bzrlib.transport.local import LocalTransport
1239
if (self.base.find('://') != -1 or
1240
not isinstance(self._transport, LocalTransport)):
1241
raise NoWorkingTree(self.base)
1242
return self.bzrdir.open_workingtree()
1901
1244
@needs_write_lock
1902
def pull(self, source, overwrite=False, stop_revision=None,
1903
_hook_master=None, run_hooks=True, possible_transports=None,
1904
_override_hook_target=None):
1907
:param _hook_master: Private parameter - set the branch to
1908
be supplied as the master to pull hooks.
1909
:param run_hooks: Private parameter - if false, this branch
1910
is being called because it's the master of the primary branch,
1911
so it should not run its hooks.
1912
:param _override_hook_target: Private parameter - set the branch to be
1913
supplied as the target_branch to pull hooks.
1915
result = PullResult()
1916
result.source_branch = source
1917
if _override_hook_target is None:
1918
result.target_branch = self
1920
result.target_branch = _override_hook_target
1245
def pull(self, source, overwrite=False, stop_revision=None):
1246
"""See Branch.pull."""
1921
1247
source.lock_read()
1923
# We assume that during 'pull' the local repository is closer than
1925
graph = self.repository.get_graph(source.repository)
1926
result.old_revno, result.old_revid = self.last_revision_info()
1927
self.update_revisions(source, stop_revision, overwrite=overwrite,
1929
result.tag_conflicts = source.tags.merge_to(self.tags, overwrite)
1930
result.new_revno, result.new_revid = self.last_revision_info()
1932
result.master_branch = _hook_master
1933
result.local_branch = result.target_branch
1935
result.master_branch = result.target_branch
1936
result.local_branch = None
1938
for hook in Branch.hooks['post_pull']:
1249
old_count = len(self.revision_history())
1251
self.update_revisions(source, stop_revision)
1252
except DivergedBranches:
1256
self.set_revision_history(source.revision_history())
1257
new_count = len(self.revision_history())
1258
return new_count - old_count
1941
1260
source.unlock()
1944
def _get_parent_location(self):
1263
def push(self, target, overwrite=False, stop_revision=None):
1264
"""See Branch.push."""
1267
old_count = len(target.revision_history())
1269
target.update_revisions(self, stop_revision)
1270
except DivergedBranches:
1274
target.set_revision_history(self.revision_history())
1275
new_count = len(target.revision_history())
1276
return new_count - old_count
1280
def get_parent(self):
1281
"""See Branch.get_parent."""
1945
1283
_locs = ['parent', 'pull', 'x-pull']
1284
assert self.base[-1] == '/'
1946
1285
for l in _locs:
1948
return self._transport.get_bytes(l).strip('\n')
1949
except errors.NoSuchFile:
1287
parent = self.control_files.get(l).read().strip('\n')
1290
# This is an old-format absolute path to a local branch
1291
# turn it into a url
1292
if parent.startswith('/'):
1293
parent = urlutils.local_path_to_url(parent.decode('utf8'))
1295
return urlutils.join(self.base[:-1], parent)
1296
except errors.InvalidURLJoin, e:
1297
raise errors.InaccessibleParent(parent, self.base)
1954
def push(self, target, overwrite=False, stop_revision=None,
1955
_override_hook_source_branch=None):
1958
This is the basic concrete implementation of push()
1960
:param _override_hook_source_branch: If specified, run
1961
the hooks passing this Branch as the source, rather than self.
1962
This is for use of RemoteBranch, where push is delegated to the
1963
underlying vfs-based Branch.
1965
# TODO: Public option to disable running hooks - should be trivial but
1967
return _run_with_write_locked_target(
1968
target, self._push_with_bound_branches, target, overwrite,
1970
_override_hook_source_branch=_override_hook_source_branch)
1972
def _push_with_bound_branches(self, target, overwrite,
1974
_override_hook_source_branch=None):
1975
"""Push from self into target, and into target's master if any.
1977
This is on the base BzrBranch class even though it doesn't support
1978
bound branches because the *target* might be bound.
1981
if _override_hook_source_branch:
1982
result.source_branch = _override_hook_source_branch
1983
for hook in Branch.hooks['post_push']:
1986
bound_location = target.get_bound_location()
1987
if bound_location and target.base != bound_location:
1988
# there is a master branch.
1990
# XXX: Why the second check? Is it even supported for a branch to
1991
# be bound to itself? -- mbp 20070507
1992
master_branch = target.get_master_branch()
1993
master_branch.lock_write()
1995
# push into the master from this branch.
1996
self._basic_push(master_branch, overwrite, stop_revision)
1997
# and push into the target branch from this. Note that we push from
1998
# this branch again, because its considered the highest bandwidth
2000
result = self._basic_push(target, overwrite, stop_revision)
2001
result.master_branch = master_branch
2002
result.local_branch = target
2006
master_branch.unlock()
2009
result = self._basic_push(target, overwrite, stop_revision)
2010
# TODO: Why set master_branch and local_branch if there's no
2011
# binding? Maybe cleaner to just leave them unset? -- mbp
2013
result.master_branch = target
2014
result.local_branch = None
2018
def _basic_push(self, target, overwrite, stop_revision):
2019
"""Basic implementation of push without bound branches or hooks.
2021
Must be called with self read locked and target write locked.
2023
result = PushResult()
2024
result.source_branch = self
2025
result.target_branch = target
2026
result.old_revno, result.old_revid = target.last_revision_info()
2027
if result.old_revid != self.last_revision():
2028
# We assume that during 'push' this repository is closer than
2030
graph = self.repository.get_graph(target.repository)
2031
target.update_revisions(self, stop_revision, overwrite=overwrite,
2033
if self._push_should_merge_tags():
2034
result.tag_conflicts = self.tags.merge_to(target.tags, overwrite)
2035
result.new_revno, result.new_revid = target.last_revision_info()
2038
def _push_should_merge_tags(self):
2039
"""Should _basic_push merge this branch's tags into the target?
2041
The default implementation returns False if this branch has no tags,
2042
and True the rest of the time. Subclasses may override this.
2044
return self.tags.supports_tags() and self.tags.get_tag_dict()
2046
def get_parent(self):
2047
"""See Branch.get_parent."""
2048
parent = self._get_parent_location()
2051
# This is an old-format absolute path to a local branch
2052
# turn it into a url
2053
if parent.startswith('/'):
2054
parent = urlutils.local_path_to_url(parent.decode('utf8'))
2056
return urlutils.join(self.base[:-1], parent)
2057
except errors.InvalidURLJoin, e:
2058
raise errors.InaccessibleParent(parent, self.base)
2060
def get_stacked_on_url(self):
2061
raise errors.UnstackableBranchFormat(self._format, self.base)
1300
def get_push_location(self):
1301
"""See Branch.get_push_location."""
1302
push_loc = self.get_config().get_user_option('push_location')
2063
1305
def set_push_location(self, location):
2064
1306
"""See Branch.set_push_location."""
2072
1314
# TODO: Maybe delete old location files?
2073
1315
# URLs should never be unicode, even on the local fs,
2074
1316
# FIXUP this and get_parent in a future branch format bump:
2075
# read and rewrite the file. RBC 20060125
1317
# read and rewrite the file, and have the new format code read
1318
# using .get not .get_utf8. RBC 20060125
1320
self.control_files._transport.delete('parent')
2077
1322
if isinstance(url, unicode):
2079
1324
url = url.encode('ascii')
2080
1325
except UnicodeEncodeError:
2081
raise errors.InvalidURL(url,
1326
raise bzrlib.errors.InvalidURL(url,
2082
1327
"Urls must be 7-bit ascii, "
2083
1328
"use bzrlib.urlutils.escape")
2084
1330
url = urlutils.relative_url(self.base, url)
2085
self._set_parent_location(url)
2087
def _set_parent_location(self, url):
2089
self._transport.delete('parent')
2091
self._transport.put_bytes('parent', url + '\n',
2092
mode=self.bzrdir._get_file_mode())
2094
def set_stacked_on_url(self, url):
2095
raise errors.UnstackableBranchFormat(self._format, self.base)
1331
self.control_files.put('parent', StringIO(url + '\n'))
1333
@deprecated_function(zero_nine)
1334
def tree_config(self):
1335
"""DEPRECATED; call get_config instead.
1336
TreeConfig has become part of BranchConfig."""
1337
return TreeConfig(self)
2098
1340
class BzrBranch5(BzrBranch):
2099
"""A format 5 branch. This supports new features over plain branches.
1341
"""A format 5 branch. This supports new features over plan branches.
2101
1343
It has support for a master_branch which is the data for bound branches.
1351
super(BzrBranch5, self).__init__(_format=_format,
1352
_control_files=_control_files,
1354
_repository=_repository)
2104
1356
@needs_write_lock
2105
def pull(self, source, overwrite=False, stop_revision=None,
2106
run_hooks=True, possible_transports=None,
2107
_override_hook_target=None):
2108
"""Pull from source into self, updating my master if any.
2110
:param run_hooks: Private parameter - if false, this branch
2111
is being called because it's the master of the primary branch,
2112
so it should not run its hooks.
1357
def pull(self, source, overwrite=False, stop_revision=None):
1358
"""Extends branch.pull to be bound branch aware."""
2114
1359
bound_location = self.get_bound_location()
2115
master_branch = None
2116
if bound_location and source.base != bound_location:
1360
if source.base != bound_location:
2117
1361
# not pulling from master, so we need to update master.
2118
master_branch = self.get_master_branch(possible_transports)
2119
master_branch.lock_write()
2122
# pull from source into master.
2123
master_branch.pull(source, overwrite, stop_revision,
2125
return super(BzrBranch5, self).pull(source, overwrite,
2126
stop_revision, _hook_master=master_branch,
2127
run_hooks=run_hooks,
2128
_override_hook_target=_override_hook_target)
2131
master_branch.unlock()
1362
master_branch = self.get_master_branch()
1364
master_branch.pull(source)
1365
source = master_branch
1366
return super(BzrBranch5, self).pull(source, overwrite, stop_revision)
1369
def push(self, target, overwrite=False, stop_revision=None):
1370
"""Updates branch.push to be bound branch aware."""
1371
bound_location = target.get_bound_location()
1372
if target.base != bound_location:
1373
# not pushing to master, so we need to update master.
1374
master_branch = target.get_master_branch()
1376
# push into the master from this branch.
1377
super(BzrBranch5, self).push(master_branch, overwrite,
1379
# and push into the target branch from this. Note that we push from
1380
# this branch again, because its considered the highest bandwidth
1382
return super(BzrBranch5, self).push(target, overwrite, stop_revision)
2133
1384
def get_bound_location(self):
2135
return self._transport.get_bytes('bound')[:-1]
1386
return self.control_files.get_utf8('bound').read()[:-1]
2136
1387
except errors.NoSuchFile:
2139
1390
@needs_read_lock
2140
def get_master_branch(self, possible_transports=None):
1391
def get_master_branch(self):
2141
1392
"""Return the branch we are bound to.
2143
1394
:return: Either a Branch, or None
2205
1470
return self.set_bound_location(None)
2207
1472
@needs_write_lock
2208
def update(self, possible_transports=None):
2209
1474
"""Synchronise this branch with the master branch if any.
2211
1476
:return: None or the last_revision that was pivoted out during the
2214
master = self.get_master_branch(possible_transports)
1479
master = self.get_master_branch()
2215
1480
if master is not None:
2216
old_tip = _mod_revision.ensure_null(self.last_revision())
1481
old_tip = self.last_revision()
2217
1482
self.pull(master, overwrite=True)
2218
if self.repository.get_graph().is_ancestor(old_tip,
2219
_mod_revision.ensure_null(self.last_revision())):
1483
if old_tip in self.repository.get_ancestry(self.last_revision()):
2225
class BzrBranch7(BzrBranch5):
2226
"""A branch with support for a fallback repository."""
2228
def _get_fallback_repository(self, url):
2229
"""Get the repository we fallback to at url."""
2230
url = urlutils.join(self.base, url)
2231
a_bzrdir = bzrdir.BzrDir.open(url,
2232
possible_transports=[self._transport])
2233
return a_bzrdir.open_branch().repository
2235
def _activate_fallback_location(self, url):
2236
"""Activate the branch/repository from url as a fallback repository."""
2237
self.repository.add_fallback_repository(
2238
self._get_fallback_repository(url))
2240
def _open_hook(self):
2242
url = self.get_stacked_on_url()
2243
except (errors.UnstackableRepositoryFormat, errors.NotStacked,
2244
errors.UnstackableBranchFormat):
2247
for hook in Branch.hooks['transform_fallback_location']:
2248
url = hook(self, url)
2250
hook_name = Branch.hooks.get_hook_name(hook)
2251
raise AssertionError(
2252
"'transform_fallback_location' hook %s returned "
2253
"None, not a URL." % hook_name)
2254
self._activate_fallback_location(url)
2256
def _check_stackable_repo(self):
2257
if not self.repository._format.supports_external_lookups:
2258
raise errors.UnstackableRepositoryFormat(self.repository._format,
2259
self.repository.base)
2261
def __init__(self, *args, **kwargs):
2262
super(BzrBranch7, self).__init__(*args, **kwargs)
2263
self._last_revision_info_cache = None
2264
self._partial_revision_history_cache = []
2266
def _clear_cached_state(self):
2267
super(BzrBranch7, self)._clear_cached_state()
2268
self._last_revision_info_cache = None
2269
self._partial_revision_history_cache = []
2271
def _last_revision_info(self):
2272
revision_string = self._transport.get_bytes('last-revision')
2273
revno, revision_id = revision_string.rstrip('\n').split(' ', 1)
2274
revision_id = cache_utf8.get_cached_utf8(revision_id)
2276
return revno, revision_id
2278
def _write_last_revision_info(self, revno, revision_id):
2279
"""Simply write out the revision id, with no checks.
2281
Use set_last_revision_info to perform this safely.
2283
Does not update the revision_history cache.
2284
Intended to be called by set_last_revision_info and
2285
_write_revision_history.
2287
revision_id = _mod_revision.ensure_null(revision_id)
2288
out_string = '%d %s\n' % (revno, revision_id)
2289
self._transport.put_bytes('last-revision', out_string,
2290
mode=self.bzrdir._get_file_mode())
2293
def set_last_revision_info(self, revno, revision_id):
2294
revision_id = _mod_revision.ensure_null(revision_id)
2295
old_revno, old_revid = self.last_revision_info()
2296
if self._get_append_revisions_only():
2297
self._check_history_violation(revision_id)
2298
self._run_pre_change_branch_tip_hooks(revno, revision_id)
2299
self._write_last_revision_info(revno, revision_id)
2300
self._clear_cached_state()
2301
self._last_revision_info_cache = revno, revision_id
2302
self._run_post_change_branch_tip_hooks(old_revno, old_revid)
2304
def _synchronize_history(self, destination, revision_id):
2305
"""Synchronize last revision and revision history between branches.
2307
:see: Branch._synchronize_history
2309
# XXX: The base Branch has a fast implementation of this method based
2310
# on set_last_revision_info, but BzrBranch/BzrBranch5 have a slower one
2311
# that uses set_revision_history. This class inherits from BzrBranch5,
2312
# but wants the fast implementation, so it calls
2313
# Branch._synchronize_history directly.
2314
Branch._synchronize_history(self, destination, revision_id)
2316
def _check_history_violation(self, revision_id):
2317
last_revision = _mod_revision.ensure_null(self.last_revision())
2318
if _mod_revision.is_null(last_revision):
2320
if last_revision not in self._lefthand_history(revision_id):
2321
raise errors.AppendRevisionsOnlyViolation(self.base)
2323
def _gen_revision_history(self):
2324
"""Generate the revision history from last revision
2326
last_revno, last_revision = self.last_revision_info()
2327
self._extend_partial_history(stop_index=last_revno-1)
2328
return list(reversed(self._partial_revision_history_cache))
2330
def _extend_partial_history(self, stop_index=None, stop_revision=None):
2331
"""Extend the partial history to include a given index
2333
If a stop_index is supplied, stop when that index has been reached.
2334
If a stop_revision is supplied, stop when that revision is
2335
encountered. Otherwise, stop when the beginning of history is
2338
:param stop_index: The index which should be present. When it is
2339
present, history extension will stop.
2340
:param revision_id: The revision id which should be present. When
2341
it is encountered, history extension will stop.
2343
repo = self.repository
2344
if len(self._partial_revision_history_cache) == 0:
2345
iterator = repo.iter_reverse_revision_history(self.last_revision())
2347
start_revision = self._partial_revision_history_cache[-1]
2348
iterator = repo.iter_reverse_revision_history(start_revision)
2349
#skip the last revision in the list
2350
next_revision = iterator.next()
2351
for revision_id in iterator:
2352
self._partial_revision_history_cache.append(revision_id)
2353
if (stop_index is not None and
2354
len(self._partial_revision_history_cache) > stop_index):
2356
if revision_id == stop_revision:
2359
def _write_revision_history(self, history):
2360
"""Factored out of set_revision_history.
2362
This performs the actual writing to disk, with format-specific checks.
2363
It is intended to be called by BzrBranch5.set_revision_history.
2365
if len(history) == 0:
2366
last_revision = 'null:'
2368
if history != self._lefthand_history(history[-1]):
2369
raise errors.NotLefthandHistory(history)
2370
last_revision = history[-1]
2371
if self._get_append_revisions_only():
2372
self._check_history_violation(last_revision)
2373
self._write_last_revision_info(len(history), last_revision)
2376
def _set_parent_location(self, url):
2377
"""Set the parent branch"""
2378
self._set_config_location('parent_location', url, make_relative=True)
2381
def _get_parent_location(self):
2382
"""Set the parent branch"""
2383
return self._get_config_location('parent_location')
2385
def set_push_location(self, location):
2386
"""See Branch.set_push_location."""
2387
self._set_config_location('push_location', location)
2389
def set_bound_location(self, location):
2390
"""See Branch.set_push_location."""
2392
config = self.get_config()
2393
if location is None:
2394
if config.get_user_option('bound') != 'True':
2397
config.set_user_option('bound', 'False', warn_masked=True)
2400
self._set_config_location('bound_location', location,
2402
config.set_user_option('bound', 'True', warn_masked=True)
2405
def _get_bound_location(self, bound):
2406
"""Return the bound location in the config file.
2408
Return None if the bound parameter does not match"""
2409
config = self.get_config()
2410
config_bound = (config.get_user_option('bound') == 'True')
2411
if config_bound != bound:
2413
return self._get_config_location('bound_location', config=config)
2415
def get_bound_location(self):
2416
"""See Branch.set_push_location."""
2417
return self._get_bound_location(True)
2419
def get_old_bound_location(self):
2420
"""See Branch.get_old_bound_location"""
2421
return self._get_bound_location(False)
2423
def get_stacked_on_url(self):
2424
# you can always ask for the URL; but you might not be able to use it
2425
# if the repo can't support stacking.
2426
## self._check_stackable_repo()
2427
stacked_url = self._get_config_location('stacked_on_location')
2428
if stacked_url is None:
2429
raise errors.NotStacked(self)
2432
def set_append_revisions_only(self, enabled):
2437
self.get_config().set_user_option('append_revisions_only', value,
2440
def set_stacked_on_url(self, url):
2441
self._check_stackable_repo()
2444
old_url = self.get_stacked_on_url()
2445
except (errors.NotStacked, errors.UnstackableBranchFormat,
2446
errors.UnstackableRepositoryFormat):
2449
# repositories don't offer an interface to remove fallback
2450
# repositories today; take the conceptually simpler option and just
2452
self.repository = self.bzrdir.find_repository()
2453
# for every revision reference the branch has, ensure it is pulled
2455
source_repository = self._get_fallback_repository(old_url)
2456
for revision_id in chain([self.last_revision()],
2457
self.tags.get_reverse_tag_dict()):
2458
self.repository.fetch(source_repository, revision_id,
2461
self._activate_fallback_location(url)
2462
# write this out after the repository is stacked to avoid setting a
2463
# stacked config that doesn't work.
2464
self._set_config_location('stacked_on_location', url)
2466
def _get_append_revisions_only(self):
2467
value = self.get_config().get_user_option('append_revisions_only')
2468
return value == 'True'
2470
def _make_tags(self):
2471
return BasicTags(self)
2474
def generate_revision_history(self, revision_id, last_rev=None,
2476
"""See BzrBranch5.generate_revision_history"""
2477
history = self._lefthand_history(revision_id, last_rev, other_branch)
2478
revno = len(history)
2479
self.set_last_revision_info(revno, revision_id)
2482
def get_rev_id(self, revno, history=None):
2483
"""Find the revision id of the specified revno."""
2485
return _mod_revision.NULL_REVISION
2487
last_revno, last_revision_id = self.last_revision_info()
2488
if revno <= 0 or revno > last_revno:
2489
raise errors.NoSuchRevision(self, revno)
2491
if history is not None:
2492
return history[revno - 1]
2494
index = last_revno - revno
2495
if len(self._partial_revision_history_cache) <= index:
2496
self._extend_partial_history(stop_index=index)
2497
if len(self._partial_revision_history_cache) > index:
2498
return self._partial_revision_history_cache[index]
2500
raise errors.NoSuchRevision(self, revno)
2503
def revision_id_to_revno(self, revision_id):
2504
"""Given a revision id, return its revno"""
2505
if _mod_revision.is_null(revision_id):
2508
index = self._partial_revision_history_cache.index(revision_id)
2510
self._extend_partial_history(stop_revision=revision_id)
2511
index = len(self._partial_revision_history_cache) - 1
2512
if self._partial_revision_history_cache[index] != revision_id:
2513
raise errors.NoSuchRevision(self, revision_id)
2514
return self.revno() - index
2517
class BzrBranch6(BzrBranch7):
2518
"""See BzrBranchFormat6 for the capabilities of this branch.
2520
This subclass of BzrBranch7 disables the new features BzrBranch7 added,
2524
def get_stacked_on_url(self):
2525
raise errors.UnstackableBranchFormat(self._format, self.base)
2527
def set_stacked_on_url(self, url):
2528
raise errors.UnstackableBranchFormat(self._format, self.base)
2531
######################################################################
2532
# results of operations
2535
class _Result(object):
2537
def _show_tag_conficts(self, to_file):
2538
if not getattr(self, 'tag_conflicts', None):
2540
to_file.write('Conflicting tags:\n')
2541
for name, value1, value2 in self.tag_conflicts:
2542
to_file.write(' %s\n' % (name, ))
2545
class PullResult(_Result):
2546
"""Result of a Branch.pull operation.
2548
:ivar old_revno: Revision number before pull.
2549
:ivar new_revno: Revision number after pull.
2550
:ivar old_revid: Tip revision id before pull.
2551
:ivar new_revid: Tip revision id after pull.
2552
:ivar source_branch: Source (local) branch object.
2553
:ivar master_branch: Master branch of the target, or the target if no
2555
:ivar local_branch: target branch if there is a Master, else None
2556
:ivar target_branch: Target/destination branch object.
2557
:ivar tag_conflicts: A list of tag conflicts, see BasicTags.merge_to
2561
# DEPRECATED: pull used to return the change in revno
2562
return self.new_revno - self.old_revno
2564
def report(self, to_file):
2566
if self.old_revid == self.new_revid:
2567
to_file.write('No revisions to pull.\n')
2569
to_file.write('Now on revision %d.\n' % self.new_revno)
2570
self._show_tag_conficts(to_file)
2573
class PushResult(_Result):
2574
"""Result of a Branch.push operation.
2576
:ivar old_revno: Revision number before push.
2577
:ivar new_revno: Revision number after push.
2578
:ivar old_revid: Tip revision id before push.
2579
:ivar new_revid: Tip revision id after push.
2580
:ivar source_branch: Source branch object.
2581
:ivar master_branch: Master branch of the target, or None.
2582
:ivar target_branch: Target/destination branch object.
2586
# DEPRECATED: push used to return the change in revno
2587
return self.new_revno - self.old_revno
2589
def report(self, to_file):
2590
"""Write a human-readable description of the result."""
2591
if self.old_revid == self.new_revid:
2592
to_file.write('No new revisions to push.\n')
2594
to_file.write('Pushed up to revision %d.\n' % self.new_revno)
2595
self._show_tag_conficts(to_file)
1489
class BranchTestProviderAdapter(object):
1490
"""A tool to generate a suite testing multiple branch formats at once.
1492
This is done by copying the test once for each transport and injecting
1493
the transport_server, transport_readonly_server, and branch_format
1494
classes into each copy. Each copy is also given a new id() to make it
1498
def __init__(self, transport_server, transport_readonly_server, formats):
1499
self._transport_server = transport_server
1500
self._transport_readonly_server = transport_readonly_server
1501
self._formats = formats
1503
def adapt(self, test):
1504
result = TestSuite()
1505
for branch_format, bzrdir_format in self._formats:
1506
new_test = deepcopy(test)
1507
new_test.transport_server = self._transport_server
1508
new_test.transport_readonly_server = self._transport_readonly_server
1509
new_test.bzrdir_format = bzrdir_format
1510
new_test.branch_format = branch_format
1511
def make_new_test_id():
1512
new_id = "%s(%s)" % (new_test.id(), branch_format.__class__.__name__)
1513
return lambda: new_id
1514
new_test.id = make_new_test_id()
1515
result.addTest(new_test)
2598
1519
class BranchCheckResult(object):