1
# Copyright (C) 2005-2011 Canonical Ltd
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11
# GNU General Public License for more details.
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
from bzrlib.lazy_import import lazy_import
18
lazy_import(globals(), """
42
revision as _mod_revision,
48
from bzrlib.bundle import serializer
49
from bzrlib.revisiontree import RevisionTree
50
from bzrlib.store.versioned import VersionedFileStore
51
from bzrlib.testament import Testament
60
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
61
from bzrlib.inter import InterObject
62
from bzrlib.inventory import (
68
from bzrlib.recordcounter import RecordCounter
69
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
70
from bzrlib.trace import (
71
log_exception_quietly, note, mutter, mutter_callsite, warning)
74
# Old formats display a warning, but only once
75
_deprecation_warning_done = False
78
class IsInWriteGroupError(errors.InternalBzrError):
80
_fmt = "May not refresh_data of repo %(repo)s while in a write group."
82
def __init__(self, repo):
83
errors.InternalBzrError.__init__(self, repo=repo)
86
class CommitBuilder(object):
87
"""Provides an interface to build up a commit.
89
This allows describing a tree to be committed without needing to
90
know the internals of the format of the repository.
93
# all clients should supply tree roots.
94
record_root_entry = True
95
# the default CommitBuilder does not manage trees whose root is versioned.
96
_versioned_root = False
98
def __init__(self, repository, parents, config, timestamp=None,
99
timezone=None, committer=None, revprops=None,
101
"""Initiate a CommitBuilder.
103
:param repository: Repository to commit to.
104
:param parents: Revision ids of the parents of the new revision.
105
:param config: Configuration to use.
106
:param timestamp: Optional timestamp recorded for commit.
107
:param timezone: Optional timezone for timestamp.
108
:param committer: Optional committer to set for commit.
109
:param revprops: Optional dictionary of revision properties.
110
:param revision_id: Optional revision id.
112
self._config = config
114
if committer is None:
115
self._committer = self._config.username()
116
elif not isinstance(committer, unicode):
117
self._committer = committer.decode() # throw if non-ascii
119
self._committer = committer
121
self.new_inventory = Inventory(None)
122
self._new_revision_id = revision_id
123
self.parents = parents
124
self.repository = repository
127
if revprops is not None:
128
self._validate_revprops(revprops)
129
self._revprops.update(revprops)
131
if timestamp is None:
132
timestamp = time.time()
133
# Restrict resolution to 1ms
134
self._timestamp = round(timestamp, 3)
137
self._timezone = osutils.local_time_offset()
139
self._timezone = int(timezone)
141
self._generate_revision_if_needed()
142
self.__heads = graph.HeadsCache(repository.get_graph()).heads
143
self._basis_delta = []
144
# API compatibility, older code that used CommitBuilder did not call
145
# .record_delete(), which means the delta that is computed would not be
146
# valid. Callers that will call record_delete() should call
147
# .will_record_deletes() to indicate that.
148
self._recording_deletes = False
149
# memo'd check for no-op commits.
150
self._any_changes = False
152
def any_changes(self):
153
"""Return True if any entries were changed.
155
This includes merge-only changes. It is the core for the --unchanged
158
:return: True if any changes have occured.
160
return self._any_changes
162
def _validate_unicode_text(self, text, context):
163
"""Verify things like commit messages don't have bogus characters."""
165
raise ValueError('Invalid value for %s: %r' % (context, text))
167
def _validate_revprops(self, revprops):
168
for key, value in revprops.iteritems():
169
# We know that the XML serializers do not round trip '\r'
170
# correctly, so refuse to accept them
171
if not isinstance(value, basestring):
172
raise ValueError('revision property (%s) is not a valid'
173
' (unicode) string: %r' % (key, value))
174
self._validate_unicode_text(value,
175
'revision property (%s)' % (key,))
177
def _ensure_fallback_inventories(self):
178
"""Ensure that appropriate inventories are available.
180
This only applies to repositories that are stacked, and is about
181
enusring the stacking invariants. Namely, that for any revision that is
182
present, we either have all of the file content, or we have the parent
183
inventory and the delta file content.
185
if not self.repository._fallback_repositories:
187
if not self.repository._format.supports_chks:
188
raise errors.BzrError("Cannot commit directly to a stacked branch"
189
" in pre-2a formats. See "
190
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
191
# This is a stacked repo, we need to make sure we have the parent
192
# inventories for the parents.
193
parent_keys = [(p,) for p in self.parents]
194
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
195
missing_parent_keys = set([pk for pk in parent_keys
196
if pk not in parent_map])
197
fallback_repos = list(reversed(self.repository._fallback_repositories))
198
missing_keys = [('inventories', pk[0])
199
for pk in missing_parent_keys]
201
while missing_keys and fallback_repos:
202
fallback_repo = fallback_repos.pop()
203
source = fallback_repo._get_source(self.repository._format)
204
sink = self.repository._get_sink()
205
stream = source.get_stream_for_missing_keys(missing_keys)
206
missing_keys = sink.insert_stream_without_locking(stream,
207
self.repository._format)
209
raise errors.BzrError('Unable to fill in parent inventories for a'
212
def commit(self, message):
213
"""Make the actual commit.
215
:return: The revision id of the recorded revision.
217
self._validate_unicode_text(message, 'commit message')
218
rev = _mod_revision.Revision(
219
timestamp=self._timestamp,
220
timezone=self._timezone,
221
committer=self._committer,
223
inventory_sha1=self.inv_sha1,
224
revision_id=self._new_revision_id,
225
properties=self._revprops)
226
rev.parent_ids = self.parents
227
self.repository.add_revision(self._new_revision_id, rev,
228
self.new_inventory, self._config)
229
self._ensure_fallback_inventories()
230
self.repository.commit_write_group()
231
return self._new_revision_id
234
"""Abort the commit that is being built.
236
self.repository.abort_write_group()
238
def revision_tree(self):
239
"""Return the tree that was just committed.
241
After calling commit() this can be called to get a RevisionTree
242
representing the newly committed tree. This is preferred to
243
calling Repository.revision_tree() because that may require
244
deserializing the inventory, while we already have a copy in
247
if self.new_inventory is None:
248
self.new_inventory = self.repository.get_inventory(
249
self._new_revision_id)
250
return RevisionTree(self.repository, self.new_inventory,
251
self._new_revision_id)
253
def finish_inventory(self):
254
"""Tell the builder that the inventory is finished.
256
:return: The inventory id in the repository, which can be used with
257
repository.get_inventory.
259
if self.new_inventory is None:
260
# an inventory delta was accumulated without creating a new
262
basis_id = self.basis_delta_revision
263
# We ignore the 'inventory' returned by add_inventory_by_delta
264
# because self.new_inventory is used to hint to the rest of the
265
# system what code path was taken
266
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
267
basis_id, self._basis_delta, self._new_revision_id,
270
if self.new_inventory.root is None:
271
raise AssertionError('Root entry should be supplied to'
272
' record_entry_contents, as of bzr 0.10.')
273
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
274
self.new_inventory.revision_id = self._new_revision_id
275
self.inv_sha1 = self.repository.add_inventory(
276
self._new_revision_id,
280
return self._new_revision_id
282
def _gen_revision_id(self):
283
"""Return new revision-id."""
284
return generate_ids.gen_revision_id(self._committer, self._timestamp)
286
def _generate_revision_if_needed(self):
287
"""Create a revision id if None was supplied.
289
If the repository can not support user-specified revision ids
290
they should override this function and raise CannotSetRevisionId
291
if _new_revision_id is not None.
293
:raises: CannotSetRevisionId
295
if self._new_revision_id is None:
296
self._new_revision_id = self._gen_revision_id()
297
self.random_revid = True
299
self.random_revid = False
301
def _heads(self, file_id, revision_ids):
302
"""Calculate the graph heads for revision_ids in the graph of file_id.
304
This can use either a per-file graph or a global revision graph as we
305
have an identity relationship between the two graphs.
307
return self.__heads(revision_ids)
309
def _check_root(self, ie, parent_invs, tree):
310
"""Helper for record_entry_contents.
312
:param ie: An entry being added.
313
:param parent_invs: The inventories of the parent revisions of the
315
:param tree: The tree that is being committed.
317
# In this revision format, root entries have no knit or weave When
318
# serializing out to disk and back in root.revision is always
320
ie.revision = self._new_revision_id
322
def _require_root_change(self, tree):
323
"""Enforce an appropriate root object change.
325
This is called once when record_iter_changes is called, if and only if
326
the root was not in the delta calculated by record_iter_changes.
328
:param tree: The tree which is being committed.
330
if len(self.parents) == 0:
331
raise errors.RootMissing()
332
entry = entry_factory['directory'](tree.path2id(''), '',
334
entry.revision = self._new_revision_id
335
self._basis_delta.append(('', '', entry.file_id, entry))
337
def _get_delta(self, ie, basis_inv, path):
338
"""Get a delta against the basis inventory for ie."""
339
if ie.file_id not in basis_inv:
341
result = (None, path, ie.file_id, ie)
342
self._basis_delta.append(result)
344
elif ie != basis_inv[ie.file_id]:
346
# TODO: avoid tis id2path call.
347
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
348
self._basis_delta.append(result)
354
def get_basis_delta(self):
355
"""Return the complete inventory delta versus the basis inventory.
357
This has been built up with the calls to record_delete and
358
record_entry_contents. The client must have already called
359
will_record_deletes() to indicate that they will be generating a
362
:return: An inventory delta, suitable for use with apply_delta, or
363
Repository.add_inventory_by_delta, etc.
365
if not self._recording_deletes:
366
raise AssertionError("recording deletes not activated.")
367
return self._basis_delta
369
def record_delete(self, path, file_id):
370
"""Record that a delete occured against a basis tree.
372
This is an optional API - when used it adds items to the basis_delta
373
being accumulated by the commit builder. It cannot be called unless the
374
method will_record_deletes() has been called to inform the builder that
375
a delta is being supplied.
377
:param path: The path of the thing deleted.
378
:param file_id: The file id that was deleted.
380
if not self._recording_deletes:
381
raise AssertionError("recording deletes not activated.")
382
delta = (path, None, file_id, None)
383
self._basis_delta.append(delta)
384
self._any_changes = True
387
def will_record_deletes(self):
388
"""Tell the commit builder that deletes are being notified.
390
This enables the accumulation of an inventory delta; for the resulting
391
commit to be valid, deletes against the basis MUST be recorded via
392
builder.record_delete().
394
self._recording_deletes = True
396
basis_id = self.parents[0]
398
basis_id = _mod_revision.NULL_REVISION
399
self.basis_delta_revision = basis_id
401
def record_entry_contents(self, ie, parent_invs, path, tree,
403
"""Record the content of ie from tree into the commit if needed.
405
Side effect: sets ie.revision when unchanged
407
:param ie: An inventory entry present in the commit.
408
:param parent_invs: The inventories of the parent revisions of the
410
:param path: The path the entry is at in the tree.
411
:param tree: The tree which contains this entry and should be used to
413
:param content_summary: Summary data from the tree about the paths
414
content - stat, length, exec, sha/link target. This is only
415
accessed when the entry has a revision of None - that is when it is
416
a candidate to commit.
417
:return: A tuple (change_delta, version_recorded, fs_hash).
418
change_delta is an inventory_delta change for this entry against
419
the basis tree of the commit, or None if no change occured against
421
version_recorded is True if a new version of the entry has been
422
recorded. For instance, committing a merge where a file was only
423
changed on the other side will return (delta, False).
424
fs_hash is either None, or the hash details for the path (currently
425
a tuple of the contents sha1 and the statvalue returned by
426
tree.get_file_with_stat()).
428
if self.new_inventory.root is None:
429
if ie.parent_id is not None:
430
raise errors.RootMissing()
431
self._check_root(ie, parent_invs, tree)
432
if ie.revision is None:
433
kind = content_summary[0]
435
# ie is carried over from a prior commit
437
# XXX: repository specific check for nested tree support goes here - if
438
# the repo doesn't want nested trees we skip it ?
439
if (kind == 'tree-reference' and
440
not self.repository._format.supports_tree_reference):
441
# mismatch between commit builder logic and repository:
442
# this needs the entry creation pushed down into the builder.
443
raise NotImplementedError('Missing repository subtree support.')
444
self.new_inventory.add(ie)
446
# TODO: slow, take it out of the inner loop.
448
basis_inv = parent_invs[0]
450
basis_inv = Inventory(root_id=None)
452
# ie.revision is always None if the InventoryEntry is considered
453
# for committing. We may record the previous parents revision if the
454
# content is actually unchanged against a sole head.
455
if ie.revision is not None:
456
if not self._versioned_root and path == '':
457
# repositories that do not version the root set the root's
458
# revision to the new commit even when no change occurs (more
459
# specifically, they do not record a revision on the root; and
460
# the rev id is assigned to the root during deserialisation -
461
# this masks when a change may have occurred against the basis.
462
# To match this we always issue a delta, because the revision
463
# of the root will always be changing.
464
if ie.file_id in basis_inv:
465
delta = (basis_inv.id2path(ie.file_id), path,
469
delta = (None, path, ie.file_id, ie)
470
self._basis_delta.append(delta)
471
return delta, False, None
473
# we don't need to commit this, because the caller already
474
# determined that an existing revision of this file is
475
# appropriate. If it's not being considered for committing then
476
# it and all its parents to the root must be unaltered so
477
# no-change against the basis.
478
if ie.revision == self._new_revision_id:
479
raise AssertionError("Impossible situation, a skipped "
480
"inventory entry (%r) claims to be modified in this "
481
"commit (%r).", (ie, self._new_revision_id))
482
return None, False, None
483
# XXX: Friction: parent_candidates should return a list not a dict
484
# so that we don't have to walk the inventories again.
485
parent_candiate_entries = ie.parent_candidates(parent_invs)
486
head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
488
for inv in parent_invs:
489
if ie.file_id in inv:
490
old_rev = inv[ie.file_id].revision
491
if old_rev in head_set:
492
heads.append(inv[ie.file_id].revision)
493
head_set.remove(inv[ie.file_id].revision)
496
# now we check to see if we need to write a new record to the
498
# We write a new entry unless there is one head to the ancestors, and
499
# the kind-derived content is unchanged.
501
# Cheapest check first: no ancestors, or more the one head in the
502
# ancestors, we write a new node.
506
# There is a single head, look it up for comparison
507
parent_entry = parent_candiate_entries[heads[0]]
508
# if the non-content specific data has changed, we'll be writing a
510
if (parent_entry.parent_id != ie.parent_id or
511
parent_entry.name != ie.name):
513
# now we need to do content specific checks:
515
# if the kind changed the content obviously has
516
if kind != parent_entry.kind:
518
# Stat cache fingerprint feedback for the caller - None as we usually
519
# don't generate one.
522
if content_summary[2] is None:
523
raise ValueError("Files must not have executable = None")
525
# We can't trust a check of the file length because of content
527
if (# if the exec bit has changed we have to store:
528
parent_entry.executable != content_summary[2]):
530
elif parent_entry.text_sha1 == content_summary[3]:
531
# all meta and content is unchanged (using a hash cache
532
# hit to check the sha)
533
ie.revision = parent_entry.revision
534
ie.text_size = parent_entry.text_size
535
ie.text_sha1 = parent_entry.text_sha1
536
ie.executable = parent_entry.executable
537
return self._get_delta(ie, basis_inv, path), False, None
539
# Either there is only a hash change(no hash cache entry,
540
# or same size content change), or there is no change on
542
# Provide the parent's hash to the store layer, so that the
543
# content is unchanged we will not store a new node.
544
nostore_sha = parent_entry.text_sha1
546
# We want to record a new node regardless of the presence or
547
# absence of a content change in the file.
549
ie.executable = content_summary[2]
550
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
552
text = file_obj.read()
556
ie.text_sha1, ie.text_size = self._add_text_to_weave(
557
ie.file_id, text, heads, nostore_sha)
558
# Let the caller know we generated a stat fingerprint.
559
fingerprint = (ie.text_sha1, stat_value)
560
except errors.ExistingContent:
561
# Turns out that the file content was unchanged, and we were
562
# only going to store a new node if it was changed. Carry over
564
ie.revision = parent_entry.revision
565
ie.text_size = parent_entry.text_size
566
ie.text_sha1 = parent_entry.text_sha1
567
ie.executable = parent_entry.executable
568
return self._get_delta(ie, basis_inv, path), False, None
569
elif kind == 'directory':
571
# all data is meta here, nothing specific to directory, so
573
ie.revision = parent_entry.revision
574
return self._get_delta(ie, basis_inv, path), False, None
575
self._add_text_to_weave(ie.file_id, '', heads, None)
576
elif kind == 'symlink':
577
current_link_target = content_summary[3]
579
# symlink target is not generic metadata, check if it has
581
if current_link_target != parent_entry.symlink_target:
584
# unchanged, carry over.
585
ie.revision = parent_entry.revision
586
ie.symlink_target = parent_entry.symlink_target
587
return self._get_delta(ie, basis_inv, path), False, None
588
ie.symlink_target = current_link_target
589
self._add_text_to_weave(ie.file_id, '', heads, None)
590
elif kind == 'tree-reference':
592
if content_summary[3] != parent_entry.reference_revision:
595
# unchanged, carry over.
596
ie.reference_revision = parent_entry.reference_revision
597
ie.revision = parent_entry.revision
598
return self._get_delta(ie, basis_inv, path), False, None
599
ie.reference_revision = content_summary[3]
600
if ie.reference_revision is None:
601
raise AssertionError("invalid content_summary for nested tree: %r"
602
% (content_summary,))
603
self._add_text_to_weave(ie.file_id, '', heads, None)
605
raise NotImplementedError('unknown kind')
606
ie.revision = self._new_revision_id
607
self._any_changes = True
608
return self._get_delta(ie, basis_inv, path), True, fingerprint
610
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
611
_entry_factory=entry_factory):
612
"""Record a new tree via iter_changes.
614
:param tree: The tree to obtain text contents from for changed objects.
615
:param basis_revision_id: The revision id of the tree the iter_changes
616
has been generated against. Currently assumed to be the same
617
as self.parents[0] - if it is not, errors may occur.
618
:param iter_changes: An iter_changes iterator with the changes to apply
619
to basis_revision_id. The iterator must not include any items with
620
a current kind of None - missing items must be either filtered out
621
or errored-on beefore record_iter_changes sees the item.
622
:param _entry_factory: Private method to bind entry_factory locally for
624
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
627
# Create an inventory delta based on deltas between all the parents and
628
# deltas between all the parent inventories. We use inventory delta's
629
# between the inventory objects because iter_changes masks
630
# last-changed-field only changes.
632
# file_id -> change map, change is fileid, paths, changed, versioneds,
633
# parents, names, kinds, executables
635
# {file_id -> revision_id -> inventory entry, for entries in parent
636
# trees that are not parents[0]
640
revtrees = list(self.repository.revision_trees(self.parents))
641
except errors.NoSuchRevision:
642
# one or more ghosts, slow path.
644
for revision_id in self.parents:
646
revtrees.append(self.repository.revision_tree(revision_id))
647
except errors.NoSuchRevision:
649
basis_revision_id = _mod_revision.NULL_REVISION
651
revtrees.append(self.repository.revision_tree(
652
_mod_revision.NULL_REVISION))
653
# The basis inventory from a repository
655
basis_inv = revtrees[0].inventory
657
basis_inv = self.repository.revision_tree(
658
_mod_revision.NULL_REVISION).inventory
659
if len(self.parents) > 0:
660
if basis_revision_id != self.parents[0] and not ghost_basis:
662
"arbitrary basis parents not yet supported with merges")
663
for revtree in revtrees[1:]:
664
for change in revtree.inventory._make_delta(basis_inv):
665
if change[1] is None:
666
# Not present in this parent.
668
if change[2] not in merged_ids:
669
if change[0] is not None:
670
basis_entry = basis_inv[change[2]]
671
merged_ids[change[2]] = [
673
basis_entry.revision,
676
parent_entries[change[2]] = {
678
basis_entry.revision:basis_entry,
680
change[3].revision:change[3],
683
merged_ids[change[2]] = [change[3].revision]
684
parent_entries[change[2]] = {change[3].revision:change[3]}
686
merged_ids[change[2]].append(change[3].revision)
687
parent_entries[change[2]][change[3].revision] = change[3]
690
# Setup the changes from the tree:
691
# changes maps file_id -> (change, [parent revision_ids])
693
for change in iter_changes:
694
# This probably looks up in basis_inv way to much.
695
if change[1][0] is not None:
696
head_candidate = [basis_inv[change[0]].revision]
699
changes[change[0]] = change, merged_ids.get(change[0],
701
unchanged_merged = set(merged_ids) - set(changes)
702
# Extend the changes dict with synthetic changes to record merges of
704
for file_id in unchanged_merged:
705
# Record a merged version of these items that did not change vs the
706
# basis. This can be either identical parallel changes, or a revert
707
# of a specific file after a merge. The recorded content will be
708
# that of the current tree (which is the same as the basis), but
709
# the per-file graph will reflect a merge.
710
# NB:XXX: We are reconstructing path information we had, this
711
# should be preserved instead.
712
# inv delta change: (file_id, (path_in_source, path_in_target),
713
# changed_content, versioned, parent, name, kind,
716
basis_entry = basis_inv[file_id]
717
except errors.NoSuchId:
718
# a change from basis->some_parents but file_id isn't in basis
719
# so was new in the merge, which means it must have changed
720
# from basis -> current, and as it hasn't the add was reverted
721
# by the user. So we discard this change.
725
(basis_inv.id2path(file_id), tree.id2path(file_id)),
727
(basis_entry.parent_id, basis_entry.parent_id),
728
(basis_entry.name, basis_entry.name),
729
(basis_entry.kind, basis_entry.kind),
730
(basis_entry.executable, basis_entry.executable))
731
changes[file_id] = (change, merged_ids[file_id])
732
# changes contains tuples with the change and a set of inventory
733
# candidates for the file.
735
# old_path, new_path, file_id, new_inventory_entry
736
seen_root = False # Is the root in the basis delta?
737
inv_delta = self._basis_delta
738
modified_rev = self._new_revision_id
739
for change, head_candidates in changes.values():
740
if change[3][1]: # versioned in target.
741
# Several things may be happening here:
742
# We may have a fork in the per-file graph
743
# - record a change with the content from tree
744
# We may have a change against < all trees
745
# - carry over the tree that hasn't changed
746
# We may have a change against all trees
747
# - record the change with the content from tree
750
entry = _entry_factory[kind](file_id, change[5][1],
752
head_set = self._heads(change[0], set(head_candidates))
755
for head_candidate in head_candidates:
756
if head_candidate in head_set:
757
heads.append(head_candidate)
758
head_set.remove(head_candidate)
761
# Could be a carry-over situation:
762
parent_entry_revs = parent_entries.get(file_id, None)
763
if parent_entry_revs:
764
parent_entry = parent_entry_revs.get(heads[0], None)
767
if parent_entry is None:
768
# The parent iter_changes was called against is the one
769
# that is the per-file head, so any change is relevant
770
# iter_changes is valid.
771
carry_over_possible = False
773
# could be a carry over situation
774
# A change against the basis may just indicate a merge,
775
# we need to check the content against the source of the
776
# merge to determine if it was changed after the merge
778
if (parent_entry.kind != entry.kind or
779
parent_entry.parent_id != entry.parent_id or
780
parent_entry.name != entry.name):
781
# Metadata common to all entries has changed
782
# against per-file parent
783
carry_over_possible = False
785
carry_over_possible = True
786
# per-type checks for changes against the parent_entry
789
# Cannot be a carry-over situation
790
carry_over_possible = False
791
# Populate the entry in the delta
793
# XXX: There is still a small race here: If someone reverts the content of a file
794
# after iter_changes examines and decides it has changed,
795
# we will unconditionally record a new version even if some
796
# other process reverts it while commit is running (with
797
# the revert happening after iter_changes did its
800
entry.executable = True
802
entry.executable = False
803
if (carry_over_possible and
804
parent_entry.executable == entry.executable):
805
# Check the file length, content hash after reading
807
nostore_sha = parent_entry.text_sha1
810
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
812
text = file_obj.read()
816
entry.text_sha1, entry.text_size = self._add_text_to_weave(
817
file_id, text, heads, nostore_sha)
818
yield file_id, change[1][1], (entry.text_sha1, stat_value)
819
except errors.ExistingContent:
820
# No content change against a carry_over parent
821
# Perhaps this should also yield a fs hash update?
823
entry.text_size = parent_entry.text_size
824
entry.text_sha1 = parent_entry.text_sha1
825
elif kind == 'symlink':
827
entry.symlink_target = tree.get_symlink_target(file_id)
828
if (carry_over_possible and
829
parent_entry.symlink_target == entry.symlink_target):
832
self._add_text_to_weave(change[0], '', heads, None)
833
elif kind == 'directory':
834
if carry_over_possible:
837
# Nothing to set on the entry.
838
# XXX: split into the Root and nonRoot versions.
839
if change[1][1] != '' or self.repository.supports_rich_root():
840
self._add_text_to_weave(change[0], '', heads, None)
841
elif kind == 'tree-reference':
842
if not self.repository._format.supports_tree_reference:
843
# This isn't quite sane as an error, but we shouldn't
844
# ever see this code path in practice: tree's don't
845
# permit references when the repo doesn't support tree
847
raise errors.UnsupportedOperation(tree.add_reference,
849
reference_revision = tree.get_reference_revision(change[0])
850
entry.reference_revision = reference_revision
851
if (carry_over_possible and
852
parent_entry.reference_revision == reference_revision):
855
self._add_text_to_weave(change[0], '', heads, None)
857
raise AssertionError('unknown kind %r' % kind)
859
entry.revision = modified_rev
861
entry.revision = parent_entry.revision
864
new_path = change[1][1]
865
inv_delta.append((change[1][0], new_path, change[0], entry))
868
self.new_inventory = None
870
# This should perhaps be guarded by a check that the basis we
871
# commit against is the basis for the commit and if not do a delta
873
self._any_changes = True
875
# housekeeping root entry changes do not affect no-change commits.
876
self._require_root_change(tree)
877
self.basis_delta_revision = basis_revision_id
879
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
880
parent_keys = tuple([(file_id, parent) for parent in parents])
881
return self.repository.texts._add_text(
882
(file_id, self._new_revision_id), parent_keys, new_text,
883
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
886
class RootCommitBuilder(CommitBuilder):
887
"""This commitbuilder actually records the root id"""
889
# the root entry gets versioned properly by this builder.
890
_versioned_root = True
892
def _check_root(self, ie, parent_invs, tree):
893
"""Helper for record_entry_contents.
895
:param ie: An entry being added.
896
:param parent_invs: The inventories of the parent revisions of the
898
:param tree: The tree that is being committed.
901
def _require_root_change(self, tree):
902
"""Enforce an appropriate root object change.
904
This is called once when record_iter_changes is called, if and only if
905
the root was not in the delta calculated by record_iter_changes.
907
:param tree: The tree which is being committed.
909
# versioned roots do not change unless the tree found a change.
912
class RepositoryWriteLockResult(LogicalLockResult):
913
"""The result of write locking a repository.
915
:ivar repository_token: The token obtained from the underlying lock, or
917
:ivar unlock: A callable which will unlock the lock.
920
def __init__(self, unlock, repository_token):
921
LogicalLockResult.__init__(self, unlock)
922
self.repository_token = repository_token
925
return "RepositoryWriteLockResult(%s, %s)" % (self.repository_token,
929
######################################################################
933
class Repository(_RelockDebugMixin, controldir.ControlComponent):
934
"""Repository holding history for one or more branches.
936
The repository holds and retrieves historical information including
937
revisions and file history. It's normally accessed only by the Branch,
938
which views a particular line of development through that history.
940
The Repository builds on top of some byte storage facilies (the revisions,
941
signatures, inventories, texts and chk_bytes attributes) and a Transport,
942
which respectively provide byte storage and a means to access the (possibly
945
The byte storage facilities are addressed via tuples, which we refer to
946
as 'keys' throughout the code base. Revision_keys, inventory_keys and
947
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
948
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
949
byte string made up of a hash identifier and a hash value.
950
We use this interface because it allows low friction with the underlying
951
code that implements disk indices, network encoding and other parts of
954
:ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
955
the serialised revisions for the repository. This can be used to obtain
956
revision graph information or to access raw serialised revisions.
957
The result of trying to insert data into the repository via this store
958
is undefined: it should be considered read-only except for implementors
960
:ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
961
the serialised signatures for the repository. This can be used to
962
obtain access to raw serialised signatures. The result of trying to
963
insert data into the repository via this store is undefined: it should
964
be considered read-only except for implementors of repositories.
965
:ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
966
the serialised inventories for the repository. This can be used to
967
obtain unserialised inventories. The result of trying to insert data
968
into the repository via this store is undefined: it should be
969
considered read-only except for implementors of repositories.
970
:ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
971
texts of files and directories for the repository. This can be used to
972
obtain file texts or file graphs. Note that Repository.iter_file_bytes
973
is usually a better interface for accessing file texts.
974
The result of trying to insert data into the repository via this store
975
is undefined: it should be considered read-only except for implementors
977
:ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
978
any data the repository chooses to store or have indexed by its hash.
979
The result of trying to insert data into the repository via this store
980
is undefined: it should be considered read-only except for implementors
982
:ivar _transport: Transport for file access to repository, typically
983
pointing to .bzr/repository.
986
# What class to use for a CommitBuilder. Often it's simpler to change this
987
# in a Repository class subclass rather than to override
988
# get_commit_builder.
989
_commit_builder_class = CommitBuilder
991
def abort_write_group(self, suppress_errors=False):
992
"""Commit the contents accrued within the current write group.
994
:param suppress_errors: if true, abort_write_group will catch and log
995
unexpected errors that happen during the abort, rather than
996
allowing them to propagate. Defaults to False.
998
:seealso: start_write_group.
1000
if self._write_group is not self.get_transaction():
1001
# has an unlock or relock occured ?
1004
'(suppressed) mismatched lock context and write group. %r, %r',
1005
self._write_group, self.get_transaction())
1007
raise errors.BzrError(
1008
'mismatched lock context and write group. %r, %r' %
1009
(self._write_group, self.get_transaction()))
1011
self._abort_write_group()
1012
except Exception, exc:
1013
self._write_group = None
1014
if not suppress_errors:
1016
mutter('abort_write_group failed')
1017
log_exception_quietly()
1018
note('bzr: ERROR (ignored): %s', exc)
1019
self._write_group = None
1021
def _abort_write_group(self):
1022
"""Template method for per-repository write group cleanup.
1024
This is called during abort before the write group is considered to be
1025
finished and should cleanup any internal state accrued during the write
1026
group. There is no requirement that data handed to the repository be
1027
*not* made available - this is not a rollback - but neither should any
1028
attempt be made to ensure that data added is fully commited. Abort is
1029
invoked when an error has occured so futher disk or network operations
1030
may not be possible or may error and if possible should not be
1034
def add_fallback_repository(self, repository):
1035
"""Add a repository to use for looking up data not held locally.
1037
:param repository: A repository.
1039
if not self._format.supports_external_lookups:
1040
raise errors.UnstackableRepositoryFormat(self._format, self.base)
1041
if self.is_locked():
1042
# This repository will call fallback.unlock() when we transition to
1043
# the unlocked state, so we make sure to increment the lock count
1044
repository.lock_read()
1045
self._check_fallback_repository(repository)
1046
self._fallback_repositories.append(repository)
1047
self.texts.add_fallback_versioned_files(repository.texts)
1048
self.inventories.add_fallback_versioned_files(repository.inventories)
1049
self.revisions.add_fallback_versioned_files(repository.revisions)
1050
self.signatures.add_fallback_versioned_files(repository.signatures)
1051
if self.chk_bytes is not None:
1052
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
1054
def _check_fallback_repository(self, repository):
1055
"""Check that this repository can fallback to repository safely.
1057
Raise an error if not.
1059
:param repository: A repository to fallback to.
1061
return InterRepository._assert_same_model(self, repository)
1063
def add_inventory(self, revision_id, inv, parents):
1064
"""Add the inventory inv to the repository as revision_id.
1066
:param parents: The revision ids of the parents that revision_id
1067
is known to have and are in the repository already.
1069
:returns: The validator(which is a sha1 digest, though what is sha'd is
1070
repository format specific) of the serialized inventory.
1072
if not self.is_in_write_group():
1073
raise AssertionError("%r not in write group" % (self,))
1074
_mod_revision.check_not_reserved_id(revision_id)
1075
if not (inv.revision_id is None or inv.revision_id == revision_id):
1076
raise AssertionError(
1077
"Mismatch between inventory revision"
1078
" id and insertion revid (%r, %r)"
1079
% (inv.revision_id, revision_id))
1080
if inv.root is None:
1081
raise errors.RootMissing()
1082
return self._add_inventory_checked(revision_id, inv, parents)
1084
def _add_inventory_checked(self, revision_id, inv, parents):
1085
"""Add inv to the repository after checking the inputs.
1087
This function can be overridden to allow different inventory styles.
1089
:seealso: add_inventory, for the contract.
1091
inv_lines = self._serializer.write_inventory_to_lines(inv)
1092
return self._inventory_add_lines(revision_id, parents,
1093
inv_lines, check_content=False)
1095
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
1096
parents, basis_inv=None, propagate_caches=False):
1097
"""Add a new inventory expressed as a delta against another revision.
1099
See the inventory developers documentation for the theory behind
1102
:param basis_revision_id: The inventory id the delta was created
1103
against. (This does not have to be a direct parent.)
1104
:param delta: The inventory delta (see Inventory.apply_delta for
1106
:param new_revision_id: The revision id that the inventory is being
1108
:param parents: The revision ids of the parents that revision_id is
1109
known to have and are in the repository already. These are supplied
1110
for repositories that depend on the inventory graph for revision
1111
graph access, as well as for those that pun ancestry with delta
1113
:param basis_inv: The basis inventory if it is already known,
1115
:param propagate_caches: If True, the caches for this inventory are
1116
copied to and updated for the result if possible.
1118
:returns: (validator, new_inv)
1119
The validator(which is a sha1 digest, though what is sha'd is
1120
repository format specific) of the serialized inventory, and the
1121
resulting inventory.
1123
if not self.is_in_write_group():
1124
raise AssertionError("%r not in write group" % (self,))
1125
_mod_revision.check_not_reserved_id(new_revision_id)
1126
basis_tree = self.revision_tree(basis_revision_id)
1127
basis_tree.lock_read()
1129
# Note that this mutates the inventory of basis_tree, which not all
1130
# inventory implementations may support: A better idiom would be to
1131
# return a new inventory, but as there is no revision tree cache in
1132
# repository this is safe for now - RBC 20081013
1133
if basis_inv is None:
1134
basis_inv = basis_tree.inventory
1135
basis_inv.apply_delta(delta)
1136
basis_inv.revision_id = new_revision_id
1137
return (self.add_inventory(new_revision_id, basis_inv, parents),
1142
def _inventory_add_lines(self, revision_id, parents, lines,
1143
check_content=True):
1144
"""Store lines in inv_vf and return the sha1 of the inventory."""
1145
parents = [(parent,) for parent in parents]
1146
result = self.inventories.add_lines((revision_id,), parents, lines,
1147
check_content=check_content)[0]
1148
self.inventories._access.flush()
1151
def add_revision(self, revision_id, rev, inv=None, config=None):
1152
"""Add rev to the revision store as revision_id.
1154
:param revision_id: the revision id to use.
1155
:param rev: The revision object.
1156
:param inv: The inventory for the revision. if None, it will be looked
1157
up in the inventory storer
1158
:param config: If None no digital signature will be created.
1159
If supplied its signature_needed method will be used
1160
to determine if a signature should be made.
1162
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1164
_mod_revision.check_not_reserved_id(revision_id)
1165
if config is not None and config.signature_needed():
1167
inv = self.get_inventory(revision_id)
1168
plaintext = Testament(rev, inv).as_short_text()
1169
self.store_revision_signature(
1170
gpg.GPGStrategy(config), plaintext, revision_id)
1171
# check inventory present
1172
if not self.inventories.get_parent_map([(revision_id,)]):
1174
raise errors.WeaveRevisionNotPresent(revision_id,
1177
# yes, this is not suitable for adding with ghosts.
1178
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1181
key = (revision_id,)
1182
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1183
self._add_revision(rev)
1185
def _add_revision(self, revision):
1186
text = self._serializer.write_revision_to_string(revision)
1187
key = (revision.revision_id,)
1188
parents = tuple((parent,) for parent in revision.parent_ids)
1189
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1191
def all_revision_ids(self):
1192
"""Returns a list of all the revision ids in the repository.
1194
This is conceptually deprecated because code should generally work on
1195
the graph reachable from a particular revision, and ignore any other
1196
revisions that might be present. There is no direct replacement
1199
if 'evil' in debug.debug_flags:
1200
mutter_callsite(2, "all_revision_ids is linear with history.")
1201
return self._all_revision_ids()
1203
def _all_revision_ids(self):
1204
"""Returns a list of all the revision ids in the repository.
1206
These are in as much topological order as the underlying store can
1209
raise NotImplementedError(self._all_revision_ids)
1211
def break_lock(self):
1212
"""Break a lock if one is present from another instance.
1214
Uses the ui factory to ask for confirmation if the lock may be from
1217
self.control_files.break_lock()
1220
def _eliminate_revisions_not_present(self, revision_ids):
1221
"""Check every revision id in revision_ids to see if we have it.
1223
Returns a set of the present revisions.
1226
graph = self.get_graph()
1227
parent_map = graph.get_parent_map(revision_ids)
1228
# The old API returned a list, should this actually be a set?
1229
return parent_map.keys()
1231
def _check_inventories(self, checker):
1232
"""Check the inventories found from the revision scan.
1234
This is responsible for verifying the sha1 of inventories and
1235
creating a pending_keys set that covers data referenced by inventories.
1237
bar = ui.ui_factory.nested_progress_bar()
1239
self._do_check_inventories(checker, bar)
1243
def _do_check_inventories(self, checker, bar):
1244
"""Helper for _check_inventories."""
1246
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1247
kinds = ['chk_bytes', 'texts']
1248
count = len(checker.pending_keys)
1249
bar.update("inventories", 0, 2)
1250
current_keys = checker.pending_keys
1251
checker.pending_keys = {}
1252
# Accumulate current checks.
1253
for key in current_keys:
1254
if key[0] != 'inventories' and key[0] not in kinds:
1255
checker._report_items.append('unknown key type %r' % (key,))
1256
keys[key[0]].add(key[1:])
1257
if keys['inventories']:
1258
# NB: output order *should* be roughly sorted - topo or
1259
# inverse topo depending on repository - either way decent
1260
# to just delta against. However, pre-CHK formats didn't
1261
# try to optimise inventory layout on disk. As such the
1262
# pre-CHK code path does not use inventory deltas.
1264
for record in self.inventories.check(keys=keys['inventories']):
1265
if record.storage_kind == 'absent':
1266
checker._report_items.append(
1267
'Missing inventory {%s}' % (record.key,))
1269
last_object = self._check_record('inventories', record,
1270
checker, last_object,
1271
current_keys[('inventories',) + record.key])
1272
del keys['inventories']
1275
bar.update("texts", 1)
1276
while (checker.pending_keys or keys['chk_bytes']
1278
# Something to check.
1279
current_keys = checker.pending_keys
1280
checker.pending_keys = {}
1281
# Accumulate current checks.
1282
for key in current_keys:
1283
if key[0] not in kinds:
1284
checker._report_items.append('unknown key type %r' % (key,))
1285
keys[key[0]].add(key[1:])
1286
# Check the outermost kind only - inventories || chk_bytes || texts
1290
for record in getattr(self, kind).check(keys=keys[kind]):
1291
if record.storage_kind == 'absent':
1292
checker._report_items.append(
1293
'Missing %s {%s}' % (kind, record.key,))
1295
last_object = self._check_record(kind, record,
1296
checker, last_object, current_keys[(kind,) + record.key])
1300
def _check_record(self, kind, record, checker, last_object, item_data):
1301
"""Check a single text from this repository."""
1302
if kind == 'inventories':
1303
rev_id = record.key[0]
1304
inv = self._deserialise_inventory(rev_id,
1305
record.get_bytes_as('fulltext'))
1306
if last_object is not None:
1307
delta = inv._make_delta(last_object)
1308
for old_path, path, file_id, ie in delta:
1311
ie.check(checker, rev_id, inv)
1313
for path, ie in inv.iter_entries():
1314
ie.check(checker, rev_id, inv)
1315
if self._format.fast_deltas:
1317
elif kind == 'chk_bytes':
1318
# No code written to check chk_bytes for this repo format.
1319
checker._report_items.append(
1320
'unsupported key type chk_bytes for %s' % (record.key,))
1321
elif kind == 'texts':
1322
self._check_text(record, checker, item_data)
1324
checker._report_items.append(
1325
'unknown key type %s for %s' % (kind, record.key))
1327
def _check_text(self, record, checker, item_data):
1328
"""Check a single text."""
1329
# Check it is extractable.
1330
# TODO: check length.
1331
if record.storage_kind == 'chunked':
1332
chunks = record.get_bytes_as(record.storage_kind)
1333
sha1 = osutils.sha_strings(chunks)
1334
length = sum(map(len, chunks))
1336
content = record.get_bytes_as('fulltext')
1337
sha1 = osutils.sha_string(content)
1338
length = len(content)
1339
if item_data and sha1 != item_data[1]:
1340
checker._report_items.append(
1341
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1342
(record.key, sha1, item_data[1], item_data[2]))
1345
def create(a_bzrdir):
1346
"""Construct the current default format repository in a_bzrdir."""
1347
return RepositoryFormat.get_default_format().initialize(a_bzrdir)
1349
def __init__(self, _format, a_bzrdir, control_files):
1350
"""instantiate a Repository.
1352
:param _format: The format of the repository on disk.
1353
:param a_bzrdir: The BzrDir of the repository.
1355
# In the future we will have a single api for all stores for
1356
# getting file texts, inventories and revisions, then
1357
# this construct will accept instances of those things.
1358
super(Repository, self).__init__()
1359
self._format = _format
1360
# the following are part of the public API for Repository:
1361
self.bzrdir = a_bzrdir
1362
self.control_files = control_files
1363
self._transport = control_files._transport
1364
self.base = self._transport.base
1366
self._reconcile_does_inventory_gc = True
1367
self._reconcile_fixes_text_parents = False
1368
self._reconcile_backsup_inventory = True
1369
self._write_group = None
1370
# Additional places to query for data.
1371
self._fallback_repositories = []
1372
# An InventoryEntry cache, used during deserialization
1373
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1374
# Is it safe to return inventory entries directly from the entry cache,
1375
# rather copying them?
1376
self._safe_to_return_from_cache = False
1379
def user_transport(self):
1380
return self.bzrdir.user_transport
1383
def control_transport(self):
1384
return self._transport
1387
if self._fallback_repositories:
1388
return '%s(%r, fallback_repositories=%r)' % (
1389
self.__class__.__name__,
1391
self._fallback_repositories)
1393
return '%s(%r)' % (self.__class__.__name__,
1396
def _has_same_fallbacks(self, other_repo):
1397
"""Returns true if the repositories have the same fallbacks."""
1398
my_fb = self._fallback_repositories
1399
other_fb = other_repo._fallback_repositories
1400
if len(my_fb) != len(other_fb):
1402
for f, g in zip(my_fb, other_fb):
1403
if not f.has_same_location(g):
1407
def has_same_location(self, other):
1408
"""Returns a boolean indicating if this repository is at the same
1409
location as another repository.
1411
This might return False even when two repository objects are accessing
1412
the same physical repository via different URLs.
1414
if self.__class__ is not other.__class__:
1416
return (self._transport.base == other._transport.base)
1418
def is_in_write_group(self):
1419
"""Return True if there is an open write group.
1421
:seealso: start_write_group.
1423
return self._write_group is not None
1425
def is_locked(self):
1426
return self.control_files.is_locked()
1428
def is_write_locked(self):
1429
"""Return True if this object is write locked."""
1430
return self.is_locked() and self.control_files._lock_mode == 'w'
1432
def lock_write(self, token=None):
1433
"""Lock this repository for writing.
1435
This causes caching within the repository obejct to start accumlating
1436
data during reads, and allows a 'write_group' to be obtained. Write
1437
groups must be used for actual data insertion.
1439
A token should be passed in if you know that you have locked the object
1440
some other way, and need to synchronise this object's state with that
1443
XXX: this docstring is duplicated in many places, e.g. lockable_files.py
1445
:param token: if this is already locked, then lock_write will fail
1446
unless the token matches the existing lock.
1447
:returns: a token if this instance supports tokens, otherwise None.
1448
:raises TokenLockingNotSupported: when a token is given but this
1449
instance doesn't support using token locks.
1450
:raises MismatchedToken: if the specified token doesn't match the token
1451
of the existing lock.
1452
:seealso: start_write_group.
1453
:return: A RepositoryWriteLockResult.
1455
locked = self.is_locked()
1456
token = self.control_files.lock_write(token=token)
1458
self._warn_if_deprecated()
1459
self._note_lock('w')
1460
for repo in self._fallback_repositories:
1461
# Writes don't affect fallback repos
1463
self._refresh_data()
1464
return RepositoryWriteLockResult(self.unlock, token)
1466
def lock_read(self):
1467
"""Lock the repository for read operations.
1469
:return: An object with an unlock method which will release the lock
1472
locked = self.is_locked()
1473
self.control_files.lock_read()
1475
self._warn_if_deprecated()
1476
self._note_lock('r')
1477
for repo in self._fallback_repositories:
1479
self._refresh_data()
1480
return LogicalLockResult(self.unlock)
1482
def get_physical_lock_status(self):
1483
return self.control_files.get_physical_lock_status()
1485
def leave_lock_in_place(self):
1486
"""Tell this repository not to release the physical lock when this
1489
If lock_write doesn't return a token, then this method is not supported.
1491
self.control_files.leave_in_place()
1493
def dont_leave_lock_in_place(self):
1494
"""Tell this repository to release the physical lock when this
1495
object is unlocked, even if it didn't originally acquire it.
1497
If lock_write doesn't return a token, then this method is not supported.
1499
self.control_files.dont_leave_in_place()
1502
def gather_stats(self, revid=None, committers=None):
1503
"""Gather statistics from a revision id.
1505
:param revid: The revision id to gather statistics from, if None, then
1506
no revision specific statistics are gathered.
1507
:param committers: Optional parameter controlling whether to grab
1508
a count of committers from the revision specific statistics.
1509
:return: A dictionary of statistics. Currently this contains:
1510
committers: The number of committers if requested.
1511
firstrev: A tuple with timestamp, timezone for the penultimate left
1512
most ancestor of revid, if revid is not the NULL_REVISION.
1513
latestrev: A tuple with timestamp, timezone for revid, if revid is
1514
not the NULL_REVISION.
1515
revisions: The total revision count in the repository.
1516
size: An estimate disk size of the repository in bytes.
1519
if revid and committers:
1520
result['committers'] = 0
1521
if revid and revid != _mod_revision.NULL_REVISION:
1523
all_committers = set()
1524
revisions = self.get_ancestry(revid)
1525
# pop the leading None
1527
first_revision = None
1529
# ignore the revisions in the middle - just grab first and last
1530
revisions = revisions[0], revisions[-1]
1531
for revision in self.get_revisions(revisions):
1532
if not first_revision:
1533
first_revision = revision
1535
all_committers.add(revision.committer)
1536
last_revision = revision
1538
result['committers'] = len(all_committers)
1539
result['firstrev'] = (first_revision.timestamp,
1540
first_revision.timezone)
1541
result['latestrev'] = (last_revision.timestamp,
1542
last_revision.timezone)
1544
# now gather global repository information
1545
# XXX: This is available for many repos regardless of listability.
1546
if self.user_transport.listable():
1547
# XXX: do we want to __define len__() ?
1548
# Maybe the versionedfiles object should provide a different
1549
# method to get the number of keys.
1550
result['revisions'] = len(self.revisions.keys())
1551
# result['size'] = t
1554
def find_branches(self, using=False):
1555
"""Find branches underneath this repository.
1557
This will include branches inside other branches.
1559
:param using: If True, list only branches using this repository.
1561
if using and not self.is_shared():
1562
return self.bzrdir.list_branches()
1563
class Evaluator(object):
1566
self.first_call = True
1568
def __call__(self, bzrdir):
1569
# On the first call, the parameter is always the bzrdir
1570
# containing the current repo.
1571
if not self.first_call:
1573
repository = bzrdir.open_repository()
1574
except errors.NoRepositoryPresent:
1577
return False, ([], repository)
1578
self.first_call = False
1579
value = (bzrdir.list_branches(), None)
1583
for branches, repository in bzrdir.BzrDir.find_bzrdirs(
1584
self.user_transport, evaluate=Evaluator()):
1585
if branches is not None:
1586
ret.extend(branches)
1587
if not using and repository is not None:
1588
ret.extend(repository.find_branches())
1592
def search_missing_revision_ids(self, other,
1593
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
1594
find_ghosts=True, revision_ids=None, if_present_ids=None):
1595
"""Return the revision ids that other has that this does not.
1597
These are returned in topological order.
1599
revision_id: only return revision ids included by revision_id.
1601
if symbol_versioning.deprecated_passed(revision_id):
1602
symbol_versioning.warn(
1603
'search_missing_revision_ids(revision_id=...) was '
1604
'deprecated in 2.4. Use revision_ids=[...] instead.',
1605
DeprecationWarning, stacklevel=3)
1606
if revision_ids is not None:
1607
raise AssertionError(
1608
'revision_ids is mutually exclusive with revision_id')
1609
if revision_id is not None:
1610
revision_ids = [revision_id]
1611
return InterRepository.get(other, self).search_missing_revision_ids(
1612
find_ghosts=find_ghosts, revision_ids=revision_ids,
1613
if_present_ids=if_present_ids)
1617
"""Open the repository rooted at base.
1619
For instance, if the repository is at URL/.bzr/repository,
1620
Repository.open(URL) -> a Repository instance.
1622
control = bzrdir.BzrDir.open(base)
1623
return control.open_repository()
1625
def copy_content_into(self, destination, revision_id=None):
1626
"""Make a complete copy of the content in self into destination.
1628
This is a destructive operation! Do not use it on existing
1631
return InterRepository.get(self, destination).copy_content(revision_id)
1633
def commit_write_group(self):
1634
"""Commit the contents accrued within the current write group.
1636
:seealso: start_write_group.
1638
:return: it may return an opaque hint that can be passed to 'pack'.
1640
if self._write_group is not self.get_transaction():
1641
# has an unlock or relock occured ?
1642
raise errors.BzrError('mismatched lock context %r and '
1644
(self.get_transaction(), self._write_group))
1645
result = self._commit_write_group()
1646
self._write_group = None
1649
def _commit_write_group(self):
1650
"""Template method for per-repository write group cleanup.
1652
This is called before the write group is considered to be
1653
finished and should ensure that all data handed to the repository
1654
for writing during the write group is safely committed (to the
1655
extent possible considering file system caching etc).
1658
def suspend_write_group(self):
1659
raise errors.UnsuspendableWriteGroup(self)
1661
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1662
"""Return the keys of missing inventory parents for revisions added in
1665
A revision is not complete if the inventory delta for that revision
1666
cannot be calculated. Therefore if the parent inventories of a
1667
revision are not present, the revision is incomplete, and e.g. cannot
1668
be streamed by a smart server. This method finds missing inventory
1669
parents for revisions added in this write group.
1671
if not self._format.supports_external_lookups:
1672
# This is only an issue for stacked repositories
1674
if not self.is_in_write_group():
1675
raise AssertionError('not in a write group')
1677
# XXX: We assume that every added revision already has its
1678
# corresponding inventory, so we only check for parent inventories that
1679
# might be missing, rather than all inventories.
1680
parents = set(self.revisions._index.get_missing_parents())
1681
parents.discard(_mod_revision.NULL_REVISION)
1682
unstacked_inventories = self.inventories._index
1683
present_inventories = unstacked_inventories.get_parent_map(
1684
key[-1:] for key in parents)
1685
parents.difference_update(present_inventories)
1686
if len(parents) == 0:
1687
# No missing parent inventories.
1689
if not check_for_missing_texts:
1690
return set(('inventories', rev_id) for (rev_id,) in parents)
1691
# Ok, now we have a list of missing inventories. But these only matter
1692
# if the inventories that reference them are missing some texts they
1693
# appear to introduce.
1694
# XXX: Texts referenced by all added inventories need to be present,
1695
# but at the moment we're only checking for texts referenced by
1696
# inventories at the graph's edge.
1697
key_deps = self.revisions._index._key_dependencies
1698
key_deps.satisfy_refs_for_keys(present_inventories)
1699
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1700
file_ids = self.fileids_altered_by_revision_ids(referrers)
1701
missing_texts = set()
1702
for file_id, version_ids in file_ids.iteritems():
1703
missing_texts.update(
1704
(file_id, version_id) for version_id in version_ids)
1705
present_texts = self.texts.get_parent_map(missing_texts)
1706
missing_texts.difference_update(present_texts)
1707
if not missing_texts:
1708
# No texts are missing, so all revisions and their deltas are
1711
# Alternatively the text versions could be returned as the missing
1712
# keys, but this is likely to be less data.
1713
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1716
def refresh_data(self):
1717
"""Re-read any data needed to synchronise with disk.
1719
This method is intended to be called after another repository instance
1720
(such as one used by a smart server) has inserted data into the
1721
repository. On all repositories this will work outside of write groups.
1722
Some repository formats (pack and newer for bzrlib native formats)
1723
support refresh_data inside write groups. If called inside a write
1724
group on a repository that does not support refreshing in a write group
1725
IsInWriteGroupError will be raised.
1727
self._refresh_data()
1729
def resume_write_group(self, tokens):
1730
if not self.is_write_locked():
1731
raise errors.NotWriteLocked(self)
1732
if self._write_group:
1733
raise errors.BzrError('already in a write group')
1734
self._resume_write_group(tokens)
1735
# so we can detect unlock/relock - the write group is now entered.
1736
self._write_group = self.get_transaction()
1738
def _resume_write_group(self, tokens):
1739
raise errors.UnsuspendableWriteGroup(self)
1741
def fetch(self, source, revision_id=None, find_ghosts=False,
1743
"""Fetch the content required to construct revision_id from source.
1745
If revision_id is None and fetch_spec is None, then all content is
1748
fetch() may not be used when the repository is in a write group -
1749
either finish the current write group before using fetch, or use
1750
fetch before starting the write group.
1752
:param find_ghosts: Find and copy revisions in the source that are
1753
ghosts in the target (and not reachable directly by walking out to
1754
the first-present revision in target from revision_id).
1755
:param revision_id: If specified, all the content needed for this
1756
revision ID will be copied to the target. Fetch will determine for
1757
itself which content needs to be copied.
1758
:param fetch_spec: If specified, a SearchResult or
1759
PendingAncestryResult that describes which revisions to copy. This
1760
allows copying multiple heads at once. Mutually exclusive with
1763
if fetch_spec is not None and revision_id is not None:
1764
raise AssertionError(
1765
"fetch_spec and revision_id are mutually exclusive.")
1766
if self.is_in_write_group():
1767
raise errors.InternalBzrError(
1768
"May not fetch while in a write group.")
1769
# fast path same-url fetch operations
1770
# TODO: lift out to somewhere common with RemoteRepository
1771
# <https://bugs.launchpad.net/bzr/+bug/401646>
1772
if (self.has_same_location(source)
1773
and fetch_spec is None
1774
and self._has_same_fallbacks(source)):
1775
# check that last_revision is in 'from' and then return a
1777
if (revision_id is not None and
1778
not _mod_revision.is_null(revision_id)):
1779
self.get_revision(revision_id)
1781
inter = InterRepository.get(source, self)
1782
return inter.fetch(revision_id=revision_id,
1783
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1785
def create_bundle(self, target, base, fileobj, format=None):
1786
return serializer.write_bundle(self, target, base, fileobj, format)
1788
def get_commit_builder(self, branch, parents, config, timestamp=None,
1789
timezone=None, committer=None, revprops=None,
1791
"""Obtain a CommitBuilder for this repository.
1793
:param branch: Branch to commit to.
1794
:param parents: Revision ids of the parents of the new revision.
1795
:param config: Configuration to use.
1796
:param timestamp: Optional timestamp recorded for commit.
1797
:param timezone: Optional timezone for timestamp.
1798
:param committer: Optional committer to set for commit.
1799
:param revprops: Optional dictionary of revision properties.
1800
:param revision_id: Optional revision id.
1802
if self._fallback_repositories and not self._format.supports_chks:
1803
raise errors.BzrError("Cannot commit directly to a stacked branch"
1804
" in pre-2a formats. See "
1805
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1806
result = self._commit_builder_class(self, parents, config,
1807
timestamp, timezone, committer, revprops, revision_id)
1808
self.start_write_group()
1811
@only_raises(errors.LockNotHeld, errors.LockBroken)
1813
if (self.control_files._lock_count == 1 and
1814
self.control_files._lock_mode == 'w'):
1815
if self._write_group is not None:
1816
self.abort_write_group()
1817
self.control_files.unlock()
1818
raise errors.BzrError(
1819
'Must end write groups before releasing write locks.')
1820
self.control_files.unlock()
1821
if self.control_files._lock_count == 0:
1822
self._inventory_entry_cache.clear()
1823
for repo in self._fallback_repositories:
1827
def clone(self, a_bzrdir, revision_id=None):
1828
"""Clone this repository into a_bzrdir using the current format.
1830
Currently no check is made that the format of this repository and
1831
the bzrdir format are compatible. FIXME RBC 20060201.
1833
:return: The newly created destination repository.
1835
# TODO: deprecate after 0.16; cloning this with all its settings is
1836
# probably not very useful -- mbp 20070423
1837
dest_repo = self._create_sprouting_repo(a_bzrdir, shared=self.is_shared())
1838
self.copy_content_into(dest_repo, revision_id)
1841
def start_write_group(self):
1842
"""Start a write group in the repository.
1844
Write groups are used by repositories which do not have a 1:1 mapping
1845
between file ids and backend store to manage the insertion of data from
1846
both fetch and commit operations.
1848
A write lock is required around the start_write_group/commit_write_group
1849
for the support of lock-requiring repository formats.
1851
One can only insert data into a repository inside a write group.
1855
if not self.is_write_locked():
1856
raise errors.NotWriteLocked(self)
1857
if self._write_group:
1858
raise errors.BzrError('already in a write group')
1859
self._start_write_group()
1860
# so we can detect unlock/relock - the write group is now entered.
1861
self._write_group = self.get_transaction()
1863
def _start_write_group(self):
1864
"""Template method for per-repository write group startup.
1866
This is called before the write group is considered to be
1871
def sprout(self, to_bzrdir, revision_id=None):
1872
"""Create a descendent repository for new development.
1874
Unlike clone, this does not copy the settings of the repository.
1876
dest_repo = self._create_sprouting_repo(to_bzrdir, shared=False)
1877
dest_repo.fetch(self, revision_id=revision_id)
1880
def _create_sprouting_repo(self, a_bzrdir, shared):
1881
if not isinstance(a_bzrdir._format, self.bzrdir._format.__class__):
1882
# use target default format.
1883
dest_repo = a_bzrdir.create_repository()
1885
# Most control formats need the repository to be specifically
1886
# created, but on some old all-in-one formats it's not needed
1888
dest_repo = self._format.initialize(a_bzrdir, shared=shared)
1889
except errors.UninitializableFormat:
1890
dest_repo = a_bzrdir.open_repository()
1893
def _get_sink(self):
1894
"""Return a sink for streaming into this repository."""
1895
return StreamSink(self)
1897
def _get_source(self, to_format):
1898
"""Return a source for streaming from this repository."""
1899
return StreamSource(self, to_format)
1902
def has_revision(self, revision_id):
1903
"""True if this repository has a copy of the revision."""
1904
return revision_id in self.has_revisions((revision_id,))
1907
def has_revisions(self, revision_ids):
1908
"""Probe to find out the presence of multiple revisions.
1910
:param revision_ids: An iterable of revision_ids.
1911
:return: A set of the revision_ids that were present.
1913
parent_map = self.revisions.get_parent_map(
1914
[(rev_id,) for rev_id in revision_ids])
1916
if _mod_revision.NULL_REVISION in revision_ids:
1917
result.add(_mod_revision.NULL_REVISION)
1918
result.update([key[0] for key in parent_map])
1922
def get_revision(self, revision_id):
1923
"""Return the Revision object for a named revision."""
1924
return self.get_revisions([revision_id])[0]
1927
def get_revision_reconcile(self, revision_id):
1928
"""'reconcile' helper routine that allows access to a revision always.
1930
This variant of get_revision does not cross check the weave graph
1931
against the revision one as get_revision does: but it should only
1932
be used by reconcile, or reconcile-alike commands that are correcting
1933
or testing the revision graph.
1935
return self._get_revisions([revision_id])[0]
1938
def get_revisions(self, revision_ids):
1939
"""Get many revisions at once.
1941
Repositories that need to check data on every revision read should
1942
subclass this method.
1944
return self._get_revisions(revision_ids)
1947
def _get_revisions(self, revision_ids):
1948
"""Core work logic to get many revisions without sanity checks."""
1950
for revid, rev in self._iter_revisions(revision_ids):
1952
raise errors.NoSuchRevision(self, revid)
1954
return [revs[revid] for revid in revision_ids]
1956
def _iter_revisions(self, revision_ids):
1957
"""Iterate over revision objects.
1959
:param revision_ids: An iterable of revisions to examine. None may be
1960
passed to request all revisions known to the repository. Note that
1961
not all repositories can find unreferenced revisions; for those
1962
repositories only referenced ones will be returned.
1963
:return: An iterator of (revid, revision) tuples. Absent revisions (
1964
those asked for but not available) are returned as (revid, None).
1966
if revision_ids is None:
1967
revision_ids = self.all_revision_ids()
1969
for rev_id in revision_ids:
1970
if not rev_id or not isinstance(rev_id, basestring):
1971
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1972
keys = [(key,) for key in revision_ids]
1973
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1974
for record in stream:
1975
revid = record.key[0]
1976
if record.storage_kind == 'absent':
1979
text = record.get_bytes_as('fulltext')
1980
rev = self._serializer.read_revision_from_string(text)
1983
def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1984
"""Produce a generator of revision deltas.
1986
Note that the input is a sequence of REVISIONS, not revision_ids.
1987
Trees will be held in memory until the generator exits.
1988
Each delta is relative to the revision's lefthand predecessor.
1990
:param specific_fileids: if not None, the result is filtered
1991
so that only those file-ids, their parents and their
1992
children are included.
1994
# Get the revision-ids of interest
1995
required_trees = set()
1996
for revision in revisions:
1997
required_trees.add(revision.revision_id)
1998
required_trees.update(revision.parent_ids[:1])
2000
# Get the matching filtered trees. Note that it's more
2001
# efficient to pass filtered trees to changes_from() rather
2002
# than doing the filtering afterwards. changes_from() could
2003
# arguably do the filtering itself but it's path-based, not
2004
# file-id based, so filtering before or afterwards is
2006
if specific_fileids is None:
2007
trees = dict((t.get_revision_id(), t) for
2008
t in self.revision_trees(required_trees))
2010
trees = dict((t.get_revision_id(), t) for
2011
t in self._filtered_revision_trees(required_trees,
2014
# Calculate the deltas
2015
for revision in revisions:
2016
if not revision.parent_ids:
2017
old_tree = self.revision_tree(_mod_revision.NULL_REVISION)
2019
old_tree = trees[revision.parent_ids[0]]
2020
yield trees[revision.revision_id].changes_from(old_tree)
2023
def get_revision_delta(self, revision_id, specific_fileids=None):
2024
"""Return the delta for one revision.
2026
The delta is relative to the left-hand predecessor of the
2029
:param specific_fileids: if not None, the result is filtered
2030
so that only those file-ids, their parents and their
2031
children are included.
2033
r = self.get_revision(revision_id)
2034
return list(self.get_deltas_for_revisions([r],
2035
specific_fileids=specific_fileids))[0]
2038
def store_revision_signature(self, gpg_strategy, plaintext, revision_id):
2039
signature = gpg_strategy.sign(plaintext)
2040
self.add_signature_text(revision_id, signature)
2043
def add_signature_text(self, revision_id, signature):
2044
self.signatures.add_lines((revision_id,), (),
2045
osutils.split_lines(signature))
2047
def find_text_key_references(self):
2048
"""Find the text key references within the repository.
2050
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
2051
to whether they were referred to by the inventory of the
2052
revision_id that they contain. The inventory texts from all present
2053
revision ids are assessed to generate this report.
2055
revision_keys = self.revisions.keys()
2056
w = self.inventories
2057
pb = ui.ui_factory.nested_progress_bar()
2059
return self._serializer._find_text_key_references(
2060
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
2064
def _inventory_xml_lines_for_keys(self, keys):
2065
"""Get a line iterator of the sort needed for findind references.
2067
Not relevant for non-xml inventory repositories.
2069
Ghosts in revision_keys are ignored.
2071
:param revision_keys: The revision keys for the inventories to inspect.
2072
:return: An iterator over (inventory line, revid) for the fulltexts of
2073
all of the xml inventories specified by revision_keys.
2075
stream = self.inventories.get_record_stream(keys, 'unordered', True)
2076
for record in stream:
2077
if record.storage_kind != 'absent':
2078
chunks = record.get_bytes_as('chunked')
2079
revid = record.key[-1]
2080
lines = osutils.chunks_to_lines(chunks)
2084
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
2086
"""Helper routine for fileids_altered_by_revision_ids.
2088
This performs the translation of xml lines to revision ids.
2090
:param line_iterator: An iterator of lines, origin_version_id
2091
:param revision_keys: The revision ids to filter for. This should be a
2092
set or other type which supports efficient __contains__ lookups, as
2093
the revision key from each parsed line will be looked up in the
2094
revision_keys filter.
2095
:return: a dictionary mapping altered file-ids to an iterable of
2096
revision_ids. Each altered file-ids has the exact revision_ids that
2097
altered it listed explicitly.
2099
seen = set(self._serializer._find_text_key_references(
2100
line_iterator).iterkeys())
2101
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
2102
parent_seen = set(self._serializer._find_text_key_references(
2103
self._inventory_xml_lines_for_keys(parent_keys)))
2104
new_keys = seen - parent_seen
2106
setdefault = result.setdefault
2107
for key in new_keys:
2108
setdefault(key[0], set()).add(key[-1])
2111
def _find_parent_ids_of_revisions(self, revision_ids):
2112
"""Find all parent ids that are mentioned in the revision graph.
2114
:return: set of revisions that are parents of revision_ids which are
2115
not part of revision_ids themselves
2117
parent_map = self.get_parent_map(revision_ids)
2119
map(parent_ids.update, parent_map.itervalues())
2120
parent_ids.difference_update(revision_ids)
2121
parent_ids.discard(_mod_revision.NULL_REVISION)
2124
def _find_parent_keys_of_revisions(self, revision_keys):
2125
"""Similar to _find_parent_ids_of_revisions, but used with keys.
2127
:param revision_keys: An iterable of revision_keys.
2128
:return: The parents of all revision_keys that are not already in
2131
parent_map = self.revisions.get_parent_map(revision_keys)
2133
map(parent_keys.update, parent_map.itervalues())
2134
parent_keys.difference_update(revision_keys)
2135
parent_keys.discard(_mod_revision.NULL_REVISION)
2138
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
2139
"""Find the file ids and versions affected by revisions.
2141
:param revisions: an iterable containing revision ids.
2142
:param _inv_weave: The inventory weave from this repository or None.
2143
If None, the inventory weave will be opened automatically.
2144
:return: a dictionary mapping altered file-ids to an iterable of
2145
revision_ids. Each altered file-ids has the exact revision_ids that
2146
altered it listed explicitly.
2148
selected_keys = set((revid,) for revid in revision_ids)
2149
w = _inv_weave or self.inventories
2150
return self._find_file_ids_from_xml_inventory_lines(
2151
w.iter_lines_added_or_present_in_keys(
2152
selected_keys, pb=None),
2155
def iter_files_bytes(self, desired_files):
2156
"""Iterate through file versions.
2158
Files will not necessarily be returned in the order they occur in
2159
desired_files. No specific order is guaranteed.
2161
Yields pairs of identifier, bytes_iterator. identifier is an opaque
2162
value supplied by the caller as part of desired_files. It should
2163
uniquely identify the file version in the caller's context. (Examples:
2164
an index number or a TreeTransform trans_id.)
2166
bytes_iterator is an iterable of bytestrings for the file. The
2167
kind of iterable and length of the bytestrings are unspecified, but for
2168
this implementation, it is a list of bytes produced by
2169
VersionedFile.get_record_stream().
2171
:param desired_files: a list of (file_id, revision_id, identifier)
2175
for file_id, revision_id, callable_data in desired_files:
2176
text_keys[(file_id, revision_id)] = callable_data
2177
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
2178
if record.storage_kind == 'absent':
2179
raise errors.RevisionNotPresent(record.key, self)
2180
yield text_keys[record.key], record.get_bytes_as('chunked')
2182
def _generate_text_key_index(self, text_key_references=None,
2184
"""Generate a new text key index for the repository.
2186
This is an expensive function that will take considerable time to run.
2188
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
2189
list of parents, also text keys. When a given key has no parents,
2190
the parents list will be [NULL_REVISION].
2192
# All revisions, to find inventory parents.
2193
if ancestors is None:
2194
graph = self.get_graph()
2195
ancestors = graph.get_parent_map(self.all_revision_ids())
2196
if text_key_references is None:
2197
text_key_references = self.find_text_key_references()
2198
pb = ui.ui_factory.nested_progress_bar()
2200
return self._do_generate_text_key_index(ancestors,
2201
text_key_references, pb)
2205
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
2206
"""Helper for _generate_text_key_index to avoid deep nesting."""
2207
revision_order = tsort.topo_sort(ancestors)
2208
invalid_keys = set()
2210
for revision_id in revision_order:
2211
revision_keys[revision_id] = set()
2212
text_count = len(text_key_references)
2213
# a cache of the text keys to allow reuse; costs a dict of all the
2214
# keys, but saves a 2-tuple for every child of a given key.
2216
for text_key, valid in text_key_references.iteritems():
2218
invalid_keys.add(text_key)
2220
revision_keys[text_key[1]].add(text_key)
2221
text_key_cache[text_key] = text_key
2222
del text_key_references
2224
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
2225
NULL_REVISION = _mod_revision.NULL_REVISION
2226
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
2227
# too small for large or very branchy trees. However, for 55K path
2228
# trees, it would be easy to use too much memory trivially. Ideally we
2229
# could gauge this by looking at available real memory etc, but this is
2230
# always a tricky proposition.
2231
inventory_cache = lru_cache.LRUCache(10)
2232
batch_size = 10 # should be ~150MB on a 55K path tree
2233
batch_count = len(revision_order) / batch_size + 1
2235
pb.update("Calculating text parents", processed_texts, text_count)
2236
for offset in xrange(batch_count):
2237
to_query = revision_order[offset * batch_size:(offset + 1) *
2241
for revision_id in to_query:
2242
parent_ids = ancestors[revision_id]
2243
for text_key in revision_keys[revision_id]:
2244
pb.update("Calculating text parents", processed_texts)
2245
processed_texts += 1
2246
candidate_parents = []
2247
for parent_id in parent_ids:
2248
parent_text_key = (text_key[0], parent_id)
2250
check_parent = parent_text_key not in \
2251
revision_keys[parent_id]
2253
# the parent parent_id is a ghost:
2254
check_parent = False
2255
# truncate the derived graph against this ghost.
2256
parent_text_key = None
2258
# look at the parent commit details inventories to
2259
# determine possible candidates in the per file graph.
2262
inv = inventory_cache[parent_id]
2264
inv = self.revision_tree(parent_id).inventory
2265
inventory_cache[parent_id] = inv
2267
parent_entry = inv[text_key[0]]
2268
except (KeyError, errors.NoSuchId):
2270
if parent_entry is not None:
2272
text_key[0], parent_entry.revision)
2274
parent_text_key = None
2275
if parent_text_key is not None:
2276
candidate_parents.append(
2277
text_key_cache[parent_text_key])
2278
parent_heads = text_graph.heads(candidate_parents)
2279
new_parents = list(parent_heads)
2280
new_parents.sort(key=lambda x:candidate_parents.index(x))
2281
if new_parents == []:
2282
new_parents = [NULL_REVISION]
2283
text_index[text_key] = new_parents
2285
for text_key in invalid_keys:
2286
text_index[text_key] = [NULL_REVISION]
2289
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
2290
"""Get an iterable listing the keys of all the data introduced by a set
2293
The keys will be ordered so that the corresponding items can be safely
2294
fetched and inserted in that order.
2296
:returns: An iterable producing tuples of (knit-kind, file-id,
2297
versions). knit-kind is one of 'file', 'inventory', 'signatures',
2298
'revisions'. file-id is None unless knit-kind is 'file'.
2300
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
2303
for result in self._find_non_file_keys_to_fetch(revision_ids):
2306
def _find_file_keys_to_fetch(self, revision_ids, pb):
2307
# XXX: it's a bit weird to control the inventory weave caching in this
2308
# generator. Ideally the caching would be done in fetch.py I think. Or
2309
# maybe this generator should explicitly have the contract that it
2310
# should not be iterated until the previously yielded item has been
2312
inv_w = self.inventories
2314
# file ids that changed
2315
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
2317
num_file_ids = len(file_ids)
2318
for file_id, altered_versions in file_ids.iteritems():
2320
pb.update("Fetch texts", count, num_file_ids)
2322
yield ("file", file_id, altered_versions)
2324
def _find_non_file_keys_to_fetch(self, revision_ids):
2326
yield ("inventory", None, revision_ids)
2329
# XXX: Note ATM no callers actually pay attention to this return
2330
# instead they just use the list of revision ids and ignore
2331
# missing sigs. Consider removing this work entirely
2332
revisions_with_signatures = set(self.signatures.get_parent_map(
2333
[(r,) for r in revision_ids]))
2334
revisions_with_signatures = set(
2335
[r for (r,) in revisions_with_signatures])
2336
revisions_with_signatures.intersection_update(revision_ids)
2337
yield ("signatures", None, revisions_with_signatures)
2340
yield ("revisions", None, revision_ids)
2343
def get_inventory(self, revision_id):
2344
"""Get Inventory object by revision id."""
2345
return self.iter_inventories([revision_id]).next()
2347
def iter_inventories(self, revision_ids, ordering=None):
2348
"""Get many inventories by revision_ids.
2350
This will buffer some or all of the texts used in constructing the
2351
inventories in memory, but will only parse a single inventory at a
2354
:param revision_ids: The expected revision ids of the inventories.
2355
:param ordering: optional ordering, e.g. 'topological'. If not
2356
specified, the order of revision_ids will be preserved (by
2357
buffering if necessary).
2358
:return: An iterator of inventories.
2360
if ((None in revision_ids)
2361
or (_mod_revision.NULL_REVISION in revision_ids)):
2362
raise ValueError('cannot get null revision inventory')
2363
return self._iter_inventories(revision_ids, ordering)
2365
def _iter_inventories(self, revision_ids, ordering):
2366
"""single-document based inventory iteration."""
2367
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
2368
for text, revision_id in inv_xmls:
2369
yield self._deserialise_inventory(revision_id, text)
2371
def _iter_inventory_xmls(self, revision_ids, ordering):
2372
if ordering is None:
2373
order_as_requested = True
2374
ordering = 'unordered'
2376
order_as_requested = False
2377
keys = [(revision_id,) for revision_id in revision_ids]
2380
if order_as_requested:
2381
key_iter = iter(keys)
2382
next_key = key_iter.next()
2383
stream = self.inventories.get_record_stream(keys, ordering, True)
2385
for record in stream:
2386
if record.storage_kind != 'absent':
2387
chunks = record.get_bytes_as('chunked')
2388
if order_as_requested:
2389
text_chunks[record.key] = chunks
2391
yield ''.join(chunks), record.key[-1]
2393
raise errors.NoSuchRevision(self, record.key)
2394
if order_as_requested:
2395
# Yield as many results as we can while preserving order.
2396
while next_key in text_chunks:
2397
chunks = text_chunks.pop(next_key)
2398
yield ''.join(chunks), next_key[-1]
2400
next_key = key_iter.next()
2401
except StopIteration:
2402
# We still want to fully consume the get_record_stream,
2403
# just in case it is not actually finished at this point
2407
def _deserialise_inventory(self, revision_id, xml):
2408
"""Transform the xml into an inventory object.
2410
:param revision_id: The expected revision id of the inventory.
2411
:param xml: A serialised inventory.
2413
result = self._serializer.read_inventory_from_string(xml, revision_id,
2414
entry_cache=self._inventory_entry_cache,
2415
return_from_cache=self._safe_to_return_from_cache)
2416
if result.revision_id != revision_id:
2417
raise AssertionError('revision id mismatch %s != %s' % (
2418
result.revision_id, revision_id))
2421
def get_serializer_format(self):
2422
return self._serializer.format_num
2425
def _get_inventory_xml(self, revision_id):
2426
"""Get serialized inventory as a string."""
2427
texts = self._iter_inventory_xmls([revision_id], 'unordered')
2429
text, revision_id = texts.next()
2430
except StopIteration:
2431
raise errors.HistoryMissing(self, 'inventory', revision_id)
2434
def get_rev_id_for_revno(self, revno, known_pair):
2435
"""Return the revision id of a revno, given a later (revno, revid)
2436
pair in the same history.
2438
:return: if found (True, revid). If the available history ran out
2439
before reaching the revno, then this returns
2440
(False, (closest_revno, closest_revid)).
2442
known_revno, known_revid = known_pair
2443
partial_history = [known_revid]
2444
distance_from_known = known_revno - revno
2445
if distance_from_known < 0:
2447
'requested revno (%d) is later than given known revno (%d)'
2448
% (revno, known_revno))
2451
self, partial_history, stop_index=distance_from_known)
2452
except errors.RevisionNotPresent, err:
2453
if err.revision_id == known_revid:
2454
# The start revision (known_revid) wasn't found.
2456
# This is a stacked repository with no fallbacks, or a there's a
2457
# left-hand ghost. Either way, even though the revision named in
2458
# the error isn't in this repo, we know it's the next step in this
2459
# left-hand history.
2460
partial_history.append(err.revision_id)
2461
if len(partial_history) <= distance_from_known:
2462
# Didn't find enough history to get a revid for the revno.
2463
earliest_revno = known_revno - len(partial_history) + 1
2464
return (False, (earliest_revno, partial_history[-1]))
2465
if len(partial_history) - 1 > distance_from_known:
2466
raise AssertionError('_iter_for_revno returned too much history')
2467
return (True, partial_history[-1])
2469
def iter_reverse_revision_history(self, revision_id):
2470
"""Iterate backwards through revision ids in the lefthand history
2472
:param revision_id: The revision id to start with. All its lefthand
2473
ancestors will be traversed.
2475
graph = self.get_graph()
2476
stop_revisions = (None, _mod_revision.NULL_REVISION)
2477
return graph.iter_lefthand_ancestry(revision_id, stop_revisions)
2479
def is_shared(self):
2480
"""Return True if this repository is flagged as a shared repository."""
2481
raise NotImplementedError(self.is_shared)
2484
def reconcile(self, other=None, thorough=False):
2485
"""Reconcile this repository."""
2486
from bzrlib.reconcile import RepoReconciler
2487
reconciler = RepoReconciler(self, thorough=thorough)
2488
reconciler.reconcile()
2491
def _refresh_data(self):
2492
"""Helper called from lock_* to ensure coherency with disk.
2494
The default implementation does nothing; it is however possible
2495
for repositories to maintain loaded indices across multiple locks
2496
by checking inside their implementation of this method to see
2497
whether their indices are still valid. This depends of course on
2498
the disk format being validatable in this manner. This method is
2499
also called by the refresh_data() public interface to cause a refresh
2500
to occur while in a write lock so that data inserted by a smart server
2501
push operation is visible on the client's instance of the physical
2506
def revision_tree(self, revision_id):
2507
"""Return Tree for a revision on this branch.
2509
`revision_id` may be NULL_REVISION for the empty tree revision.
2511
revision_id = _mod_revision.ensure_null(revision_id)
2512
# TODO: refactor this to use an existing revision object
2513
# so we don't need to read it in twice.
2514
if revision_id == _mod_revision.NULL_REVISION:
2515
return RevisionTree(self, Inventory(root_id=None),
2516
_mod_revision.NULL_REVISION)
2518
inv = self.get_inventory(revision_id)
2519
return RevisionTree(self, inv, revision_id)
2521
def revision_trees(self, revision_ids):
2522
"""Return Trees for revisions in this repository.
2524
:param revision_ids: a sequence of revision-ids;
2525
a revision-id may not be None or 'null:'
2527
inventories = self.iter_inventories(revision_ids)
2528
for inv in inventories:
2529
yield RevisionTree(self, inv, inv.revision_id)
2531
def _filtered_revision_trees(self, revision_ids, file_ids):
2532
"""Return Tree for a revision on this branch with only some files.
2534
:param revision_ids: a sequence of revision-ids;
2535
a revision-id may not be None or 'null:'
2536
:param file_ids: if not None, the result is filtered
2537
so that only those file-ids, their parents and their
2538
children are included.
2540
inventories = self.iter_inventories(revision_ids)
2541
for inv in inventories:
2542
# Should we introduce a FilteredRevisionTree class rather
2543
# than pre-filter the inventory here?
2544
filtered_inv = inv.filter(file_ids)
2545
yield RevisionTree(self, filtered_inv, filtered_inv.revision_id)
2548
def get_ancestry(self, revision_id, topo_sorted=True):
2549
"""Return a list of revision-ids integrated by a revision.
2551
The first element of the list is always None, indicating the origin
2552
revision. This might change when we have history horizons, or
2553
perhaps we should have a new API.
2555
This is topologically sorted.
2557
if _mod_revision.is_null(revision_id):
2559
if not self.has_revision(revision_id):
2560
raise errors.NoSuchRevision(self, revision_id)
2561
graph = self.get_graph()
2563
search = graph._make_breadth_first_searcher([revision_id])
2566
found, ghosts = search.next_with_ghosts()
2567
except StopIteration:
2570
if _mod_revision.NULL_REVISION in keys:
2571
keys.remove(_mod_revision.NULL_REVISION)
2573
parent_map = graph.get_parent_map(keys)
2574
keys = tsort.topo_sort(parent_map)
2575
return [None] + list(keys)
2577
def pack(self, hint=None, clean_obsolete_packs=False):
2578
"""Compress the data within the repository.
2580
This operation only makes sense for some repository types. For other
2581
types it should be a no-op that just returns.
2583
This stub method does not require a lock, but subclasses should use
2584
@needs_write_lock as this is a long running call it's reasonable to
2585
implicitly lock for the user.
2587
:param hint: If not supplied, the whole repository is packed.
2588
If supplied, the repository may use the hint parameter as a
2589
hint for the parts of the repository to pack. A hint can be
2590
obtained from the result of commit_write_group(). Out of
2591
date hints are simply ignored, because concurrent operations
2592
can obsolete them rapidly.
2594
:param clean_obsolete_packs: Clean obsolete packs immediately after
2598
def get_transaction(self):
2599
return self.control_files.get_transaction()
2601
def get_parent_map(self, revision_ids):
2602
"""See graph.StackedParentsProvider.get_parent_map"""
2603
# revisions index works in keys; this just works in revisions
2604
# therefore wrap and unwrap
2607
for revision_id in revision_ids:
2608
if revision_id == _mod_revision.NULL_REVISION:
2609
result[revision_id] = ()
2610
elif revision_id is None:
2611
raise ValueError('get_parent_map(None) is not valid')
2613
query_keys.append((revision_id ,))
2614
for ((revision_id,), parent_keys) in \
2615
self.revisions.get_parent_map(query_keys).iteritems():
2617
result[revision_id] = tuple([parent_revid
2618
for (parent_revid,) in parent_keys])
2620
result[revision_id] = (_mod_revision.NULL_REVISION,)
2623
def _make_parents_provider(self):
2627
def get_known_graph_ancestry(self, revision_ids):
2628
"""Return the known graph for a set of revision ids and their ancestors.
2630
st = static_tuple.StaticTuple
2631
revision_keys = [st(r_id).intern() for r_id in revision_ids]
2632
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
2633
return graph.GraphThunkIdsToKeys(known_graph)
2635
def get_graph(self, other_repository=None):
2636
"""Return the graph walker for this repository format"""
2637
parents_provider = self._make_parents_provider()
2638
if (other_repository is not None and
2639
not self.has_same_location(other_repository)):
2640
parents_provider = graph.StackedParentsProvider(
2641
[parents_provider, other_repository._make_parents_provider()])
2642
return graph.Graph(parents_provider)
2644
def _get_versioned_file_checker(self, text_key_references=None,
2646
"""Return an object suitable for checking versioned files.
2648
:param text_key_references: if non-None, an already built
2649
dictionary mapping text keys ((fileid, revision_id) tuples)
2650
to whether they were referred to by the inventory of the
2651
revision_id that they contain. If None, this will be
2653
:param ancestors: Optional result from
2654
self.get_graph().get_parent_map(self.all_revision_ids()) if already
2657
return _VersionedFileChecker(self,
2658
text_key_references=text_key_references, ancestors=ancestors)
2660
def revision_ids_to_search_result(self, result_set):
2661
"""Convert a set of revision ids to a graph SearchResult."""
2662
result_parents = set()
2663
for parents in self.get_graph().get_parent_map(
2664
result_set).itervalues():
2665
result_parents.update(parents)
2666
included_keys = result_set.intersection(result_parents)
2667
start_keys = result_set.difference(included_keys)
2668
exclude_keys = result_parents.difference(result_set)
2669
result = graph.SearchResult(start_keys, exclude_keys,
2670
len(result_set), result_set)
2674
def set_make_working_trees(self, new_value):
2675
"""Set the policy flag for making working trees when creating branches.
2677
This only applies to branches that use this repository.
2679
The default is 'True'.
2680
:param new_value: True to restore the default, False to disable making
2683
raise NotImplementedError(self.set_make_working_trees)
2685
def make_working_trees(self):
2686
"""Returns the policy for making working trees on new branches."""
2687
raise NotImplementedError(self.make_working_trees)
2690
def sign_revision(self, revision_id, gpg_strategy):
2691
plaintext = Testament.from_revision(self, revision_id).as_short_text()
2692
self.store_revision_signature(gpg_strategy, plaintext, revision_id)
2695
def has_signature_for_revision_id(self, revision_id):
2696
"""Query for a revision signature for revision_id in the repository."""
2697
if not self.has_revision(revision_id):
2698
raise errors.NoSuchRevision(self, revision_id)
2699
sig_present = (1 == len(
2700
self.signatures.get_parent_map([(revision_id,)])))
2704
def get_signature_text(self, revision_id):
2705
"""Return the text for a signature."""
2706
stream = self.signatures.get_record_stream([(revision_id,)],
2708
record = stream.next()
2709
if record.storage_kind == 'absent':
2710
raise errors.NoSuchRevision(self, revision_id)
2711
return record.get_bytes_as('fulltext')
2714
def check(self, revision_ids=None, callback_refs=None, check_repo=True):
2715
"""Check consistency of all history of given revision_ids.
2717
Different repository implementations should override _check().
2719
:param revision_ids: A non-empty list of revision_ids whose ancestry
2720
will be checked. Typically the last revision_id of a branch.
2721
:param callback_refs: A dict of check-refs to resolve and callback
2722
the check/_check method on the items listed as wanting the ref.
2724
:param check_repo: If False do not check the repository contents, just
2725
calculate the data callback_refs requires and call them back.
2727
return self._check(revision_ids, callback_refs=callback_refs,
2728
check_repo=check_repo)
2730
def _check(self, revision_ids, callback_refs, check_repo):
2731
result = check.Check(self, check_repo=check_repo)
2732
result.check(callback_refs)
2735
def _warn_if_deprecated(self, branch=None):
2736
global _deprecation_warning_done
2737
if _deprecation_warning_done:
2741
conf = config.GlobalConfig()
2743
conf = branch.get_config()
2744
if conf.suppress_warning('format_deprecation'):
2746
warning("Format %s for %s is deprecated -"
2747
" please use 'bzr upgrade' to get better performance"
2748
% (self._format, self.bzrdir.transport.base))
2750
_deprecation_warning_done = True
2752
def supports_rich_root(self):
2753
return self._format.rich_root_data
2755
def _check_ascii_revisionid(self, revision_id, method):
2756
"""Private helper for ascii-only repositories."""
2757
# weave repositories refuse to store revisionids that are non-ascii.
2758
if revision_id is not None:
2759
# weaves require ascii revision ids.
2760
if isinstance(revision_id, unicode):
2762
revision_id.encode('ascii')
2763
except UnicodeEncodeError:
2764
raise errors.NonAsciiRevisionId(method, self)
2767
revision_id.decode('ascii')
2768
except UnicodeDecodeError:
2769
raise errors.NonAsciiRevisionId(method, self)
2771
def revision_graph_can_have_wrong_parents(self):
2772
"""Is it possible for this repository to have a revision graph with
2775
If True, then this repository must also implement
2776
_find_inconsistent_revision_parents so that check and reconcile can
2777
check for inconsistencies before proceeding with other checks that may
2778
depend on the revision index being consistent.
2780
raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
2783
def install_revision(repository, rev, revision_tree):
2784
"""Install all revision data into a repository."""
2785
install_revisions(repository, [(rev, revision_tree, None)])
2788
def install_revisions(repository, iterable, num_revisions=None, pb=None):
2789
"""Install all revision data into a repository.
2791
Accepts an iterable of revision, tree, signature tuples. The signature
2794
repository.start_write_group()
2796
inventory_cache = lru_cache.LRUCache(10)
2797
for n, (revision, revision_tree, signature) in enumerate(iterable):
2798
_install_revision(repository, revision, revision_tree, signature,
2801
pb.update('Transferring revisions', n + 1, num_revisions)
2803
repository.abort_write_group()
2806
repository.commit_write_group()
2809
def _install_revision(repository, rev, revision_tree, signature,
2811
"""Install all revision data into a repository."""
2812
present_parents = []
2814
for p_id in rev.parent_ids:
2815
if repository.has_revision(p_id):
2816
present_parents.append(p_id)
2817
parent_trees[p_id] = repository.revision_tree(p_id)
2819
parent_trees[p_id] = repository.revision_tree(
2820
_mod_revision.NULL_REVISION)
2822
inv = revision_tree.inventory
2823
entries = inv.iter_entries()
2824
# backwards compatibility hack: skip the root id.
2825
if not repository.supports_rich_root():
2826
path, root = entries.next()
2827
if root.revision != rev.revision_id:
2828
raise errors.IncompatibleRevision(repr(repository))
2830
for path, ie in entries:
2831
text_keys[(ie.file_id, ie.revision)] = ie
2832
text_parent_map = repository.texts.get_parent_map(text_keys)
2833
missing_texts = set(text_keys) - set(text_parent_map)
2834
# Add the texts that are not already present
2835
for text_key in missing_texts:
2836
ie = text_keys[text_key]
2838
# FIXME: TODO: The following loop overlaps/duplicates that done by
2839
# commit to determine parents. There is a latent/real bug here where
2840
# the parents inserted are not those commit would do - in particular
2841
# they are not filtered by heads(). RBC, AB
2842
for revision, tree in parent_trees.iteritems():
2843
if ie.file_id not in tree:
2845
parent_id = tree.inventory[ie.file_id].revision
2846
if parent_id in text_parents:
2848
text_parents.append((ie.file_id, parent_id))
2849
lines = revision_tree.get_file(ie.file_id).readlines()
2850
repository.texts.add_lines(text_key, text_parents, lines)
2852
# install the inventory
2853
if repository._format._commit_inv_deltas and len(rev.parent_ids):
2854
# Cache this inventory
2855
inventory_cache[rev.revision_id] = inv
2857
basis_inv = inventory_cache[rev.parent_ids[0]]
2859
repository.add_inventory(rev.revision_id, inv, present_parents)
2861
delta = inv._make_delta(basis_inv)
2862
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
2863
rev.revision_id, present_parents)
2865
repository.add_inventory(rev.revision_id, inv, present_parents)
2866
except errors.RevisionAlreadyPresent:
2868
if signature is not None:
2869
repository.add_signature_text(rev.revision_id, signature)
2870
repository.add_revision(rev.revision_id, rev, inv)
2873
class MetaDirRepository(Repository):
2874
"""Repositories in the new meta-dir layout.
2876
:ivar _transport: Transport for access to repository control files,
2877
typically pointing to .bzr/repository.
2880
def __init__(self, _format, a_bzrdir, control_files):
2881
super(MetaDirRepository, self).__init__(_format, a_bzrdir, control_files)
2882
self._transport = control_files._transport
2884
def is_shared(self):
2885
"""Return True if this repository is flagged as a shared repository."""
2886
return self._transport.has('shared-storage')
2889
def set_make_working_trees(self, new_value):
2890
"""Set the policy flag for making working trees when creating branches.
2892
This only applies to branches that use this repository.
2894
The default is 'True'.
2895
:param new_value: True to restore the default, False to disable making
2900
self._transport.delete('no-working-trees')
2901
except errors.NoSuchFile:
2904
self._transport.put_bytes('no-working-trees', '',
2905
mode=self.bzrdir._get_file_mode())
2907
def make_working_trees(self):
2908
"""Returns the policy for making working trees on new branches."""
2909
return not self._transport.has('no-working-trees')
2912
class MetaDirVersionedFileRepository(MetaDirRepository):
2913
"""Repositories in a meta-dir, that work via versioned file objects."""
2915
def __init__(self, _format, a_bzrdir, control_files):
2916
super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
2920
class RepositoryFormatRegistry(controldir.ControlComponentFormatRegistry):
2921
"""Repository format registry."""
2923
def get_default(self):
2924
"""Return the current default format."""
2925
from bzrlib import bzrdir
2926
return bzrdir.format_registry.make_bzrdir('default').repository_format
2929
network_format_registry = registry.FormatRegistry()
2930
"""Registry of formats indexed by their network name.
2932
The network name for a repository format is an identifier that can be used when
2933
referring to formats with smart server operations. See
2934
RepositoryFormat.network_name() for more detail.
2938
format_registry = RepositoryFormatRegistry(network_format_registry)
2939
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
2941
This can contain either format instances themselves, or classes/factories that
2942
can be called to obtain one.
2946
#####################################################################
2947
# Repository Formats
2949
class RepositoryFormat(object):
2950
"""A repository format.
2952
Formats provide four things:
2953
* An initialization routine to construct repository data on disk.
2954
* a optional format string which is used when the BzrDir supports
2956
* an open routine which returns a Repository instance.
2957
* A network name for referring to the format in smart server RPC
2960
There is one and only one Format subclass for each on-disk format. But
2961
there can be one Repository subclass that is used for several different
2962
formats. The _format attribute on a Repository instance can be used to
2963
determine the disk format.
2965
Formats are placed in a registry by their format string for reference
2966
during opening. These should be subclasses of RepositoryFormat for
2969
Once a format is deprecated, just deprecate the initialize and open
2970
methods on the format class. Do not deprecate the object, as the
2971
object may be created even when a repository instance hasn't been
2974
Common instance attributes:
2975
_matchingbzrdir - the bzrdir format that the repository format was
2976
originally written to work with. This can be used if manually
2977
constructing a bzrdir and repository, or more commonly for test suite
2981
# Set to True or False in derived classes. True indicates that the format
2982
# supports ghosts gracefully.
2983
supports_ghosts = None
2984
# Can this repository be given external locations to lookup additional
2985
# data. Set to True or False in derived classes.
2986
supports_external_lookups = None
2987
# Does this format support CHK bytestring lookups. Set to True or False in
2989
supports_chks = None
2990
# Should commit add an inventory, or an inventory delta to the repository.
2991
_commit_inv_deltas = True
2992
# What order should fetch operations request streams in?
2993
# The default is unordered as that is the cheapest for an origin to
2995
_fetch_order = 'unordered'
2996
# Does this repository format use deltas that can be fetched as-deltas ?
2997
# (E.g. knits, where the knit deltas can be transplanted intact.
2998
# We default to False, which will ensure that enough data to get
2999
# a full text out of any fetch stream will be grabbed.
3000
_fetch_uses_deltas = False
3001
# Should fetch trigger a reconcile after the fetch? Only needed for
3002
# some repository formats that can suffer internal inconsistencies.
3003
_fetch_reconcile = False
3004
# Does this format have < O(tree_size) delta generation. Used to hint what
3005
# code path for commit, amongst other things.
3007
# Does doing a pack operation compress data? Useful for the pack UI command
3008
# (so if there is one pack, the operation can still proceed because it may
3009
# help), and for fetching when data won't have come from the same
3011
pack_compresses = False
3012
# Does the repository inventory storage understand references to trees?
3013
supports_tree_reference = None
3014
# Is the format experimental ?
3015
experimental = False
3016
# Does this repository format escape funky characters, or does it create files with
3017
# similar names as the versioned files in its contents on disk ?
3018
supports_funky_characters = True
3019
# Does this repository format support leaving locks?
3020
supports_leaving_lock = True
3023
return "%s()" % self.__class__.__name__
3025
def __eq__(self, other):
3026
# format objects are generally stateless
3027
return isinstance(other, self.__class__)
3029
def __ne__(self, other):
3030
return not self == other
3033
def find_format(klass, a_bzrdir):
3034
"""Return the format for the repository object in a_bzrdir.
3036
This is used by bzr native formats that have a "format" file in
3037
the repository. Other methods may be used by different types of
3041
transport = a_bzrdir.get_repository_transport(None)
3042
format_string = transport.get_bytes("format")
3043
return format_registry.get(format_string)
3044
except errors.NoSuchFile:
3045
raise errors.NoRepositoryPresent(a_bzrdir)
3047
raise errors.UnknownFormatError(format=format_string,
3051
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3052
def register_format(klass, format):
3053
format_registry.register(format)
3056
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3057
def unregister_format(klass, format):
3058
format_registry.remove(format)
3061
@symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3062
def get_default_format(klass):
3063
"""Return the current default format."""
3064
return format_registry.get_default()
3066
def get_format_string(self):
3067
"""Return the ASCII format string that identifies this format.
3069
Note that in pre format ?? repositories the format string is
3070
not permitted nor written to disk.
3072
raise NotImplementedError(self.get_format_string)
3074
def get_format_description(self):
3075
"""Return the short description for this format."""
3076
raise NotImplementedError(self.get_format_description)
3078
# TODO: this shouldn't be in the base class, it's specific to things that
3079
# use weaves or knits -- mbp 20070207
3080
def _get_versioned_file_store(self,
3085
versionedfile_class=None,
3086
versionedfile_kwargs={},
3088
if versionedfile_class is None:
3089
versionedfile_class = self._versionedfile_class
3090
weave_transport = control_files._transport.clone(name)
3091
dir_mode = control_files._dir_mode
3092
file_mode = control_files._file_mode
3093
return VersionedFileStore(weave_transport, prefixed=prefixed,
3095
file_mode=file_mode,
3096
versionedfile_class=versionedfile_class,
3097
versionedfile_kwargs=versionedfile_kwargs,
3100
def initialize(self, a_bzrdir, shared=False):
3101
"""Initialize a repository of this format in a_bzrdir.
3103
:param a_bzrdir: The bzrdir to put the new repository in it.
3104
:param shared: The repository should be initialized as a sharable one.
3105
:returns: The new repository object.
3107
This may raise UninitializableFormat if shared repository are not
3108
compatible the a_bzrdir.
3110
raise NotImplementedError(self.initialize)
3112
def is_supported(self):
3113
"""Is this format supported?
3115
Supported formats must be initializable and openable.
3116
Unsupported formats may not support initialization or committing or
3117
some other features depending on the reason for not being supported.
3121
def network_name(self):
3122
"""A simple byte string uniquely identifying this format for RPC calls.
3124
MetaDir repository formats use their disk format string to identify the
3125
repository over the wire. All in one formats such as bzr < 0.8, and
3126
foreign formats like svn/git and hg should use some marker which is
3127
unique and immutable.
3129
raise NotImplementedError(self.network_name)
3131
def check_conversion_target(self, target_format):
3132
if self.rich_root_data and not target_format.rich_root_data:
3133
raise errors.BadConversionTarget(
3134
'Does not support rich root data.', target_format,
3136
if (self.supports_tree_reference and
3137
not getattr(target_format, 'supports_tree_reference', False)):
3138
raise errors.BadConversionTarget(
3139
'Does not support nested trees', target_format,
3142
def open(self, a_bzrdir, _found=False):
3143
"""Return an instance of this format for the bzrdir a_bzrdir.
3145
_found is a private parameter, do not use it.
3147
raise NotImplementedError(self.open)
3149
def _run_post_repo_init_hooks(self, repository, a_bzrdir, shared):
3150
from bzrlib.bzrdir import BzrDir, RepoInitHookParams
3151
hooks = BzrDir.hooks['post_repo_init']
3154
params = RepoInitHookParams(repository, self, a_bzrdir, shared)
3159
class MetaDirRepositoryFormat(RepositoryFormat):
3160
"""Common base class for the new repositories using the metadir layout."""
3162
rich_root_data = False
3163
supports_tree_reference = False
3164
supports_external_lookups = False
3165
supports_leaving_lock = True
3168
def _matchingbzrdir(self):
3169
matching = bzrdir.BzrDirMetaFormat1()
3170
matching.repository_format = self
3174
super(MetaDirRepositoryFormat, self).__init__()
3176
def _create_control_files(self, a_bzrdir):
3177
"""Create the required files and the initial control_files object."""
3178
# FIXME: RBC 20060125 don't peek under the covers
3179
# NB: no need to escape relative paths that are url safe.
3180
repository_transport = a_bzrdir.get_repository_transport(self)
3181
control_files = lockable_files.LockableFiles(repository_transport,
3182
'lock', lockdir.LockDir)
3183
control_files.create_lock()
3184
return control_files
3186
def _upload_blank_content(self, a_bzrdir, dirs, files, utf8_files, shared):
3187
"""Upload the initial blank content."""
3188
control_files = self._create_control_files(a_bzrdir)
3189
control_files.lock_write()
3190
transport = control_files._transport
3192
utf8_files += [('shared-storage', '')]
3194
transport.mkdir_multi(dirs, mode=a_bzrdir._get_dir_mode())
3195
for (filename, content_stream) in files:
3196
transport.put_file(filename, content_stream,
3197
mode=a_bzrdir._get_file_mode())
3198
for (filename, content_bytes) in utf8_files:
3199
transport.put_bytes_non_atomic(filename, content_bytes,
3200
mode=a_bzrdir._get_file_mode())
3202
control_files.unlock()
3204
def network_name(self):
3205
"""Metadir formats have matching disk and network format strings."""
3206
return self.get_format_string()
3209
# Pre-0.8 formats that don't have a disk format string (because they are
3210
# versioned by the matching control directory). We use the control directories
3211
# disk format string as a key for the network_name because they meet the
3212
# constraints (simple string, unique, immutable).
3213
network_format_registry.register_lazy(
3214
"Bazaar-NG branch, format 5\n",
3215
'bzrlib.repofmt.weaverepo',
3216
'RepositoryFormat5',
3218
network_format_registry.register_lazy(
3219
"Bazaar-NG branch, format 6\n",
3220
'bzrlib.repofmt.weaverepo',
3221
'RepositoryFormat6',
3224
format_registry.register_extra_lazy(
3225
'bzrlib.repofmt.weaverepo',
3226
'RepositoryFormat4')
3227
format_registry.register_extra_lazy(
3228
'bzrlib.repofmt.weaverepo',
3229
'RepositoryFormat5')
3230
format_registry.register_extra_lazy(
3231
'bzrlib.repofmt.weaverepo',
3232
'RepositoryFormat6')
3234
# formats which have no format string are not discoverable or independently
3235
# creatable on disk, so are not registered in format_registry. They're
3236
# all in bzrlib.repofmt.weaverepo now. When an instance of one of these is
3237
# needed, it's constructed directly by the BzrDir. Non-native formats where
3238
# the repository is not separately opened are similar.
3240
format_registry.register_lazy(
3241
'Bazaar-NG Repository format 7',
3242
'bzrlib.repofmt.weaverepo',
3246
format_registry.register_lazy(
3247
'Bazaar-NG Knit Repository Format 1',
3248
'bzrlib.repofmt.knitrepo',
3249
'RepositoryFormatKnit1',
3252
format_registry.register_lazy(
3253
'Bazaar Knit Repository Format 3 (bzr 0.15)\n',
3254
'bzrlib.repofmt.knitrepo',
3255
'RepositoryFormatKnit3',
3258
format_registry.register_lazy(
3259
'Bazaar Knit Repository Format 4 (bzr 1.0)\n',
3260
'bzrlib.repofmt.knitrepo',
3261
'RepositoryFormatKnit4',
3264
# Pack-based formats. There is one format for pre-subtrees, and one for
3265
# post-subtrees to allow ease of testing.
3266
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
3267
format_registry.register_lazy(
3268
'Bazaar pack repository format 1 (needs bzr 0.92)\n',
3269
'bzrlib.repofmt.pack_repo',
3270
'RepositoryFormatKnitPack1',
3272
format_registry.register_lazy(
3273
'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
3274
'bzrlib.repofmt.pack_repo',
3275
'RepositoryFormatKnitPack3',
3277
format_registry.register_lazy(
3278
'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
3279
'bzrlib.repofmt.pack_repo',
3280
'RepositoryFormatKnitPack4',
3282
format_registry.register_lazy(
3283
'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
3284
'bzrlib.repofmt.pack_repo',
3285
'RepositoryFormatKnitPack5',
3287
format_registry.register_lazy(
3288
'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
3289
'bzrlib.repofmt.pack_repo',
3290
'RepositoryFormatKnitPack5RichRoot',
3292
format_registry.register_lazy(
3293
'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
3294
'bzrlib.repofmt.pack_repo',
3295
'RepositoryFormatKnitPack5RichRootBroken',
3297
format_registry.register_lazy(
3298
'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
3299
'bzrlib.repofmt.pack_repo',
3300
'RepositoryFormatKnitPack6',
3302
format_registry.register_lazy(
3303
'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
3304
'bzrlib.repofmt.pack_repo',
3305
'RepositoryFormatKnitPack6RichRoot',
3307
format_registry.register_lazy(
3308
'Bazaar repository format 2a (needs bzr 1.16 or later)\n',
3309
'bzrlib.repofmt.groupcompress_repo',
3310
'RepositoryFormat2a',
3313
# Development formats.
3314
# Check their docstrings to see if/when they are obsolete.
3315
format_registry.register_lazy(
3316
("Bazaar development format 2 with subtree support "
3317
"(needs bzr.dev from before 1.8)\n"),
3318
'bzrlib.repofmt.pack_repo',
3319
'RepositoryFormatPackDevelopment2Subtree',
3321
format_registry.register_lazy(
3322
'Bazaar development format 8\n',
3323
'bzrlib.repofmt.groupcompress_repo',
3324
'RepositoryFormat2aSubtree',
3328
class InterRepository(InterObject):
3329
"""This class represents operations taking place between two repositories.
3331
Its instances have methods like copy_content and fetch, and contain
3332
references to the source and target repositories these operations can be
3335
Often we will provide convenience methods on 'repository' which carry out
3336
operations with another repository - they will always forward to
3337
InterRepository.get(other).method_name(parameters).
3340
_walk_to_common_revisions_batch_size = 50
3342
"""The available optimised InterRepository types."""
3345
def copy_content(self, revision_id=None):
3346
"""Make a complete copy of the content in self into destination.
3348
This is a destructive operation! Do not use it on existing
3351
:param revision_id: Only copy the content needed to construct
3352
revision_id and its parents.
3355
self.target.set_make_working_trees(self.source.make_working_trees())
3356
except NotImplementedError:
3358
self.target.fetch(self.source, revision_id=revision_id)
3361
def fetch(self, revision_id=None, find_ghosts=False,
3363
"""Fetch the content required to construct revision_id.
3365
The content is copied from self.source to self.target.
3367
:param revision_id: if None all content is copied, if NULL_REVISION no
3371
ui.ui_factory.warn_experimental_format_fetch(self)
3372
from bzrlib.fetch import RepoFetcher
3373
# See <https://launchpad.net/bugs/456077> asking for a warning here
3374
if self.source._format.network_name() != self.target._format.network_name():
3375
ui.ui_factory.show_user_warning('cross_format_fetch',
3376
from_format=self.source._format,
3377
to_format=self.target._format)
3378
f = RepoFetcher(to_repository=self.target,
3379
from_repository=self.source,
3380
last_revision=revision_id,
3381
fetch_spec=fetch_spec,
3382
find_ghosts=find_ghosts)
3384
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
3385
"""Walk out from revision_ids in source to revisions target has.
3387
:param revision_ids: The start point for the search.
3388
:return: A set of revision ids.
3390
target_graph = self.target.get_graph()
3391
revision_ids = frozenset(revision_ids)
3393
all_wanted_revs = revision_ids.union(if_present_ids)
3395
all_wanted_revs = revision_ids
3396
missing_revs = set()
3397
source_graph = self.source.get_graph()
3398
# ensure we don't pay silly lookup costs.
3399
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
3400
null_set = frozenset([_mod_revision.NULL_REVISION])
3401
searcher_exhausted = False
3405
# Iterate the searcher until we have enough next_revs
3406
while len(next_revs) < self._walk_to_common_revisions_batch_size:
3408
next_revs_part, ghosts_part = searcher.next_with_ghosts()
3409
next_revs.update(next_revs_part)
3410
ghosts.update(ghosts_part)
3411
except StopIteration:
3412
searcher_exhausted = True
3414
# If there are ghosts in the source graph, and the caller asked for
3415
# them, make sure that they are present in the target.
3416
# We don't care about other ghosts as we can't fetch them and
3417
# haven't been asked to.
3418
ghosts_to_check = set(revision_ids.intersection(ghosts))
3419
revs_to_get = set(next_revs).union(ghosts_to_check)
3421
have_revs = set(target_graph.get_parent_map(revs_to_get))
3422
# we always have NULL_REVISION present.
3423
have_revs = have_revs.union(null_set)
3424
# Check if the target is missing any ghosts we need.
3425
ghosts_to_check.difference_update(have_revs)
3427
# One of the caller's revision_ids is a ghost in both the
3428
# source and the target.
3429
raise errors.NoSuchRevision(
3430
self.source, ghosts_to_check.pop())
3431
missing_revs.update(next_revs - have_revs)
3432
# Because we may have walked past the original stop point, make
3433
# sure everything is stopped
3434
stop_revs = searcher.find_seen_ancestors(have_revs)
3435
searcher.stop_searching_any(stop_revs)
3436
if searcher_exhausted:
3438
return searcher.get_result()
3441
def search_missing_revision_ids(self,
3442
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
3443
find_ghosts=True, revision_ids=None, if_present_ids=None):
3444
"""Return the revision ids that source has that target does not.
3446
:param revision_id: only return revision ids included by this
3448
:param revision_ids: return revision ids included by these
3449
revision_ids. NoSuchRevision will be raised if any of these
3450
revisions are not present.
3451
:param if_present_ids: like revision_ids, but will not cause
3452
NoSuchRevision if any of these are absent, instead they will simply
3453
not be in the result. This is useful for e.g. finding revisions
3454
to fetch for tags, which may reference absent revisions.
3455
:param find_ghosts: If True find missing revisions in deep history
3456
rather than just finding the surface difference.
3457
:return: A bzrlib.graph.SearchResult.
3459
if symbol_versioning.deprecated_passed(revision_id):
3460
symbol_versioning.warn(
3461
'search_missing_revision_ids(revision_id=...) was '
3462
'deprecated in 2.4. Use revision_ids=[...] instead.',
3463
DeprecationWarning, stacklevel=2)
3464
if revision_ids is not None:
3465
raise AssertionError(
3466
'revision_ids is mutually exclusive with revision_id')
3467
if revision_id is not None:
3468
revision_ids = [revision_id]
3470
# stop searching at found target revisions.
3471
if not find_ghosts and (revision_ids is not None or if_present_ids is
3473
return self._walk_to_common_revisions(revision_ids,
3474
if_present_ids=if_present_ids)
3475
# generic, possibly worst case, slow code path.
3476
target_ids = set(self.target.all_revision_ids())
3477
source_ids = self._present_source_revisions_for(
3478
revision_ids, if_present_ids)
3479
result_set = set(source_ids).difference(target_ids)
3480
return self.source.revision_ids_to_search_result(result_set)
3482
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
3483
"""Returns set of all revisions in ancestry of revision_ids present in
3486
:param revision_ids: if None, all revisions in source are returned.
3487
:param if_present_ids: like revision_ids, but if any/all of these are
3488
absent no error is raised.
3490
if revision_ids is not None or if_present_ids is not None:
3491
# First, ensure all specified revisions exist. Callers expect
3492
# NoSuchRevision when they pass absent revision_ids here.
3493
if revision_ids is None:
3494
revision_ids = set()
3495
if if_present_ids is None:
3496
if_present_ids = set()
3497
revision_ids = set(revision_ids)
3498
if_present_ids = set(if_present_ids)
3499
all_wanted_ids = revision_ids.union(if_present_ids)
3500
graph = self.source.get_graph()
3501
present_revs = set(graph.get_parent_map(all_wanted_ids))
3502
missing = revision_ids.difference(present_revs)
3504
raise errors.NoSuchRevision(self.source, missing.pop())
3505
found_ids = all_wanted_ids.intersection(present_revs)
3506
source_ids = [rev_id for (rev_id, parents) in
3507
graph.iter_ancestry(found_ids)
3508
if rev_id != _mod_revision.NULL_REVISION
3509
and parents is not None]
3511
source_ids = self.source.all_revision_ids()
3512
return set(source_ids)
3515
def _same_model(source, target):
3516
"""True if source and target have the same data representation.
3518
Note: this is always called on the base class; overriding it in a
3519
subclass will have no effect.
3522
InterRepository._assert_same_model(source, target)
3524
except errors.IncompatibleRepositories, e:
3528
def _assert_same_model(source, target):
3529
"""Raise an exception if two repositories do not use the same model.
3531
if source.supports_rich_root() != target.supports_rich_root():
3532
raise errors.IncompatibleRepositories(source, target,
3533
"different rich-root support")
3534
if source._serializer != target._serializer:
3535
raise errors.IncompatibleRepositories(source, target,
3536
"different serializers")
3539
class InterSameDataRepository(InterRepository):
3540
"""Code for converting between repositories that represent the same data.
3542
Data format and model must match for this to work.
3546
def _get_repo_format_to_test(self):
3547
"""Repository format for testing with.
3549
InterSameData can pull from subtree to subtree and from non-subtree to
3550
non-subtree, so we test this with the richest repository format.
3552
from bzrlib.repofmt import knitrepo
3553
return knitrepo.RepositoryFormatKnit3()
3556
def is_compatible(source, target):
3557
return InterRepository._same_model(source, target)
3560
class InterDifferingSerializer(InterRepository):
3563
def _get_repo_format_to_test(self):
3567
def is_compatible(source, target):
3568
"""Be compatible with Knit2 source and Knit3 target"""
3569
# This is redundant with format.check_conversion_target(), however that
3570
# raises an exception, and we just want to say "False" as in we won't
3571
# support converting between these formats.
3572
if 'IDS_never' in debug.debug_flags:
3574
if source.supports_rich_root() and not target.supports_rich_root():
3576
if (source._format.supports_tree_reference
3577
and not target._format.supports_tree_reference):
3579
if target._fallback_repositories and target._format.supports_chks:
3580
# IDS doesn't know how to copy CHKs for the parent inventories it
3581
# adds to stacked repos.
3583
if 'IDS_always' in debug.debug_flags:
3585
# Only use this code path for local source and target. IDS does far
3586
# too much IO (both bandwidth and roundtrips) over a network.
3587
if not source.bzrdir.transport.base.startswith('file:///'):
3589
if not target.bzrdir.transport.base.startswith('file:///'):
3593
def _get_trees(self, revision_ids, cache):
3595
for rev_id in revision_ids:
3597
possible_trees.append((rev_id, cache[rev_id]))
3599
# Not cached, but inventory might be present anyway.
3601
tree = self.source.revision_tree(rev_id)
3602
except errors.NoSuchRevision:
3603
# Nope, parent is ghost.
3606
cache[rev_id] = tree
3607
possible_trees.append((rev_id, tree))
3608
return possible_trees
3610
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
3611
"""Get the best delta and base for this revision.
3613
:return: (basis_id, delta)
3616
# Generate deltas against each tree, to find the shortest.
3617
texts_possibly_new_in_tree = set()
3618
for basis_id, basis_tree in possible_trees:
3619
delta = tree.inventory._make_delta(basis_tree.inventory)
3620
for old_path, new_path, file_id, new_entry in delta:
3621
if new_path is None:
3622
# This file_id isn't present in the new rev, so we don't
3626
# Rich roots are handled elsewhere...
3628
kind = new_entry.kind
3629
if kind != 'directory' and kind != 'file':
3630
# No text record associated with this inventory entry.
3632
# This is a directory or file that has changed somehow.
3633
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
3634
deltas.append((len(delta), basis_id, delta))
3636
return deltas[0][1:]
3638
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
3639
"""Find all parent revisions that are absent, but for which the
3640
inventory is present, and copy those inventories.
3642
This is necessary to preserve correctness when the source is stacked
3643
without fallbacks configured. (Note that in cases like upgrade the
3644
source may be not have _fallback_repositories even though it is
3648
for parents in parent_map.values():
3649
parent_revs.update(parents)
3650
present_parents = self.source.get_parent_map(parent_revs)
3651
absent_parents = set(parent_revs).difference(present_parents)
3652
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
3653
(rev_id,) for rev_id in absent_parents)
3654
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
3655
for parent_tree in self.source.revision_trees(parent_inv_ids):
3656
current_revision_id = parent_tree.get_revision_id()
3657
parents_parents_keys = parent_invs_keys_for_stacking[
3658
(current_revision_id,)]
3659
parents_parents = [key[-1] for key in parents_parents_keys]
3660
basis_id = _mod_revision.NULL_REVISION
3661
basis_tree = self.source.revision_tree(basis_id)
3662
delta = parent_tree.inventory._make_delta(basis_tree.inventory)
3663
self.target.add_inventory_by_delta(
3664
basis_id, delta, current_revision_id, parents_parents)
3665
cache[current_revision_id] = parent_tree
3667
def _fetch_batch(self, revision_ids, basis_id, cache):
3668
"""Fetch across a few revisions.
3670
:param revision_ids: The revisions to copy
3671
:param basis_id: The revision_id of a tree that must be in cache, used
3672
as a basis for delta when no other base is available
3673
:param cache: A cache of RevisionTrees that we can use.
3674
:return: The revision_id of the last converted tree. The RevisionTree
3675
for it will be in cache
3677
# Walk though all revisions; get inventory deltas, copy referenced
3678
# texts that delta references, insert the delta, revision and
3680
root_keys_to_create = set()
3683
pending_revisions = []
3684
parent_map = self.source.get_parent_map(revision_ids)
3685
self._fetch_parent_invs_for_stacking(parent_map, cache)
3686
self.source._safe_to_return_from_cache = True
3687
for tree in self.source.revision_trees(revision_ids):
3688
# Find a inventory delta for this revision.
3689
# Find text entries that need to be copied, too.
3690
current_revision_id = tree.get_revision_id()
3691
parent_ids = parent_map.get(current_revision_id, ())
3692
parent_trees = self._get_trees(parent_ids, cache)
3693
possible_trees = list(parent_trees)
3694
if len(possible_trees) == 0:
3695
# There either aren't any parents, or the parents are ghosts,
3696
# so just use the last converted tree.
3697
possible_trees.append((basis_id, cache[basis_id]))
3698
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
3700
revision = self.source.get_revision(current_revision_id)
3701
pending_deltas.append((basis_id, delta,
3702
current_revision_id, revision.parent_ids))
3703
if self._converting_to_rich_root:
3704
self._revision_id_to_root_id[current_revision_id] = \
3706
# Determine which texts are in present in this revision but not in
3707
# any of the available parents.
3708
texts_possibly_new_in_tree = set()
3709
for old_path, new_path, file_id, entry in delta:
3710
if new_path is None:
3711
# This file_id isn't present in the new rev
3715
if not self.target.supports_rich_root():
3716
# The target doesn't support rich root, so we don't
3719
if self._converting_to_rich_root:
3720
# This can't be copied normally, we have to insert
3722
root_keys_to_create.add((file_id, entry.revision))
3725
texts_possibly_new_in_tree.add((file_id, entry.revision))
3726
for basis_id, basis_tree in possible_trees:
3727
basis_inv = basis_tree.inventory
3728
for file_key in list(texts_possibly_new_in_tree):
3729
file_id, file_revision = file_key
3731
entry = basis_inv[file_id]
3732
except errors.NoSuchId:
3734
if entry.revision == file_revision:
3735
texts_possibly_new_in_tree.remove(file_key)
3736
text_keys.update(texts_possibly_new_in_tree)
3737
pending_revisions.append(revision)
3738
cache[current_revision_id] = tree
3739
basis_id = current_revision_id
3740
self.source._safe_to_return_from_cache = False
3742
from_texts = self.source.texts
3743
to_texts = self.target.texts
3744
if root_keys_to_create:
3745
root_stream = _mod_fetch._new_root_data_stream(
3746
root_keys_to_create, self._revision_id_to_root_id, parent_map,
3748
to_texts.insert_record_stream(root_stream)
3749
to_texts.insert_record_stream(from_texts.get_record_stream(
3750
text_keys, self.target._format._fetch_order,
3751
not self.target._format._fetch_uses_deltas))
3752
# insert inventory deltas
3753
for delta in pending_deltas:
3754
self.target.add_inventory_by_delta(*delta)
3755
if self.target._fallback_repositories:
3756
# Make sure this stacked repository has all the parent inventories
3757
# for the new revisions that we are about to insert. We do this
3758
# before adding the revisions so that no revision is added until
3759
# all the inventories it may depend on are added.
3760
# Note that this is overzealous, as we may have fetched these in an
3763
revision_ids = set()
3764
for revision in pending_revisions:
3765
revision_ids.add(revision.revision_id)
3766
parent_ids.update(revision.parent_ids)
3767
parent_ids.difference_update(revision_ids)
3768
parent_ids.discard(_mod_revision.NULL_REVISION)
3769
parent_map = self.source.get_parent_map(parent_ids)
3770
# we iterate over parent_map and not parent_ids because we don't
3771
# want to try copying any revision which is a ghost
3772
for parent_tree in self.source.revision_trees(parent_map):
3773
current_revision_id = parent_tree.get_revision_id()
3774
parents_parents = parent_map[current_revision_id]
3775
possible_trees = self._get_trees(parents_parents, cache)
3776
if len(possible_trees) == 0:
3777
# There either aren't any parents, or the parents are
3778
# ghosts, so just use the last converted tree.
3779
possible_trees.append((basis_id, cache[basis_id]))
3780
basis_id, delta = self._get_delta_for_revision(parent_tree,
3781
parents_parents, possible_trees)
3782
self.target.add_inventory_by_delta(
3783
basis_id, delta, current_revision_id, parents_parents)
3784
# insert signatures and revisions
3785
for revision in pending_revisions:
3787
signature = self.source.get_signature_text(
3788
revision.revision_id)
3789
self.target.add_signature_text(revision.revision_id,
3791
except errors.NoSuchRevision:
3793
self.target.add_revision(revision.revision_id, revision)
3796
def _fetch_all_revisions(self, revision_ids, pb):
3797
"""Fetch everything for the list of revisions.
3799
:param revision_ids: The list of revisions to fetch. Must be in
3801
:param pb: A ProgressTask
3804
basis_id, basis_tree = self._get_basis(revision_ids[0])
3806
cache = lru_cache.LRUCache(100)
3807
cache[basis_id] = basis_tree
3808
del basis_tree # We don't want to hang on to it here
3812
for offset in range(0, len(revision_ids), batch_size):
3813
self.target.start_write_group()
3815
pb.update('Transferring revisions', offset,
3817
batch = revision_ids[offset:offset+batch_size]
3818
basis_id = self._fetch_batch(batch, basis_id, cache)
3820
self.source._safe_to_return_from_cache = False
3821
self.target.abort_write_group()
3824
hint = self.target.commit_write_group()
3827
if hints and self.target._format.pack_compresses:
3828
self.target.pack(hint=hints)
3829
pb.update('Transferring revisions', len(revision_ids),
3833
def fetch(self, revision_id=None, find_ghosts=False,
3835
"""See InterRepository.fetch()."""
3836
if fetch_spec is not None:
3837
revision_ids = fetch_spec.get_keys()
3840
ui.ui_factory.warn_experimental_format_fetch(self)
3841
if (not self.source.supports_rich_root()
3842
and self.target.supports_rich_root()):
3843
self._converting_to_rich_root = True
3844
self._revision_id_to_root_id = {}
3846
self._converting_to_rich_root = False
3847
# See <https://launchpad.net/bugs/456077> asking for a warning here
3848
if self.source._format.network_name() != self.target._format.network_name():
3849
ui.ui_factory.show_user_warning('cross_format_fetch',
3850
from_format=self.source._format,
3851
to_format=self.target._format)
3852
if revision_ids is None:
3854
search_revision_ids = [revision_id]
3856
search_revision_ids = None
3857
revision_ids = self.target.search_missing_revision_ids(self.source,
3858
revision_ids=search_revision_ids,
3859
find_ghosts=find_ghosts).get_keys()
3860
if not revision_ids:
3862
revision_ids = tsort.topo_sort(
3863
self.source.get_graph().get_parent_map(revision_ids))
3864
if not revision_ids:
3866
# Walk though all revisions; get inventory deltas, copy referenced
3867
# texts that delta references, insert the delta, revision and
3869
pb = ui.ui_factory.nested_progress_bar()
3871
self._fetch_all_revisions(revision_ids, pb)
3874
return len(revision_ids), 0
3876
def _get_basis(self, first_revision_id):
3877
"""Get a revision and tree which exists in the target.
3879
This assumes that first_revision_id is selected for transmission
3880
because all other ancestors are already present. If we can't find an
3881
ancestor we fall back to NULL_REVISION since we know that is safe.
3883
:return: (basis_id, basis_tree)
3885
first_rev = self.source.get_revision(first_revision_id)
3887
basis_id = first_rev.parent_ids[0]
3888
# only valid as a basis if the target has it
3889
self.target.get_revision(basis_id)
3890
# Try to get a basis tree - if it's a ghost it will hit the
3891
# NoSuchRevision case.
3892
basis_tree = self.source.revision_tree(basis_id)
3893
except (IndexError, errors.NoSuchRevision):
3894
basis_id = _mod_revision.NULL_REVISION
3895
basis_tree = self.source.revision_tree(basis_id)
3896
return basis_id, basis_tree
3899
InterRepository.register_optimiser(InterDifferingSerializer)
3900
InterRepository.register_optimiser(InterSameDataRepository)
3903
class CopyConverter(object):
3904
"""A repository conversion tool which just performs a copy of the content.
3906
This is slow but quite reliable.
3909
def __init__(self, target_format):
3910
"""Create a CopyConverter.
3912
:param target_format: The format the resulting repository should be.
3914
self.target_format = target_format
3916
def convert(self, repo, pb):
3917
"""Perform the conversion of to_convert, giving feedback via pb.
3919
:param to_convert: The disk object to convert.
3920
:param pb: a progress bar to use for progress information.
3922
pb = ui.ui_factory.nested_progress_bar()
3925
# this is only useful with metadir layouts - separated repo content.
3926
# trigger an assertion if not such
3927
repo._format.get_format_string()
3928
self.repo_dir = repo.bzrdir
3929
pb.update('Moving repository to repository.backup')
3930
self.repo_dir.transport.move('repository', 'repository.backup')
3931
backup_transport = self.repo_dir.transport.clone('repository.backup')
3932
repo._format.check_conversion_target(self.target_format)
3933
self.source_repo = repo._format.open(self.repo_dir,
3935
_override_transport=backup_transport)
3936
pb.update('Creating new repository')
3937
converted = self.target_format.initialize(self.repo_dir,
3938
self.source_repo.is_shared())
3939
converted.lock_write()
3941
pb.update('Copying content')
3942
self.source_repo.copy_content_into(converted)
3945
pb.update('Deleting old repository content')
3946
self.repo_dir.transport.delete_tree('repository.backup')
3947
ui.ui_factory.note('repository converted')
3951
class _VersionedFileChecker(object):
3953
def __init__(self, repository, text_key_references=None, ancestors=None):
3954
self.repository = repository
3955
self.text_index = self.repository._generate_text_key_index(
3956
text_key_references=text_key_references, ancestors=ancestors)
3958
def calculate_file_version_parents(self, text_key):
3959
"""Calculate the correct parents for a file version according to
3962
parent_keys = self.text_index[text_key]
3963
if parent_keys == [_mod_revision.NULL_REVISION]:
3965
return tuple(parent_keys)
3967
def check_file_version_parents(self, texts, progress_bar=None):
3968
"""Check the parents stored in a versioned file are correct.
3970
It also detects file versions that are not referenced by their
3971
corresponding revision's inventory.
3973
:returns: A tuple of (wrong_parents, dangling_file_versions).
3974
wrong_parents is a dict mapping {revision_id: (stored_parents,
3975
correct_parents)} for each revision_id where the stored parents
3976
are not correct. dangling_file_versions is a set of (file_id,
3977
revision_id) tuples for versions that are present in this versioned
3978
file, but not used by the corresponding inventory.
3980
local_progress = None
3981
if progress_bar is None:
3982
local_progress = ui.ui_factory.nested_progress_bar()
3983
progress_bar = local_progress
3985
return self._check_file_version_parents(texts, progress_bar)
3988
local_progress.finished()
3990
def _check_file_version_parents(self, texts, progress_bar):
3991
"""See check_file_version_parents."""
3993
self.file_ids = set([file_id for file_id, _ in
3994
self.text_index.iterkeys()])
3995
# text keys is now grouped by file_id
3996
n_versions = len(self.text_index)
3997
progress_bar.update('loading text store', 0, n_versions)
3998
parent_map = self.repository.texts.get_parent_map(self.text_index)
3999
# On unlistable transports this could well be empty/error...
4000
text_keys = self.repository.texts.keys()
4001
unused_keys = frozenset(text_keys) - set(self.text_index)
4002
for num, key in enumerate(self.text_index.iterkeys()):
4003
progress_bar.update('checking text graph', num, n_versions)
4004
correct_parents = self.calculate_file_version_parents(key)
4006
knit_parents = parent_map[key]
4007
except errors.RevisionNotPresent:
4010
if correct_parents != knit_parents:
4011
wrong_parents[key] = (knit_parents, correct_parents)
4012
return wrong_parents, unused_keys
4015
def _old_get_graph(repository, revision_id):
4016
"""DO NOT USE. That is all. I'm serious."""
4017
graph = repository.get_graph()
4018
revision_graph = dict(((key, value) for key, value in
4019
graph.iter_ancestry([revision_id]) if value is not None))
4020
return _strip_NULL_ghosts(revision_graph)
4023
def _strip_NULL_ghosts(revision_graph):
4024
"""Also don't use this. more compatibility code for unmigrated clients."""
4025
# Filter ghosts, and null:
4026
if _mod_revision.NULL_REVISION in revision_graph:
4027
del revision_graph[_mod_revision.NULL_REVISION]
4028
for key, parents in revision_graph.items():
4029
revision_graph[key] = tuple(parent for parent in parents if parent
4031
return revision_graph
4034
class StreamSink(object):
4035
"""An object that can insert a stream into a repository.
4037
This interface handles the complexity of reserialising inventories and
4038
revisions from different formats, and allows unidirectional insertion into
4039
stacked repositories without looking for the missing basis parents
4043
def __init__(self, target_repo):
4044
self.target_repo = target_repo
4046
def insert_stream(self, stream, src_format, resume_tokens):
4047
"""Insert a stream's content into the target repository.
4049
:param src_format: a bzr repository format.
4051
:return: a list of resume tokens and an iterable of keys additional
4052
items required before the insertion can be completed.
4054
self.target_repo.lock_write()
4057
self.target_repo.resume_write_group(resume_tokens)
4060
self.target_repo.start_write_group()
4063
# locked_insert_stream performs a commit|suspend.
4064
missing_keys = self.insert_stream_without_locking(stream,
4065
src_format, is_resume)
4067
# suspend the write group and tell the caller what we is
4068
# missing. We know we can suspend or else we would not have
4069
# entered this code path. (All repositories that can handle
4070
# missing keys can handle suspending a write group).
4071
write_group_tokens = self.target_repo.suspend_write_group()
4072
return write_group_tokens, missing_keys
4073
hint = self.target_repo.commit_write_group()
4074
to_serializer = self.target_repo._format._serializer
4075
src_serializer = src_format._serializer
4076
if (to_serializer != src_serializer and
4077
self.target_repo._format.pack_compresses):
4078
self.target_repo.pack(hint=hint)
4081
self.target_repo.abort_write_group(suppress_errors=True)
4084
self.target_repo.unlock()
4086
def insert_stream_without_locking(self, stream, src_format,
4088
"""Insert a stream's content into the target repository.
4090
This assumes that you already have a locked repository and an active
4093
:param src_format: a bzr repository format.
4094
:param is_resume: Passed down to get_missing_parent_inventories to
4095
indicate if we should be checking for missing texts at the same
4098
:return: A set of keys that are missing.
4100
if not self.target_repo.is_write_locked():
4101
raise errors.ObjectNotLocked(self)
4102
if not self.target_repo.is_in_write_group():
4103
raise errors.BzrError('you must already be in a write group')
4104
to_serializer = self.target_repo._format._serializer
4105
src_serializer = src_format._serializer
4107
if to_serializer == src_serializer:
4108
# If serializers match and the target is a pack repository, set the
4109
# write cache size on the new pack. This avoids poor performance
4110
# on transports where append is unbuffered (such as
4111
# RemoteTransport). This is safe to do because nothing should read
4112
# back from the target repository while a stream with matching
4113
# serialization is being inserted.
4114
# The exception is that a delta record from the source that should
4115
# be a fulltext may need to be expanded by the target (see
4116
# test_fetch_revisions_with_deltas_into_pack); but we take care to
4117
# explicitly flush any buffered writes first in that rare case.
4119
new_pack = self.target_repo._pack_collection._new_pack
4120
except AttributeError:
4121
# Not a pack repository
4124
new_pack.set_write_cache_size(1024*1024)
4125
for substream_type, substream in stream:
4126
if 'stream' in debug.debug_flags:
4127
mutter('inserting substream: %s', substream_type)
4128
if substream_type == 'texts':
4129
self.target_repo.texts.insert_record_stream(substream)
4130
elif substream_type == 'inventories':
4131
if src_serializer == to_serializer:
4132
self.target_repo.inventories.insert_record_stream(
4135
self._extract_and_insert_inventories(
4136
substream, src_serializer)
4137
elif substream_type == 'inventory-deltas':
4138
self._extract_and_insert_inventory_deltas(
4139
substream, src_serializer)
4140
elif substream_type == 'chk_bytes':
4141
# XXX: This doesn't support conversions, as it assumes the
4142
# conversion was done in the fetch code.
4143
self.target_repo.chk_bytes.insert_record_stream(substream)
4144
elif substream_type == 'revisions':
4145
# This may fallback to extract-and-insert more often than
4146
# required if the serializers are different only in terms of
4148
if src_serializer == to_serializer:
4149
self.target_repo.revisions.insert_record_stream(substream)
4151
self._extract_and_insert_revisions(substream,
4153
elif substream_type == 'signatures':
4154
self.target_repo.signatures.insert_record_stream(substream)
4156
raise AssertionError('kaboom! %s' % (substream_type,))
4157
# Done inserting data, and the missing_keys calculations will try to
4158
# read back from the inserted data, so flush the writes to the new pack
4159
# (if this is pack format).
4160
if new_pack is not None:
4161
new_pack._write_data('', flush=True)
4162
# Find all the new revisions (including ones from resume_tokens)
4163
missing_keys = self.target_repo.get_missing_parent_inventories(
4164
check_for_missing_texts=is_resume)
4166
for prefix, versioned_file in (
4167
('texts', self.target_repo.texts),
4168
('inventories', self.target_repo.inventories),
4169
('revisions', self.target_repo.revisions),
4170
('signatures', self.target_repo.signatures),
4171
('chk_bytes', self.target_repo.chk_bytes),
4173
if versioned_file is None:
4175
# TODO: key is often going to be a StaticTuple object
4176
# I don't believe we can define a method by which
4177
# (prefix,) + StaticTuple will work, though we could
4178
# define a StaticTuple.sq_concat that would allow you to
4179
# pass in either a tuple or a StaticTuple as the second
4180
# object, so instead we could have:
4181
# StaticTuple(prefix) + key here...
4182
missing_keys.update((prefix,) + key for key in
4183
versioned_file.get_missing_compression_parent_keys())
4184
except NotImplementedError:
4185
# cannot even attempt suspending, and missing would have failed
4186
# during stream insertion.
4187
missing_keys = set()
4190
def _extract_and_insert_inventory_deltas(self, substream, serializer):
4191
target_rich_root = self.target_repo._format.rich_root_data
4192
target_tree_refs = self.target_repo._format.supports_tree_reference
4193
for record in substream:
4194
# Insert the delta directly
4195
inventory_delta_bytes = record.get_bytes_as('fulltext')
4196
deserialiser = inventory_delta.InventoryDeltaDeserializer()
4198
parse_result = deserialiser.parse_text_bytes(
4199
inventory_delta_bytes)
4200
except inventory_delta.IncompatibleInventoryDelta, err:
4201
trace.mutter("Incompatible delta: %s", err.msg)
4202
raise errors.IncompatibleRevision(self.target_repo._format)
4203
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
4204
revision_id = new_id
4205
parents = [key[0] for key in record.parents]
4206
self.target_repo.add_inventory_by_delta(
4207
basis_id, inv_delta, revision_id, parents)
4209
def _extract_and_insert_inventories(self, substream, serializer,
4211
"""Generate a new inventory versionedfile in target, converting data.
4213
The inventory is retrieved from the source, (deserializing it), and
4214
stored in the target (reserializing it in a different format).
4216
target_rich_root = self.target_repo._format.rich_root_data
4217
target_tree_refs = self.target_repo._format.supports_tree_reference
4218
for record in substream:
4219
# It's not a delta, so it must be a fulltext in the source
4220
# serializer's format.
4221
bytes = record.get_bytes_as('fulltext')
4222
revision_id = record.key[0]
4223
inv = serializer.read_inventory_from_string(bytes, revision_id)
4224
parents = [key[0] for key in record.parents]
4225
self.target_repo.add_inventory(revision_id, inv, parents)
4226
# No need to keep holding this full inv in memory when the rest of
4227
# the substream is likely to be all deltas.
4230
def _extract_and_insert_revisions(self, substream, serializer):
4231
for record in substream:
4232
bytes = record.get_bytes_as('fulltext')
4233
revision_id = record.key[0]
4234
rev = serializer.read_revision_from_string(bytes)
4235
if rev.revision_id != revision_id:
4236
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
4237
self.target_repo.add_revision(revision_id, rev)
4240
if self.target_repo._format._fetch_reconcile:
4241
self.target_repo.reconcile()
4244
class StreamSource(object):
4245
"""A source of a stream for fetching between repositories."""
4247
def __init__(self, from_repository, to_format):
4248
"""Create a StreamSource streaming from from_repository."""
4249
self.from_repository = from_repository
4250
self.to_format = to_format
4251
self._record_counter = RecordCounter()
4253
def delta_on_metadata(self):
4254
"""Return True if delta's are permitted on metadata streams.
4256
That is on revisions and signatures.
4258
src_serializer = self.from_repository._format._serializer
4259
target_serializer = self.to_format._serializer
4260
return (self.to_format._fetch_uses_deltas and
4261
src_serializer == target_serializer)
4263
def _fetch_revision_texts(self, revs):
4264
# fetch signatures first and then the revision texts
4265
# may need to be a InterRevisionStore call here.
4266
from_sf = self.from_repository.signatures
4267
# A missing signature is just skipped.
4268
keys = [(rev_id,) for rev_id in revs]
4269
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
4271
self.to_format._fetch_order,
4272
not self.to_format._fetch_uses_deltas))
4273
# If a revision has a delta, this is actually expanded inside the
4274
# insert_record_stream code now, which is an alternate fix for
4276
from_rf = self.from_repository.revisions
4277
revisions = from_rf.get_record_stream(
4279
self.to_format._fetch_order,
4280
not self.delta_on_metadata())
4281
return [('signatures', signatures), ('revisions', revisions)]
4283
def _generate_root_texts(self, revs):
4284
"""This will be called by get_stream between fetching weave texts and
4285
fetching the inventory weave.
4287
if self._rich_root_upgrade():
4288
return _mod_fetch.Inter1and2Helper(
4289
self.from_repository).generate_root_texts(revs)
4293
def get_stream(self, search):
4295
revs = search.get_keys()
4296
graph = self.from_repository.get_graph()
4297
revs = tsort.topo_sort(graph.get_parent_map(revs))
4298
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
4300
for knit_kind, file_id, revisions in data_to_fetch:
4301
if knit_kind != phase:
4303
# Make a new progress bar for this phase
4304
if knit_kind == "file":
4305
# Accumulate file texts
4306
text_keys.extend([(file_id, revision) for revision in
4308
elif knit_kind == "inventory":
4309
# Now copy the file texts.
4310
from_texts = self.from_repository.texts
4311
yield ('texts', from_texts.get_record_stream(
4312
text_keys, self.to_format._fetch_order,
4313
not self.to_format._fetch_uses_deltas))
4314
# Cause an error if a text occurs after we have done the
4317
# Before we process the inventory we generate the root
4318
# texts (if necessary) so that the inventories references
4320
for _ in self._generate_root_texts(revs):
4322
# we fetch only the referenced inventories because we do not
4323
# know for unselected inventories whether all their required
4324
# texts are present in the other repository - it could be
4326
for info in self._get_inventory_stream(revs):
4328
elif knit_kind == "signatures":
4329
# Nothing to do here; this will be taken care of when
4330
# _fetch_revision_texts happens.
4332
elif knit_kind == "revisions":
4333
for record in self._fetch_revision_texts(revs):
4336
raise AssertionError("Unknown knit kind %r" % knit_kind)
4338
def get_stream_for_missing_keys(self, missing_keys):
4339
# missing keys can only occur when we are byte copying and not
4340
# translating (because translation means we don't send
4341
# unreconstructable deltas ever).
4343
keys['texts'] = set()
4344
keys['revisions'] = set()
4345
keys['inventories'] = set()
4346
keys['chk_bytes'] = set()
4347
keys['signatures'] = set()
4348
for key in missing_keys:
4349
keys[key[0]].add(key[1:])
4350
if len(keys['revisions']):
4351
# If we allowed copying revisions at this point, we could end up
4352
# copying a revision without copying its required texts: a
4353
# violation of the requirements for repository integrity.
4354
raise AssertionError(
4355
'cannot copy revisions to fill in missing deltas %s' % (
4356
keys['revisions'],))
4357
for substream_kind, keys in keys.iteritems():
4358
vf = getattr(self.from_repository, substream_kind)
4359
if vf is None and keys:
4360
raise AssertionError(
4361
"cannot fill in keys for a versioned file we don't"
4362
" have: %s needs %s" % (substream_kind, keys))
4364
# No need to stream something we don't have
4366
if substream_kind == 'inventories':
4367
# Some missing keys are genuinely ghosts, filter those out.
4368
present = self.from_repository.inventories.get_parent_map(keys)
4369
revs = [key[0] for key in present]
4370
# Get the inventory stream more-or-less as we do for the
4371
# original stream; there's no reason to assume that records
4372
# direct from the source will be suitable for the sink. (Think
4373
# e.g. 2a -> 1.9-rich-root).
4374
for info in self._get_inventory_stream(revs, missing=True):
4378
# Ask for full texts always so that we don't need more round trips
4379
# after this stream.
4380
# Some of the missing keys are genuinely ghosts, so filter absent
4381
# records. The Sink is responsible for doing another check to
4382
# ensure that ghosts don't introduce missing data for future
4384
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
4385
self.to_format._fetch_order, True))
4386
yield substream_kind, stream
4388
def inventory_fetch_order(self):
4389
if self._rich_root_upgrade():
4390
return 'topological'
4392
return self.to_format._fetch_order
4394
def _rich_root_upgrade(self):
4395
return (not self.from_repository._format.rich_root_data and
4396
self.to_format.rich_root_data)
4398
def _get_inventory_stream(self, revision_ids, missing=False):
4399
from_format = self.from_repository._format
4400
if (from_format.supports_chks and self.to_format.supports_chks and
4401
from_format.network_name() == self.to_format.network_name()):
4402
raise AssertionError(
4403
"this case should be handled by GroupCHKStreamSource")
4404
elif 'forceinvdeltas' in debug.debug_flags:
4405
return self._get_convertable_inventory_stream(revision_ids,
4406
delta_versus_null=missing)
4407
elif from_format.network_name() == self.to_format.network_name():
4409
return self._get_simple_inventory_stream(revision_ids,
4411
elif (not from_format.supports_chks and not self.to_format.supports_chks
4412
and from_format._serializer == self.to_format._serializer):
4413
# Essentially the same format.
4414
return self._get_simple_inventory_stream(revision_ids,
4417
# Any time we switch serializations, we want to use an
4418
# inventory-delta based approach.
4419
return self._get_convertable_inventory_stream(revision_ids,
4420
delta_versus_null=missing)
4422
def _get_simple_inventory_stream(self, revision_ids, missing=False):
4423
# NB: This currently reopens the inventory weave in source;
4424
# using a single stream interface instead would avoid this.
4425
from_weave = self.from_repository.inventories
4427
delta_closure = True
4429
delta_closure = not self.delta_on_metadata()
4430
yield ('inventories', from_weave.get_record_stream(
4431
[(rev_id,) for rev_id in revision_ids],
4432
self.inventory_fetch_order(), delta_closure))
4434
def _get_convertable_inventory_stream(self, revision_ids,
4435
delta_versus_null=False):
4436
# The two formats are sufficiently different that there is no fast
4437
# path, so we need to send just inventorydeltas, which any
4438
# sufficiently modern client can insert into any repository.
4439
# The StreamSink code expects to be able to
4440
# convert on the target, so we need to put bytes-on-the-wire that can
4441
# be converted. That means inventory deltas (if the remote is <1.19,
4442
# RemoteStreamSink will fallback to VFS to insert the deltas).
4443
yield ('inventory-deltas',
4444
self._stream_invs_as_deltas(revision_ids,
4445
delta_versus_null=delta_versus_null))
4447
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
4448
"""Return a stream of inventory-deltas for the given rev ids.
4450
:param revision_ids: The list of inventories to transmit
4451
:param delta_versus_null: Don't try to find a minimal delta for this
4452
entry, instead compute the delta versus the NULL_REVISION. This
4453
effectively streams a complete inventory. Used for stuff like
4454
filling in missing parents, etc.
4456
from_repo = self.from_repository
4457
revision_keys = [(rev_id,) for rev_id in revision_ids]
4458
parent_map = from_repo.inventories.get_parent_map(revision_keys)
4459
# XXX: possibly repos could implement a more efficient iter_inv_deltas
4461
inventories = self.from_repository.iter_inventories(
4462
revision_ids, 'topological')
4463
format = from_repo._format
4464
invs_sent_so_far = set([_mod_revision.NULL_REVISION])
4465
inventory_cache = lru_cache.LRUCache(50)
4466
null_inventory = from_repo.revision_tree(
4467
_mod_revision.NULL_REVISION).inventory
4468
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
4469
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
4470
# repo back into a non-rich-root repo ought to be allowed)
4471
serializer = inventory_delta.InventoryDeltaSerializer(
4472
versioned_root=format.rich_root_data,
4473
tree_references=format.supports_tree_reference)
4474
for inv in inventories:
4475
key = (inv.revision_id,)
4476
parent_keys = parent_map.get(key, ())
4478
if not delta_versus_null and parent_keys:
4479
# The caller did not ask for complete inventories and we have
4480
# some parents that we can delta against. Make a delta against
4481
# each parent so that we can find the smallest.
4482
parent_ids = [parent_key[0] for parent_key in parent_keys]
4483
for parent_id in parent_ids:
4484
if parent_id not in invs_sent_so_far:
4485
# We don't know that the remote side has this basis, so
4488
if parent_id == _mod_revision.NULL_REVISION:
4489
parent_inv = null_inventory
4491
parent_inv = inventory_cache.get(parent_id, None)
4492
if parent_inv is None:
4493
parent_inv = from_repo.get_inventory(parent_id)
4494
candidate_delta = inv._make_delta(parent_inv)
4495
if (delta is None or
4496
len(delta) > len(candidate_delta)):
4497
delta = candidate_delta
4498
basis_id = parent_id
4500
# Either none of the parents ended up being suitable, or we
4501
# were asked to delta against NULL
4502
basis_id = _mod_revision.NULL_REVISION
4503
delta = inv._make_delta(null_inventory)
4504
invs_sent_so_far.add(inv.revision_id)
4505
inventory_cache[inv.revision_id] = inv
4506
delta_serialized = ''.join(
4507
serializer.delta_to_lines(basis_id, key[-1], delta))
4508
yield versionedfile.FulltextContentFactory(
4509
key, parent_keys, None, delta_serialized)
4512
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
4513
stop_revision=None):
4514
"""Extend the partial history to include a given index
4516
If a stop_index is supplied, stop when that index has been reached.
4517
If a stop_revision is supplied, stop when that revision is
4518
encountered. Otherwise, stop when the beginning of history is
4521
:param stop_index: The index which should be present. When it is
4522
present, history extension will stop.
4523
:param stop_revision: The revision id which should be present. When
4524
it is encountered, history extension will stop.
4526
start_revision = partial_history_cache[-1]
4527
iterator = repo.iter_reverse_revision_history(start_revision)
4529
#skip the last revision in the list
4532
if (stop_index is not None and
4533
len(partial_history_cache) > stop_index):
4535
if partial_history_cache[-1] == stop_revision:
4537
revision_id = iterator.next()
4538
partial_history_cache.append(revision_id)
4539
except StopIteration: