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 .lazy_import import lazy_import
23
lazy_import(globals(), """
28
config as _mod_config,
37
revision as _mod_revision,
38
serializer as _mod_serializer,
46
from breezy.recordcounter import RecordCounter
47
from breezy.inventorytree import InventoryRevisionTree
48
from breezy.testament import Testament
49
from breezy.i18n import gettext
55
from .decorators import (
60
from .inventory import (
67
from .repository import (
73
from .bzrrepository import (
75
RepositoryFormatMetaDir,
89
class VersionedFileRepositoryFormat(RepositoryFormat):
90
"""Base class for all repository formats that are VersionedFiles-based."""
92
supports_full_versioned_files = True
93
supports_versioned_directories = True
94
supports_unreferenced_revisions = True
96
# Should commit add an inventory, or an inventory delta to the repository.
97
_commit_inv_deltas = True
98
# What order should fetch operations request streams in?
99
# The default is unordered as that is the cheapest for an origin to
101
_fetch_order = 'unordered'
102
# Does this repository format use deltas that can be fetched as-deltas ?
103
# (E.g. knits, where the knit deltas can be transplanted intact.
104
# We default to False, which will ensure that enough data to get
105
# a full text out of any fetch stream will be grabbed.
106
_fetch_uses_deltas = False
109
class VersionedFileCommitBuilder(CommitBuilder):
110
"""Commit builder implementation for versioned files based repositories.
113
# this commit builder supports the record_entry_contents interface
114
supports_record_entry_contents = True
116
# the default CommitBuilder does not manage trees whose root is versioned.
117
_versioned_root = False
119
def __init__(self, repository, parents, config_stack, timestamp=None,
120
timezone=None, committer=None, revprops=None,
121
revision_id=None, lossy=False):
122
super(VersionedFileCommitBuilder, self).__init__(repository,
123
parents, config_stack, timestamp, timezone, committer, revprops,
126
basis_id = self.parents[0]
128
basis_id = _mod_revision.NULL_REVISION
129
self.basis_delta_revision = basis_id
130
self.new_inventory = Inventory(None)
131
self._basis_delta = []
132
self.__heads = graph.HeadsCache(repository.get_graph()).heads
133
# memo'd check for no-op commits.
134
self._any_changes = False
135
# API compatibility, older code that used CommitBuilder did not call
136
# .record_delete(), which means the delta that is computed would not be
137
# valid. Callers that will call record_delete() should call
138
# .will_record_deletes() to indicate that.
139
self._recording_deletes = False
141
def will_record_deletes(self):
142
"""Tell the commit builder that deletes are being notified.
144
This enables the accumulation of an inventory delta; for the resulting
145
commit to be valid, deletes against the basis MUST be recorded via
146
builder.record_delete().
148
self._recording_deletes = True
150
def any_changes(self):
151
"""Return True if any entries were changed.
153
This includes merge-only changes. It is the core for the --unchanged
156
:return: True if any changes have occured.
158
return self._any_changes
160
def _ensure_fallback_inventories(self):
161
"""Ensure that appropriate inventories are available.
163
This only applies to repositories that are stacked, and is about
164
enusring the stacking invariants. Namely, that for any revision that is
165
present, we either have all of the file content, or we have the parent
166
inventory and the delta file content.
168
if not self.repository._fallback_repositories:
170
if not self.repository._format.supports_chks:
171
raise errors.BzrError("Cannot commit directly to a stacked branch"
172
" in pre-2a formats. See "
173
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
174
# This is a stacked repo, we need to make sure we have the parent
175
# inventories for the parents.
176
parent_keys = [(p,) for p in self.parents]
177
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
178
missing_parent_keys = {pk for pk in parent_keys
179
if pk not in parent_map}
180
fallback_repos = list(reversed(self.repository._fallback_repositories))
181
missing_keys = [('inventories', pk[0])
182
for pk in missing_parent_keys]
184
while missing_keys and fallback_repos:
185
fallback_repo = fallback_repos.pop()
186
source = fallback_repo._get_source(self.repository._format)
187
sink = self.repository._get_sink()
188
stream = source.get_stream_for_missing_keys(missing_keys)
189
missing_keys = sink.insert_stream_without_locking(stream,
190
self.repository._format)
192
raise errors.BzrError('Unable to fill in parent inventories for a'
195
def commit(self, message):
196
"""Make the actual commit.
198
:return: The revision id of the recorded revision.
200
self._validate_unicode_text(message, 'commit message')
201
rev = _mod_revision.Revision(
202
timestamp=self._timestamp,
203
timezone=self._timezone,
204
committer=self._committer,
206
inventory_sha1=self.inv_sha1,
207
revision_id=self._new_revision_id,
208
properties=self._revprops)
209
rev.parent_ids = self.parents
210
if self._config_stack.get('create_signatures') == _mod_config.SIGN_ALWAYS:
211
testament = Testament(rev, self.revision_tree())
212
plaintext = testament.as_short_text()
213
self.repository.store_revision_signature(
214
gpg.GPGStrategy(self._config_stack), plaintext,
215
self._new_revision_id)
216
self.repository._add_revision(rev)
217
self._ensure_fallback_inventories()
218
self.repository.commit_write_group()
219
return self._new_revision_id
222
"""Abort the commit that is being built.
224
self.repository.abort_write_group()
226
def revision_tree(self):
227
"""Return the tree that was just committed.
229
After calling commit() this can be called to get a
230
RevisionTree representing the newly committed tree. This is
231
preferred to calling Repository.revision_tree() because that may
232
require deserializing the inventory, while we already have a copy in
235
if self.new_inventory is None:
236
self.new_inventory = self.repository.get_inventory(
237
self._new_revision_id)
238
return InventoryRevisionTree(self.repository, self.new_inventory,
239
self._new_revision_id)
241
def finish_inventory(self):
242
"""Tell the builder that the inventory is finished.
244
:return: The inventory id in the repository, which can be used with
245
repository.get_inventory.
247
if self.new_inventory is None:
248
# an inventory delta was accumulated without creating a new
250
basis_id = self.basis_delta_revision
251
# We ignore the 'inventory' returned by add_inventory_by_delta
252
# because self.new_inventory is used to hint to the rest of the
253
# system what code path was taken
254
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
255
basis_id, self._basis_delta, self._new_revision_id,
258
if self.new_inventory.root is None:
259
raise AssertionError('Root entry should be supplied to'
260
' record_entry_contents, as of bzr 0.10.')
261
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
262
self.new_inventory.revision_id = self._new_revision_id
263
self.inv_sha1 = self.repository.add_inventory(
264
self._new_revision_id,
268
return self._new_revision_id
270
def _check_root(self, ie, parent_invs, tree):
271
"""Helper for record_entry_contents.
273
:param ie: An entry being added.
274
:param parent_invs: The inventories of the parent revisions of the
276
:param tree: The tree that is being committed.
278
# In this revision format, root entries have no knit or weave When
279
# serializing out to disk and back in root.revision is always
281
ie.revision = self._new_revision_id
283
def _require_root_change(self, tree):
284
"""Enforce an appropriate root object change.
286
This is called once when record_iter_changes is called, if and only if
287
the root was not in the delta calculated by record_iter_changes.
289
:param tree: The tree which is being committed.
291
if len(self.parents) == 0:
292
raise errors.RootMissing()
293
entry = entry_factory['directory'](tree.path2id(''), '',
295
entry.revision = self._new_revision_id
296
self._basis_delta.append(('', '', entry.file_id, entry))
298
def _get_delta(self, ie, basis_inv, path):
299
"""Get a delta against the basis inventory for ie."""
300
if not basis_inv.has_id(ie.file_id):
302
result = (None, path, ie.file_id, ie)
303
self._basis_delta.append(result)
305
elif ie != basis_inv[ie.file_id]:
307
# TODO: avoid tis id2path call.
308
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
309
self._basis_delta.append(result)
315
def _heads(self, file_id, revision_ids):
316
"""Calculate the graph heads for revision_ids in the graph of file_id.
318
This can use either a per-file graph or a global revision graph as we
319
have an identity relationship between the two graphs.
321
return self.__heads(revision_ids)
323
def get_basis_delta(self):
324
"""Return the complete inventory delta versus the basis inventory.
326
This has been built up with the calls to record_delete and
327
record_entry_contents. The client must have already called
328
will_record_deletes() to indicate that they will be generating a
331
:return: An inventory delta, suitable for use with apply_delta, or
332
Repository.add_inventory_by_delta, etc.
334
if not self._recording_deletes:
335
raise AssertionError("recording deletes not activated.")
336
return self._basis_delta
338
def record_delete(self, path, file_id):
339
"""Record that a delete occured against a basis tree.
341
This is an optional API - when used it adds items to the basis_delta
342
being accumulated by the commit builder. It cannot be called unless the
343
method will_record_deletes() has been called to inform the builder that
344
a delta is being supplied.
346
:param path: The path of the thing deleted.
347
:param file_id: The file id that was deleted.
349
if not self._recording_deletes:
350
raise AssertionError("recording deletes not activated.")
351
delta = (path, None, file_id, None)
352
self._basis_delta.append(delta)
353
self._any_changes = True
356
def record_entry_contents(self, ie, parent_invs, path, tree,
358
"""Record the content of ie from tree into the commit if needed.
360
Side effect: sets ie.revision when unchanged
362
:param ie: An inventory entry present in the commit.
363
:param parent_invs: The inventories of the parent revisions of the
365
:param path: The path the entry is at in the tree.
366
:param tree: The tree which contains this entry and should be used to
368
:param content_summary: Summary data from the tree about the paths
369
content - stat, length, exec, sha/link target. This is only
370
accessed when the entry has a revision of None - that is when it is
371
a candidate to commit.
372
:return: A tuple (change_delta, version_recorded, fs_hash).
373
change_delta is an inventory_delta change for this entry against
374
the basis tree of the commit, or None if no change occured against
376
version_recorded is True if a new version of the entry has been
377
recorded. For instance, committing a merge where a file was only
378
changed on the other side will return (delta, False).
379
fs_hash is either None, or the hash details for the path (currently
380
a tuple of the contents sha1 and the statvalue returned by
381
tree.get_file_with_stat()).
383
if self.new_inventory.root is None:
384
if ie.parent_id is not None:
385
raise errors.RootMissing()
386
self._check_root(ie, parent_invs, tree)
387
if ie.revision is None:
388
kind = content_summary[0]
390
# ie is carried over from a prior commit
392
# XXX: repository specific check for nested tree support goes here - if
393
# the repo doesn't want nested trees we skip it ?
394
if (kind == 'tree-reference' and
395
not self.repository._format.supports_tree_reference):
396
# mismatch between commit builder logic and repository:
397
# this needs the entry creation pushed down into the builder.
398
raise NotImplementedError('Missing repository subtree support.')
399
self.new_inventory.add(ie)
401
# TODO: slow, take it out of the inner loop.
403
basis_inv = parent_invs[0]
405
basis_inv = Inventory(root_id=None)
407
# ie.revision is always None if the InventoryEntry is considered
408
# for committing. We may record the previous parents revision if the
409
# content is actually unchanged against a sole head.
410
if ie.revision is not None:
411
if not self._versioned_root and path == '':
412
# repositories that do not version the root set the root's
413
# revision to the new commit even when no change occurs (more
414
# specifically, they do not record a revision on the root; and
415
# the rev id is assigned to the root during deserialisation -
416
# this masks when a change may have occurred against the basis.
417
# To match this we always issue a delta, because the revision
418
# of the root will always be changing.
419
if basis_inv.has_id(ie.file_id):
420
delta = (basis_inv.id2path(ie.file_id), path,
424
delta = (None, path, ie.file_id, ie)
425
self._basis_delta.append(delta)
426
return delta, False, None
428
# we don't need to commit this, because the caller already
429
# determined that an existing revision of this file is
430
# appropriate. If it's not being considered for committing then
431
# it and all its parents to the root must be unaltered so
432
# no-change against the basis.
433
if ie.revision == self._new_revision_id:
434
raise AssertionError("Impossible situation, a skipped "
435
"inventory entry (%r) claims to be modified in this "
436
"commit (%r).", (ie, self._new_revision_id))
437
return None, False, None
438
# XXX: Friction: parent_candidates should return a list not a dict
439
# so that we don't have to walk the inventories again.
440
parent_candidate_entries = ie.parent_candidates(parent_invs)
441
head_set = self._heads(ie.file_id, parent_candidate_entries)
443
for inv in parent_invs:
444
if inv.has_id(ie.file_id):
445
old_rev = inv[ie.file_id].revision
446
if old_rev in head_set:
447
heads.append(inv[ie.file_id].revision)
448
head_set.remove(inv[ie.file_id].revision)
451
# now we check to see if we need to write a new record to the
453
# We write a new entry unless there is one head to the ancestors, and
454
# the kind-derived content is unchanged.
456
# Cheapest check first: no ancestors, or more the one head in the
457
# ancestors, we write a new node.
461
# There is a single head, look it up for comparison
462
parent_entry = parent_candidate_entries[heads[0]]
463
# if the non-content specific data has changed, we'll be writing a
465
if (parent_entry.parent_id != ie.parent_id or
466
parent_entry.name != ie.name):
468
# now we need to do content specific checks:
470
# if the kind changed the content obviously has
471
if kind != parent_entry.kind:
473
# Stat cache fingerprint feedback for the caller - None as we usually
474
# don't generate one.
477
if content_summary[2] is None:
478
raise ValueError("Files must not have executable = None")
480
# We can't trust a check of the file length because of content
482
if (# if the exec bit has changed we have to store:
483
parent_entry.executable != content_summary[2]):
485
elif parent_entry.text_sha1 == content_summary[3]:
486
# all meta and content is unchanged (using a hash cache
487
# hit to check the sha)
488
ie.revision = parent_entry.revision
489
ie.text_size = parent_entry.text_size
490
ie.text_sha1 = parent_entry.text_sha1
491
ie.executable = parent_entry.executable
492
return self._get_delta(ie, basis_inv, path), False, None
494
# Either there is only a hash change(no hash cache entry,
495
# or same size content change), or there is no change on
497
# Provide the parent's hash to the store layer, so that the
498
# content is unchanged we will not store a new node.
499
nostore_sha = parent_entry.text_sha1
501
# We want to record a new node regardless of the presence or
502
# absence of a content change in the file.
504
ie.executable = content_summary[2]
505
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
507
text = file_obj.read()
511
ie.text_sha1, ie.text_size = self._add_text_to_weave(
512
ie.file_id, text, heads, nostore_sha)
513
# Let the caller know we generated a stat fingerprint.
514
fingerprint = (ie.text_sha1, stat_value)
515
except errors.ExistingContent:
516
# Turns out that the file content was unchanged, and we were
517
# only going to store a new node if it was changed. Carry over
519
ie.revision = parent_entry.revision
520
ie.text_size = parent_entry.text_size
521
ie.text_sha1 = parent_entry.text_sha1
522
ie.executable = parent_entry.executable
523
return self._get_delta(ie, basis_inv, path), False, None
524
elif kind == 'directory':
526
# all data is meta here, nothing specific to directory, so
528
ie.revision = parent_entry.revision
529
return self._get_delta(ie, basis_inv, path), False, None
530
self._add_text_to_weave(ie.file_id, '', heads, None)
531
elif kind == 'symlink':
532
current_link_target = content_summary[3]
534
# symlink target is not generic metadata, check if it has
536
if current_link_target != parent_entry.symlink_target:
539
# unchanged, carry over.
540
ie.revision = parent_entry.revision
541
ie.symlink_target = parent_entry.symlink_target
542
return self._get_delta(ie, basis_inv, path), False, None
543
ie.symlink_target = current_link_target
544
self._add_text_to_weave(ie.file_id, '', heads, None)
545
elif kind == 'tree-reference':
547
if content_summary[3] != parent_entry.reference_revision:
550
# unchanged, carry over.
551
ie.reference_revision = parent_entry.reference_revision
552
ie.revision = parent_entry.revision
553
return self._get_delta(ie, basis_inv, path), False, None
554
ie.reference_revision = content_summary[3]
555
if ie.reference_revision is None:
556
raise AssertionError("invalid content_summary for nested tree: %r"
557
% (content_summary,))
558
self._add_text_to_weave(ie.file_id, '', heads, None)
560
raise NotImplementedError('unknown kind')
561
ie.revision = self._new_revision_id
562
# The initial commit adds a root directory, but this in itself is not
563
# a worthwhile commit.
564
if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
566
self._any_changes = True
567
return self._get_delta(ie, basis_inv, path), True, fingerprint
569
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
570
_entry_factory=entry_factory):
571
"""Record a new tree via iter_changes.
573
:param tree: The tree to obtain text contents from for changed objects.
574
:param basis_revision_id: The revision id of the tree the iter_changes
575
has been generated against. Currently assumed to be the same
576
as self.parents[0] - if it is not, errors may occur.
577
:param iter_changes: An iter_changes iterator with the changes to apply
578
to basis_revision_id. The iterator must not include any items with
579
a current kind of None - missing items must be either filtered out
580
or errored-on before record_iter_changes sees the item.
581
:param _entry_factory: Private method to bind entry_factory locally for
583
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
586
# Create an inventory delta based on deltas between all the parents and
587
# deltas between all the parent inventories. We use inventory delta's
588
# between the inventory objects because iter_changes masks
589
# last-changed-field only changes.
591
# file_id -> change map, change is fileid, paths, changed, versioneds,
592
# parents, names, kinds, executables
594
# {file_id -> revision_id -> inventory entry, for entries in parent
595
# trees that are not parents[0]
599
revtrees = list(self.repository.revision_trees(self.parents))
600
except errors.NoSuchRevision:
601
# one or more ghosts, slow path.
603
for revision_id in self.parents:
605
revtrees.append(self.repository.revision_tree(revision_id))
606
except errors.NoSuchRevision:
608
basis_revision_id = _mod_revision.NULL_REVISION
610
revtrees.append(self.repository.revision_tree(
611
_mod_revision.NULL_REVISION))
612
# The basis inventory from a repository
614
basis_tree = revtrees[0]
616
basis_tree = self.repository.revision_tree(
617
_mod_revision.NULL_REVISION)
618
basis_inv = basis_tree.root_inventory
619
if len(self.parents) > 0:
620
if basis_revision_id != self.parents[0] and not ghost_basis:
622
"arbitrary basis parents not yet supported with merges")
623
for revtree in revtrees[1:]:
624
for change in revtree.root_inventory._make_delta(basis_inv):
625
if change[1] is None:
626
# Not present in this parent.
628
if change[2] not in merged_ids:
629
if change[0] is not None:
630
basis_entry = basis_inv[change[2]]
631
merged_ids[change[2]] = [
633
basis_entry.revision,
636
parent_entries[change[2]] = {
638
basis_entry.revision:basis_entry,
640
change[3].revision:change[3],
643
merged_ids[change[2]] = [change[3].revision]
644
parent_entries[change[2]] = {change[3].revision:change[3]}
646
merged_ids[change[2]].append(change[3].revision)
647
parent_entries[change[2]][change[3].revision] = change[3]
650
# Setup the changes from the tree:
651
# changes maps file_id -> (change, [parent revision_ids])
653
for change in iter_changes:
654
# This probably looks up in basis_inv way to much.
655
if change[1][0] is not None:
656
head_candidate = [basis_inv[change[0]].revision]
659
changes[change[0]] = change, merged_ids.get(change[0],
661
unchanged_merged = set(merged_ids) - set(changes)
662
# Extend the changes dict with synthetic changes to record merges of
664
for file_id in unchanged_merged:
665
# Record a merged version of these items that did not change vs the
666
# basis. This can be either identical parallel changes, or a revert
667
# of a specific file after a merge. The recorded content will be
668
# that of the current tree (which is the same as the basis), but
669
# the per-file graph will reflect a merge.
670
# NB:XXX: We are reconstructing path information we had, this
671
# should be preserved instead.
672
# inv delta change: (file_id, (path_in_source, path_in_target),
673
# changed_content, versioned, parent, name, kind,
676
basis_entry = basis_inv[file_id]
677
except errors.NoSuchId:
678
# a change from basis->some_parents but file_id isn't in basis
679
# so was new in the merge, which means it must have changed
680
# from basis -> current, and as it hasn't the add was reverted
681
# by the user. So we discard this change.
685
(basis_inv.id2path(file_id), tree.id2path(file_id)),
687
(basis_entry.parent_id, basis_entry.parent_id),
688
(basis_entry.name, basis_entry.name),
689
(basis_entry.kind, basis_entry.kind),
690
(basis_entry.executable, basis_entry.executable))
691
changes[file_id] = (change, merged_ids[file_id])
692
# changes contains tuples with the change and a set of inventory
693
# candidates for the file.
695
# old_path, new_path, file_id, new_inventory_entry
696
seen_root = False # Is the root in the basis delta?
697
inv_delta = self._basis_delta
698
modified_rev = self._new_revision_id
699
for change, head_candidates in viewvalues(changes):
700
if change[3][1]: # versioned in target.
701
# Several things may be happening here:
702
# We may have a fork in the per-file graph
703
# - record a change with the content from tree
704
# We may have a change against < all trees
705
# - carry over the tree that hasn't changed
706
# We may have a change against all trees
707
# - record the change with the content from tree
710
entry = _entry_factory[kind](file_id, change[5][1],
712
head_set = self._heads(change[0], set(head_candidates))
715
for head_candidate in head_candidates:
716
if head_candidate in head_set:
717
heads.append(head_candidate)
718
head_set.remove(head_candidate)
721
# Could be a carry-over situation:
722
parent_entry_revs = parent_entries.get(file_id, None)
723
if parent_entry_revs:
724
parent_entry = parent_entry_revs.get(heads[0], None)
727
if parent_entry is None:
728
# The parent iter_changes was called against is the one
729
# that is the per-file head, so any change is relevant
730
# iter_changes is valid.
731
carry_over_possible = False
733
# could be a carry over situation
734
# A change against the basis may just indicate a merge,
735
# we need to check the content against the source of the
736
# merge to determine if it was changed after the merge
738
if (parent_entry.kind != entry.kind or
739
parent_entry.parent_id != entry.parent_id or
740
parent_entry.name != entry.name):
741
# Metadata common to all entries has changed
742
# against per-file parent
743
carry_over_possible = False
745
carry_over_possible = True
746
# per-type checks for changes against the parent_entry
749
# Cannot be a carry-over situation
750
carry_over_possible = False
751
# Populate the entry in the delta
753
# XXX: There is still a small race here: If someone reverts the content of a file
754
# after iter_changes examines and decides it has changed,
755
# we will unconditionally record a new version even if some
756
# other process reverts it while commit is running (with
757
# the revert happening after iter_changes did its
760
entry.executable = True
762
entry.executable = False
763
if (carry_over_possible and
764
parent_entry.executable == entry.executable):
765
# Check the file length, content hash after reading
767
nostore_sha = parent_entry.text_sha1
770
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
772
text = file_obj.read()
776
entry.text_sha1, entry.text_size = self._add_text_to_weave(
777
file_id, text, heads, nostore_sha)
778
yield file_id, change[1][1], (entry.text_sha1, stat_value)
779
except errors.ExistingContent:
780
# No content change against a carry_over parent
781
# Perhaps this should also yield a fs hash update?
783
entry.text_size = parent_entry.text_size
784
entry.text_sha1 = parent_entry.text_sha1
785
elif kind == 'symlink':
787
entry.symlink_target = tree.get_symlink_target(file_id)
788
if (carry_over_possible and
789
parent_entry.symlink_target == entry.symlink_target):
792
self._add_text_to_weave(change[0], '', heads, None)
793
elif kind == 'directory':
794
if carry_over_possible:
797
# Nothing to set on the entry.
798
# XXX: split into the Root and nonRoot versions.
799
if change[1][1] != '' or self.repository.supports_rich_root():
800
self._add_text_to_weave(change[0], '', heads, None)
801
elif kind == 'tree-reference':
802
if not self.repository._format.supports_tree_reference:
803
# This isn't quite sane as an error, but we shouldn't
804
# ever see this code path in practice: tree's don't
805
# permit references when the repo doesn't support tree
807
raise errors.UnsupportedOperation(tree.add_reference,
809
reference_revision = tree.get_reference_revision(change[0])
810
entry.reference_revision = reference_revision
811
if (carry_over_possible and
812
parent_entry.reference_revision == reference_revision):
815
self._add_text_to_weave(change[0], '', heads, None)
817
raise AssertionError('unknown kind %r' % kind)
819
entry.revision = modified_rev
821
entry.revision = parent_entry.revision
824
new_path = change[1][1]
825
inv_delta.append((change[1][0], new_path, change[0], entry))
828
self.new_inventory = None
829
# The initial commit adds a root directory, but this in itself is not
830
# a worthwhile commit.
831
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
832
(len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
833
# This should perhaps be guarded by a check that the basis we
834
# commit against is the basis for the commit and if not do a delta
836
self._any_changes = True
838
# housekeeping root entry changes do not affect no-change commits.
839
self._require_root_change(tree)
840
self.basis_delta_revision = basis_revision_id
842
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
843
parent_keys = tuple([(file_id, parent) for parent in parents])
844
return self.repository.texts._add_text(
845
(file_id, self._new_revision_id), parent_keys, new_text,
846
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
849
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
850
"""This commitbuilder actually records the root id"""
852
# the root entry gets versioned properly by this builder.
853
_versioned_root = True
855
def _check_root(self, ie, parent_invs, tree):
856
"""Helper for record_entry_contents.
858
:param ie: An entry being added.
859
:param parent_invs: The inventories of the parent revisions of the
861
:param tree: The tree that is being committed.
864
def _require_root_change(self, tree):
865
"""Enforce an appropriate root object change.
867
This is called once when record_iter_changes is called, if and only if
868
the root was not in the delta calculated by record_iter_changes.
870
:param tree: The tree which is being committed.
872
# versioned roots do not change unless the tree found a change.
875
class VersionedFileRepository(Repository):
876
"""Repository holding history for one or more branches.
878
The repository holds and retrieves historical information including
879
revisions and file history. It's normally accessed only by the Branch,
880
which views a particular line of development through that history.
882
The Repository builds on top of some byte storage facilies (the revisions,
883
signatures, inventories, texts and chk_bytes attributes) and a Transport,
884
which respectively provide byte storage and a means to access the (possibly
887
The byte storage facilities are addressed via tuples, which we refer to
888
as 'keys' throughout the code base. Revision_keys, inventory_keys and
889
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
890
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
891
byte string made up of a hash identifier and a hash value.
892
We use this interface because it allows low friction with the underlying
893
code that implements disk indices, network encoding and other parts of
896
:ivar revisions: A breezy.versionedfile.VersionedFiles instance containing
897
the serialised revisions for the repository. This can be used to obtain
898
revision graph information or to access raw serialised revisions.
899
The result of trying to insert data into the repository via this store
900
is undefined: it should be considered read-only except for implementors
902
:ivar signatures: A breezy.versionedfile.VersionedFiles instance containing
903
the serialised signatures for the repository. This can be used to
904
obtain access to raw serialised signatures. The result of trying to
905
insert data into the repository via this store is undefined: it should
906
be considered read-only except for implementors of repositories.
907
:ivar inventories: A breezy.versionedfile.VersionedFiles instance containing
908
the serialised inventories for the repository. This can be used to
909
obtain unserialised inventories. The result of trying to insert data
910
into the repository via this store is undefined: it should be
911
considered read-only except for implementors of repositories.
912
:ivar texts: A breezy.versionedfile.VersionedFiles instance containing the
913
texts of files and directories for the repository. This can be used to
914
obtain file texts or file graphs. Note that Repository.iter_file_bytes
915
is usually a better interface for accessing file texts.
916
The result of trying to insert data into the repository via this store
917
is undefined: it should be considered read-only except for implementors
919
:ivar chk_bytes: A breezy.versionedfile.VersionedFiles instance containing
920
any data the repository chooses to store or have indexed by its hash.
921
The result of trying to insert data into the repository via this store
922
is undefined: it should be considered read-only except for implementors
924
:ivar _transport: Transport for file access to repository, typically
925
pointing to .bzr/repository.
928
# What class to use for a CommitBuilder. Often it's simpler to change this
929
# in a Repository class subclass rather than to override
930
# get_commit_builder.
931
_commit_builder_class = VersionedFileCommitBuilder
933
def add_fallback_repository(self, repository):
934
"""Add a repository to use for looking up data not held locally.
936
:param repository: A repository.
938
if not self._format.supports_external_lookups:
939
raise errors.UnstackableRepositoryFormat(self._format, self.base)
940
# This can raise an exception, so should be done before we lock the
941
# fallback repository.
942
self._check_fallback_repository(repository)
944
# This repository will call fallback.unlock() when we transition to
945
# the unlocked state, so we make sure to increment the lock count
946
repository.lock_read()
947
self._fallback_repositories.append(repository)
948
self.texts.add_fallback_versioned_files(repository.texts)
949
self.inventories.add_fallback_versioned_files(repository.inventories)
950
self.revisions.add_fallback_versioned_files(repository.revisions)
951
self.signatures.add_fallback_versioned_files(repository.signatures)
952
if self.chk_bytes is not None:
953
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
955
@only_raises(errors.LockNotHeld, errors.LockBroken)
957
super(VersionedFileRepository, self).unlock()
958
if self.control_files._lock_count == 0:
959
self._inventory_entry_cache.clear()
961
def add_inventory(self, revision_id, inv, parents):
962
"""Add the inventory inv to the repository as revision_id.
964
:param parents: The revision ids of the parents that revision_id
965
is known to have and are in the repository already.
967
:returns: The validator(which is a sha1 digest, though what is sha'd is
968
repository format specific) of the serialized inventory.
970
if not self.is_in_write_group():
971
raise AssertionError("%r not in write group" % (self,))
972
_mod_revision.check_not_reserved_id(revision_id)
973
if not (inv.revision_id is None or inv.revision_id == revision_id):
974
raise AssertionError(
975
"Mismatch between inventory revision"
976
" id and insertion revid (%r, %r)"
977
% (inv.revision_id, revision_id))
979
raise errors.RootMissing()
980
return self._add_inventory_checked(revision_id, inv, parents)
982
def _add_inventory_checked(self, revision_id, inv, parents):
983
"""Add inv to the repository after checking the inputs.
985
This function can be overridden to allow different inventory styles.
987
:seealso: add_inventory, for the contract.
989
inv_lines = self._serializer.write_inventory_to_lines(inv)
990
return self._inventory_add_lines(revision_id, parents,
991
inv_lines, check_content=False)
993
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
994
parents, basis_inv=None, propagate_caches=False):
995
"""Add a new inventory expressed as a delta against another revision.
997
See the inventory developers documentation for the theory behind
1000
:param basis_revision_id: The inventory id the delta was created
1001
against. (This does not have to be a direct parent.)
1002
:param delta: The inventory delta (see Inventory.apply_delta for
1004
:param new_revision_id: The revision id that the inventory is being
1006
:param parents: The revision ids of the parents that revision_id is
1007
known to have and are in the repository already. These are supplied
1008
for repositories that depend on the inventory graph for revision
1009
graph access, as well as for those that pun ancestry with delta
1011
:param basis_inv: The basis inventory if it is already known,
1013
:param propagate_caches: If True, the caches for this inventory are
1014
copied to and updated for the result if possible.
1016
:returns: (validator, new_inv)
1017
The validator(which is a sha1 digest, though what is sha'd is
1018
repository format specific) of the serialized inventory, and the
1019
resulting inventory.
1021
if not self.is_in_write_group():
1022
raise AssertionError("%r not in write group" % (self,))
1023
_mod_revision.check_not_reserved_id(new_revision_id)
1024
basis_tree = self.revision_tree(basis_revision_id)
1025
basis_tree.lock_read()
1027
# Note that this mutates the inventory of basis_tree, which not all
1028
# inventory implementations may support: A better idiom would be to
1029
# return a new inventory, but as there is no revision tree cache in
1030
# repository this is safe for now - RBC 20081013
1031
if basis_inv is None:
1032
basis_inv = basis_tree.root_inventory
1033
basis_inv.apply_delta(delta)
1034
basis_inv.revision_id = new_revision_id
1035
return (self.add_inventory(new_revision_id, basis_inv, parents),
1040
def _inventory_add_lines(self, revision_id, parents, lines,
1041
check_content=True):
1042
"""Store lines in inv_vf and return the sha1 of the inventory."""
1043
parents = [(parent,) for parent in parents]
1044
result = self.inventories.add_lines((revision_id,), parents, lines,
1045
check_content=check_content)[0]
1046
self.inventories._access.flush()
1049
def add_revision(self, revision_id, rev, inv=None):
1050
"""Add rev to the revision store as revision_id.
1052
:param revision_id: the revision id to use.
1053
:param rev: The revision object.
1054
:param inv: The inventory for the revision. if None, it will be looked
1055
up in the inventory storer
1057
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1059
_mod_revision.check_not_reserved_id(revision_id)
1060
# check inventory present
1061
if not self.inventories.get_parent_map([(revision_id,)]):
1063
raise errors.WeaveRevisionNotPresent(revision_id,
1066
# yes, this is not suitable for adding with ghosts.
1067
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1070
key = (revision_id,)
1071
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1072
self._add_revision(rev)
1074
def _add_revision(self, revision):
1075
text = self._serializer.write_revision_to_string(revision)
1076
key = (revision.revision_id,)
1077
parents = tuple((parent,) for parent in revision.parent_ids)
1078
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1080
def _check_inventories(self, checker):
1081
"""Check the inventories found from the revision scan.
1083
This is responsible for verifying the sha1 of inventories and
1084
creating a pending_keys set that covers data referenced by inventories.
1086
bar = ui.ui_factory.nested_progress_bar()
1088
self._do_check_inventories(checker, bar)
1092
def _do_check_inventories(self, checker, bar):
1093
"""Helper for _check_inventories."""
1095
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1096
kinds = ['chk_bytes', 'texts']
1097
count = len(checker.pending_keys)
1098
bar.update(gettext("inventories"), 0, 2)
1099
current_keys = checker.pending_keys
1100
checker.pending_keys = {}
1101
# Accumulate current checks.
1102
for key in current_keys:
1103
if key[0] != 'inventories' and key[0] not in kinds:
1104
checker._report_items.append('unknown key type %r' % (key,))
1105
keys[key[0]].add(key[1:])
1106
if keys['inventories']:
1107
# NB: output order *should* be roughly sorted - topo or
1108
# inverse topo depending on repository - either way decent
1109
# to just delta against. However, pre-CHK formats didn't
1110
# try to optimise inventory layout on disk. As such the
1111
# pre-CHK code path does not use inventory deltas.
1113
for record in self.inventories.check(keys=keys['inventories']):
1114
if record.storage_kind == 'absent':
1115
checker._report_items.append(
1116
'Missing inventory {%s}' % (record.key,))
1118
last_object = self._check_record('inventories', record,
1119
checker, last_object,
1120
current_keys[('inventories',) + record.key])
1121
del keys['inventories']
1124
bar.update(gettext("texts"), 1)
1125
while (checker.pending_keys or keys['chk_bytes']
1127
# Something to check.
1128
current_keys = checker.pending_keys
1129
checker.pending_keys = {}
1130
# Accumulate current checks.
1131
for key in current_keys:
1132
if key[0] not in kinds:
1133
checker._report_items.append('unknown key type %r' % (key,))
1134
keys[key[0]].add(key[1:])
1135
# Check the outermost kind only - inventories || chk_bytes || texts
1139
for record in getattr(self, kind).check(keys=keys[kind]):
1140
if record.storage_kind == 'absent':
1141
checker._report_items.append(
1142
'Missing %s {%s}' % (kind, record.key,))
1144
last_object = self._check_record(kind, record,
1145
checker, last_object, current_keys[(kind,) + record.key])
1149
def _check_record(self, kind, record, checker, last_object, item_data):
1150
"""Check a single text from this repository."""
1151
if kind == 'inventories':
1152
rev_id = record.key[0]
1153
inv = self._deserialise_inventory(rev_id,
1154
record.get_bytes_as('fulltext'))
1155
if last_object is not None:
1156
delta = inv._make_delta(last_object)
1157
for old_path, path, file_id, ie in delta:
1160
ie.check(checker, rev_id, inv)
1162
for path, ie in inv.iter_entries():
1163
ie.check(checker, rev_id, inv)
1164
if self._format.fast_deltas:
1166
elif kind == 'chk_bytes':
1167
# No code written to check chk_bytes for this repo format.
1168
checker._report_items.append(
1169
'unsupported key type chk_bytes for %s' % (record.key,))
1170
elif kind == 'texts':
1171
self._check_text(record, checker, item_data)
1173
checker._report_items.append(
1174
'unknown key type %s for %s' % (kind, record.key))
1176
def _check_text(self, record, checker, item_data):
1177
"""Check a single text."""
1178
# Check it is extractable.
1179
# TODO: check length.
1180
if record.storage_kind == 'chunked':
1181
chunks = record.get_bytes_as(record.storage_kind)
1182
sha1 = osutils.sha_strings(chunks)
1183
length = sum(map(len, chunks))
1185
content = record.get_bytes_as('fulltext')
1186
sha1 = osutils.sha_string(content)
1187
length = len(content)
1188
if item_data and sha1 != item_data[1]:
1189
checker._report_items.append(
1190
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1191
(record.key, sha1, item_data[1], item_data[2]))
1194
def _eliminate_revisions_not_present(self, revision_ids):
1195
"""Check every revision id in revision_ids to see if we have it.
1197
Returns a set of the present revisions.
1200
graph = self.get_graph()
1201
parent_map = graph.get_parent_map(revision_ids)
1202
# The old API returned a list, should this actually be a set?
1203
return list(parent_map)
1205
def __init__(self, _format, a_controldir, control_files):
1206
"""Instantiate a VersionedFileRepository.
1208
:param _format: The format of the repository on disk.
1209
:param controldir: The ControlDir of the repository.
1210
:param control_files: Control files to use for locking, etc.
1212
# In the future we will have a single api for all stores for
1213
# getting file texts, inventories and revisions, then
1214
# this construct will accept instances of those things.
1215
super(VersionedFileRepository, self).__init__(_format, a_controldir,
1217
self._transport = control_files._transport
1218
self.base = self._transport.base
1220
self._reconcile_does_inventory_gc = True
1221
self._reconcile_fixes_text_parents = False
1222
self._reconcile_backsup_inventory = True
1223
# An InventoryEntry cache, used during deserialization
1224
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1225
# Is it safe to return inventory entries directly from the entry cache,
1226
# rather copying them?
1227
self._safe_to_return_from_cache = False
1229
def fetch(self, source, revision_id=None, find_ghosts=False,
1231
"""Fetch the content required to construct revision_id from source.
1233
If revision_id is None and fetch_spec is None, then all content is
1236
fetch() may not be used when the repository is in a write group -
1237
either finish the current write group before using fetch, or use
1238
fetch before starting the write group.
1240
:param find_ghosts: Find and copy revisions in the source that are
1241
ghosts in the target (and not reachable directly by walking out to
1242
the first-present revision in target from revision_id).
1243
:param revision_id: If specified, all the content needed for this
1244
revision ID will be copied to the target. Fetch will determine for
1245
itself which content needs to be copied.
1246
:param fetch_spec: If specified, a SearchResult or
1247
PendingAncestryResult that describes which revisions to copy. This
1248
allows copying multiple heads at once. Mutually exclusive with
1251
if fetch_spec is not None and revision_id is not None:
1252
raise AssertionError(
1253
"fetch_spec and revision_id are mutually exclusive.")
1254
if self.is_in_write_group():
1255
raise errors.InternalBzrError(
1256
"May not fetch while in a write group.")
1257
# fast path same-url fetch operations
1258
# TODO: lift out to somewhere common with RemoteRepository
1259
# <https://bugs.launchpad.net/bzr/+bug/401646>
1260
if (self.has_same_location(source)
1261
and fetch_spec is None
1262
and self._has_same_fallbacks(source)):
1263
# check that last_revision is in 'from' and then return a
1265
if (revision_id is not None and
1266
not _mod_revision.is_null(revision_id)):
1267
self.get_revision(revision_id)
1269
inter = InterRepository.get(source, self)
1270
if (fetch_spec is not None and
1271
not getattr(inter, "supports_fetch_spec", False)):
1272
raise errors.UnsupportedOperation(
1273
"fetch_spec not supported for %r" % inter)
1274
return inter.fetch(revision_id=revision_id,
1275
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1278
def gather_stats(self, revid=None, committers=None):
1279
"""See Repository.gather_stats()."""
1280
result = super(VersionedFileRepository, self).gather_stats(revid, committers)
1281
# now gather global repository information
1282
# XXX: This is available for many repos regardless of listability.
1283
if self.user_transport.listable():
1284
# XXX: do we want to __define len__() ?
1285
# Maybe the versionedfiles object should provide a different
1286
# method to get the number of keys.
1287
result['revisions'] = len(self.revisions.keys())
1288
# result['size'] = t
1291
def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
1292
timezone=None, committer=None, revprops=None,
1293
revision_id=None, lossy=False):
1294
"""Obtain a CommitBuilder for this repository.
1296
:param branch: Branch to commit to.
1297
:param parents: Revision ids of the parents of the new revision.
1298
:param config_stack: Configuration stack to use.
1299
:param timestamp: Optional timestamp recorded for commit.
1300
:param timezone: Optional timezone for timestamp.
1301
:param committer: Optional committer to set for commit.
1302
:param revprops: Optional dictionary of revision properties.
1303
:param revision_id: Optional revision id.
1304
:param lossy: Whether to discard data that can not be natively
1305
represented, when pushing to a foreign VCS
1307
if self._fallback_repositories and not self._format.supports_chks:
1308
raise errors.BzrError("Cannot commit directly to a stacked branch"
1309
" in pre-2a formats. See "
1310
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1311
result = self._commit_builder_class(self, parents, config_stack,
1312
timestamp, timezone, committer, revprops, revision_id,
1314
self.start_write_group()
1317
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1318
"""Return the keys of missing inventory parents for revisions added in
1321
A revision is not complete if the inventory delta for that revision
1322
cannot be calculated. Therefore if the parent inventories of a
1323
revision are not present, the revision is incomplete, and e.g. cannot
1324
be streamed by a smart server. This method finds missing inventory
1325
parents for revisions added in this write group.
1327
if not self._format.supports_external_lookups:
1328
# This is only an issue for stacked repositories
1330
if not self.is_in_write_group():
1331
raise AssertionError('not in a write group')
1333
# XXX: We assume that every added revision already has its
1334
# corresponding inventory, so we only check for parent inventories that
1335
# might be missing, rather than all inventories.
1336
parents = set(self.revisions._index.get_missing_parents())
1337
parents.discard(_mod_revision.NULL_REVISION)
1338
unstacked_inventories = self.inventories._index
1339
present_inventories = unstacked_inventories.get_parent_map(
1340
key[-1:] for key in parents)
1341
parents.difference_update(present_inventories)
1342
if len(parents) == 0:
1343
# No missing parent inventories.
1345
if not check_for_missing_texts:
1346
return set(('inventories', rev_id) for (rev_id,) in parents)
1347
# Ok, now we have a list of missing inventories. But these only matter
1348
# if the inventories that reference them are missing some texts they
1349
# appear to introduce.
1350
# XXX: Texts referenced by all added inventories need to be present,
1351
# but at the moment we're only checking for texts referenced by
1352
# inventories at the graph's edge.
1353
key_deps = self.revisions._index._key_dependencies
1354
key_deps.satisfy_refs_for_keys(present_inventories)
1355
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1356
file_ids = self.fileids_altered_by_revision_ids(referrers)
1357
missing_texts = set()
1358
for file_id, version_ids in viewitems(file_ids):
1359
missing_texts.update(
1360
(file_id, version_id) for version_id in version_ids)
1361
present_texts = self.texts.get_parent_map(missing_texts)
1362
missing_texts.difference_update(present_texts)
1363
if not missing_texts:
1364
# No texts are missing, so all revisions and their deltas are
1367
# Alternatively the text versions could be returned as the missing
1368
# keys, but this is likely to be less data.
1369
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1373
def has_revisions(self, revision_ids):
1374
"""Probe to find out the presence of multiple revisions.
1376
:param revision_ids: An iterable of revision_ids.
1377
:return: A set of the revision_ids that were present.
1379
parent_map = self.revisions.get_parent_map(
1380
[(rev_id,) for rev_id in revision_ids])
1382
if _mod_revision.NULL_REVISION in revision_ids:
1383
result.add(_mod_revision.NULL_REVISION)
1384
result.update([key[0] for key in parent_map])
1388
def get_revision_reconcile(self, revision_id):
1389
"""'reconcile' helper routine that allows access to a revision always.
1391
This variant of get_revision does not cross check the weave graph
1392
against the revision one as get_revision does: but it should only
1393
be used by reconcile, or reconcile-alike commands that are correcting
1394
or testing the revision graph.
1396
return self._get_revisions([revision_id])[0]
1399
def get_revisions(self, revision_ids):
1400
"""Get many revisions at once.
1402
Repositories that need to check data on every revision read should
1403
subclass this method.
1405
return self._get_revisions(revision_ids)
1408
def _get_revisions(self, revision_ids):
1409
"""Core work logic to get many revisions without sanity checks."""
1411
for revid, rev in self._iter_revisions(revision_ids):
1413
raise errors.NoSuchRevision(self, revid)
1415
return [revs[revid] for revid in revision_ids]
1417
def _iter_revisions(self, revision_ids):
1418
"""Iterate over revision objects.
1420
:param revision_ids: An iterable of revisions to examine. None may be
1421
passed to request all revisions known to the repository. Note that
1422
not all repositories can find unreferenced revisions; for those
1423
repositories only referenced ones will be returned.
1424
:return: An iterator of (revid, revision) tuples. Absent revisions (
1425
those asked for but not available) are returned as (revid, None).
1427
if revision_ids is None:
1428
revision_ids = self.all_revision_ids()
1430
for rev_id in revision_ids:
1431
if not rev_id or not isinstance(rev_id, basestring):
1432
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1433
keys = [(key,) for key in revision_ids]
1434
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1435
for record in stream:
1436
revid = record.key[0]
1437
if record.storage_kind == 'absent':
1440
text = record.get_bytes_as('fulltext')
1441
rev = self._serializer.read_revision_from_string(text)
1445
def add_signature_text(self, revision_id, signature):
1446
"""Store a signature text for a revision.
1448
:param revision_id: Revision id of the revision
1449
:param signature: Signature text.
1451
self.signatures.add_lines((revision_id,), (),
1452
osutils.split_lines(signature))
1454
def find_text_key_references(self):
1455
"""Find the text key references within the repository.
1457
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1458
to whether they were referred to by the inventory of the
1459
revision_id that they contain. The inventory texts from all present
1460
revision ids are assessed to generate this report.
1462
revision_keys = self.revisions.keys()
1463
w = self.inventories
1464
pb = ui.ui_factory.nested_progress_bar()
1466
return self._serializer._find_text_key_references(
1467
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1471
def _inventory_xml_lines_for_keys(self, keys):
1472
"""Get a line iterator of the sort needed for findind references.
1474
Not relevant for non-xml inventory repositories.
1476
Ghosts in revision_keys are ignored.
1478
:param revision_keys: The revision keys for the inventories to inspect.
1479
:return: An iterator over (inventory line, revid) for the fulltexts of
1480
all of the xml inventories specified by revision_keys.
1482
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1483
for record in stream:
1484
if record.storage_kind != 'absent':
1485
chunks = record.get_bytes_as('chunked')
1486
revid = record.key[-1]
1487
lines = osutils.chunks_to_lines(chunks)
1491
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1493
"""Helper routine for fileids_altered_by_revision_ids.
1495
This performs the translation of xml lines to revision ids.
1497
:param line_iterator: An iterator of lines, origin_version_id
1498
:param revision_keys: The revision ids to filter for. This should be a
1499
set or other type which supports efficient __contains__ lookups, as
1500
the revision key from each parsed line will be looked up in the
1501
revision_keys filter.
1502
:return: a dictionary mapping altered file-ids to an iterable of
1503
revision_ids. Each altered file-ids has the exact revision_ids that
1504
altered it listed explicitly.
1506
seen = set(self._serializer._find_text_key_references(line_iterator))
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)
1525
parent_keys = set(itertools.chain.from_iterable(
1526
viewvalues(parent_map)))
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 viewitems(text_key_references):
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 range(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).root_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 viewitems(file_ids):
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 = {r for (r,) in revisions_with_signatures}
1728
revisions_with_signatures.intersection_update(revision_ids)
1729
yield ("signatures", None, revisions_with_signatures)
1732
yield ("revisions", None, revision_ids)
1735
def get_inventory(self, revision_id):
1736
"""Get Inventory object by revision id."""
1737
return next(self.iter_inventories([revision_id]))
1739
def iter_inventories(self, revision_ids, ordering=None):
1740
"""Get many inventories by revision_ids.
1742
This will buffer some or all of the texts used in constructing the
1743
inventories in memory, but will only parse a single inventory at a
1746
:param revision_ids: The expected revision ids of the inventories.
1747
:param ordering: optional ordering, e.g. 'topological'. If not
1748
specified, the order of revision_ids will be preserved (by
1749
buffering if necessary).
1750
:return: An iterator of inventories.
1752
if ((None in revision_ids)
1753
or (_mod_revision.NULL_REVISION in revision_ids)):
1754
raise ValueError('cannot get null revision inventory')
1755
for inv, revid in self._iter_inventories(revision_ids, ordering):
1757
raise errors.NoSuchRevision(self, revid)
1760
def _iter_inventories(self, revision_ids, ordering):
1761
"""single-document based inventory iteration."""
1762
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1763
for text, revision_id in inv_xmls:
1765
yield None, revision_id
1767
yield self._deserialise_inventory(revision_id, text), revision_id
1769
def _iter_inventory_xmls(self, revision_ids, ordering):
1770
if ordering is None:
1771
order_as_requested = True
1772
ordering = 'unordered'
1774
order_as_requested = False
1775
keys = [(revision_id,) for revision_id in revision_ids]
1778
if order_as_requested:
1779
key_iter = iter(keys)
1780
next_key = next(key_iter)
1781
stream = self.inventories.get_record_stream(keys, ordering, True)
1783
for record in stream:
1784
if record.storage_kind != 'absent':
1785
chunks = record.get_bytes_as('chunked')
1786
if order_as_requested:
1787
text_chunks[record.key] = chunks
1789
yield ''.join(chunks), record.key[-1]
1791
yield None, record.key[-1]
1792
if order_as_requested:
1793
# Yield as many results as we can while preserving order.
1794
while next_key in text_chunks:
1795
chunks = text_chunks.pop(next_key)
1796
yield ''.join(chunks), next_key[-1]
1798
next_key = next(key_iter)
1799
except StopIteration:
1800
# We still want to fully consume the get_record_stream,
1801
# just in case it is not actually finished at this point
1805
def _deserialise_inventory(self, revision_id, xml):
1806
"""Transform the xml into an inventory object.
1808
:param revision_id: The expected revision id of the inventory.
1809
:param xml: A serialised inventory.
1811
result = self._serializer.read_inventory_from_string(xml, revision_id,
1812
entry_cache=self._inventory_entry_cache,
1813
return_from_cache=self._safe_to_return_from_cache)
1814
if result.revision_id != revision_id:
1815
raise AssertionError('revision id mismatch %s != %s' % (
1816
result.revision_id, revision_id))
1819
def get_serializer_format(self):
1820
return self._serializer.format_num
1823
def _get_inventory_xml(self, revision_id):
1824
"""Get serialized inventory as a string."""
1825
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1826
text, revision_id = next(texts)
1828
raise errors.NoSuchRevision(self, revision_id)
1832
def revision_tree(self, revision_id):
1833
"""Return Tree for a revision on this branch.
1835
`revision_id` may be NULL_REVISION for the empty tree revision.
1837
revision_id = _mod_revision.ensure_null(revision_id)
1838
# TODO: refactor this to use an existing revision object
1839
# so we don't need to read it in twice.
1840
if revision_id == _mod_revision.NULL_REVISION:
1841
return InventoryRevisionTree(self,
1842
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1844
inv = self.get_inventory(revision_id)
1845
return InventoryRevisionTree(self, inv, revision_id)
1847
def revision_trees(self, revision_ids):
1848
"""Return Trees for revisions in this repository.
1850
:param revision_ids: a sequence of revision-ids;
1851
a revision-id may not be None or 'null:'
1853
inventories = self.iter_inventories(revision_ids)
1854
for inv in inventories:
1855
yield InventoryRevisionTree(self, inv, inv.revision_id)
1857
def _filtered_revision_trees(self, revision_ids, file_ids):
1858
"""Return Tree for a revision on this branch with only some files.
1860
:param revision_ids: a sequence of revision-ids;
1861
a revision-id may not be None or 'null:'
1862
:param file_ids: if not None, the result is filtered
1863
so that only those file-ids, their parents and their
1864
children are included.
1866
inventories = self.iter_inventories(revision_ids)
1867
for inv in inventories:
1868
# Should we introduce a FilteredRevisionTree class rather
1869
# than pre-filter the inventory here?
1870
filtered_inv = inv.filter(file_ids)
1871
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1873
def get_parent_map(self, revision_ids):
1874
"""See graph.StackedParentsProvider.get_parent_map"""
1875
# revisions index works in keys; this just works in revisions
1876
# therefore wrap and unwrap
1879
for revision_id in revision_ids:
1880
if revision_id == _mod_revision.NULL_REVISION:
1881
result[revision_id] = ()
1882
elif revision_id is None:
1883
raise ValueError('get_parent_map(None) is not valid')
1885
query_keys.append((revision_id ,))
1886
for (revision_id,), parent_keys in viewitems(
1887
self.revisions.get_parent_map(query_keys)):
1889
result[revision_id] = tuple([parent_revid
1890
for (parent_revid,) in parent_keys])
1892
result[revision_id] = (_mod_revision.NULL_REVISION,)
1896
def get_known_graph_ancestry(self, revision_ids):
1897
"""Return the known graph for a set of revision ids and their ancestors.
1899
st = static_tuple.StaticTuple
1900
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1901
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1902
return graph.GraphThunkIdsToKeys(known_graph)
1905
def get_file_graph(self):
1906
"""Return the graph walker for text revisions."""
1907
return graph.Graph(self.texts)
1909
def revision_ids_to_search_result(self, result_set):
1910
"""Convert a set of revision ids to a graph SearchResult."""
1911
result_parents = set(itertools.chain.from_iterable(viewvalues(
1912
self.get_graph().get_parent_map(result_set))))
1913
included_keys = result_set.intersection(result_parents)
1914
start_keys = result_set.difference(included_keys)
1915
exclude_keys = result_parents.difference(result_set)
1916
result = vf_search.SearchResult(start_keys, exclude_keys,
1917
len(result_set), result_set)
1920
def _get_versioned_file_checker(self, text_key_references=None,
1922
"""Return an object suitable for checking versioned files.
1924
:param text_key_references: if non-None, an already built
1925
dictionary mapping text keys ((fileid, revision_id) tuples)
1926
to whether they were referred to by the inventory of the
1927
revision_id that they contain. If None, this will be
1929
:param ancestors: Optional result from
1930
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1933
return _VersionedFileChecker(self,
1934
text_key_references=text_key_references, ancestors=ancestors)
1937
def has_signature_for_revision_id(self, revision_id):
1938
"""Query for a revision signature for revision_id in the repository."""
1939
if not self.has_revision(revision_id):
1940
raise errors.NoSuchRevision(self, revision_id)
1941
sig_present = (1 == len(
1942
self.signatures.get_parent_map([(revision_id,)])))
1946
def get_signature_text(self, revision_id):
1947
"""Return the text for a signature."""
1948
stream = self.signatures.get_record_stream([(revision_id,)],
1950
record = next(stream)
1951
if record.storage_kind == 'absent':
1952
raise errors.NoSuchRevision(self, revision_id)
1953
return record.get_bytes_as('fulltext')
1956
def _check(self, revision_ids, callback_refs, check_repo):
1957
result = check.VersionedFileCheck(self, check_repo=check_repo)
1958
result.check(callback_refs)
1961
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1962
"""Find revisions with different parent lists in the revision object
1963
and in the index graph.
1965
:param revisions_iterator: None, or an iterator of (revid,
1966
Revision-or-None). This iterator controls the revisions checked.
1967
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1968
parents-in-revision).
1970
if not self.is_locked():
1971
raise AssertionError()
1973
if revisions_iterator is None:
1974
revisions_iterator = self._iter_revisions(None)
1975
for revid, revision in revisions_iterator:
1976
if revision is None:
1978
parent_map = vf.get_parent_map([(revid,)])
1979
parents_according_to_index = tuple(parent[-1] for parent in
1980
parent_map[(revid,)])
1981
parents_according_to_revision = tuple(revision.parent_ids)
1982
if parents_according_to_index != parents_according_to_revision:
1983
yield (revid, parents_according_to_index,
1984
parents_according_to_revision)
1986
def _check_for_inconsistent_revision_parents(self):
1987
inconsistencies = list(self._find_inconsistent_revision_parents())
1989
raise errors.BzrCheckError(
1990
"Revision knit has inconsistent parents.")
1992
def _get_sink(self):
1993
"""Return a sink for streaming into this repository."""
1994
return StreamSink(self)
1996
def _get_source(self, to_format):
1997
"""Return a source for streaming from this repository."""
1998
return StreamSource(self, to_format)
2001
class MetaDirVersionedFileRepository(MetaDirRepository,
2002
VersionedFileRepository):
2003
"""Repositories in a meta-dir, that work via versioned file objects."""
2005
def __init__(self, _format, a_controldir, control_files):
2006
super(MetaDirVersionedFileRepository, self).__init__(_format, a_controldir,
2010
class MetaDirVersionedFileRepositoryFormat(RepositoryFormatMetaDir,
2011
VersionedFileRepositoryFormat):
2012
"""Base class for repository formats using versioned files in metadirs."""
2015
class StreamSink(object):
2016
"""An object that can insert a stream into a repository.
2018
This interface handles the complexity of reserialising inventories and
2019
revisions from different formats, and allows unidirectional insertion into
2020
stacked repositories without looking for the missing basis parents
2024
def __init__(self, target_repo):
2025
self.target_repo = target_repo
2027
def insert_stream(self, stream, src_format, resume_tokens):
2028
"""Insert a stream's content into the target repository.
2030
:param src_format: a bzr repository format.
2032
:return: a list of resume tokens and an iterable of keys additional
2033
items required before the insertion can be completed.
2035
self.target_repo.lock_write()
2038
self.target_repo.resume_write_group(resume_tokens)
2041
self.target_repo.start_write_group()
2044
# locked_insert_stream performs a commit|suspend.
2045
missing_keys = self.insert_stream_without_locking(stream,
2046
src_format, is_resume)
2048
# suspend the write group and tell the caller what we is
2049
# missing. We know we can suspend or else we would not have
2050
# entered this code path. (All repositories that can handle
2051
# missing keys can handle suspending a write group).
2052
write_group_tokens = self.target_repo.suspend_write_group()
2053
return write_group_tokens, missing_keys
2054
hint = self.target_repo.commit_write_group()
2055
to_serializer = self.target_repo._format._serializer
2056
src_serializer = src_format._serializer
2057
if (to_serializer != src_serializer and
2058
self.target_repo._format.pack_compresses):
2059
self.target_repo.pack(hint=hint)
2062
self.target_repo.abort_write_group(suppress_errors=True)
2065
self.target_repo.unlock()
2067
def insert_stream_without_locking(self, stream, src_format,
2069
"""Insert a stream's content into the target repository.
2071
This assumes that you already have a locked repository and an active
2074
:param src_format: a bzr repository format.
2075
:param is_resume: Passed down to get_missing_parent_inventories to
2076
indicate if we should be checking for missing texts at the same
2079
:return: A set of keys that are missing.
2081
if not self.target_repo.is_write_locked():
2082
raise errors.ObjectNotLocked(self)
2083
if not self.target_repo.is_in_write_group():
2084
raise errors.BzrError('you must already be in a write group')
2085
to_serializer = self.target_repo._format._serializer
2086
src_serializer = src_format._serializer
2088
if to_serializer == src_serializer:
2089
# If serializers match and the target is a pack repository, set the
2090
# write cache size on the new pack. This avoids poor performance
2091
# on transports where append is unbuffered (such as
2092
# RemoteTransport). This is safe to do because nothing should read
2093
# back from the target repository while a stream with matching
2094
# serialization is being inserted.
2095
# The exception is that a delta record from the source that should
2096
# be a fulltext may need to be expanded by the target (see
2097
# test_fetch_revisions_with_deltas_into_pack); but we take care to
2098
# explicitly flush any buffered writes first in that rare case.
2100
new_pack = self.target_repo._pack_collection._new_pack
2101
except AttributeError:
2102
# Not a pack repository
2105
new_pack.set_write_cache_size(1024*1024)
2106
for substream_type, substream in stream:
2107
if 'stream' in debug.debug_flags:
2108
mutter('inserting substream: %s', substream_type)
2109
if substream_type == 'texts':
2110
self.target_repo.texts.insert_record_stream(substream)
2111
elif substream_type == 'inventories':
2112
if src_serializer == to_serializer:
2113
self.target_repo.inventories.insert_record_stream(
2116
self._extract_and_insert_inventories(
2117
substream, src_serializer)
2118
elif substream_type == 'inventory-deltas':
2119
self._extract_and_insert_inventory_deltas(
2120
substream, src_serializer)
2121
elif substream_type == 'chk_bytes':
2122
# XXX: This doesn't support conversions, as it assumes the
2123
# conversion was done in the fetch code.
2124
self.target_repo.chk_bytes.insert_record_stream(substream)
2125
elif substream_type == 'revisions':
2126
# This may fallback to extract-and-insert more often than
2127
# required if the serializers are different only in terms of
2129
if src_serializer == to_serializer:
2130
self.target_repo.revisions.insert_record_stream(substream)
2132
self._extract_and_insert_revisions(substream,
2134
elif substream_type == 'signatures':
2135
self.target_repo.signatures.insert_record_stream(substream)
2137
raise AssertionError('kaboom! %s' % (substream_type,))
2138
# Done inserting data, and the missing_keys calculations will try to
2139
# read back from the inserted data, so flush the writes to the new pack
2140
# (if this is pack format).
2141
if new_pack is not None:
2142
new_pack._write_data('', flush=True)
2143
# Find all the new revisions (including ones from resume_tokens)
2144
missing_keys = self.target_repo.get_missing_parent_inventories(
2145
check_for_missing_texts=is_resume)
2147
for prefix, versioned_file in (
2148
('texts', self.target_repo.texts),
2149
('inventories', self.target_repo.inventories),
2150
('revisions', self.target_repo.revisions),
2151
('signatures', self.target_repo.signatures),
2152
('chk_bytes', self.target_repo.chk_bytes),
2154
if versioned_file is None:
2156
# TODO: key is often going to be a StaticTuple object
2157
# I don't believe we can define a method by which
2158
# (prefix,) + StaticTuple will work, though we could
2159
# define a StaticTuple.sq_concat that would allow you to
2160
# pass in either a tuple or a StaticTuple as the second
2161
# object, so instead we could have:
2162
# StaticTuple(prefix) + key here...
2163
missing_keys.update((prefix,) + key for key in
2164
versioned_file.get_missing_compression_parent_keys())
2165
except NotImplementedError:
2166
# cannot even attempt suspending, and missing would have failed
2167
# during stream insertion.
2168
missing_keys = set()
2171
def _extract_and_insert_inventory_deltas(self, substream, serializer):
2172
target_rich_root = self.target_repo._format.rich_root_data
2173
target_tree_refs = self.target_repo._format.supports_tree_reference
2174
for record in substream:
2175
# Insert the delta directly
2176
inventory_delta_bytes = record.get_bytes_as('fulltext')
2177
deserialiser = inventory_delta.InventoryDeltaDeserializer()
2179
parse_result = deserialiser.parse_text_bytes(
2180
inventory_delta_bytes)
2181
except inventory_delta.IncompatibleInventoryDelta as err:
2182
mutter("Incompatible delta: %s", err.msg)
2183
raise errors.IncompatibleRevision(self.target_repo._format)
2184
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
2185
revision_id = new_id
2186
parents = [key[0] for key in record.parents]
2187
self.target_repo.add_inventory_by_delta(
2188
basis_id, inv_delta, revision_id, parents)
2190
def _extract_and_insert_inventories(self, substream, serializer,
2192
"""Generate a new inventory versionedfile in target, converting data.
2194
The inventory is retrieved from the source, (deserializing it), and
2195
stored in the target (reserializing it in a different format).
2197
target_rich_root = self.target_repo._format.rich_root_data
2198
target_tree_refs = self.target_repo._format.supports_tree_reference
2199
for record in substream:
2200
# It's not a delta, so it must be a fulltext in the source
2201
# serializer's format.
2202
bytes = record.get_bytes_as('fulltext')
2203
revision_id = record.key[0]
2204
inv = serializer.read_inventory_from_string(bytes, revision_id)
2205
parents = [key[0] for key in record.parents]
2206
self.target_repo.add_inventory(revision_id, inv, parents)
2207
# No need to keep holding this full inv in memory when the rest of
2208
# the substream is likely to be all deltas.
2211
def _extract_and_insert_revisions(self, substream, serializer):
2212
for record in substream:
2213
bytes = record.get_bytes_as('fulltext')
2214
revision_id = record.key[0]
2215
rev = serializer.read_revision_from_string(bytes)
2216
if rev.revision_id != revision_id:
2217
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
2218
self.target_repo.add_revision(revision_id, rev)
2221
if self.target_repo._format._fetch_reconcile:
2222
self.target_repo.reconcile()
2225
class StreamSource(object):
2226
"""A source of a stream for fetching between repositories."""
2228
def __init__(self, from_repository, to_format):
2229
"""Create a StreamSource streaming from from_repository."""
2230
self.from_repository = from_repository
2231
self.to_format = to_format
2232
self._record_counter = RecordCounter()
2234
def delta_on_metadata(self):
2235
"""Return True if delta's are permitted on metadata streams.
2237
That is on revisions and signatures.
2239
src_serializer = self.from_repository._format._serializer
2240
target_serializer = self.to_format._serializer
2241
return (self.to_format._fetch_uses_deltas and
2242
src_serializer == target_serializer)
2244
def _fetch_revision_texts(self, revs):
2245
# fetch signatures first and then the revision texts
2246
# may need to be a InterRevisionStore call here.
2247
from_sf = self.from_repository.signatures
2248
# A missing signature is just skipped.
2249
keys = [(rev_id,) for rev_id in revs]
2250
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2252
self.to_format._fetch_order,
2253
not self.to_format._fetch_uses_deltas))
2254
# If a revision has a delta, this is actually expanded inside the
2255
# insert_record_stream code now, which is an alternate fix for
2257
from_rf = self.from_repository.revisions
2258
revisions = from_rf.get_record_stream(
2260
self.to_format._fetch_order,
2261
not self.delta_on_metadata())
2262
return [('signatures', signatures), ('revisions', revisions)]
2264
def _generate_root_texts(self, revs):
2265
"""This will be called by get_stream between fetching weave texts and
2266
fetching the inventory weave.
2268
if self._rich_root_upgrade():
2269
return _mod_fetch.Inter1and2Helper(
2270
self.from_repository).generate_root_texts(revs)
2274
def get_stream(self, search):
2276
revs = search.get_keys()
2277
graph = self.from_repository.get_graph()
2278
revs = tsort.topo_sort(graph.get_parent_map(revs))
2279
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2281
for knit_kind, file_id, revisions in data_to_fetch:
2282
if knit_kind != phase:
2284
# Make a new progress bar for this phase
2285
if knit_kind == "file":
2286
# Accumulate file texts
2287
text_keys.extend([(file_id, revision) for revision in
2289
elif knit_kind == "inventory":
2290
# Now copy the file texts.
2291
from_texts = self.from_repository.texts
2292
yield ('texts', from_texts.get_record_stream(
2293
text_keys, self.to_format._fetch_order,
2294
not self.to_format._fetch_uses_deltas))
2295
# Cause an error if a text occurs after we have done the
2298
# Before we process the inventory we generate the root
2299
# texts (if necessary) so that the inventories references
2301
for _ in self._generate_root_texts(revs):
2303
# we fetch only the referenced inventories because we do not
2304
# know for unselected inventories whether all their required
2305
# texts are present in the other repository - it could be
2307
for info in self._get_inventory_stream(revs):
2309
elif knit_kind == "signatures":
2310
# Nothing to do here; this will be taken care of when
2311
# _fetch_revision_texts happens.
2313
elif knit_kind == "revisions":
2314
for record in self._fetch_revision_texts(revs):
2317
raise AssertionError("Unknown knit kind %r" % knit_kind)
2319
def get_stream_for_missing_keys(self, missing_keys):
2320
# missing keys can only occur when we are byte copying and not
2321
# translating (because translation means we don't send
2322
# unreconstructable deltas ever).
2324
keys['texts'] = set()
2325
keys['revisions'] = set()
2326
keys['inventories'] = set()
2327
keys['chk_bytes'] = set()
2328
keys['signatures'] = set()
2329
for key in missing_keys:
2330
keys[key[0]].add(key[1:])
2331
if len(keys['revisions']):
2332
# If we allowed copying revisions at this point, we could end up
2333
# copying a revision without copying its required texts: a
2334
# violation of the requirements for repository integrity.
2335
raise AssertionError(
2336
'cannot copy revisions to fill in missing deltas %s' % (
2337
keys['revisions'],))
2338
for substream_kind, keys in viewitems(keys):
2339
vf = getattr(self.from_repository, substream_kind)
2340
if vf is None and keys:
2341
raise AssertionError(
2342
"cannot fill in keys for a versioned file we don't"
2343
" have: %s needs %s" % (substream_kind, keys))
2345
# No need to stream something we don't have
2347
if substream_kind == 'inventories':
2348
# Some missing keys are genuinely ghosts, filter those out.
2349
present = self.from_repository.inventories.get_parent_map(keys)
2350
revs = [key[0] for key in present]
2351
# Get the inventory stream more-or-less as we do for the
2352
# original stream; there's no reason to assume that records
2353
# direct from the source will be suitable for the sink. (Think
2354
# e.g. 2a -> 1.9-rich-root).
2355
for info in self._get_inventory_stream(revs, missing=True):
2359
# Ask for full texts always so that we don't need more round trips
2360
# after this stream.
2361
# Some of the missing keys are genuinely ghosts, so filter absent
2362
# records. The Sink is responsible for doing another check to
2363
# ensure that ghosts don't introduce missing data for future
2365
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2366
self.to_format._fetch_order, True))
2367
yield substream_kind, stream
2369
def inventory_fetch_order(self):
2370
if self._rich_root_upgrade():
2371
return 'topological'
2373
return self.to_format._fetch_order
2375
def _rich_root_upgrade(self):
2376
return (not self.from_repository._format.rich_root_data and
2377
self.to_format.rich_root_data)
2379
def _get_inventory_stream(self, revision_ids, missing=False):
2380
from_format = self.from_repository._format
2381
if (from_format.supports_chks and self.to_format.supports_chks and
2382
from_format.network_name() == self.to_format.network_name()):
2383
raise AssertionError(
2384
"this case should be handled by GroupCHKStreamSource")
2385
elif 'forceinvdeltas' in debug.debug_flags:
2386
return self._get_convertable_inventory_stream(revision_ids,
2387
delta_versus_null=missing)
2388
elif from_format.network_name() == self.to_format.network_name():
2390
return self._get_simple_inventory_stream(revision_ids,
2392
elif (not from_format.supports_chks and not self.to_format.supports_chks
2393
and from_format._serializer == self.to_format._serializer):
2394
# Essentially the same format.
2395
return self._get_simple_inventory_stream(revision_ids,
2398
# Any time we switch serializations, we want to use an
2399
# inventory-delta based approach.
2400
return self._get_convertable_inventory_stream(revision_ids,
2401
delta_versus_null=missing)
2403
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2404
# NB: This currently reopens the inventory weave in source;
2405
# using a single stream interface instead would avoid this.
2406
from_weave = self.from_repository.inventories
2408
delta_closure = True
2410
delta_closure = not self.delta_on_metadata()
2411
yield ('inventories', from_weave.get_record_stream(
2412
[(rev_id,) for rev_id in revision_ids],
2413
self.inventory_fetch_order(), delta_closure))
2415
def _get_convertable_inventory_stream(self, revision_ids,
2416
delta_versus_null=False):
2417
# The two formats are sufficiently different that there is no fast
2418
# path, so we need to send just inventorydeltas, which any
2419
# sufficiently modern client can insert into any repository.
2420
# The StreamSink code expects to be able to
2421
# convert on the target, so we need to put bytes-on-the-wire that can
2422
# be converted. That means inventory deltas (if the remote is <1.19,
2423
# RemoteStreamSink will fallback to VFS to insert the deltas).
2424
yield ('inventory-deltas',
2425
self._stream_invs_as_deltas(revision_ids,
2426
delta_versus_null=delta_versus_null))
2428
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2429
"""Return a stream of inventory-deltas for the given rev ids.
2431
:param revision_ids: The list of inventories to transmit
2432
:param delta_versus_null: Don't try to find a minimal delta for this
2433
entry, instead compute the delta versus the NULL_REVISION. This
2434
effectively streams a complete inventory. Used for stuff like
2435
filling in missing parents, etc.
2437
from_repo = self.from_repository
2438
revision_keys = [(rev_id,) for rev_id in revision_ids]
2439
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2440
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2442
inventories = self.from_repository.iter_inventories(
2443
revision_ids, 'topological')
2444
format = from_repo._format
2445
invs_sent_so_far = {_mod_revision.NULL_REVISION}
2446
inventory_cache = lru_cache.LRUCache(50)
2447
null_inventory = from_repo.revision_tree(
2448
_mod_revision.NULL_REVISION).root_inventory
2449
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2450
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2451
# repo back into a non-rich-root repo ought to be allowed)
2452
serializer = inventory_delta.InventoryDeltaSerializer(
2453
versioned_root=format.rich_root_data,
2454
tree_references=format.supports_tree_reference)
2455
for inv in inventories:
2456
key = (inv.revision_id,)
2457
parent_keys = parent_map.get(key, ())
2459
if not delta_versus_null and parent_keys:
2460
# The caller did not ask for complete inventories and we have
2461
# some parents that we can delta against. Make a delta against
2462
# each parent so that we can find the smallest.
2463
parent_ids = [parent_key[0] for parent_key in parent_keys]
2464
for parent_id in parent_ids:
2465
if parent_id not in invs_sent_so_far:
2466
# We don't know that the remote side has this basis, so
2469
if parent_id == _mod_revision.NULL_REVISION:
2470
parent_inv = null_inventory
2472
parent_inv = inventory_cache.get(parent_id, None)
2473
if parent_inv is None:
2474
parent_inv = from_repo.get_inventory(parent_id)
2475
candidate_delta = inv._make_delta(parent_inv)
2476
if (delta is None or
2477
len(delta) > len(candidate_delta)):
2478
delta = candidate_delta
2479
basis_id = parent_id
2481
# Either none of the parents ended up being suitable, or we
2482
# were asked to delta against NULL
2483
basis_id = _mod_revision.NULL_REVISION
2484
delta = inv._make_delta(null_inventory)
2485
invs_sent_so_far.add(inv.revision_id)
2486
inventory_cache[inv.revision_id] = inv
2487
delta_serialized = ''.join(
2488
serializer.delta_to_lines(basis_id, key[-1], delta))
2489
yield versionedfile.FulltextContentFactory(
2490
key, parent_keys, None, delta_serialized)
2493
class _VersionedFileChecker(object):
2495
def __init__(self, repository, text_key_references=None, ancestors=None):
2496
self.repository = repository
2497
self.text_index = self.repository._generate_text_key_index(
2498
text_key_references=text_key_references, ancestors=ancestors)
2500
def calculate_file_version_parents(self, text_key):
2501
"""Calculate the correct parents for a file version according to
2504
parent_keys = self.text_index[text_key]
2505
if parent_keys == [_mod_revision.NULL_REVISION]:
2507
return tuple(parent_keys)
2509
def check_file_version_parents(self, texts, progress_bar=None):
2510
"""Check the parents stored in a versioned file are correct.
2512
It also detects file versions that are not referenced by their
2513
corresponding revision's inventory.
2515
:returns: A tuple of (wrong_parents, dangling_file_versions).
2516
wrong_parents is a dict mapping {revision_id: (stored_parents,
2517
correct_parents)} for each revision_id where the stored parents
2518
are not correct. dangling_file_versions is a set of (file_id,
2519
revision_id) tuples for versions that are present in this versioned
2520
file, but not used by the corresponding inventory.
2522
local_progress = None
2523
if progress_bar is None:
2524
local_progress = ui.ui_factory.nested_progress_bar()
2525
progress_bar = local_progress
2527
return self._check_file_version_parents(texts, progress_bar)
2530
local_progress.finished()
2532
def _check_file_version_parents(self, texts, progress_bar):
2533
"""See check_file_version_parents."""
2535
self.file_ids = {file_id for file_id, _ in self.text_index}
2536
# text keys is now grouped by file_id
2537
n_versions = len(self.text_index)
2538
progress_bar.update(gettext('loading text store'), 0, n_versions)
2539
parent_map = self.repository.texts.get_parent_map(self.text_index)
2540
# On unlistable transports this could well be empty/error...
2541
text_keys = self.repository.texts.keys()
2542
unused_keys = frozenset(text_keys) - set(self.text_index)
2543
for num, key in enumerate(self.text_index):
2544
progress_bar.update(gettext('checking text graph'), num, n_versions)
2545
correct_parents = self.calculate_file_version_parents(key)
2547
knit_parents = parent_map[key]
2548
except errors.RevisionNotPresent:
2551
if correct_parents != knit_parents:
2552
wrong_parents[key] = (knit_parents, correct_parents)
2553
return wrong_parents, unused_keys
2556
class InterVersionedFileRepository(InterRepository):
2558
_walk_to_common_revisions_batch_size = 50
2560
supports_fetch_spec = True
2563
def fetch(self, revision_id=None, find_ghosts=False,
2565
"""Fetch the content required to construct revision_id.
2567
The content is copied from self.source to self.target.
2569
:param revision_id: if None all content is copied, if NULL_REVISION no
2573
if self.target._format.experimental:
2574
ui.ui_factory.show_user_warning('experimental_format_fetch',
2575
from_format=self.source._format,
2576
to_format=self.target._format)
2577
from breezy.fetch import RepoFetcher
2578
# See <https://launchpad.net/bugs/456077> asking for a warning here
2579
if self.source._format.network_name() != self.target._format.network_name():
2580
ui.ui_factory.show_user_warning('cross_format_fetch',
2581
from_format=self.source._format,
2582
to_format=self.target._format)
2583
f = RepoFetcher(to_repository=self.target,
2584
from_repository=self.source,
2585
last_revision=revision_id,
2586
fetch_spec=fetch_spec,
2587
find_ghosts=find_ghosts)
2589
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2590
"""Walk out from revision_ids in source to revisions target has.
2592
:param revision_ids: The start point for the search.
2593
:return: A set of revision ids.
2595
target_graph = self.target.get_graph()
2596
revision_ids = frozenset(revision_ids)
2598
all_wanted_revs = revision_ids.union(if_present_ids)
2600
all_wanted_revs = revision_ids
2601
missing_revs = set()
2602
source_graph = self.source.get_graph()
2603
# ensure we don't pay silly lookup costs.
2604
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2605
null_set = frozenset([_mod_revision.NULL_REVISION])
2606
searcher_exhausted = False
2610
# Iterate the searcher until we have enough next_revs
2611
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2613
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2614
next_revs.update(next_revs_part)
2615
ghosts.update(ghosts_part)
2616
except StopIteration:
2617
searcher_exhausted = True
2619
# If there are ghosts in the source graph, and the caller asked for
2620
# them, make sure that they are present in the target.
2621
# We don't care about other ghosts as we can't fetch them and
2622
# haven't been asked to.
2623
ghosts_to_check = set(revision_ids.intersection(ghosts))
2624
revs_to_get = set(next_revs).union(ghosts_to_check)
2626
have_revs = set(target_graph.get_parent_map(revs_to_get))
2627
# we always have NULL_REVISION present.
2628
have_revs = have_revs.union(null_set)
2629
# Check if the target is missing any ghosts we need.
2630
ghosts_to_check.difference_update(have_revs)
2632
# One of the caller's revision_ids is a ghost in both the
2633
# source and the target.
2634
raise errors.NoSuchRevision(
2635
self.source, ghosts_to_check.pop())
2636
missing_revs.update(next_revs - have_revs)
2637
# Because we may have walked past the original stop point, make
2638
# sure everything is stopped
2639
stop_revs = searcher.find_seen_ancestors(have_revs)
2640
searcher.stop_searching_any(stop_revs)
2641
if searcher_exhausted:
2643
(started_keys, excludes, included_keys) = searcher.get_state()
2644
return vf_search.SearchResult(started_keys, excludes,
2645
len(included_keys), included_keys)
2648
def search_missing_revision_ids(self,
2649
find_ghosts=True, revision_ids=None, if_present_ids=None,
2651
"""Return the revision ids that source has that target does not.
2653
:param revision_ids: return revision ids included by these
2654
revision_ids. NoSuchRevision will be raised if any of these
2655
revisions are not present.
2656
:param if_present_ids: like revision_ids, but will not cause
2657
NoSuchRevision if any of these are absent, instead they will simply
2658
not be in the result. This is useful for e.g. finding revisions
2659
to fetch for tags, which may reference absent revisions.
2660
:param find_ghosts: If True find missing revisions in deep history
2661
rather than just finding the surface difference.
2662
:return: A breezy.graph.SearchResult.
2664
# stop searching at found target revisions.
2665
if not find_ghosts and (revision_ids is not None or if_present_ids is
2667
result = self._walk_to_common_revisions(revision_ids,
2668
if_present_ids=if_present_ids)
2671
result_set = result.get_keys()
2673
# generic, possibly worst case, slow code path.
2674
target_ids = set(self.target.all_revision_ids())
2675
source_ids = self._present_source_revisions_for(
2676
revision_ids, if_present_ids)
2677
result_set = set(source_ids).difference(target_ids)
2678
if limit is not None:
2679
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2680
result_set = set(itertools.islice(topo_ordered, limit))
2681
return self.source.revision_ids_to_search_result(result_set)
2683
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2684
"""Returns set of all revisions in ancestry of revision_ids present in
2687
:param revision_ids: if None, all revisions in source are returned.
2688
:param if_present_ids: like revision_ids, but if any/all of these are
2689
absent no error is raised.
2691
if revision_ids is not None or if_present_ids is not None:
2692
# First, ensure all specified revisions exist. Callers expect
2693
# NoSuchRevision when they pass absent revision_ids here.
2694
if revision_ids is None:
2695
revision_ids = set()
2696
if if_present_ids is None:
2697
if_present_ids = set()
2698
revision_ids = set(revision_ids)
2699
if_present_ids = set(if_present_ids)
2700
all_wanted_ids = revision_ids.union(if_present_ids)
2701
graph = self.source.get_graph()
2702
present_revs = set(graph.get_parent_map(all_wanted_ids))
2703
missing = revision_ids.difference(present_revs)
2705
raise errors.NoSuchRevision(self.source, missing.pop())
2706
found_ids = all_wanted_ids.intersection(present_revs)
2707
source_ids = [rev_id for (rev_id, parents) in
2708
graph.iter_ancestry(found_ids)
2709
if rev_id != _mod_revision.NULL_REVISION
2710
and parents is not None]
2712
source_ids = self.source.all_revision_ids()
2713
return set(source_ids)
2716
def _get_repo_format_to_test(self):
2720
def is_compatible(cls, source, target):
2721
# The default implementation is compatible with everything
2722
return (source._format.supports_full_versioned_files and
2723
target._format.supports_full_versioned_files)
2726
class InterDifferingSerializer(InterVersionedFileRepository):
2729
def _get_repo_format_to_test(self):
2733
def is_compatible(source, target):
2734
if not source._format.supports_full_versioned_files:
2736
if not target._format.supports_full_versioned_files:
2738
# This is redundant with format.check_conversion_target(), however that
2739
# raises an exception, and we just want to say "False" as in we won't
2740
# support converting between these formats.
2741
if 'IDS_never' in debug.debug_flags:
2743
if source.supports_rich_root() and not target.supports_rich_root():
2745
if (source._format.supports_tree_reference
2746
and not target._format.supports_tree_reference):
2748
if target._fallback_repositories and target._format.supports_chks:
2749
# IDS doesn't know how to copy CHKs for the parent inventories it
2750
# adds to stacked repos.
2752
if 'IDS_always' in debug.debug_flags:
2754
# Only use this code path for local source and target. IDS does far
2755
# too much IO (both bandwidth and roundtrips) over a network.
2756
if not source.controldir.transport.base.startswith('file:///'):
2758
if not target.controldir.transport.base.startswith('file:///'):
2762
def _get_trees(self, revision_ids, cache):
2764
for rev_id in revision_ids:
2766
possible_trees.append((rev_id, cache[rev_id]))
2768
# Not cached, but inventory might be present anyway.
2770
tree = self.source.revision_tree(rev_id)
2771
except errors.NoSuchRevision:
2772
# Nope, parent is ghost.
2775
cache[rev_id] = tree
2776
possible_trees.append((rev_id, tree))
2777
return possible_trees
2779
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2780
"""Get the best delta and base for this revision.
2782
:return: (basis_id, delta)
2785
# Generate deltas against each tree, to find the shortest.
2786
# FIXME: Support nested trees
2787
texts_possibly_new_in_tree = set()
2788
for basis_id, basis_tree in possible_trees:
2789
delta = tree.root_inventory._make_delta(basis_tree.root_inventory)
2790
for old_path, new_path, file_id, new_entry in delta:
2791
if new_path is None:
2792
# This file_id isn't present in the new rev, so we don't
2796
# Rich roots are handled elsewhere...
2798
kind = new_entry.kind
2799
if kind != 'directory' and kind != 'file':
2800
# No text record associated with this inventory entry.
2802
# This is a directory or file that has changed somehow.
2803
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2804
deltas.append((len(delta), basis_id, delta))
2806
return deltas[0][1:]
2808
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2809
"""Find all parent revisions that are absent, but for which the
2810
inventory is present, and copy those inventories.
2812
This is necessary to preserve correctness when the source is stacked
2813
without fallbacks configured. (Note that in cases like upgrade the
2814
source may be not have _fallback_repositories even though it is
2817
parent_revs = set(itertools.chain.from_iterable(viewvalues(
2819
present_parents = self.source.get_parent_map(parent_revs)
2820
absent_parents = parent_revs.difference(present_parents)
2821
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2822
(rev_id,) for rev_id in absent_parents)
2823
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2824
for parent_tree in self.source.revision_trees(parent_inv_ids):
2825
current_revision_id = parent_tree.get_revision_id()
2826
parents_parents_keys = parent_invs_keys_for_stacking[
2827
(current_revision_id,)]
2828
parents_parents = [key[-1] for key in parents_parents_keys]
2829
basis_id = _mod_revision.NULL_REVISION
2830
basis_tree = self.source.revision_tree(basis_id)
2831
delta = parent_tree.root_inventory._make_delta(
2832
basis_tree.root_inventory)
2833
self.target.add_inventory_by_delta(
2834
basis_id, delta, current_revision_id, parents_parents)
2835
cache[current_revision_id] = parent_tree
2837
def _fetch_batch(self, revision_ids, basis_id, cache):
2838
"""Fetch across a few revisions.
2840
:param revision_ids: The revisions to copy
2841
:param basis_id: The revision_id of a tree that must be in cache, used
2842
as a basis for delta when no other base is available
2843
:param cache: A cache of RevisionTrees that we can use.
2844
:return: The revision_id of the last converted tree. The RevisionTree
2845
for it will be in cache
2847
# Walk though all revisions; get inventory deltas, copy referenced
2848
# texts that delta references, insert the delta, revision and
2850
root_keys_to_create = set()
2853
pending_revisions = []
2854
parent_map = self.source.get_parent_map(revision_ids)
2855
self._fetch_parent_invs_for_stacking(parent_map, cache)
2856
self.source._safe_to_return_from_cache = True
2857
for tree in self.source.revision_trees(revision_ids):
2858
# Find a inventory delta for this revision.
2859
# Find text entries that need to be copied, too.
2860
current_revision_id = tree.get_revision_id()
2861
parent_ids = parent_map.get(current_revision_id, ())
2862
parent_trees = self._get_trees(parent_ids, cache)
2863
possible_trees = list(parent_trees)
2864
if len(possible_trees) == 0:
2865
# There either aren't any parents, or the parents are ghosts,
2866
# so just use the last converted tree.
2867
possible_trees.append((basis_id, cache[basis_id]))
2868
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2870
revision = self.source.get_revision(current_revision_id)
2871
pending_deltas.append((basis_id, delta,
2872
current_revision_id, revision.parent_ids))
2873
if self._converting_to_rich_root:
2874
self._revision_id_to_root_id[current_revision_id] = \
2876
# Determine which texts are in present in this revision but not in
2877
# any of the available parents.
2878
texts_possibly_new_in_tree = set()
2879
for old_path, new_path, file_id, entry in delta:
2880
if new_path is None:
2881
# This file_id isn't present in the new rev
2885
if not self.target.supports_rich_root():
2886
# The target doesn't support rich root, so we don't
2889
if self._converting_to_rich_root:
2890
# This can't be copied normally, we have to insert
2892
root_keys_to_create.add((file_id, entry.revision))
2895
texts_possibly_new_in_tree.add((file_id, entry.revision))
2896
for basis_id, basis_tree in possible_trees:
2897
basis_inv = basis_tree.root_inventory
2898
for file_key in list(texts_possibly_new_in_tree):
2899
file_id, file_revision = file_key
2901
entry = basis_inv[file_id]
2902
except errors.NoSuchId:
2904
if entry.revision == file_revision:
2905
texts_possibly_new_in_tree.remove(file_key)
2906
text_keys.update(texts_possibly_new_in_tree)
2907
pending_revisions.append(revision)
2908
cache[current_revision_id] = tree
2909
basis_id = current_revision_id
2910
self.source._safe_to_return_from_cache = False
2912
from_texts = self.source.texts
2913
to_texts = self.target.texts
2914
if root_keys_to_create:
2915
root_stream = _mod_fetch._new_root_data_stream(
2916
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2918
to_texts.insert_record_stream(root_stream)
2919
to_texts.insert_record_stream(from_texts.get_record_stream(
2920
text_keys, self.target._format._fetch_order,
2921
not self.target._format._fetch_uses_deltas))
2922
# insert inventory deltas
2923
for delta in pending_deltas:
2924
self.target.add_inventory_by_delta(*delta)
2925
if self.target._fallback_repositories:
2926
# Make sure this stacked repository has all the parent inventories
2927
# for the new revisions that we are about to insert. We do this
2928
# before adding the revisions so that no revision is added until
2929
# all the inventories it may depend on are added.
2930
# Note that this is overzealous, as we may have fetched these in an
2933
revision_ids = set()
2934
for revision in pending_revisions:
2935
revision_ids.add(revision.revision_id)
2936
parent_ids.update(revision.parent_ids)
2937
parent_ids.difference_update(revision_ids)
2938
parent_ids.discard(_mod_revision.NULL_REVISION)
2939
parent_map = self.source.get_parent_map(parent_ids)
2940
# we iterate over parent_map and not parent_ids because we don't
2941
# want to try copying any revision which is a ghost
2942
for parent_tree in self.source.revision_trees(parent_map):
2943
current_revision_id = parent_tree.get_revision_id()
2944
parents_parents = parent_map[current_revision_id]
2945
possible_trees = self._get_trees(parents_parents, cache)
2946
if len(possible_trees) == 0:
2947
# There either aren't any parents, or the parents are
2948
# ghosts, so just use the last converted tree.
2949
possible_trees.append((basis_id, cache[basis_id]))
2950
basis_id, delta = self._get_delta_for_revision(parent_tree,
2951
parents_parents, possible_trees)
2952
self.target.add_inventory_by_delta(
2953
basis_id, delta, current_revision_id, parents_parents)
2954
# insert signatures and revisions
2955
for revision in pending_revisions:
2957
signature = self.source.get_signature_text(
2958
revision.revision_id)
2959
self.target.add_signature_text(revision.revision_id,
2961
except errors.NoSuchRevision:
2963
self.target.add_revision(revision.revision_id, revision)
2966
def _fetch_all_revisions(self, revision_ids, pb):
2967
"""Fetch everything for the list of revisions.
2969
:param revision_ids: The list of revisions to fetch. Must be in
2971
:param pb: A ProgressTask
2974
basis_id, basis_tree = self._get_basis(revision_ids[0])
2976
cache = lru_cache.LRUCache(100)
2977
cache[basis_id] = basis_tree
2978
del basis_tree # We don't want to hang on to it here
2982
for offset in range(0, len(revision_ids), batch_size):
2983
self.target.start_write_group()
2985
pb.update(gettext('Transferring revisions'), offset,
2987
batch = revision_ids[offset:offset+batch_size]
2988
basis_id = self._fetch_batch(batch, basis_id, cache)
2990
self.source._safe_to_return_from_cache = False
2991
self.target.abort_write_group()
2994
hint = self.target.commit_write_group()
2997
if hints and self.target._format.pack_compresses:
2998
self.target.pack(hint=hints)
2999
pb.update(gettext('Transferring revisions'), len(revision_ids),
3003
def fetch(self, revision_id=None, find_ghosts=False,
3005
"""See InterRepository.fetch()."""
3006
if fetch_spec is not None:
3007
revision_ids = fetch_spec.get_keys()
3010
if self.source._format.experimental:
3011
ui.ui_factory.show_user_warning('experimental_format_fetch',
3012
from_format=self.source._format,
3013
to_format=self.target._format)
3014
if (not self.source.supports_rich_root()
3015
and self.target.supports_rich_root()):
3016
self._converting_to_rich_root = True
3017
self._revision_id_to_root_id = {}
3019
self._converting_to_rich_root = False
3020
# See <https://launchpad.net/bugs/456077> asking for a warning here
3021
if self.source._format.network_name() != self.target._format.network_name():
3022
ui.ui_factory.show_user_warning('cross_format_fetch',
3023
from_format=self.source._format,
3024
to_format=self.target._format)
3025
if revision_ids is None:
3027
search_revision_ids = [revision_id]
3029
search_revision_ids = None
3030
revision_ids = self.target.search_missing_revision_ids(self.source,
3031
revision_ids=search_revision_ids,
3032
find_ghosts=find_ghosts).get_keys()
3033
if not revision_ids:
3035
revision_ids = tsort.topo_sort(
3036
self.source.get_graph().get_parent_map(revision_ids))
3037
if not revision_ids:
3039
# Walk though all revisions; get inventory deltas, copy referenced
3040
# texts that delta references, insert the delta, revision and
3042
pb = ui.ui_factory.nested_progress_bar()
3044
self._fetch_all_revisions(revision_ids, pb)
3047
return len(revision_ids), 0
3049
def _get_basis(self, first_revision_id):
3050
"""Get a revision and tree which exists in the target.
3052
This assumes that first_revision_id is selected for transmission
3053
because all other ancestors are already present. If we can't find an
3054
ancestor we fall back to NULL_REVISION since we know that is safe.
3056
:return: (basis_id, basis_tree)
3058
first_rev = self.source.get_revision(first_revision_id)
3060
basis_id = first_rev.parent_ids[0]
3061
# only valid as a basis if the target has it
3062
self.target.get_revision(basis_id)
3063
# Try to get a basis tree - if it's a ghost it will hit the
3064
# NoSuchRevision case.
3065
basis_tree = self.source.revision_tree(basis_id)
3066
except (IndexError, errors.NoSuchRevision):
3067
basis_id = _mod_revision.NULL_REVISION
3068
basis_tree = self.source.revision_tree(basis_id)
3069
return basis_id, basis_tree
3072
class InterSameDataRepository(InterVersionedFileRepository):
3073
"""Code for converting between repositories that represent the same data.
3075
Data format and model must match for this to work.
3079
def _get_repo_format_to_test(self):
3080
"""Repository format for testing with.
3082
InterSameData can pull from subtree to subtree and from non-subtree to
3083
non-subtree, so we test this with the richest repository format.
3085
from breezy.repofmt import knitrepo
3086
return knitrepo.RepositoryFormatKnit3()
3089
def is_compatible(source, target):
3091
InterRepository._same_model(source, target) and
3092
source._format.supports_full_versioned_files and
3093
target._format.supports_full_versioned_files)
3096
InterRepository.register_optimiser(InterVersionedFileRepository)
3097
InterRepository.register_optimiser(InterDifferingSerializer)
3098
InterRepository.register_optimiser(InterSameDataRepository)
3101
def install_revisions(repository, iterable, num_revisions=None, pb=None):
3102
"""Install all revision data into a repository.
3104
Accepts an iterable of revision, tree, signature tuples. The signature
3107
repository.start_write_group()
3109
inventory_cache = lru_cache.LRUCache(10)
3110
for n, (revision, revision_tree, signature) in enumerate(iterable):
3111
_install_revision(repository, revision, revision_tree, signature,
3114
pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
3116
repository.abort_write_group()
3119
repository.commit_write_group()
3122
def _install_revision(repository, rev, revision_tree, signature,
3124
"""Install all revision data into a repository."""
3125
present_parents = []
3127
for p_id in rev.parent_ids:
3128
if repository.has_revision(p_id):
3129
present_parents.append(p_id)
3130
parent_trees[p_id] = repository.revision_tree(p_id)
3132
parent_trees[p_id] = repository.revision_tree(
3133
_mod_revision.NULL_REVISION)
3135
# FIXME: Support nested trees
3136
inv = revision_tree.root_inventory
3137
entries = inv.iter_entries()
3138
# backwards compatibility hack: skip the root id.
3139
if not repository.supports_rich_root():
3140
path, root = next(entries)
3141
if root.revision != rev.revision_id:
3142
raise errors.IncompatibleRevision(repr(repository))
3144
for path, ie in entries:
3145
text_keys[(ie.file_id, ie.revision)] = ie
3146
text_parent_map = repository.texts.get_parent_map(text_keys)
3147
missing_texts = set(text_keys) - set(text_parent_map)
3148
# Add the texts that are not already present
3149
for text_key in missing_texts:
3150
ie = text_keys[text_key]
3152
# FIXME: TODO: The following loop overlaps/duplicates that done by
3153
# commit to determine parents. There is a latent/real bug here where
3154
# the parents inserted are not those commit would do - in particular
3155
# they are not filtered by heads(). RBC, AB
3156
for revision, tree in viewitems(parent_trees):
3157
if not tree.has_id(ie.file_id):
3159
parent_id = tree.get_file_revision(ie.file_id)
3160
if parent_id in text_parents:
3162
text_parents.append((ie.file_id, parent_id))
3163
lines = revision_tree.get_file(ie.file_id).readlines()
3164
repository.texts.add_lines(text_key, text_parents, lines)
3166
# install the inventory
3167
if repository._format._commit_inv_deltas and len(rev.parent_ids):
3168
# Cache this inventory
3169
inventory_cache[rev.revision_id] = inv
3171
basis_inv = inventory_cache[rev.parent_ids[0]]
3173
repository.add_inventory(rev.revision_id, inv, present_parents)
3175
delta = inv._make_delta(basis_inv)
3176
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
3177
rev.revision_id, present_parents)
3179
repository.add_inventory(rev.revision_id, inv, present_parents)
3180
except errors.RevisionAlreadyPresent:
3182
if signature is not None:
3183
repository.add_signature_text(rev.revision_id, signature)
3184
repository.add_revision(rev.revision_id, rev, inv)
3187
def install_revision(repository, rev, revision_tree):
3188
"""Install all revision data into a repository."""
3189
install_revisions(repository, [(rev, revision_tree, None)])