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
"""Repository formats built around versioned files."""
19
from __future__ import absolute_import
22
from bzrlib.lazy_import import lazy_import
23
lazy_import(globals(), """
28
config as _mod_config,
37
revision as _mod_revision,
38
serializer as _mod_serializer,
47
from bzrlib.recordcounter import RecordCounter
48
from bzrlib.revisiontree import InventoryRevisionTree
49
from bzrlib.testament import Testament
50
from bzrlib.i18n import gettext
56
from bzrlib.decorators import (
61
from bzrlib.inventory import (
68
from bzrlib.repository import (
72
RepositoryFormatMetaDir,
77
from bzrlib.trace import (
82
class VersionedFileRepositoryFormat(RepositoryFormat):
83
"""Base class for all repository formats that are VersionedFiles-based."""
85
supports_full_versioned_files = True
86
supports_versioned_directories = True
87
supports_unreferenced_revisions = True
89
# Should commit add an inventory, or an inventory delta to the repository.
90
_commit_inv_deltas = True
91
# What order should fetch operations request streams in?
92
# The default is unordered as that is the cheapest for an origin to
94
_fetch_order = 'unordered'
95
# Does this repository format use deltas that can be fetched as-deltas ?
96
# (E.g. knits, where the knit deltas can be transplanted intact.
97
# We default to False, which will ensure that enough data to get
98
# a full text out of any fetch stream will be grabbed.
99
_fetch_uses_deltas = False
102
class VersionedFileCommitBuilder(CommitBuilder):
103
"""Commit builder implementation for versioned files based repositories.
106
# this commit builder supports the record_entry_contents interface
107
supports_record_entry_contents = True
109
# the default CommitBuilder does not manage trees whose root is versioned.
110
_versioned_root = False
112
def __init__(self, repository, parents, config_stack, timestamp=None,
113
timezone=None, committer=None, revprops=None,
114
revision_id=None, lossy=False):
115
super(VersionedFileCommitBuilder, self).__init__(repository,
116
parents, config_stack, timestamp, timezone, committer, revprops,
119
basis_id = self.parents[0]
121
basis_id = _mod_revision.NULL_REVISION
122
self.basis_delta_revision = basis_id
123
self.new_inventory = Inventory(None)
124
self._basis_delta = []
125
self.__heads = graph.HeadsCache(repository.get_graph()).heads
126
# memo'd check for no-op commits.
127
self._any_changes = False
128
# API compatibility, older code that used CommitBuilder did not call
129
# .record_delete(), which means the delta that is computed would not be
130
# valid. Callers that will call record_delete() should call
131
# .will_record_deletes() to indicate that.
132
self._recording_deletes = False
134
def will_record_deletes(self):
135
"""Tell the commit builder that deletes are being notified.
137
This enables the accumulation of an inventory delta; for the resulting
138
commit to be valid, deletes against the basis MUST be recorded via
139
builder.record_delete().
141
self._recording_deletes = True
143
def any_changes(self):
144
"""Return True if any entries were changed.
146
This includes merge-only changes. It is the core for the --unchanged
149
:return: True if any changes have occured.
151
return self._any_changes
153
def _ensure_fallback_inventories(self):
154
"""Ensure that appropriate inventories are available.
156
This only applies to repositories that are stacked, and is about
157
enusring the stacking invariants. Namely, that for any revision that is
158
present, we either have all of the file content, or we have the parent
159
inventory and the delta file content.
161
if not self.repository._fallback_repositories:
163
if not self.repository._format.supports_chks:
164
raise errors.BzrError("Cannot commit directly to a stacked branch"
165
" in pre-2a formats. See "
166
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
167
# This is a stacked repo, we need to make sure we have the parent
168
# inventories for the parents.
169
parent_keys = [(p,) for p in self.parents]
170
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
171
missing_parent_keys = set([pk for pk in parent_keys
172
if pk not in parent_map])
173
fallback_repos = list(reversed(self.repository._fallback_repositories))
174
missing_keys = [('inventories', pk[0])
175
for pk in missing_parent_keys]
177
while missing_keys and fallback_repos:
178
fallback_repo = fallback_repos.pop()
179
source = fallback_repo._get_source(self.repository._format)
180
sink = self.repository._get_sink()
181
stream = source.get_stream_for_missing_keys(missing_keys)
182
missing_keys = sink.insert_stream_without_locking(stream,
183
self.repository._format)
185
raise errors.BzrError('Unable to fill in parent inventories for a'
188
def commit(self, message):
189
"""Make the actual commit.
191
:return: The revision id of the recorded revision.
193
self._validate_unicode_text(message, 'commit message')
194
rev = _mod_revision.Revision(
195
timestamp=self._timestamp,
196
timezone=self._timezone,
197
committer=self._committer,
199
inventory_sha1=self.inv_sha1,
200
revision_id=self._new_revision_id,
201
properties=self._revprops)
202
rev.parent_ids = self.parents
203
self.repository.add_revision(self._new_revision_id, rev,
204
self.new_inventory, self._config_stack)
205
self._ensure_fallback_inventories()
206
self.repository.commit_write_group()
207
return self._new_revision_id
210
"""Abort the commit that is being built.
212
self.repository.abort_write_group()
214
def revision_tree(self):
215
"""Return the tree that was just committed.
217
After calling commit() this can be called to get a
218
RevisionTree representing the newly committed tree. This is
219
preferred to calling Repository.revision_tree() because that may
220
require deserializing the inventory, while we already have a copy in
223
if self.new_inventory is None:
224
self.new_inventory = self.repository.get_inventory(
225
self._new_revision_id)
226
return InventoryRevisionTree(self.repository, self.new_inventory,
227
self._new_revision_id)
229
def finish_inventory(self):
230
"""Tell the builder that the inventory is finished.
232
:return: The inventory id in the repository, which can be used with
233
repository.get_inventory.
235
if self.new_inventory is None:
236
# an inventory delta was accumulated without creating a new
238
basis_id = self.basis_delta_revision
239
# We ignore the 'inventory' returned by add_inventory_by_delta
240
# because self.new_inventory is used to hint to the rest of the
241
# system what code path was taken
242
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
243
basis_id, self._basis_delta, self._new_revision_id,
246
if self.new_inventory.root is None:
247
raise AssertionError('Root entry should be supplied to'
248
' record_entry_contents, as of bzr 0.10.')
249
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
250
self.new_inventory.revision_id = self._new_revision_id
251
self.inv_sha1 = self.repository.add_inventory(
252
self._new_revision_id,
256
return self._new_revision_id
258
def _check_root(self, ie, parent_invs, tree):
259
"""Helper for record_entry_contents.
261
:param ie: An entry being added.
262
:param parent_invs: The inventories of the parent revisions of the
264
:param tree: The tree that is being committed.
266
# In this revision format, root entries have no knit or weave When
267
# serializing out to disk and back in root.revision is always
269
ie.revision = self._new_revision_id
271
def _require_root_change(self, tree):
272
"""Enforce an appropriate root object change.
274
This is called once when record_iter_changes is called, if and only if
275
the root was not in the delta calculated by record_iter_changes.
277
:param tree: The tree which is being committed.
279
if len(self.parents) == 0:
280
raise errors.RootMissing()
281
entry = entry_factory['directory'](tree.path2id(''), '',
283
entry.revision = self._new_revision_id
284
self._basis_delta.append(('', '', entry.file_id, entry))
286
def _get_delta(self, ie, basis_inv, path):
287
"""Get a delta against the basis inventory for ie."""
288
if not basis_inv.has_id(ie.file_id):
290
result = (None, path, ie.file_id, ie)
291
self._basis_delta.append(result)
293
elif ie != basis_inv[ie.file_id]:
295
# TODO: avoid tis id2path call.
296
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
297
self._basis_delta.append(result)
303
def _heads(self, file_id, revision_ids):
304
"""Calculate the graph heads for revision_ids in the graph of file_id.
306
This can use either a per-file graph or a global revision graph as we
307
have an identity relationship between the two graphs.
309
return self.__heads(revision_ids)
311
def get_basis_delta(self):
312
"""Return the complete inventory delta versus the basis inventory.
314
This has been built up with the calls to record_delete and
315
record_entry_contents. The client must have already called
316
will_record_deletes() to indicate that they will be generating a
319
:return: An inventory delta, suitable for use with apply_delta, or
320
Repository.add_inventory_by_delta, etc.
322
if not self._recording_deletes:
323
raise AssertionError("recording deletes not activated.")
324
return self._basis_delta
326
def record_delete(self, path, file_id):
327
"""Record that a delete occured against a basis tree.
329
This is an optional API - when used it adds items to the basis_delta
330
being accumulated by the commit builder. It cannot be called unless the
331
method will_record_deletes() has been called to inform the builder that
332
a delta is being supplied.
334
:param path: The path of the thing deleted.
335
:param file_id: The file id that was deleted.
337
if not self._recording_deletes:
338
raise AssertionError("recording deletes not activated.")
339
delta = (path, None, file_id, None)
340
self._basis_delta.append(delta)
341
self._any_changes = True
344
def record_entry_contents(self, ie, parent_invs, path, tree,
346
"""Record the content of ie from tree into the commit if needed.
348
Side effect: sets ie.revision when unchanged
350
:param ie: An inventory entry present in the commit.
351
:param parent_invs: The inventories of the parent revisions of the
353
:param path: The path the entry is at in the tree.
354
:param tree: The tree which contains this entry and should be used to
356
:param content_summary: Summary data from the tree about the paths
357
content - stat, length, exec, sha/link target. This is only
358
accessed when the entry has a revision of None - that is when it is
359
a candidate to commit.
360
:return: A tuple (change_delta, version_recorded, fs_hash).
361
change_delta is an inventory_delta change for this entry against
362
the basis tree of the commit, or None if no change occured against
364
version_recorded is True if a new version of the entry has been
365
recorded. For instance, committing a merge where a file was only
366
changed on the other side will return (delta, False).
367
fs_hash is either None, or the hash details for the path (currently
368
a tuple of the contents sha1 and the statvalue returned by
369
tree.get_file_with_stat()).
371
if self.new_inventory.root is None:
372
if ie.parent_id is not None:
373
raise errors.RootMissing()
374
self._check_root(ie, parent_invs, tree)
375
if ie.revision is None:
376
kind = content_summary[0]
378
# ie is carried over from a prior commit
380
# XXX: repository specific check for nested tree support goes here - if
381
# the repo doesn't want nested trees we skip it ?
382
if (kind == 'tree-reference' and
383
not self.repository._format.supports_tree_reference):
384
# mismatch between commit builder logic and repository:
385
# this needs the entry creation pushed down into the builder.
386
raise NotImplementedError('Missing repository subtree support.')
387
self.new_inventory.add(ie)
389
# TODO: slow, take it out of the inner loop.
391
basis_inv = parent_invs[0]
393
basis_inv = Inventory(root_id=None)
395
# ie.revision is always None if the InventoryEntry is considered
396
# for committing. We may record the previous parents revision if the
397
# content is actually unchanged against a sole head.
398
if ie.revision is not None:
399
if not self._versioned_root and path == '':
400
# repositories that do not version the root set the root's
401
# revision to the new commit even when no change occurs (more
402
# specifically, they do not record a revision on the root; and
403
# the rev id is assigned to the root during deserialisation -
404
# this masks when a change may have occurred against the basis.
405
# To match this we always issue a delta, because the revision
406
# of the root will always be changing.
407
if basis_inv.has_id(ie.file_id):
408
delta = (basis_inv.id2path(ie.file_id), path,
412
delta = (None, path, ie.file_id, ie)
413
self._basis_delta.append(delta)
414
return delta, False, None
416
# we don't need to commit this, because the caller already
417
# determined that an existing revision of this file is
418
# appropriate. If it's not being considered for committing then
419
# it and all its parents to the root must be unaltered so
420
# no-change against the basis.
421
if ie.revision == self._new_revision_id:
422
raise AssertionError("Impossible situation, a skipped "
423
"inventory entry (%r) claims to be modified in this "
424
"commit (%r).", (ie, self._new_revision_id))
425
return None, False, None
426
# XXX: Friction: parent_candidates should return a list not a dict
427
# so that we don't have to walk the inventories again.
428
parent_candidate_entries = ie.parent_candidates(parent_invs)
429
head_set = self._heads(ie.file_id, parent_candidate_entries.keys())
431
for inv in parent_invs:
432
if inv.has_id(ie.file_id):
433
old_rev = inv[ie.file_id].revision
434
if old_rev in head_set:
435
heads.append(inv[ie.file_id].revision)
436
head_set.remove(inv[ie.file_id].revision)
439
# now we check to see if we need to write a new record to the
441
# We write a new entry unless there is one head to the ancestors, and
442
# the kind-derived content is unchanged.
444
# Cheapest check first: no ancestors, or more the one head in the
445
# ancestors, we write a new node.
449
# There is a single head, look it up for comparison
450
parent_entry = parent_candidate_entries[heads[0]]
451
# if the non-content specific data has changed, we'll be writing a
453
if (parent_entry.parent_id != ie.parent_id or
454
parent_entry.name != ie.name):
456
# now we need to do content specific checks:
458
# if the kind changed the content obviously has
459
if kind != parent_entry.kind:
461
# Stat cache fingerprint feedback for the caller - None as we usually
462
# don't generate one.
465
if content_summary[2] is None:
466
raise ValueError("Files must not have executable = None")
468
# We can't trust a check of the file length because of content
470
if (# if the exec bit has changed we have to store:
471
parent_entry.executable != content_summary[2]):
473
elif parent_entry.text_sha1 == content_summary[3]:
474
# all meta and content is unchanged (using a hash cache
475
# hit to check the sha)
476
ie.revision = parent_entry.revision
477
ie.text_size = parent_entry.text_size
478
ie.text_sha1 = parent_entry.text_sha1
479
ie.executable = parent_entry.executable
480
return self._get_delta(ie, basis_inv, path), False, None
482
# Either there is only a hash change(no hash cache entry,
483
# or same size content change), or there is no change on
485
# Provide the parent's hash to the store layer, so that the
486
# content is unchanged we will not store a new node.
487
nostore_sha = parent_entry.text_sha1
489
# We want to record a new node regardless of the presence or
490
# absence of a content change in the file.
492
ie.executable = content_summary[2]
493
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
495
text = file_obj.read()
499
ie.text_sha1, ie.text_size = self._add_text_to_weave(
500
ie.file_id, text, heads, nostore_sha)
501
# Let the caller know we generated a stat fingerprint.
502
fingerprint = (ie.text_sha1, stat_value)
503
except errors.ExistingContent:
504
# Turns out that the file content was unchanged, and we were
505
# only going to store a new node if it was changed. Carry over
507
ie.revision = parent_entry.revision
508
ie.text_size = parent_entry.text_size
509
ie.text_sha1 = parent_entry.text_sha1
510
ie.executable = parent_entry.executable
511
return self._get_delta(ie, basis_inv, path), False, None
512
elif kind == 'directory':
514
# all data is meta here, nothing specific to directory, so
516
ie.revision = parent_entry.revision
517
return self._get_delta(ie, basis_inv, path), False, None
518
self._add_text_to_weave(ie.file_id, '', heads, None)
519
elif kind == 'symlink':
520
current_link_target = content_summary[3]
522
# symlink target is not generic metadata, check if it has
524
if current_link_target != parent_entry.symlink_target:
527
# unchanged, carry over.
528
ie.revision = parent_entry.revision
529
ie.symlink_target = parent_entry.symlink_target
530
return self._get_delta(ie, basis_inv, path), False, None
531
ie.symlink_target = current_link_target
532
self._add_text_to_weave(ie.file_id, '', heads, None)
533
elif kind == 'tree-reference':
535
if content_summary[3] != parent_entry.reference_revision:
538
# unchanged, carry over.
539
ie.reference_revision = parent_entry.reference_revision
540
ie.revision = parent_entry.revision
541
return self._get_delta(ie, basis_inv, path), False, None
542
ie.reference_revision = content_summary[3]
543
if ie.reference_revision is None:
544
raise AssertionError("invalid content_summary for nested tree: %r"
545
% (content_summary,))
546
self._add_text_to_weave(ie.file_id, '', heads, None)
548
raise NotImplementedError('unknown kind')
549
ie.revision = self._new_revision_id
550
# The initial commit adds a root directory, but this in itself is not
551
# a worthwhile commit.
552
if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
554
self._any_changes = True
555
return self._get_delta(ie, basis_inv, path), True, fingerprint
557
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
558
_entry_factory=entry_factory):
559
"""Record a new tree via iter_changes.
561
:param tree: The tree to obtain text contents from for changed objects.
562
:param basis_revision_id: The revision id of the tree the iter_changes
563
has been generated against. Currently assumed to be the same
564
as self.parents[0] - if it is not, errors may occur.
565
:param iter_changes: An iter_changes iterator with the changes to apply
566
to basis_revision_id. The iterator must not include any items with
567
a current kind of None - missing items must be either filtered out
568
or errored-on before record_iter_changes sees the item.
569
:param _entry_factory: Private method to bind entry_factory locally for
571
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
574
# Create an inventory delta based on deltas between all the parents and
575
# deltas between all the parent inventories. We use inventory delta's
576
# between the inventory objects because iter_changes masks
577
# last-changed-field only changes.
579
# file_id -> change map, change is fileid, paths, changed, versioneds,
580
# parents, names, kinds, executables
582
# {file_id -> revision_id -> inventory entry, for entries in parent
583
# trees that are not parents[0]
587
revtrees = list(self.repository.revision_trees(self.parents))
588
except errors.NoSuchRevision:
589
# one or more ghosts, slow path.
591
for revision_id in self.parents:
593
revtrees.append(self.repository.revision_tree(revision_id))
594
except errors.NoSuchRevision:
596
basis_revision_id = _mod_revision.NULL_REVISION
598
revtrees.append(self.repository.revision_tree(
599
_mod_revision.NULL_REVISION))
600
# The basis inventory from a repository
602
basis_inv = revtrees[0].inventory
604
basis_inv = self.repository.revision_tree(
605
_mod_revision.NULL_REVISION).inventory
606
if len(self.parents) > 0:
607
if basis_revision_id != self.parents[0] and not ghost_basis:
609
"arbitrary basis parents not yet supported with merges")
610
for revtree in revtrees[1:]:
611
for change in revtree.inventory._make_delta(basis_inv):
612
if change[1] is None:
613
# Not present in this parent.
615
if change[2] not in merged_ids:
616
if change[0] is not None:
617
basis_entry = basis_inv[change[2]]
618
merged_ids[change[2]] = [
620
basis_entry.revision,
623
parent_entries[change[2]] = {
625
basis_entry.revision:basis_entry,
627
change[3].revision:change[3],
630
merged_ids[change[2]] = [change[3].revision]
631
parent_entries[change[2]] = {change[3].revision:change[3]}
633
merged_ids[change[2]].append(change[3].revision)
634
parent_entries[change[2]][change[3].revision] = change[3]
637
# Setup the changes from the tree:
638
# changes maps file_id -> (change, [parent revision_ids])
640
for change in iter_changes:
641
# This probably looks up in basis_inv way to much.
642
if change[1][0] is not None:
643
head_candidate = [basis_inv[change[0]].revision]
646
changes[change[0]] = change, merged_ids.get(change[0],
648
unchanged_merged = set(merged_ids) - set(changes)
649
# Extend the changes dict with synthetic changes to record merges of
651
for file_id in unchanged_merged:
652
# Record a merged version of these items that did not change vs the
653
# basis. This can be either identical parallel changes, or a revert
654
# of a specific file after a merge. The recorded content will be
655
# that of the current tree (which is the same as the basis), but
656
# the per-file graph will reflect a merge.
657
# NB:XXX: We are reconstructing path information we had, this
658
# should be preserved instead.
659
# inv delta change: (file_id, (path_in_source, path_in_target),
660
# changed_content, versioned, parent, name, kind,
663
basis_entry = basis_inv[file_id]
664
except errors.NoSuchId:
665
# a change from basis->some_parents but file_id isn't in basis
666
# so was new in the merge, which means it must have changed
667
# from basis -> current, and as it hasn't the add was reverted
668
# by the user. So we discard this change.
672
(basis_inv.id2path(file_id), tree.id2path(file_id)),
674
(basis_entry.parent_id, basis_entry.parent_id),
675
(basis_entry.name, basis_entry.name),
676
(basis_entry.kind, basis_entry.kind),
677
(basis_entry.executable, basis_entry.executable))
678
changes[file_id] = (change, merged_ids[file_id])
679
# changes contains tuples with the change and a set of inventory
680
# candidates for the file.
682
# old_path, new_path, file_id, new_inventory_entry
683
seen_root = False # Is the root in the basis delta?
684
inv_delta = self._basis_delta
685
modified_rev = self._new_revision_id
686
for change, head_candidates in changes.values():
687
if change[3][1]: # versioned in target.
688
# Several things may be happening here:
689
# We may have a fork in the per-file graph
690
# - record a change with the content from tree
691
# We may have a change against < all trees
692
# - carry over the tree that hasn't changed
693
# We may have a change against all trees
694
# - record the change with the content from tree
697
entry = _entry_factory[kind](file_id, change[5][1],
699
head_set = self._heads(change[0], set(head_candidates))
702
for head_candidate in head_candidates:
703
if head_candidate in head_set:
704
heads.append(head_candidate)
705
head_set.remove(head_candidate)
708
# Could be a carry-over situation:
709
parent_entry_revs = parent_entries.get(file_id, None)
710
if parent_entry_revs:
711
parent_entry = parent_entry_revs.get(heads[0], None)
714
if parent_entry is None:
715
# The parent iter_changes was called against is the one
716
# that is the per-file head, so any change is relevant
717
# iter_changes is valid.
718
carry_over_possible = False
720
# could be a carry over situation
721
# A change against the basis may just indicate a merge,
722
# we need to check the content against the source of the
723
# merge to determine if it was changed after the merge
725
if (parent_entry.kind != entry.kind or
726
parent_entry.parent_id != entry.parent_id or
727
parent_entry.name != entry.name):
728
# Metadata common to all entries has changed
729
# against per-file parent
730
carry_over_possible = False
732
carry_over_possible = True
733
# per-type checks for changes against the parent_entry
736
# Cannot be a carry-over situation
737
carry_over_possible = False
738
# Populate the entry in the delta
740
# XXX: There is still a small race here: If someone reverts the content of a file
741
# after iter_changes examines and decides it has changed,
742
# we will unconditionally record a new version even if some
743
# other process reverts it while commit is running (with
744
# the revert happening after iter_changes did its
747
entry.executable = True
749
entry.executable = False
750
if (carry_over_possible and
751
parent_entry.executable == entry.executable):
752
# Check the file length, content hash after reading
754
nostore_sha = parent_entry.text_sha1
757
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
759
text = file_obj.read()
763
entry.text_sha1, entry.text_size = self._add_text_to_weave(
764
file_id, text, heads, nostore_sha)
765
yield file_id, change[1][1], (entry.text_sha1, stat_value)
766
except errors.ExistingContent:
767
# No content change against a carry_over parent
768
# Perhaps this should also yield a fs hash update?
770
entry.text_size = parent_entry.text_size
771
entry.text_sha1 = parent_entry.text_sha1
772
elif kind == 'symlink':
774
entry.symlink_target = tree.get_symlink_target(file_id)
775
if (carry_over_possible and
776
parent_entry.symlink_target == entry.symlink_target):
779
self._add_text_to_weave(change[0], '', heads, None)
780
elif kind == 'directory':
781
if carry_over_possible:
784
# Nothing to set on the entry.
785
# XXX: split into the Root and nonRoot versions.
786
if change[1][1] != '' or self.repository.supports_rich_root():
787
self._add_text_to_weave(change[0], '', heads, None)
788
elif kind == 'tree-reference':
789
if not self.repository._format.supports_tree_reference:
790
# This isn't quite sane as an error, but we shouldn't
791
# ever see this code path in practice: tree's don't
792
# permit references when the repo doesn't support tree
794
raise errors.UnsupportedOperation(tree.add_reference,
796
reference_revision = tree.get_reference_revision(change[0])
797
entry.reference_revision = reference_revision
798
if (carry_over_possible and
799
parent_entry.reference_revision == reference_revision):
802
self._add_text_to_weave(change[0], '', heads, None)
804
raise AssertionError('unknown kind %r' % kind)
806
entry.revision = modified_rev
808
entry.revision = parent_entry.revision
811
new_path = change[1][1]
812
inv_delta.append((change[1][0], new_path, change[0], entry))
815
self.new_inventory = None
816
# The initial commit adds a root directory, but this in itself is not
817
# a worthwhile commit.
818
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
819
(len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
820
# This should perhaps be guarded by a check that the basis we
821
# commit against is the basis for the commit and if not do a delta
823
self._any_changes = True
825
# housekeeping root entry changes do not affect no-change commits.
826
self._require_root_change(tree)
827
self.basis_delta_revision = basis_revision_id
829
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
830
parent_keys = tuple([(file_id, parent) for parent in parents])
831
return self.repository.texts._add_text(
832
(file_id, self._new_revision_id), parent_keys, new_text,
833
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
836
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
837
"""This commitbuilder actually records the root id"""
839
# the root entry gets versioned properly by this builder.
840
_versioned_root = True
842
def _check_root(self, ie, parent_invs, tree):
843
"""Helper for record_entry_contents.
845
:param ie: An entry being added.
846
:param parent_invs: The inventories of the parent revisions of the
848
:param tree: The tree that is being committed.
851
def _require_root_change(self, tree):
852
"""Enforce an appropriate root object change.
854
This is called once when record_iter_changes is called, if and only if
855
the root was not in the delta calculated by record_iter_changes.
857
:param tree: The tree which is being committed.
859
# versioned roots do not change unless the tree found a change.
862
class VersionedFileRepository(Repository):
863
"""Repository holding history for one or more branches.
865
The repository holds and retrieves historical information including
866
revisions and file history. It's normally accessed only by the Branch,
867
which views a particular line of development through that history.
869
The Repository builds on top of some byte storage facilies (the revisions,
870
signatures, inventories, texts and chk_bytes attributes) and a Transport,
871
which respectively provide byte storage and a means to access the (possibly
874
The byte storage facilities are addressed via tuples, which we refer to
875
as 'keys' throughout the code base. Revision_keys, inventory_keys and
876
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
877
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
878
byte string made up of a hash identifier and a hash value.
879
We use this interface because it allows low friction with the underlying
880
code that implements disk indices, network encoding and other parts of
883
:ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
884
the serialised revisions for the repository. This can be used to obtain
885
revision graph information or to access raw serialised revisions.
886
The result of trying to insert data into the repository via this store
887
is undefined: it should be considered read-only except for implementors
889
:ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
890
the serialised signatures for the repository. This can be used to
891
obtain access to raw serialised signatures. The result of trying to
892
insert data into the repository via this store is undefined: it should
893
be considered read-only except for implementors of repositories.
894
:ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
895
the serialised inventories for the repository. This can be used to
896
obtain unserialised inventories. The result of trying to insert data
897
into the repository via this store is undefined: it should be
898
considered read-only except for implementors of repositories.
899
:ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
900
texts of files and directories for the repository. This can be used to
901
obtain file texts or file graphs. Note that Repository.iter_file_bytes
902
is usually a better interface for accessing file texts.
903
The result of trying to insert data into the repository via this store
904
is undefined: it should be considered read-only except for implementors
906
:ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
907
any data the repository chooses to store or have indexed by its hash.
908
The result of trying to insert data into the repository via this store
909
is undefined: it should be considered read-only except for implementors
911
:ivar _transport: Transport for file access to repository, typically
912
pointing to .bzr/repository.
915
# What class to use for a CommitBuilder. Often it's simpler to change this
916
# in a Repository class subclass rather than to override
917
# get_commit_builder.
918
_commit_builder_class = VersionedFileCommitBuilder
920
def add_fallback_repository(self, repository):
921
"""Add a repository to use for looking up data not held locally.
923
:param repository: A repository.
925
if not self._format.supports_external_lookups:
926
raise errors.UnstackableRepositoryFormat(self._format, self.base)
927
# This can raise an exception, so should be done before we lock the
928
# fallback repository.
929
self._check_fallback_repository(repository)
931
# This repository will call fallback.unlock() when we transition to
932
# the unlocked state, so we make sure to increment the lock count
933
repository.lock_read()
934
self._fallback_repositories.append(repository)
935
self.texts.add_fallback_versioned_files(repository.texts)
936
self.inventories.add_fallback_versioned_files(repository.inventories)
937
self.revisions.add_fallback_versioned_files(repository.revisions)
938
self.signatures.add_fallback_versioned_files(repository.signatures)
939
if self.chk_bytes is not None:
940
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
942
@only_raises(errors.LockNotHeld, errors.LockBroken)
944
super(VersionedFileRepository, self).unlock()
945
if self.control_files._lock_count == 0:
946
self._inventory_entry_cache.clear()
948
def add_inventory(self, revision_id, inv, parents):
949
"""Add the inventory inv to the repository as revision_id.
951
:param parents: The revision ids of the parents that revision_id
952
is known to have and are in the repository already.
954
:returns: The validator(which is a sha1 digest, though what is sha'd is
955
repository format specific) of the serialized inventory.
957
if not self.is_in_write_group():
958
raise AssertionError("%r not in write group" % (self,))
959
_mod_revision.check_not_reserved_id(revision_id)
960
if not (inv.revision_id is None or inv.revision_id == revision_id):
961
raise AssertionError(
962
"Mismatch between inventory revision"
963
" id and insertion revid (%r, %r)"
964
% (inv.revision_id, revision_id))
966
raise errors.RootMissing()
967
return self._add_inventory_checked(revision_id, inv, parents)
969
def _add_inventory_checked(self, revision_id, inv, parents):
970
"""Add inv to the repository after checking the inputs.
972
This function can be overridden to allow different inventory styles.
974
:seealso: add_inventory, for the contract.
976
inv_lines = self._serializer.write_inventory_to_lines(inv)
977
return self._inventory_add_lines(revision_id, parents,
978
inv_lines, check_content=False)
980
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
981
parents, basis_inv=None, propagate_caches=False):
982
"""Add a new inventory expressed as a delta against another revision.
984
See the inventory developers documentation for the theory behind
987
:param basis_revision_id: The inventory id the delta was created
988
against. (This does not have to be a direct parent.)
989
:param delta: The inventory delta (see Inventory.apply_delta for
991
:param new_revision_id: The revision id that the inventory is being
993
:param parents: The revision ids of the parents that revision_id is
994
known to have and are in the repository already. These are supplied
995
for repositories that depend on the inventory graph for revision
996
graph access, as well as for those that pun ancestry with delta
998
:param basis_inv: The basis inventory if it is already known,
1000
:param propagate_caches: If True, the caches for this inventory are
1001
copied to and updated for the result if possible.
1003
:returns: (validator, new_inv)
1004
The validator(which is a sha1 digest, though what is sha'd is
1005
repository format specific) of the serialized inventory, and the
1006
resulting inventory.
1008
if not self.is_in_write_group():
1009
raise AssertionError("%r not in write group" % (self,))
1010
_mod_revision.check_not_reserved_id(new_revision_id)
1011
basis_tree = self.revision_tree(basis_revision_id)
1012
basis_tree.lock_read()
1014
# Note that this mutates the inventory of basis_tree, which not all
1015
# inventory implementations may support: A better idiom would be to
1016
# return a new inventory, but as there is no revision tree cache in
1017
# repository this is safe for now - RBC 20081013
1018
if basis_inv is None:
1019
basis_inv = basis_tree.inventory
1020
basis_inv.apply_delta(delta)
1021
basis_inv.revision_id = new_revision_id
1022
return (self.add_inventory(new_revision_id, basis_inv, parents),
1027
def _inventory_add_lines(self, revision_id, parents, lines,
1028
check_content=True):
1029
"""Store lines in inv_vf and return the sha1 of the inventory."""
1030
parents = [(parent,) for parent in parents]
1031
result = self.inventories.add_lines((revision_id,), parents, lines,
1032
check_content=check_content)[0]
1033
self.inventories._access.flush()
1036
def add_revision(self, revision_id, rev, inv=None, config=None):
1037
"""Add rev to the revision store as revision_id.
1039
:param revision_id: the revision id to use.
1040
:param rev: The revision object.
1041
:param inv: The inventory for the revision. if None, it will be looked
1042
up in the inventory storer
1043
:param config: If None no digital signature will be created.
1044
If supplied its signature_needed method will be used
1045
to determine if a signature should be made.
1047
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1049
_mod_revision.check_not_reserved_id(revision_id)
1050
if (config is not None and
1051
config.get('create_signatures') == _mod_config.SIGN_ALWAYS):
1053
inv = self.get_inventory(revision_id)
1054
tree = InventoryRevisionTree(self, inv, revision_id)
1055
testament = Testament(rev, tree)
1056
plaintext = testament.as_short_text()
1057
self.store_revision_signature(
1058
gpg.GPGStrategy(config), plaintext, revision_id)
1059
# check inventory present
1060
if not self.inventories.get_parent_map([(revision_id,)]):
1062
raise errors.WeaveRevisionNotPresent(revision_id,
1065
# yes, this is not suitable for adding with ghosts.
1066
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1069
key = (revision_id,)
1070
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1071
self._add_revision(rev)
1073
def _add_revision(self, revision):
1074
text = self._serializer.write_revision_to_string(revision)
1075
key = (revision.revision_id,)
1076
parents = tuple((parent,) for parent in revision.parent_ids)
1077
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1079
def _check_inventories(self, checker):
1080
"""Check the inventories found from the revision scan.
1082
This is responsible for verifying the sha1 of inventories and
1083
creating a pending_keys set that covers data referenced by inventories.
1085
bar = ui.ui_factory.nested_progress_bar()
1087
self._do_check_inventories(checker, bar)
1091
def _do_check_inventories(self, checker, bar):
1092
"""Helper for _check_inventories."""
1094
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1095
kinds = ['chk_bytes', 'texts']
1096
count = len(checker.pending_keys)
1097
bar.update(gettext("inventories"), 0, 2)
1098
current_keys = checker.pending_keys
1099
checker.pending_keys = {}
1100
# Accumulate current checks.
1101
for key in current_keys:
1102
if key[0] != 'inventories' and key[0] not in kinds:
1103
checker._report_items.append('unknown key type %r' % (key,))
1104
keys[key[0]].add(key[1:])
1105
if keys['inventories']:
1106
# NB: output order *should* be roughly sorted - topo or
1107
# inverse topo depending on repository - either way decent
1108
# to just delta against. However, pre-CHK formats didn't
1109
# try to optimise inventory layout on disk. As such the
1110
# pre-CHK code path does not use inventory deltas.
1112
for record in self.inventories.check(keys=keys['inventories']):
1113
if record.storage_kind == 'absent':
1114
checker._report_items.append(
1115
'Missing inventory {%s}' % (record.key,))
1117
last_object = self._check_record('inventories', record,
1118
checker, last_object,
1119
current_keys[('inventories',) + record.key])
1120
del keys['inventories']
1123
bar.update(gettext("texts"), 1)
1124
while (checker.pending_keys or keys['chk_bytes']
1126
# Something to check.
1127
current_keys = checker.pending_keys
1128
checker.pending_keys = {}
1129
# Accumulate current checks.
1130
for key in current_keys:
1131
if key[0] not in kinds:
1132
checker._report_items.append('unknown key type %r' % (key,))
1133
keys[key[0]].add(key[1:])
1134
# Check the outermost kind only - inventories || chk_bytes || texts
1138
for record in getattr(self, kind).check(keys=keys[kind]):
1139
if record.storage_kind == 'absent':
1140
checker._report_items.append(
1141
'Missing %s {%s}' % (kind, record.key,))
1143
last_object = self._check_record(kind, record,
1144
checker, last_object, current_keys[(kind,) + record.key])
1148
def _check_record(self, kind, record, checker, last_object, item_data):
1149
"""Check a single text from this repository."""
1150
if kind == 'inventories':
1151
rev_id = record.key[0]
1152
inv = self._deserialise_inventory(rev_id,
1153
record.get_bytes_as('fulltext'))
1154
if last_object is not None:
1155
delta = inv._make_delta(last_object)
1156
for old_path, path, file_id, ie in delta:
1159
ie.check(checker, rev_id, inv)
1161
for path, ie in inv.iter_entries():
1162
ie.check(checker, rev_id, inv)
1163
if self._format.fast_deltas:
1165
elif kind == 'chk_bytes':
1166
# No code written to check chk_bytes for this repo format.
1167
checker._report_items.append(
1168
'unsupported key type chk_bytes for %s' % (record.key,))
1169
elif kind == 'texts':
1170
self._check_text(record, checker, item_data)
1172
checker._report_items.append(
1173
'unknown key type %s for %s' % (kind, record.key))
1175
def _check_text(self, record, checker, item_data):
1176
"""Check a single text."""
1177
# Check it is extractable.
1178
# TODO: check length.
1179
if record.storage_kind == 'chunked':
1180
chunks = record.get_bytes_as(record.storage_kind)
1181
sha1 = osutils.sha_strings(chunks)
1182
length = sum(map(len, chunks))
1184
content = record.get_bytes_as('fulltext')
1185
sha1 = osutils.sha_string(content)
1186
length = len(content)
1187
if item_data and sha1 != item_data[1]:
1188
checker._report_items.append(
1189
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1190
(record.key, sha1, item_data[1], item_data[2]))
1193
def _eliminate_revisions_not_present(self, revision_ids):
1194
"""Check every revision id in revision_ids to see if we have it.
1196
Returns a set of the present revisions.
1199
graph = self.get_graph()
1200
parent_map = graph.get_parent_map(revision_ids)
1201
# The old API returned a list, should this actually be a set?
1202
return parent_map.keys()
1204
def __init__(self, _format, a_bzrdir, control_files):
1205
"""Instantiate a VersionedFileRepository.
1207
:param _format: The format of the repository on disk.
1208
:param controldir: The ControlDir of the repository.
1209
:param control_files: Control files to use for locking, etc.
1211
# In the future we will have a single api for all stores for
1212
# getting file texts, inventories and revisions, then
1213
# this construct will accept instances of those things.
1214
super(VersionedFileRepository, self).__init__(_format, a_bzrdir,
1216
self._transport = control_files._transport
1217
self.base = self._transport.base
1219
self._reconcile_does_inventory_gc = True
1220
self._reconcile_fixes_text_parents = False
1221
self._reconcile_backsup_inventory = True
1222
# An InventoryEntry cache, used during deserialization
1223
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1224
# Is it safe to return inventory entries directly from the entry cache,
1225
# rather copying them?
1226
self._safe_to_return_from_cache = False
1228
def fetch(self, source, revision_id=None, find_ghosts=False,
1230
"""Fetch the content required to construct revision_id from source.
1232
If revision_id is None and fetch_spec is None, then all content is
1235
fetch() may not be used when the repository is in a write group -
1236
either finish the current write group before using fetch, or use
1237
fetch before starting the write group.
1239
:param find_ghosts: Find and copy revisions in the source that are
1240
ghosts in the target (and not reachable directly by walking out to
1241
the first-present revision in target from revision_id).
1242
:param revision_id: If specified, all the content needed for this
1243
revision ID will be copied to the target. Fetch will determine for
1244
itself which content needs to be copied.
1245
:param fetch_spec: If specified, a SearchResult or
1246
PendingAncestryResult that describes which revisions to copy. This
1247
allows copying multiple heads at once. Mutually exclusive with
1250
if fetch_spec is not None and revision_id is not None:
1251
raise AssertionError(
1252
"fetch_spec and revision_id are mutually exclusive.")
1253
if self.is_in_write_group():
1254
raise errors.InternalBzrError(
1255
"May not fetch while in a write group.")
1256
# fast path same-url fetch operations
1257
# TODO: lift out to somewhere common with RemoteRepository
1258
# <https://bugs.launchpad.net/bzr/+bug/401646>
1259
if (self.has_same_location(source)
1260
and fetch_spec is None
1261
and self._has_same_fallbacks(source)):
1262
# check that last_revision is in 'from' and then return a
1264
if (revision_id is not None and
1265
not _mod_revision.is_null(revision_id)):
1266
self.get_revision(revision_id)
1268
inter = InterRepository.get(source, self)
1269
if (fetch_spec is not None and
1270
not getattr(inter, "supports_fetch_spec", False)):
1271
raise errors.UnsupportedOperation(
1272
"fetch_spec not supported for %r" % inter)
1273
return inter.fetch(revision_id=revision_id,
1274
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1277
def gather_stats(self, revid=None, committers=None):
1278
"""See Repository.gather_stats()."""
1279
result = super(VersionedFileRepository, self).gather_stats(revid, committers)
1280
# now gather global repository information
1281
# XXX: This is available for many repos regardless of listability.
1282
if self.user_transport.listable():
1283
# XXX: do we want to __define len__() ?
1284
# Maybe the versionedfiles object should provide a different
1285
# method to get the number of keys.
1286
result['revisions'] = len(self.revisions.keys())
1287
# result['size'] = t
1290
def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
1291
timezone=None, committer=None, revprops=None,
1292
revision_id=None, lossy=False):
1293
"""Obtain a CommitBuilder for this repository.
1295
:param branch: Branch to commit to.
1296
:param parents: Revision ids of the parents of the new revision.
1297
:param config_stack: Configuration stack to use.
1298
:param timestamp: Optional timestamp recorded for commit.
1299
:param timezone: Optional timezone for timestamp.
1300
:param committer: Optional committer to set for commit.
1301
:param revprops: Optional dictionary of revision properties.
1302
:param revision_id: Optional revision id.
1303
:param lossy: Whether to discard data that can not be natively
1304
represented, when pushing to a foreign VCS
1306
if self._fallback_repositories and not self._format.supports_chks:
1307
raise errors.BzrError("Cannot commit directly to a stacked branch"
1308
" in pre-2a formats. See "
1309
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1310
result = self._commit_builder_class(self, parents, config_stack,
1311
timestamp, timezone, committer, revprops, revision_id,
1313
self.start_write_group()
1316
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1317
"""Return the keys of missing inventory parents for revisions added in
1320
A revision is not complete if the inventory delta for that revision
1321
cannot be calculated. Therefore if the parent inventories of a
1322
revision are not present, the revision is incomplete, and e.g. cannot
1323
be streamed by a smart server. This method finds missing inventory
1324
parents for revisions added in this write group.
1326
if not self._format.supports_external_lookups:
1327
# This is only an issue for stacked repositories
1329
if not self.is_in_write_group():
1330
raise AssertionError('not in a write group')
1332
# XXX: We assume that every added revision already has its
1333
# corresponding inventory, so we only check for parent inventories that
1334
# might be missing, rather than all inventories.
1335
parents = set(self.revisions._index.get_missing_parents())
1336
parents.discard(_mod_revision.NULL_REVISION)
1337
unstacked_inventories = self.inventories._index
1338
present_inventories = unstacked_inventories.get_parent_map(
1339
key[-1:] for key in parents)
1340
parents.difference_update(present_inventories)
1341
if len(parents) == 0:
1342
# No missing parent inventories.
1344
if not check_for_missing_texts:
1345
return set(('inventories', rev_id) for (rev_id,) in parents)
1346
# Ok, now we have a list of missing inventories. But these only matter
1347
# if the inventories that reference them are missing some texts they
1348
# appear to introduce.
1349
# XXX: Texts referenced by all added inventories need to be present,
1350
# but at the moment we're only checking for texts referenced by
1351
# inventories at the graph's edge.
1352
key_deps = self.revisions._index._key_dependencies
1353
key_deps.satisfy_refs_for_keys(present_inventories)
1354
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1355
file_ids = self.fileids_altered_by_revision_ids(referrers)
1356
missing_texts = set()
1357
for file_id, version_ids in file_ids.iteritems():
1358
missing_texts.update(
1359
(file_id, version_id) for version_id in version_ids)
1360
present_texts = self.texts.get_parent_map(missing_texts)
1361
missing_texts.difference_update(present_texts)
1362
if not missing_texts:
1363
# No texts are missing, so all revisions and their deltas are
1366
# Alternatively the text versions could be returned as the missing
1367
# keys, but this is likely to be less data.
1368
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1372
def has_revisions(self, revision_ids):
1373
"""Probe to find out the presence of multiple revisions.
1375
:param revision_ids: An iterable of revision_ids.
1376
:return: A set of the revision_ids that were present.
1378
parent_map = self.revisions.get_parent_map(
1379
[(rev_id,) for rev_id in revision_ids])
1381
if _mod_revision.NULL_REVISION in revision_ids:
1382
result.add(_mod_revision.NULL_REVISION)
1383
result.update([key[0] for key in parent_map])
1387
def get_revision_reconcile(self, revision_id):
1388
"""'reconcile' helper routine that allows access to a revision always.
1390
This variant of get_revision does not cross check the weave graph
1391
against the revision one as get_revision does: but it should only
1392
be used by reconcile, or reconcile-alike commands that are correcting
1393
or testing the revision graph.
1395
return self._get_revisions([revision_id])[0]
1398
def get_revisions(self, revision_ids):
1399
"""Get many revisions at once.
1401
Repositories that need to check data on every revision read should
1402
subclass this method.
1404
return self._get_revisions(revision_ids)
1407
def _get_revisions(self, revision_ids):
1408
"""Core work logic to get many revisions without sanity checks."""
1410
for revid, rev in self._iter_revisions(revision_ids):
1412
raise errors.NoSuchRevision(self, revid)
1414
return [revs[revid] for revid in revision_ids]
1416
def _iter_revisions(self, revision_ids):
1417
"""Iterate over revision objects.
1419
:param revision_ids: An iterable of revisions to examine. None may be
1420
passed to request all revisions known to the repository. Note that
1421
not all repositories can find unreferenced revisions; for those
1422
repositories only referenced ones will be returned.
1423
:return: An iterator of (revid, revision) tuples. Absent revisions (
1424
those asked for but not available) are returned as (revid, None).
1426
if revision_ids is None:
1427
revision_ids = self.all_revision_ids()
1429
for rev_id in revision_ids:
1430
if not rev_id or not isinstance(rev_id, basestring):
1431
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1432
keys = [(key,) for key in revision_ids]
1433
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1434
for record in stream:
1435
revid = record.key[0]
1436
if record.storage_kind == 'absent':
1439
text = record.get_bytes_as('fulltext')
1440
rev = self._serializer.read_revision_from_string(text)
1444
def add_signature_text(self, revision_id, signature):
1445
"""Store a signature text for a revision.
1447
:param revision_id: Revision id of the revision
1448
:param signature: Signature text.
1450
self.signatures.add_lines((revision_id,), (),
1451
osutils.split_lines(signature))
1453
def find_text_key_references(self):
1454
"""Find the text key references within the repository.
1456
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1457
to whether they were referred to by the inventory of the
1458
revision_id that they contain. The inventory texts from all present
1459
revision ids are assessed to generate this report.
1461
revision_keys = self.revisions.keys()
1462
w = self.inventories
1463
pb = ui.ui_factory.nested_progress_bar()
1465
return self._serializer._find_text_key_references(
1466
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1470
def _inventory_xml_lines_for_keys(self, keys):
1471
"""Get a line iterator of the sort needed for findind references.
1473
Not relevant for non-xml inventory repositories.
1475
Ghosts in revision_keys are ignored.
1477
:param revision_keys: The revision keys for the inventories to inspect.
1478
:return: An iterator over (inventory line, revid) for the fulltexts of
1479
all of the xml inventories specified by revision_keys.
1481
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1482
for record in stream:
1483
if record.storage_kind != 'absent':
1484
chunks = record.get_bytes_as('chunked')
1485
revid = record.key[-1]
1486
lines = osutils.chunks_to_lines(chunks)
1490
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1492
"""Helper routine for fileids_altered_by_revision_ids.
1494
This performs the translation of xml lines to revision ids.
1496
:param line_iterator: An iterator of lines, origin_version_id
1497
:param revision_keys: The revision ids to filter for. This should be a
1498
set or other type which supports efficient __contains__ lookups, as
1499
the revision key from each parsed line will be looked up in the
1500
revision_keys filter.
1501
:return: a dictionary mapping altered file-ids to an iterable of
1502
revision_ids. Each altered file-ids has the exact revision_ids that
1503
altered it listed explicitly.
1505
seen = set(self._serializer._find_text_key_references(
1506
line_iterator).iterkeys())
1507
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1508
parent_seen = set(self._serializer._find_text_key_references(
1509
self._inventory_xml_lines_for_keys(parent_keys)))
1510
new_keys = seen - parent_seen
1512
setdefault = result.setdefault
1513
for key in new_keys:
1514
setdefault(key[0], set()).add(key[-1])
1517
def _find_parent_keys_of_revisions(self, revision_keys):
1518
"""Similar to _find_parent_ids_of_revisions, but used with keys.
1520
:param revision_keys: An iterable of revision_keys.
1521
:return: The parents of all revision_keys that are not already in
1524
parent_map = self.revisions.get_parent_map(revision_keys)
1526
map(parent_keys.update, parent_map.itervalues())
1527
parent_keys.difference_update(revision_keys)
1528
parent_keys.discard(_mod_revision.NULL_REVISION)
1531
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1532
"""Find the file ids and versions affected by revisions.
1534
:param revisions: an iterable containing revision ids.
1535
:param _inv_weave: The inventory weave from this repository or None.
1536
If None, the inventory weave will be opened automatically.
1537
:return: a dictionary mapping altered file-ids to an iterable of
1538
revision_ids. Each altered file-ids has the exact revision_ids that
1539
altered it listed explicitly.
1541
selected_keys = set((revid,) for revid in revision_ids)
1542
w = _inv_weave or self.inventories
1543
return self._find_file_ids_from_xml_inventory_lines(
1544
w.iter_lines_added_or_present_in_keys(
1545
selected_keys, pb=None),
1548
def iter_files_bytes(self, desired_files):
1549
"""Iterate through file versions.
1551
Files will not necessarily be returned in the order they occur in
1552
desired_files. No specific order is guaranteed.
1554
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1555
value supplied by the caller as part of desired_files. It should
1556
uniquely identify the file version in the caller's context. (Examples:
1557
an index number or a TreeTransform trans_id.)
1559
bytes_iterator is an iterable of bytestrings for the file. The
1560
kind of iterable and length of the bytestrings are unspecified, but for
1561
this implementation, it is a list of bytes produced by
1562
VersionedFile.get_record_stream().
1564
:param desired_files: a list of (file_id, revision_id, identifier)
1568
for file_id, revision_id, callable_data in desired_files:
1569
text_keys[(file_id, revision_id)] = callable_data
1570
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1571
if record.storage_kind == 'absent':
1572
raise errors.RevisionNotPresent(record.key[1], record.key[0])
1573
yield text_keys[record.key], record.get_bytes_as('chunked')
1575
def _generate_text_key_index(self, text_key_references=None,
1577
"""Generate a new text key index for the repository.
1579
This is an expensive function that will take considerable time to run.
1581
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1582
list of parents, also text keys. When a given key has no parents,
1583
the parents list will be [NULL_REVISION].
1585
# All revisions, to find inventory parents.
1586
if ancestors is None:
1587
graph = self.get_graph()
1588
ancestors = graph.get_parent_map(self.all_revision_ids())
1589
if text_key_references is None:
1590
text_key_references = self.find_text_key_references()
1591
pb = ui.ui_factory.nested_progress_bar()
1593
return self._do_generate_text_key_index(ancestors,
1594
text_key_references, pb)
1598
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1599
"""Helper for _generate_text_key_index to avoid deep nesting."""
1600
revision_order = tsort.topo_sort(ancestors)
1601
invalid_keys = set()
1603
for revision_id in revision_order:
1604
revision_keys[revision_id] = set()
1605
text_count = len(text_key_references)
1606
# a cache of the text keys to allow reuse; costs a dict of all the
1607
# keys, but saves a 2-tuple for every child of a given key.
1609
for text_key, valid in text_key_references.iteritems():
1611
invalid_keys.add(text_key)
1613
revision_keys[text_key[1]].add(text_key)
1614
text_key_cache[text_key] = text_key
1615
del text_key_references
1617
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1618
NULL_REVISION = _mod_revision.NULL_REVISION
1619
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1620
# too small for large or very branchy trees. However, for 55K path
1621
# trees, it would be easy to use too much memory trivially. Ideally we
1622
# could gauge this by looking at available real memory etc, but this is
1623
# always a tricky proposition.
1624
inventory_cache = lru_cache.LRUCache(10)
1625
batch_size = 10 # should be ~150MB on a 55K path tree
1626
batch_count = len(revision_order) / batch_size + 1
1628
pb.update(gettext("Calculating text parents"), processed_texts, text_count)
1629
for offset in xrange(batch_count):
1630
to_query = revision_order[offset * batch_size:(offset + 1) *
1634
for revision_id in to_query:
1635
parent_ids = ancestors[revision_id]
1636
for text_key in revision_keys[revision_id]:
1637
pb.update(gettext("Calculating text parents"), processed_texts)
1638
processed_texts += 1
1639
candidate_parents = []
1640
for parent_id in parent_ids:
1641
parent_text_key = (text_key[0], parent_id)
1643
check_parent = parent_text_key not in \
1644
revision_keys[parent_id]
1646
# the parent parent_id is a ghost:
1647
check_parent = False
1648
# truncate the derived graph against this ghost.
1649
parent_text_key = None
1651
# look at the parent commit details inventories to
1652
# determine possible candidates in the per file graph.
1655
inv = inventory_cache[parent_id]
1657
inv = self.revision_tree(parent_id).inventory
1658
inventory_cache[parent_id] = inv
1660
parent_entry = inv[text_key[0]]
1661
except (KeyError, errors.NoSuchId):
1663
if parent_entry is not None:
1665
text_key[0], parent_entry.revision)
1667
parent_text_key = None
1668
if parent_text_key is not None:
1669
candidate_parents.append(
1670
text_key_cache[parent_text_key])
1671
parent_heads = text_graph.heads(candidate_parents)
1672
new_parents = list(parent_heads)
1673
new_parents.sort(key=lambda x:candidate_parents.index(x))
1674
if new_parents == []:
1675
new_parents = [NULL_REVISION]
1676
text_index[text_key] = new_parents
1678
for text_key in invalid_keys:
1679
text_index[text_key] = [NULL_REVISION]
1682
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1683
"""Get an iterable listing the keys of all the data introduced by a set
1686
The keys will be ordered so that the corresponding items can be safely
1687
fetched and inserted in that order.
1689
:returns: An iterable producing tuples of (knit-kind, file-id,
1690
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1691
'revisions'. file-id is None unless knit-kind is 'file'.
1693
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
1696
for result in self._find_non_file_keys_to_fetch(revision_ids):
1699
def _find_file_keys_to_fetch(self, revision_ids, pb):
1700
# XXX: it's a bit weird to control the inventory weave caching in this
1701
# generator. Ideally the caching would be done in fetch.py I think. Or
1702
# maybe this generator should explicitly have the contract that it
1703
# should not be iterated until the previously yielded item has been
1705
inv_w = self.inventories
1707
# file ids that changed
1708
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1710
num_file_ids = len(file_ids)
1711
for file_id, altered_versions in file_ids.iteritems():
1713
pb.update(gettext("Fetch texts"), count, num_file_ids)
1715
yield ("file", file_id, altered_versions)
1717
def _find_non_file_keys_to_fetch(self, revision_ids):
1719
yield ("inventory", None, revision_ids)
1722
# XXX: Note ATM no callers actually pay attention to this return
1723
# instead they just use the list of revision ids and ignore
1724
# missing sigs. Consider removing this work entirely
1725
revisions_with_signatures = set(self.signatures.get_parent_map(
1726
[(r,) for r in revision_ids]))
1727
revisions_with_signatures = set(
1728
[r for (r,) in revisions_with_signatures])
1729
revisions_with_signatures.intersection_update(revision_ids)
1730
yield ("signatures", None, revisions_with_signatures)
1733
yield ("revisions", None, revision_ids)
1736
def get_inventory(self, revision_id):
1737
"""Get Inventory object by revision id."""
1738
return self.iter_inventories([revision_id]).next()
1740
def iter_inventories(self, revision_ids, ordering=None):
1741
"""Get many inventories by revision_ids.
1743
This will buffer some or all of the texts used in constructing the
1744
inventories in memory, but will only parse a single inventory at a
1747
:param revision_ids: The expected revision ids of the inventories.
1748
:param ordering: optional ordering, e.g. 'topological'. If not
1749
specified, the order of revision_ids will be preserved (by
1750
buffering if necessary).
1751
:return: An iterator of inventories.
1753
if ((None in revision_ids)
1754
or (_mod_revision.NULL_REVISION in revision_ids)):
1755
raise ValueError('cannot get null revision inventory')
1756
for inv, revid in self._iter_inventories(revision_ids, ordering):
1758
raise errors.NoSuchRevision(self, revid)
1761
def _iter_inventories(self, revision_ids, ordering):
1762
"""single-document based inventory iteration."""
1763
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1764
for text, revision_id in inv_xmls:
1766
yield None, revision_id
1768
yield self._deserialise_inventory(revision_id, text), revision_id
1770
def _iter_inventory_xmls(self, revision_ids, ordering):
1771
if ordering is None:
1772
order_as_requested = True
1773
ordering = 'unordered'
1775
order_as_requested = False
1776
keys = [(revision_id,) for revision_id in revision_ids]
1779
if order_as_requested:
1780
key_iter = iter(keys)
1781
next_key = key_iter.next()
1782
stream = self.inventories.get_record_stream(keys, ordering, True)
1784
for record in stream:
1785
if record.storage_kind != 'absent':
1786
chunks = record.get_bytes_as('chunked')
1787
if order_as_requested:
1788
text_chunks[record.key] = chunks
1790
yield ''.join(chunks), record.key[-1]
1792
yield None, record.key[-1]
1793
if order_as_requested:
1794
# Yield as many results as we can while preserving order.
1795
while next_key in text_chunks:
1796
chunks = text_chunks.pop(next_key)
1797
yield ''.join(chunks), next_key[-1]
1799
next_key = key_iter.next()
1800
except StopIteration:
1801
# We still want to fully consume the get_record_stream,
1802
# just in case it is not actually finished at this point
1806
def _deserialise_inventory(self, revision_id, xml):
1807
"""Transform the xml into an inventory object.
1809
:param revision_id: The expected revision id of the inventory.
1810
:param xml: A serialised inventory.
1812
result = self._serializer.read_inventory_from_string(xml, revision_id,
1813
entry_cache=self._inventory_entry_cache,
1814
return_from_cache=self._safe_to_return_from_cache)
1815
if result.revision_id != revision_id:
1816
raise AssertionError('revision id mismatch %s != %s' % (
1817
result.revision_id, revision_id))
1820
def get_serializer_format(self):
1821
return self._serializer.format_num
1824
def _get_inventory_xml(self, revision_id):
1825
"""Get serialized inventory as a string."""
1826
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1827
text, revision_id = texts.next()
1829
raise errors.NoSuchRevision(self, revision_id)
1833
def revision_tree(self, revision_id):
1834
"""Return Tree for a revision on this branch.
1836
`revision_id` may be NULL_REVISION for the empty tree revision.
1838
revision_id = _mod_revision.ensure_null(revision_id)
1839
# TODO: refactor this to use an existing revision object
1840
# so we don't need to read it in twice.
1841
if revision_id == _mod_revision.NULL_REVISION:
1842
return InventoryRevisionTree(self,
1843
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1845
inv = self.get_inventory(revision_id)
1846
return InventoryRevisionTree(self, inv, revision_id)
1848
def revision_trees(self, revision_ids):
1849
"""Return Trees for revisions in this repository.
1851
:param revision_ids: a sequence of revision-ids;
1852
a revision-id may not be None or 'null:'
1854
inventories = self.iter_inventories(revision_ids)
1855
for inv in inventories:
1856
yield InventoryRevisionTree(self, inv, inv.revision_id)
1858
def _filtered_revision_trees(self, revision_ids, file_ids):
1859
"""Return Tree for a revision on this branch with only some files.
1861
:param revision_ids: a sequence of revision-ids;
1862
a revision-id may not be None or 'null:'
1863
:param file_ids: if not None, the result is filtered
1864
so that only those file-ids, their parents and their
1865
children are included.
1867
inventories = self.iter_inventories(revision_ids)
1868
for inv in inventories:
1869
# Should we introduce a FilteredRevisionTree class rather
1870
# than pre-filter the inventory here?
1871
filtered_inv = inv.filter(file_ids)
1872
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1874
def get_parent_map(self, revision_ids):
1875
"""See graph.StackedParentsProvider.get_parent_map"""
1876
# revisions index works in keys; this just works in revisions
1877
# therefore wrap and unwrap
1880
for revision_id in revision_ids:
1881
if revision_id == _mod_revision.NULL_REVISION:
1882
result[revision_id] = ()
1883
elif revision_id is None:
1884
raise ValueError('get_parent_map(None) is not valid')
1886
query_keys.append((revision_id ,))
1887
for ((revision_id,), parent_keys) in \
1888
self.revisions.get_parent_map(query_keys).iteritems():
1890
result[revision_id] = tuple([parent_revid
1891
for (parent_revid,) in parent_keys])
1893
result[revision_id] = (_mod_revision.NULL_REVISION,)
1897
def get_known_graph_ancestry(self, revision_ids):
1898
"""Return the known graph for a set of revision ids and their ancestors.
1900
st = static_tuple.StaticTuple
1901
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1902
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1903
return graph.GraphThunkIdsToKeys(known_graph)
1906
def get_file_graph(self):
1907
"""Return the graph walker for text revisions."""
1908
return graph.Graph(self.texts)
1910
def revision_ids_to_search_result(self, result_set):
1911
"""Convert a set of revision ids to a graph SearchResult."""
1912
result_parents = set()
1913
for parents in self.get_graph().get_parent_map(
1914
result_set).itervalues():
1915
result_parents.update(parents)
1916
included_keys = result_set.intersection(result_parents)
1917
start_keys = result_set.difference(included_keys)
1918
exclude_keys = result_parents.difference(result_set)
1919
result = vf_search.SearchResult(start_keys, exclude_keys,
1920
len(result_set), result_set)
1923
def _get_versioned_file_checker(self, text_key_references=None,
1925
"""Return an object suitable for checking versioned files.
1927
:param text_key_references: if non-None, an already built
1928
dictionary mapping text keys ((fileid, revision_id) tuples)
1929
to whether they were referred to by the inventory of the
1930
revision_id that they contain. If None, this will be
1932
:param ancestors: Optional result from
1933
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1936
return _VersionedFileChecker(self,
1937
text_key_references=text_key_references, ancestors=ancestors)
1940
def has_signature_for_revision_id(self, revision_id):
1941
"""Query for a revision signature for revision_id in the repository."""
1942
if not self.has_revision(revision_id):
1943
raise errors.NoSuchRevision(self, revision_id)
1944
sig_present = (1 == len(
1945
self.signatures.get_parent_map([(revision_id,)])))
1949
def get_signature_text(self, revision_id):
1950
"""Return the text for a signature."""
1951
stream = self.signatures.get_record_stream([(revision_id,)],
1953
record = stream.next()
1954
if record.storage_kind == 'absent':
1955
raise errors.NoSuchRevision(self, revision_id)
1956
return record.get_bytes_as('fulltext')
1959
def _check(self, revision_ids, callback_refs, check_repo):
1960
result = check.VersionedFileCheck(self, check_repo=check_repo)
1961
result.check(callback_refs)
1964
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1965
"""Find revisions with different parent lists in the revision object
1966
and in the index graph.
1968
:param revisions_iterator: None, or an iterator of (revid,
1969
Revision-or-None). This iterator controls the revisions checked.
1970
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1971
parents-in-revision).
1973
if not self.is_locked():
1974
raise AssertionError()
1976
if revisions_iterator is None:
1977
revisions_iterator = self._iter_revisions(None)
1978
for revid, revision in revisions_iterator:
1979
if revision is None:
1981
parent_map = vf.get_parent_map([(revid,)])
1982
parents_according_to_index = tuple(parent[-1] for parent in
1983
parent_map[(revid,)])
1984
parents_according_to_revision = tuple(revision.parent_ids)
1985
if parents_according_to_index != parents_according_to_revision:
1986
yield (revid, parents_according_to_index,
1987
parents_according_to_revision)
1989
def _check_for_inconsistent_revision_parents(self):
1990
inconsistencies = list(self._find_inconsistent_revision_parents())
1992
raise errors.BzrCheckError(
1993
"Revision knit has inconsistent parents.")
1995
def _get_sink(self):
1996
"""Return a sink for streaming into this repository."""
1997
return StreamSink(self)
1999
def _get_source(self, to_format):
2000
"""Return a source for streaming from this repository."""
2001
return StreamSource(self, to_format)
2004
class MetaDirVersionedFileRepository(MetaDirRepository,
2005
VersionedFileRepository):
2006
"""Repositories in a meta-dir, that work via versioned file objects."""
2008
def __init__(self, _format, a_bzrdir, control_files):
2009
super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
2013
class MetaDirVersionedFileRepositoryFormat(RepositoryFormatMetaDir,
2014
VersionedFileRepositoryFormat):
2015
"""Base class for repository formats using versioned files in metadirs."""
2018
class StreamSink(object):
2019
"""An object that can insert a stream into a repository.
2021
This interface handles the complexity of reserialising inventories and
2022
revisions from different formats, and allows unidirectional insertion into
2023
stacked repositories without looking for the missing basis parents
2027
def __init__(self, target_repo):
2028
self.target_repo = target_repo
2030
def insert_stream(self, stream, src_format, resume_tokens):
2031
"""Insert a stream's content into the target repository.
2033
:param src_format: a bzr repository format.
2035
:return: a list of resume tokens and an iterable of keys additional
2036
items required before the insertion can be completed.
2038
self.target_repo.lock_write()
2041
self.target_repo.resume_write_group(resume_tokens)
2044
self.target_repo.start_write_group()
2047
# locked_insert_stream performs a commit|suspend.
2048
missing_keys = self.insert_stream_without_locking(stream,
2049
src_format, is_resume)
2051
# suspend the write group and tell the caller what we is
2052
# missing. We know we can suspend or else we would not have
2053
# entered this code path. (All repositories that can handle
2054
# missing keys can handle suspending a write group).
2055
write_group_tokens = self.target_repo.suspend_write_group()
2056
return write_group_tokens, missing_keys
2057
hint = self.target_repo.commit_write_group()
2058
to_serializer = self.target_repo._format._serializer
2059
src_serializer = src_format._serializer
2060
if (to_serializer != src_serializer and
2061
self.target_repo._format.pack_compresses):
2062
self.target_repo.pack(hint=hint)
2065
self.target_repo.abort_write_group(suppress_errors=True)
2068
self.target_repo.unlock()
2070
def insert_stream_without_locking(self, stream, src_format,
2072
"""Insert a stream's content into the target repository.
2074
This assumes that you already have a locked repository and an active
2077
:param src_format: a bzr repository format.
2078
:param is_resume: Passed down to get_missing_parent_inventories to
2079
indicate if we should be checking for missing texts at the same
2082
:return: A set of keys that are missing.
2084
if not self.target_repo.is_write_locked():
2085
raise errors.ObjectNotLocked(self)
2086
if not self.target_repo.is_in_write_group():
2087
raise errors.BzrError('you must already be in a write group')
2088
to_serializer = self.target_repo._format._serializer
2089
src_serializer = src_format._serializer
2091
if to_serializer == src_serializer:
2092
# If serializers match and the target is a pack repository, set the
2093
# write cache size on the new pack. This avoids poor performance
2094
# on transports where append is unbuffered (such as
2095
# RemoteTransport). This is safe to do because nothing should read
2096
# back from the target repository while a stream with matching
2097
# serialization is being inserted.
2098
# The exception is that a delta record from the source that should
2099
# be a fulltext may need to be expanded by the target (see
2100
# test_fetch_revisions_with_deltas_into_pack); but we take care to
2101
# explicitly flush any buffered writes first in that rare case.
2103
new_pack = self.target_repo._pack_collection._new_pack
2104
except AttributeError:
2105
# Not a pack repository
2108
new_pack.set_write_cache_size(1024*1024)
2109
for substream_type, substream in stream:
2110
if 'stream' in debug.debug_flags:
2111
mutter('inserting substream: %s', substream_type)
2112
if substream_type == 'texts':
2113
self.target_repo.texts.insert_record_stream(substream)
2114
elif substream_type == 'inventories':
2115
if src_serializer == to_serializer:
2116
self.target_repo.inventories.insert_record_stream(
2119
self._extract_and_insert_inventories(
2120
substream, src_serializer)
2121
elif substream_type == 'inventory-deltas':
2122
self._extract_and_insert_inventory_deltas(
2123
substream, src_serializer)
2124
elif substream_type == 'chk_bytes':
2125
# XXX: This doesn't support conversions, as it assumes the
2126
# conversion was done in the fetch code.
2127
self.target_repo.chk_bytes.insert_record_stream(substream)
2128
elif substream_type == 'revisions':
2129
# This may fallback to extract-and-insert more often than
2130
# required if the serializers are different only in terms of
2132
if src_serializer == to_serializer:
2133
self.target_repo.revisions.insert_record_stream(substream)
2135
self._extract_and_insert_revisions(substream,
2137
elif substream_type == 'signatures':
2138
self.target_repo.signatures.insert_record_stream(substream)
2140
raise AssertionError('kaboom! %s' % (substream_type,))
2141
# Done inserting data, and the missing_keys calculations will try to
2142
# read back from the inserted data, so flush the writes to the new pack
2143
# (if this is pack format).
2144
if new_pack is not None:
2145
new_pack._write_data('', flush=True)
2146
# Find all the new revisions (including ones from resume_tokens)
2147
missing_keys = self.target_repo.get_missing_parent_inventories(
2148
check_for_missing_texts=is_resume)
2150
for prefix, versioned_file in (
2151
('texts', self.target_repo.texts),
2152
('inventories', self.target_repo.inventories),
2153
('revisions', self.target_repo.revisions),
2154
('signatures', self.target_repo.signatures),
2155
('chk_bytes', self.target_repo.chk_bytes),
2157
if versioned_file is None:
2159
# TODO: key is often going to be a StaticTuple object
2160
# I don't believe we can define a method by which
2161
# (prefix,) + StaticTuple will work, though we could
2162
# define a StaticTuple.sq_concat that would allow you to
2163
# pass in either a tuple or a StaticTuple as the second
2164
# object, so instead we could have:
2165
# StaticTuple(prefix) + key here...
2166
missing_keys.update((prefix,) + key for key in
2167
versioned_file.get_missing_compression_parent_keys())
2168
except NotImplementedError:
2169
# cannot even attempt suspending, and missing would have failed
2170
# during stream insertion.
2171
missing_keys = set()
2174
def _extract_and_insert_inventory_deltas(self, substream, serializer):
2175
target_rich_root = self.target_repo._format.rich_root_data
2176
target_tree_refs = self.target_repo._format.supports_tree_reference
2177
for record in substream:
2178
# Insert the delta directly
2179
inventory_delta_bytes = record.get_bytes_as('fulltext')
2180
deserialiser = inventory_delta.InventoryDeltaDeserializer()
2182
parse_result = deserialiser.parse_text_bytes(
2183
inventory_delta_bytes)
2184
except inventory_delta.IncompatibleInventoryDelta, err:
2185
mutter("Incompatible delta: %s", err.msg)
2186
raise errors.IncompatibleRevision(self.target_repo._format)
2187
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
2188
revision_id = new_id
2189
parents = [key[0] for key in record.parents]
2190
self.target_repo.add_inventory_by_delta(
2191
basis_id, inv_delta, revision_id, parents)
2193
def _extract_and_insert_inventories(self, substream, serializer,
2195
"""Generate a new inventory versionedfile in target, converting data.
2197
The inventory is retrieved from the source, (deserializing it), and
2198
stored in the target (reserializing it in a different format).
2200
target_rich_root = self.target_repo._format.rich_root_data
2201
target_tree_refs = self.target_repo._format.supports_tree_reference
2202
for record in substream:
2203
# It's not a delta, so it must be a fulltext in the source
2204
# serializer's format.
2205
bytes = record.get_bytes_as('fulltext')
2206
revision_id = record.key[0]
2207
inv = serializer.read_inventory_from_string(bytes, revision_id)
2208
parents = [key[0] for key in record.parents]
2209
self.target_repo.add_inventory(revision_id, inv, parents)
2210
# No need to keep holding this full inv in memory when the rest of
2211
# the substream is likely to be all deltas.
2214
def _extract_and_insert_revisions(self, substream, serializer):
2215
for record in substream:
2216
bytes = record.get_bytes_as('fulltext')
2217
revision_id = record.key[0]
2218
rev = serializer.read_revision_from_string(bytes)
2219
if rev.revision_id != revision_id:
2220
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
2221
self.target_repo.add_revision(revision_id, rev)
2224
if self.target_repo._format._fetch_reconcile:
2225
self.target_repo.reconcile()
2228
class StreamSource(object):
2229
"""A source of a stream for fetching between repositories."""
2231
def __init__(self, from_repository, to_format):
2232
"""Create a StreamSource streaming from from_repository."""
2233
self.from_repository = from_repository
2234
self.to_format = to_format
2235
self._record_counter = RecordCounter()
2237
def delta_on_metadata(self):
2238
"""Return True if delta's are permitted on metadata streams.
2240
That is on revisions and signatures.
2242
src_serializer = self.from_repository._format._serializer
2243
target_serializer = self.to_format._serializer
2244
return (self.to_format._fetch_uses_deltas and
2245
src_serializer == target_serializer)
2247
def _fetch_revision_texts(self, revs):
2248
# fetch signatures first and then the revision texts
2249
# may need to be a InterRevisionStore call here.
2250
from_sf = self.from_repository.signatures
2251
# A missing signature is just skipped.
2252
keys = [(rev_id,) for rev_id in revs]
2253
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2255
self.to_format._fetch_order,
2256
not self.to_format._fetch_uses_deltas))
2257
# If a revision has a delta, this is actually expanded inside the
2258
# insert_record_stream code now, which is an alternate fix for
2260
from_rf = self.from_repository.revisions
2261
revisions = from_rf.get_record_stream(
2263
self.to_format._fetch_order,
2264
not self.delta_on_metadata())
2265
return [('signatures', signatures), ('revisions', revisions)]
2267
def _generate_root_texts(self, revs):
2268
"""This will be called by get_stream between fetching weave texts and
2269
fetching the inventory weave.
2271
if self._rich_root_upgrade():
2272
return _mod_fetch.Inter1and2Helper(
2273
self.from_repository).generate_root_texts(revs)
2277
def get_stream(self, search):
2279
revs = search.get_keys()
2280
graph = self.from_repository.get_graph()
2281
revs = tsort.topo_sort(graph.get_parent_map(revs))
2282
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2284
for knit_kind, file_id, revisions in data_to_fetch:
2285
if knit_kind != phase:
2287
# Make a new progress bar for this phase
2288
if knit_kind == "file":
2289
# Accumulate file texts
2290
text_keys.extend([(file_id, revision) for revision in
2292
elif knit_kind == "inventory":
2293
# Now copy the file texts.
2294
from_texts = self.from_repository.texts
2295
yield ('texts', from_texts.get_record_stream(
2296
text_keys, self.to_format._fetch_order,
2297
not self.to_format._fetch_uses_deltas))
2298
# Cause an error if a text occurs after we have done the
2301
# Before we process the inventory we generate the root
2302
# texts (if necessary) so that the inventories references
2304
for _ in self._generate_root_texts(revs):
2306
# we fetch only the referenced inventories because we do not
2307
# know for unselected inventories whether all their required
2308
# texts are present in the other repository - it could be
2310
for info in self._get_inventory_stream(revs):
2312
elif knit_kind == "signatures":
2313
# Nothing to do here; this will be taken care of when
2314
# _fetch_revision_texts happens.
2316
elif knit_kind == "revisions":
2317
for record in self._fetch_revision_texts(revs):
2320
raise AssertionError("Unknown knit kind %r" % knit_kind)
2322
def get_stream_for_missing_keys(self, missing_keys):
2323
# missing keys can only occur when we are byte copying and not
2324
# translating (because translation means we don't send
2325
# unreconstructable deltas ever).
2327
keys['texts'] = set()
2328
keys['revisions'] = set()
2329
keys['inventories'] = set()
2330
keys['chk_bytes'] = set()
2331
keys['signatures'] = set()
2332
for key in missing_keys:
2333
keys[key[0]].add(key[1:])
2334
if len(keys['revisions']):
2335
# If we allowed copying revisions at this point, we could end up
2336
# copying a revision without copying its required texts: a
2337
# violation of the requirements for repository integrity.
2338
raise AssertionError(
2339
'cannot copy revisions to fill in missing deltas %s' % (
2340
keys['revisions'],))
2341
for substream_kind, keys in keys.iteritems():
2342
vf = getattr(self.from_repository, substream_kind)
2343
if vf is None and keys:
2344
raise AssertionError(
2345
"cannot fill in keys for a versioned file we don't"
2346
" have: %s needs %s" % (substream_kind, keys))
2348
# No need to stream something we don't have
2350
if substream_kind == 'inventories':
2351
# Some missing keys are genuinely ghosts, filter those out.
2352
present = self.from_repository.inventories.get_parent_map(keys)
2353
revs = [key[0] for key in present]
2354
# Get the inventory stream more-or-less as we do for the
2355
# original stream; there's no reason to assume that records
2356
# direct from the source will be suitable for the sink. (Think
2357
# e.g. 2a -> 1.9-rich-root).
2358
for info in self._get_inventory_stream(revs, missing=True):
2362
# Ask for full texts always so that we don't need more round trips
2363
# after this stream.
2364
# Some of the missing keys are genuinely ghosts, so filter absent
2365
# records. The Sink is responsible for doing another check to
2366
# ensure that ghosts don't introduce missing data for future
2368
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2369
self.to_format._fetch_order, True))
2370
yield substream_kind, stream
2372
def inventory_fetch_order(self):
2373
if self._rich_root_upgrade():
2374
return 'topological'
2376
return self.to_format._fetch_order
2378
def _rich_root_upgrade(self):
2379
return (not self.from_repository._format.rich_root_data and
2380
self.to_format.rich_root_data)
2382
def _get_inventory_stream(self, revision_ids, missing=False):
2383
from_format = self.from_repository._format
2384
if (from_format.supports_chks and self.to_format.supports_chks and
2385
from_format.network_name() == self.to_format.network_name()):
2386
raise AssertionError(
2387
"this case should be handled by GroupCHKStreamSource")
2388
elif 'forceinvdeltas' in debug.debug_flags:
2389
return self._get_convertable_inventory_stream(revision_ids,
2390
delta_versus_null=missing)
2391
elif from_format.network_name() == self.to_format.network_name():
2393
return self._get_simple_inventory_stream(revision_ids,
2395
elif (not from_format.supports_chks and not self.to_format.supports_chks
2396
and from_format._serializer == self.to_format._serializer):
2397
# Essentially the same format.
2398
return self._get_simple_inventory_stream(revision_ids,
2401
# Any time we switch serializations, we want to use an
2402
# inventory-delta based approach.
2403
return self._get_convertable_inventory_stream(revision_ids,
2404
delta_versus_null=missing)
2406
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2407
# NB: This currently reopens the inventory weave in source;
2408
# using a single stream interface instead would avoid this.
2409
from_weave = self.from_repository.inventories
2411
delta_closure = True
2413
delta_closure = not self.delta_on_metadata()
2414
yield ('inventories', from_weave.get_record_stream(
2415
[(rev_id,) for rev_id in revision_ids],
2416
self.inventory_fetch_order(), delta_closure))
2418
def _get_convertable_inventory_stream(self, revision_ids,
2419
delta_versus_null=False):
2420
# The two formats are sufficiently different that there is no fast
2421
# path, so we need to send just inventorydeltas, which any
2422
# sufficiently modern client can insert into any repository.
2423
# The StreamSink code expects to be able to
2424
# convert on the target, so we need to put bytes-on-the-wire that can
2425
# be converted. That means inventory deltas (if the remote is <1.19,
2426
# RemoteStreamSink will fallback to VFS to insert the deltas).
2427
yield ('inventory-deltas',
2428
self._stream_invs_as_deltas(revision_ids,
2429
delta_versus_null=delta_versus_null))
2431
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2432
"""Return a stream of inventory-deltas for the given rev ids.
2434
:param revision_ids: The list of inventories to transmit
2435
:param delta_versus_null: Don't try to find a minimal delta for this
2436
entry, instead compute the delta versus the NULL_REVISION. This
2437
effectively streams a complete inventory. Used for stuff like
2438
filling in missing parents, etc.
2440
from_repo = self.from_repository
2441
revision_keys = [(rev_id,) for rev_id in revision_ids]
2442
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2443
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2445
inventories = self.from_repository.iter_inventories(
2446
revision_ids, 'topological')
2447
format = from_repo._format
2448
invs_sent_so_far = set([_mod_revision.NULL_REVISION])
2449
inventory_cache = lru_cache.LRUCache(50)
2450
null_inventory = from_repo.revision_tree(
2451
_mod_revision.NULL_REVISION).inventory
2452
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2453
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2454
# repo back into a non-rich-root repo ought to be allowed)
2455
serializer = inventory_delta.InventoryDeltaSerializer(
2456
versioned_root=format.rich_root_data,
2457
tree_references=format.supports_tree_reference)
2458
for inv in inventories:
2459
key = (inv.revision_id,)
2460
parent_keys = parent_map.get(key, ())
2462
if not delta_versus_null and parent_keys:
2463
# The caller did not ask for complete inventories and we have
2464
# some parents that we can delta against. Make a delta against
2465
# each parent so that we can find the smallest.
2466
parent_ids = [parent_key[0] for parent_key in parent_keys]
2467
for parent_id in parent_ids:
2468
if parent_id not in invs_sent_so_far:
2469
# We don't know that the remote side has this basis, so
2472
if parent_id == _mod_revision.NULL_REVISION:
2473
parent_inv = null_inventory
2475
parent_inv = inventory_cache.get(parent_id, None)
2476
if parent_inv is None:
2477
parent_inv = from_repo.get_inventory(parent_id)
2478
candidate_delta = inv._make_delta(parent_inv)
2479
if (delta is None or
2480
len(delta) > len(candidate_delta)):
2481
delta = candidate_delta
2482
basis_id = parent_id
2484
# Either none of the parents ended up being suitable, or we
2485
# were asked to delta against NULL
2486
basis_id = _mod_revision.NULL_REVISION
2487
delta = inv._make_delta(null_inventory)
2488
invs_sent_so_far.add(inv.revision_id)
2489
inventory_cache[inv.revision_id] = inv
2490
delta_serialized = ''.join(
2491
serializer.delta_to_lines(basis_id, key[-1], delta))
2492
yield versionedfile.FulltextContentFactory(
2493
key, parent_keys, None, delta_serialized)
2496
class _VersionedFileChecker(object):
2498
def __init__(self, repository, text_key_references=None, ancestors=None):
2499
self.repository = repository
2500
self.text_index = self.repository._generate_text_key_index(
2501
text_key_references=text_key_references, ancestors=ancestors)
2503
def calculate_file_version_parents(self, text_key):
2504
"""Calculate the correct parents for a file version according to
2507
parent_keys = self.text_index[text_key]
2508
if parent_keys == [_mod_revision.NULL_REVISION]:
2510
return tuple(parent_keys)
2512
def check_file_version_parents(self, texts, progress_bar=None):
2513
"""Check the parents stored in a versioned file are correct.
2515
It also detects file versions that are not referenced by their
2516
corresponding revision's inventory.
2518
:returns: A tuple of (wrong_parents, dangling_file_versions).
2519
wrong_parents is a dict mapping {revision_id: (stored_parents,
2520
correct_parents)} for each revision_id where the stored parents
2521
are not correct. dangling_file_versions is a set of (file_id,
2522
revision_id) tuples for versions that are present in this versioned
2523
file, but not used by the corresponding inventory.
2525
local_progress = None
2526
if progress_bar is None:
2527
local_progress = ui.ui_factory.nested_progress_bar()
2528
progress_bar = local_progress
2530
return self._check_file_version_parents(texts, progress_bar)
2533
local_progress.finished()
2535
def _check_file_version_parents(self, texts, progress_bar):
2536
"""See check_file_version_parents."""
2538
self.file_ids = set([file_id for file_id, _ in
2539
self.text_index.iterkeys()])
2540
# text keys is now grouped by file_id
2541
n_versions = len(self.text_index)
2542
progress_bar.update(gettext('loading text store'), 0, n_versions)
2543
parent_map = self.repository.texts.get_parent_map(self.text_index)
2544
# On unlistable transports this could well be empty/error...
2545
text_keys = self.repository.texts.keys()
2546
unused_keys = frozenset(text_keys) - set(self.text_index)
2547
for num, key in enumerate(self.text_index.iterkeys()):
2548
progress_bar.update(gettext('checking text graph'), num, n_versions)
2549
correct_parents = self.calculate_file_version_parents(key)
2551
knit_parents = parent_map[key]
2552
except errors.RevisionNotPresent:
2555
if correct_parents != knit_parents:
2556
wrong_parents[key] = (knit_parents, correct_parents)
2557
return wrong_parents, unused_keys
2560
class InterVersionedFileRepository(InterRepository):
2562
_walk_to_common_revisions_batch_size = 50
2564
supports_fetch_spec = True
2567
def fetch(self, revision_id=None, find_ghosts=False,
2569
"""Fetch the content required to construct revision_id.
2571
The content is copied from self.source to self.target.
2573
:param revision_id: if None all content is copied, if NULL_REVISION no
2577
if self.target._format.experimental:
2578
ui.ui_factory.show_user_warning('experimental_format_fetch',
2579
from_format=self.source._format,
2580
to_format=self.target._format)
2581
from bzrlib.fetch import RepoFetcher
2582
# See <https://launchpad.net/bugs/456077> asking for a warning here
2583
if self.source._format.network_name() != self.target._format.network_name():
2584
ui.ui_factory.show_user_warning('cross_format_fetch',
2585
from_format=self.source._format,
2586
to_format=self.target._format)
2587
f = RepoFetcher(to_repository=self.target,
2588
from_repository=self.source,
2589
last_revision=revision_id,
2590
fetch_spec=fetch_spec,
2591
find_ghosts=find_ghosts)
2593
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2594
"""Walk out from revision_ids in source to revisions target has.
2596
:param revision_ids: The start point for the search.
2597
:return: A set of revision ids.
2599
target_graph = self.target.get_graph()
2600
revision_ids = frozenset(revision_ids)
2602
all_wanted_revs = revision_ids.union(if_present_ids)
2604
all_wanted_revs = revision_ids
2605
missing_revs = set()
2606
source_graph = self.source.get_graph()
2607
# ensure we don't pay silly lookup costs.
2608
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2609
null_set = frozenset([_mod_revision.NULL_REVISION])
2610
searcher_exhausted = False
2614
# Iterate the searcher until we have enough next_revs
2615
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2617
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2618
next_revs.update(next_revs_part)
2619
ghosts.update(ghosts_part)
2620
except StopIteration:
2621
searcher_exhausted = True
2623
# If there are ghosts in the source graph, and the caller asked for
2624
# them, make sure that they are present in the target.
2625
# We don't care about other ghosts as we can't fetch them and
2626
# haven't been asked to.
2627
ghosts_to_check = set(revision_ids.intersection(ghosts))
2628
revs_to_get = set(next_revs).union(ghosts_to_check)
2630
have_revs = set(target_graph.get_parent_map(revs_to_get))
2631
# we always have NULL_REVISION present.
2632
have_revs = have_revs.union(null_set)
2633
# Check if the target is missing any ghosts we need.
2634
ghosts_to_check.difference_update(have_revs)
2636
# One of the caller's revision_ids is a ghost in both the
2637
# source and the target.
2638
raise errors.NoSuchRevision(
2639
self.source, ghosts_to_check.pop())
2640
missing_revs.update(next_revs - have_revs)
2641
# Because we may have walked past the original stop point, make
2642
# sure everything is stopped
2643
stop_revs = searcher.find_seen_ancestors(have_revs)
2644
searcher.stop_searching_any(stop_revs)
2645
if searcher_exhausted:
2647
(started_keys, excludes, included_keys) = searcher.get_state()
2648
return vf_search.SearchResult(started_keys, excludes,
2649
len(included_keys), included_keys)
2652
def search_missing_revision_ids(self,
2653
revision_id=symbol_versioning.DEPRECATED_PARAMETER,
2654
find_ghosts=True, revision_ids=None, if_present_ids=None,
2656
"""Return the revision ids that source has that target does not.
2658
:param revision_id: only return revision ids included by this
2660
:param revision_ids: return revision ids included by these
2661
revision_ids. NoSuchRevision will be raised if any of these
2662
revisions are not present.
2663
:param if_present_ids: like revision_ids, but will not cause
2664
NoSuchRevision if any of these are absent, instead they will simply
2665
not be in the result. This is useful for e.g. finding revisions
2666
to fetch for tags, which may reference absent revisions.
2667
:param find_ghosts: If True find missing revisions in deep history
2668
rather than just finding the surface difference.
2669
:return: A bzrlib.graph.SearchResult.
2671
if symbol_versioning.deprecated_passed(revision_id):
2672
symbol_versioning.warn(
2673
'search_missing_revision_ids(revision_id=...) was '
2674
'deprecated in 2.4. Use revision_ids=[...] instead.',
2675
DeprecationWarning, stacklevel=2)
2676
if revision_ids is not None:
2677
raise AssertionError(
2678
'revision_ids is mutually exclusive with revision_id')
2679
if revision_id is not None:
2680
revision_ids = [revision_id]
2682
# stop searching at found target revisions.
2683
if not find_ghosts and (revision_ids is not None or if_present_ids is
2685
result = self._walk_to_common_revisions(revision_ids,
2686
if_present_ids=if_present_ids)
2689
result_set = result.get_keys()
2691
# generic, possibly worst case, slow code path.
2692
target_ids = set(self.target.all_revision_ids())
2693
source_ids = self._present_source_revisions_for(
2694
revision_ids, if_present_ids)
2695
result_set = set(source_ids).difference(target_ids)
2696
if limit is not None:
2697
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2698
result_set = set(itertools.islice(topo_ordered, limit))
2699
return self.source.revision_ids_to_search_result(result_set)
2701
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2702
"""Returns set of all revisions in ancestry of revision_ids present in
2705
:param revision_ids: if None, all revisions in source are returned.
2706
:param if_present_ids: like revision_ids, but if any/all of these are
2707
absent no error is raised.
2709
if revision_ids is not None or if_present_ids is not None:
2710
# First, ensure all specified revisions exist. Callers expect
2711
# NoSuchRevision when they pass absent revision_ids here.
2712
if revision_ids is None:
2713
revision_ids = set()
2714
if if_present_ids is None:
2715
if_present_ids = set()
2716
revision_ids = set(revision_ids)
2717
if_present_ids = set(if_present_ids)
2718
all_wanted_ids = revision_ids.union(if_present_ids)
2719
graph = self.source.get_graph()
2720
present_revs = set(graph.get_parent_map(all_wanted_ids))
2721
missing = revision_ids.difference(present_revs)
2723
raise errors.NoSuchRevision(self.source, missing.pop())
2724
found_ids = all_wanted_ids.intersection(present_revs)
2725
source_ids = [rev_id for (rev_id, parents) in
2726
graph.iter_ancestry(found_ids)
2727
if rev_id != _mod_revision.NULL_REVISION
2728
and parents is not None]
2730
source_ids = self.source.all_revision_ids()
2731
return set(source_ids)
2734
def _get_repo_format_to_test(self):
2738
def is_compatible(cls, source, target):
2739
# The default implementation is compatible with everything
2740
return (source._format.supports_full_versioned_files and
2741
target._format.supports_full_versioned_files)
2744
class InterDifferingSerializer(InterVersionedFileRepository):
2747
def _get_repo_format_to_test(self):
2751
def is_compatible(source, target):
2752
if not source._format.supports_full_versioned_files:
2754
if not target._format.supports_full_versioned_files:
2756
# This is redundant with format.check_conversion_target(), however that
2757
# raises an exception, and we just want to say "False" as in we won't
2758
# support converting between these formats.
2759
if 'IDS_never' in debug.debug_flags:
2761
if source.supports_rich_root() and not target.supports_rich_root():
2763
if (source._format.supports_tree_reference
2764
and not target._format.supports_tree_reference):
2766
if target._fallback_repositories and target._format.supports_chks:
2767
# IDS doesn't know how to copy CHKs for the parent inventories it
2768
# adds to stacked repos.
2770
if 'IDS_always' in debug.debug_flags:
2772
# Only use this code path for local source and target. IDS does far
2773
# too much IO (both bandwidth and roundtrips) over a network.
2774
if not source.bzrdir.transport.base.startswith('file:///'):
2776
if not target.bzrdir.transport.base.startswith('file:///'):
2780
def _get_trees(self, revision_ids, cache):
2782
for rev_id in revision_ids:
2784
possible_trees.append((rev_id, cache[rev_id]))
2786
# Not cached, but inventory might be present anyway.
2788
tree = self.source.revision_tree(rev_id)
2789
except errors.NoSuchRevision:
2790
# Nope, parent is ghost.
2793
cache[rev_id] = tree
2794
possible_trees.append((rev_id, tree))
2795
return possible_trees
2797
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2798
"""Get the best delta and base for this revision.
2800
:return: (basis_id, delta)
2803
# Generate deltas against each tree, to find the shortest.
2804
texts_possibly_new_in_tree = set()
2805
for basis_id, basis_tree in possible_trees:
2806
delta = tree.inventory._make_delta(basis_tree.inventory)
2807
for old_path, new_path, file_id, new_entry in delta:
2808
if new_path is None:
2809
# This file_id isn't present in the new rev, so we don't
2813
# Rich roots are handled elsewhere...
2815
kind = new_entry.kind
2816
if kind != 'directory' and kind != 'file':
2817
# No text record associated with this inventory entry.
2819
# This is a directory or file that has changed somehow.
2820
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2821
deltas.append((len(delta), basis_id, delta))
2823
return deltas[0][1:]
2825
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2826
"""Find all parent revisions that are absent, but for which the
2827
inventory is present, and copy those inventories.
2829
This is necessary to preserve correctness when the source is stacked
2830
without fallbacks configured. (Note that in cases like upgrade the
2831
source may be not have _fallback_repositories even though it is
2835
for parents in parent_map.values():
2836
parent_revs.update(parents)
2837
present_parents = self.source.get_parent_map(parent_revs)
2838
absent_parents = set(parent_revs).difference(present_parents)
2839
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2840
(rev_id,) for rev_id in absent_parents)
2841
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2842
for parent_tree in self.source.revision_trees(parent_inv_ids):
2843
current_revision_id = parent_tree.get_revision_id()
2844
parents_parents_keys = parent_invs_keys_for_stacking[
2845
(current_revision_id,)]
2846
parents_parents = [key[-1] for key in parents_parents_keys]
2847
basis_id = _mod_revision.NULL_REVISION
2848
basis_tree = self.source.revision_tree(basis_id)
2849
delta = parent_tree.inventory._make_delta(basis_tree.inventory)
2850
self.target.add_inventory_by_delta(
2851
basis_id, delta, current_revision_id, parents_parents)
2852
cache[current_revision_id] = parent_tree
2854
def _fetch_batch(self, revision_ids, basis_id, cache):
2855
"""Fetch across a few revisions.
2857
:param revision_ids: The revisions to copy
2858
:param basis_id: The revision_id of a tree that must be in cache, used
2859
as a basis for delta when no other base is available
2860
:param cache: A cache of RevisionTrees that we can use.
2861
:return: The revision_id of the last converted tree. The RevisionTree
2862
for it will be in cache
2864
# Walk though all revisions; get inventory deltas, copy referenced
2865
# texts that delta references, insert the delta, revision and
2867
root_keys_to_create = set()
2870
pending_revisions = []
2871
parent_map = self.source.get_parent_map(revision_ids)
2872
self._fetch_parent_invs_for_stacking(parent_map, cache)
2873
self.source._safe_to_return_from_cache = True
2874
for tree in self.source.revision_trees(revision_ids):
2875
# Find a inventory delta for this revision.
2876
# Find text entries that need to be copied, too.
2877
current_revision_id = tree.get_revision_id()
2878
parent_ids = parent_map.get(current_revision_id, ())
2879
parent_trees = self._get_trees(parent_ids, cache)
2880
possible_trees = list(parent_trees)
2881
if len(possible_trees) == 0:
2882
# There either aren't any parents, or the parents are ghosts,
2883
# so just use the last converted tree.
2884
possible_trees.append((basis_id, cache[basis_id]))
2885
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2887
revision = self.source.get_revision(current_revision_id)
2888
pending_deltas.append((basis_id, delta,
2889
current_revision_id, revision.parent_ids))
2890
if self._converting_to_rich_root:
2891
self._revision_id_to_root_id[current_revision_id] = \
2893
# Determine which texts are in present in this revision but not in
2894
# any of the available parents.
2895
texts_possibly_new_in_tree = set()
2896
for old_path, new_path, file_id, entry in delta:
2897
if new_path is None:
2898
# This file_id isn't present in the new rev
2902
if not self.target.supports_rich_root():
2903
# The target doesn't support rich root, so we don't
2906
if self._converting_to_rich_root:
2907
# This can't be copied normally, we have to insert
2909
root_keys_to_create.add((file_id, entry.revision))
2912
texts_possibly_new_in_tree.add((file_id, entry.revision))
2913
for basis_id, basis_tree in possible_trees:
2914
basis_inv = basis_tree.inventory
2915
for file_key in list(texts_possibly_new_in_tree):
2916
file_id, file_revision = file_key
2918
entry = basis_inv[file_id]
2919
except errors.NoSuchId:
2921
if entry.revision == file_revision:
2922
texts_possibly_new_in_tree.remove(file_key)
2923
text_keys.update(texts_possibly_new_in_tree)
2924
pending_revisions.append(revision)
2925
cache[current_revision_id] = tree
2926
basis_id = current_revision_id
2927
self.source._safe_to_return_from_cache = False
2929
from_texts = self.source.texts
2930
to_texts = self.target.texts
2931
if root_keys_to_create:
2932
root_stream = _mod_fetch._new_root_data_stream(
2933
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2935
to_texts.insert_record_stream(root_stream)
2936
to_texts.insert_record_stream(from_texts.get_record_stream(
2937
text_keys, self.target._format._fetch_order,
2938
not self.target._format._fetch_uses_deltas))
2939
# insert inventory deltas
2940
for delta in pending_deltas:
2941
self.target.add_inventory_by_delta(*delta)
2942
if self.target._fallback_repositories:
2943
# Make sure this stacked repository has all the parent inventories
2944
# for the new revisions that we are about to insert. We do this
2945
# before adding the revisions so that no revision is added until
2946
# all the inventories it may depend on are added.
2947
# Note that this is overzealous, as we may have fetched these in an
2950
revision_ids = set()
2951
for revision in pending_revisions:
2952
revision_ids.add(revision.revision_id)
2953
parent_ids.update(revision.parent_ids)
2954
parent_ids.difference_update(revision_ids)
2955
parent_ids.discard(_mod_revision.NULL_REVISION)
2956
parent_map = self.source.get_parent_map(parent_ids)
2957
# we iterate over parent_map and not parent_ids because we don't
2958
# want to try copying any revision which is a ghost
2959
for parent_tree in self.source.revision_trees(parent_map):
2960
current_revision_id = parent_tree.get_revision_id()
2961
parents_parents = parent_map[current_revision_id]
2962
possible_trees = self._get_trees(parents_parents, cache)
2963
if len(possible_trees) == 0:
2964
# There either aren't any parents, or the parents are
2965
# ghosts, so just use the last converted tree.
2966
possible_trees.append((basis_id, cache[basis_id]))
2967
basis_id, delta = self._get_delta_for_revision(parent_tree,
2968
parents_parents, possible_trees)
2969
self.target.add_inventory_by_delta(
2970
basis_id, delta, current_revision_id, parents_parents)
2971
# insert signatures and revisions
2972
for revision in pending_revisions:
2974
signature = self.source.get_signature_text(
2975
revision.revision_id)
2976
self.target.add_signature_text(revision.revision_id,
2978
except errors.NoSuchRevision:
2980
self.target.add_revision(revision.revision_id, revision)
2983
def _fetch_all_revisions(self, revision_ids, pb):
2984
"""Fetch everything for the list of revisions.
2986
:param revision_ids: The list of revisions to fetch. Must be in
2988
:param pb: A ProgressTask
2991
basis_id, basis_tree = self._get_basis(revision_ids[0])
2993
cache = lru_cache.LRUCache(100)
2994
cache[basis_id] = basis_tree
2995
del basis_tree # We don't want to hang on to it here
2999
for offset in range(0, len(revision_ids), batch_size):
3000
self.target.start_write_group()
3002
pb.update(gettext('Transferring revisions'), offset,
3004
batch = revision_ids[offset:offset+batch_size]
3005
basis_id = self._fetch_batch(batch, basis_id, cache)
3007
self.source._safe_to_return_from_cache = False
3008
self.target.abort_write_group()
3011
hint = self.target.commit_write_group()
3014
if hints and self.target._format.pack_compresses:
3015
self.target.pack(hint=hints)
3016
pb.update(gettext('Transferring revisions'), len(revision_ids),
3020
def fetch(self, revision_id=None, find_ghosts=False,
3022
"""See InterRepository.fetch()."""
3023
if fetch_spec is not None:
3024
revision_ids = fetch_spec.get_keys()
3027
if self.source._format.experimental:
3028
ui.ui_factory.show_user_warning('experimental_format_fetch',
3029
from_format=self.source._format,
3030
to_format=self.target._format)
3031
if (not self.source.supports_rich_root()
3032
and self.target.supports_rich_root()):
3033
self._converting_to_rich_root = True
3034
self._revision_id_to_root_id = {}
3036
self._converting_to_rich_root = False
3037
# See <https://launchpad.net/bugs/456077> asking for a warning here
3038
if self.source._format.network_name() != self.target._format.network_name():
3039
ui.ui_factory.show_user_warning('cross_format_fetch',
3040
from_format=self.source._format,
3041
to_format=self.target._format)
3042
if revision_ids is None:
3044
search_revision_ids = [revision_id]
3046
search_revision_ids = None
3047
revision_ids = self.target.search_missing_revision_ids(self.source,
3048
revision_ids=search_revision_ids,
3049
find_ghosts=find_ghosts).get_keys()
3050
if not revision_ids:
3052
revision_ids = tsort.topo_sort(
3053
self.source.get_graph().get_parent_map(revision_ids))
3054
if not revision_ids:
3056
# Walk though all revisions; get inventory deltas, copy referenced
3057
# texts that delta references, insert the delta, revision and
3059
pb = ui.ui_factory.nested_progress_bar()
3061
self._fetch_all_revisions(revision_ids, pb)
3064
return len(revision_ids), 0
3066
def _get_basis(self, first_revision_id):
3067
"""Get a revision and tree which exists in the target.
3069
This assumes that first_revision_id is selected for transmission
3070
because all other ancestors are already present. If we can't find an
3071
ancestor we fall back to NULL_REVISION since we know that is safe.
3073
:return: (basis_id, basis_tree)
3075
first_rev = self.source.get_revision(first_revision_id)
3077
basis_id = first_rev.parent_ids[0]
3078
# only valid as a basis if the target has it
3079
self.target.get_revision(basis_id)
3080
# Try to get a basis tree - if it's a ghost it will hit the
3081
# NoSuchRevision case.
3082
basis_tree = self.source.revision_tree(basis_id)
3083
except (IndexError, errors.NoSuchRevision):
3084
basis_id = _mod_revision.NULL_REVISION
3085
basis_tree = self.source.revision_tree(basis_id)
3086
return basis_id, basis_tree
3089
class InterSameDataRepository(InterVersionedFileRepository):
3090
"""Code for converting between repositories that represent the same data.
3092
Data format and model must match for this to work.
3096
def _get_repo_format_to_test(self):
3097
"""Repository format for testing with.
3099
InterSameData can pull from subtree to subtree and from non-subtree to
3100
non-subtree, so we test this with the richest repository format.
3102
from bzrlib.repofmt import knitrepo
3103
return knitrepo.RepositoryFormatKnit3()
3106
def is_compatible(source, target):
3108
InterRepository._same_model(source, target) and
3109
source._format.supports_full_versioned_files and
3110
target._format.supports_full_versioned_files)
3113
InterRepository.register_optimiser(InterVersionedFileRepository)
3114
InterRepository.register_optimiser(InterDifferingSerializer)
3115
InterRepository.register_optimiser(InterSameDataRepository)
3118
def install_revisions(repository, iterable, num_revisions=None, pb=None):
3119
"""Install all revision data into a repository.
3121
Accepts an iterable of revision, tree, signature tuples. The signature
3124
repository.start_write_group()
3126
inventory_cache = lru_cache.LRUCache(10)
3127
for n, (revision, revision_tree, signature) in enumerate(iterable):
3128
_install_revision(repository, revision, revision_tree, signature,
3131
pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
3133
repository.abort_write_group()
3136
repository.commit_write_group()
3139
def _install_revision(repository, rev, revision_tree, signature,
3141
"""Install all revision data into a repository."""
3142
present_parents = []
3144
for p_id in rev.parent_ids:
3145
if repository.has_revision(p_id):
3146
present_parents.append(p_id)
3147
parent_trees[p_id] = repository.revision_tree(p_id)
3149
parent_trees[p_id] = repository.revision_tree(
3150
_mod_revision.NULL_REVISION)
3152
inv = revision_tree.inventory
3153
entries = inv.iter_entries()
3154
# backwards compatibility hack: skip the root id.
3155
if not repository.supports_rich_root():
3156
path, root = entries.next()
3157
if root.revision != rev.revision_id:
3158
raise errors.IncompatibleRevision(repr(repository))
3160
for path, ie in entries:
3161
text_keys[(ie.file_id, ie.revision)] = ie
3162
text_parent_map = repository.texts.get_parent_map(text_keys)
3163
missing_texts = set(text_keys) - set(text_parent_map)
3164
# Add the texts that are not already present
3165
for text_key in missing_texts:
3166
ie = text_keys[text_key]
3168
# FIXME: TODO: The following loop overlaps/duplicates that done by
3169
# commit to determine parents. There is a latent/real bug here where
3170
# the parents inserted are not those commit would do - in particular
3171
# they are not filtered by heads(). RBC, AB
3172
for revision, tree in parent_trees.iteritems():
3173
if not tree.has_id(ie.file_id):
3175
parent_id = tree.get_file_revision(ie.file_id)
3176
if parent_id in text_parents:
3178
text_parents.append((ie.file_id, parent_id))
3179
lines = revision_tree.get_file(ie.file_id).readlines()
3180
repository.texts.add_lines(text_key, text_parents, lines)
3182
# install the inventory
3183
if repository._format._commit_inv_deltas and len(rev.parent_ids):
3184
# Cache this inventory
3185
inventory_cache[rev.revision_id] = inv
3187
basis_inv = inventory_cache[rev.parent_ids[0]]
3189
repository.add_inventory(rev.revision_id, inv, present_parents)
3191
delta = inv._make_delta(basis_inv)
3192
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
3193
rev.revision_id, present_parents)
3195
repository.add_inventory(rev.revision_id, inv, present_parents)
3196
except errors.RevisionAlreadyPresent:
3198
if signature is not None:
3199
repository.add_signature_text(rev.revision_id, signature)
3200
repository.add_revision(rev.revision_id, rev, inv)
3203
def install_revision(repository, rev, revision_tree):
3204
"""Install all revision data into a repository."""
3205
install_revisions(repository, [(rev, revision_tree, None)])