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.revisiontree 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 (
71
RepositoryFormatMetaDir,
81
class VersionedFileRepositoryFormat(RepositoryFormat):
82
"""Base class for all repository formats that are VersionedFiles-based."""
84
supports_full_versioned_files = True
85
supports_versioned_directories = True
86
supports_unreferenced_revisions = True
88
# Should commit add an inventory, or an inventory delta to the repository.
89
_commit_inv_deltas = True
90
# What order should fetch operations request streams in?
91
# The default is unordered as that is the cheapest for an origin to
93
_fetch_order = 'unordered'
94
# Does this repository format use deltas that can be fetched as-deltas ?
95
# (E.g. knits, where the knit deltas can be transplanted intact.
96
# We default to False, which will ensure that enough data to get
97
# a full text out of any fetch stream will be grabbed.
98
_fetch_uses_deltas = False
101
class VersionedFileCommitBuilder(CommitBuilder):
102
"""Commit builder implementation for versioned files based repositories.
105
# this commit builder supports the record_entry_contents interface
106
supports_record_entry_contents = True
108
# the default CommitBuilder does not manage trees whose root is versioned.
109
_versioned_root = False
111
def __init__(self, repository, parents, config_stack, timestamp=None,
112
timezone=None, committer=None, revprops=None,
113
revision_id=None, lossy=False):
114
super(VersionedFileCommitBuilder, self).__init__(repository,
115
parents, config_stack, timestamp, timezone, committer, revprops,
118
basis_id = self.parents[0]
120
basis_id = _mod_revision.NULL_REVISION
121
self.basis_delta_revision = basis_id
122
self.new_inventory = Inventory(None)
123
self._basis_delta = []
124
self.__heads = graph.HeadsCache(repository.get_graph()).heads
125
# memo'd check for no-op commits.
126
self._any_changes = False
127
# API compatibility, older code that used CommitBuilder did not call
128
# .record_delete(), which means the delta that is computed would not be
129
# valid. Callers that will call record_delete() should call
130
# .will_record_deletes() to indicate that.
131
self._recording_deletes = False
133
def will_record_deletes(self):
134
"""Tell the commit builder that deletes are being notified.
136
This enables the accumulation of an inventory delta; for the resulting
137
commit to be valid, deletes against the basis MUST be recorded via
138
builder.record_delete().
140
self._recording_deletes = True
142
def any_changes(self):
143
"""Return True if any entries were changed.
145
This includes merge-only changes. It is the core for the --unchanged
148
:return: True if any changes have occured.
150
return self._any_changes
152
def _ensure_fallback_inventories(self):
153
"""Ensure that appropriate inventories are available.
155
This only applies to repositories that are stacked, and is about
156
enusring the stacking invariants. Namely, that for any revision that is
157
present, we either have all of the file content, or we have the parent
158
inventory and the delta file content.
160
if not self.repository._fallback_repositories:
162
if not self.repository._format.supports_chks:
163
raise errors.BzrError("Cannot commit directly to a stacked branch"
164
" in pre-2a formats. See "
165
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
166
# This is a stacked repo, we need to make sure we have the parent
167
# inventories for the parents.
168
parent_keys = [(p,) for p in self.parents]
169
parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
170
missing_parent_keys = {pk for pk in parent_keys
171
if pk not in parent_map}
172
fallback_repos = list(reversed(self.repository._fallback_repositories))
173
missing_keys = [('inventories', pk[0])
174
for pk in missing_parent_keys]
176
while missing_keys and fallback_repos:
177
fallback_repo = fallback_repos.pop()
178
source = fallback_repo._get_source(self.repository._format)
179
sink = self.repository._get_sink()
180
stream = source.get_stream_for_missing_keys(missing_keys)
181
missing_keys = sink.insert_stream_without_locking(stream,
182
self.repository._format)
184
raise errors.BzrError('Unable to fill in parent inventories for a'
187
def commit(self, message):
188
"""Make the actual commit.
190
:return: The revision id of the recorded revision.
192
self._validate_unicode_text(message, 'commit message')
193
rev = _mod_revision.Revision(
194
timestamp=self._timestamp,
195
timezone=self._timezone,
196
committer=self._committer,
198
inventory_sha1=self.inv_sha1,
199
revision_id=self._new_revision_id,
200
properties=self._revprops)
201
rev.parent_ids = self.parents
202
if self._config_stack.get('create_signatures') == _mod_config.SIGN_ALWAYS:
203
testament = Testament(rev, self.revision_tree())
204
plaintext = testament.as_short_text()
205
self.repository.store_revision_signature(
206
gpg.GPGStrategy(self._config_stack), plaintext,
207
self._new_revision_id)
208
self.repository._add_revision(rev)
209
self._ensure_fallback_inventories()
210
self.repository.commit_write_group()
211
return self._new_revision_id
214
"""Abort the commit that is being built.
216
self.repository.abort_write_group()
218
def revision_tree(self):
219
"""Return the tree that was just committed.
221
After calling commit() this can be called to get a
222
RevisionTree representing the newly committed tree. This is
223
preferred to calling Repository.revision_tree() because that may
224
require deserializing the inventory, while we already have a copy in
227
if self.new_inventory is None:
228
self.new_inventory = self.repository.get_inventory(
229
self._new_revision_id)
230
return InventoryRevisionTree(self.repository, self.new_inventory,
231
self._new_revision_id)
233
def finish_inventory(self):
234
"""Tell the builder that the inventory is finished.
236
:return: The inventory id in the repository, which can be used with
237
repository.get_inventory.
239
if self.new_inventory is None:
240
# an inventory delta was accumulated without creating a new
242
basis_id = self.basis_delta_revision
243
# We ignore the 'inventory' returned by add_inventory_by_delta
244
# because self.new_inventory is used to hint to the rest of the
245
# system what code path was taken
246
self.inv_sha1, _ = self.repository.add_inventory_by_delta(
247
basis_id, self._basis_delta, self._new_revision_id,
250
if self.new_inventory.root is None:
251
raise AssertionError('Root entry should be supplied to'
252
' record_entry_contents, as of bzr 0.10.')
253
self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
254
self.new_inventory.revision_id = self._new_revision_id
255
self.inv_sha1 = self.repository.add_inventory(
256
self._new_revision_id,
260
return self._new_revision_id
262
def _check_root(self, ie, parent_invs, tree):
263
"""Helper for record_entry_contents.
265
:param ie: An entry being added.
266
:param parent_invs: The inventories of the parent revisions of the
268
:param tree: The tree that is being committed.
270
# In this revision format, root entries have no knit or weave When
271
# serializing out to disk and back in root.revision is always
273
ie.revision = self._new_revision_id
275
def _require_root_change(self, tree):
276
"""Enforce an appropriate root object change.
278
This is called once when record_iter_changes is called, if and only if
279
the root was not in the delta calculated by record_iter_changes.
281
:param tree: The tree which is being committed.
283
if len(self.parents) == 0:
284
raise errors.RootMissing()
285
entry = entry_factory['directory'](tree.path2id(''), '',
287
entry.revision = self._new_revision_id
288
self._basis_delta.append(('', '', entry.file_id, entry))
290
def _get_delta(self, ie, basis_inv, path):
291
"""Get a delta against the basis inventory for ie."""
292
if not basis_inv.has_id(ie.file_id):
294
result = (None, path, ie.file_id, ie)
295
self._basis_delta.append(result)
297
elif ie != basis_inv[ie.file_id]:
299
# TODO: avoid tis id2path call.
300
result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
301
self._basis_delta.append(result)
307
def _heads(self, file_id, revision_ids):
308
"""Calculate the graph heads for revision_ids in the graph of file_id.
310
This can use either a per-file graph or a global revision graph as we
311
have an identity relationship between the two graphs.
313
return self.__heads(revision_ids)
315
def get_basis_delta(self):
316
"""Return the complete inventory delta versus the basis inventory.
318
This has been built up with the calls to record_delete and
319
record_entry_contents. The client must have already called
320
will_record_deletes() to indicate that they will be generating a
323
:return: An inventory delta, suitable for use with apply_delta, or
324
Repository.add_inventory_by_delta, etc.
326
if not self._recording_deletes:
327
raise AssertionError("recording deletes not activated.")
328
return self._basis_delta
330
def record_delete(self, path, file_id):
331
"""Record that a delete occured against a basis tree.
333
This is an optional API - when used it adds items to the basis_delta
334
being accumulated by the commit builder. It cannot be called unless the
335
method will_record_deletes() has been called to inform the builder that
336
a delta is being supplied.
338
:param path: The path of the thing deleted.
339
:param file_id: The file id that was deleted.
341
if not self._recording_deletes:
342
raise AssertionError("recording deletes not activated.")
343
delta = (path, None, file_id, None)
344
self._basis_delta.append(delta)
345
self._any_changes = True
348
def record_entry_contents(self, ie, parent_invs, path, tree,
350
"""Record the content of ie from tree into the commit if needed.
352
Side effect: sets ie.revision when unchanged
354
:param ie: An inventory entry present in the commit.
355
:param parent_invs: The inventories of the parent revisions of the
357
:param path: The path the entry is at in the tree.
358
:param tree: The tree which contains this entry and should be used to
360
:param content_summary: Summary data from the tree about the paths
361
content - stat, length, exec, sha/link target. This is only
362
accessed when the entry has a revision of None - that is when it is
363
a candidate to commit.
364
:return: A tuple (change_delta, version_recorded, fs_hash).
365
change_delta is an inventory_delta change for this entry against
366
the basis tree of the commit, or None if no change occured against
368
version_recorded is True if a new version of the entry has been
369
recorded. For instance, committing a merge where a file was only
370
changed on the other side will return (delta, False).
371
fs_hash is either None, or the hash details for the path (currently
372
a tuple of the contents sha1 and the statvalue returned by
373
tree.get_file_with_stat()).
375
if self.new_inventory.root is None:
376
if ie.parent_id is not None:
377
raise errors.RootMissing()
378
self._check_root(ie, parent_invs, tree)
379
if ie.revision is None:
380
kind = content_summary[0]
382
# ie is carried over from a prior commit
384
# XXX: repository specific check for nested tree support goes here - if
385
# the repo doesn't want nested trees we skip it ?
386
if (kind == 'tree-reference' and
387
not self.repository._format.supports_tree_reference):
388
# mismatch between commit builder logic and repository:
389
# this needs the entry creation pushed down into the builder.
390
raise NotImplementedError('Missing repository subtree support.')
391
self.new_inventory.add(ie)
393
# TODO: slow, take it out of the inner loop.
395
basis_inv = parent_invs[0]
397
basis_inv = Inventory(root_id=None)
399
# ie.revision is always None if the InventoryEntry is considered
400
# for committing. We may record the previous parents revision if the
401
# content is actually unchanged against a sole head.
402
if ie.revision is not None:
403
if not self._versioned_root and path == '':
404
# repositories that do not version the root set the root's
405
# revision to the new commit even when no change occurs (more
406
# specifically, they do not record a revision on the root; and
407
# the rev id is assigned to the root during deserialisation -
408
# this masks when a change may have occurred against the basis.
409
# To match this we always issue a delta, because the revision
410
# of the root will always be changing.
411
if basis_inv.has_id(ie.file_id):
412
delta = (basis_inv.id2path(ie.file_id), path,
416
delta = (None, path, ie.file_id, ie)
417
self._basis_delta.append(delta)
418
return delta, False, None
420
# we don't need to commit this, because the caller already
421
# determined that an existing revision of this file is
422
# appropriate. If it's not being considered for committing then
423
# it and all its parents to the root must be unaltered so
424
# no-change against the basis.
425
if ie.revision == self._new_revision_id:
426
raise AssertionError("Impossible situation, a skipped "
427
"inventory entry (%r) claims to be modified in this "
428
"commit (%r).", (ie, self._new_revision_id))
429
return None, False, None
430
# XXX: Friction: parent_candidates should return a list not a dict
431
# so that we don't have to walk the inventories again.
432
parent_candidate_entries = ie.parent_candidates(parent_invs)
433
head_set = self._heads(ie.file_id, parent_candidate_entries.keys())
435
for inv in parent_invs:
436
if inv.has_id(ie.file_id):
437
old_rev = inv[ie.file_id].revision
438
if old_rev in head_set:
439
heads.append(inv[ie.file_id].revision)
440
head_set.remove(inv[ie.file_id].revision)
443
# now we check to see if we need to write a new record to the
445
# We write a new entry unless there is one head to the ancestors, and
446
# the kind-derived content is unchanged.
448
# Cheapest check first: no ancestors, or more the one head in the
449
# ancestors, we write a new node.
453
# There is a single head, look it up for comparison
454
parent_entry = parent_candidate_entries[heads[0]]
455
# if the non-content specific data has changed, we'll be writing a
457
if (parent_entry.parent_id != ie.parent_id or
458
parent_entry.name != ie.name):
460
# now we need to do content specific checks:
462
# if the kind changed the content obviously has
463
if kind != parent_entry.kind:
465
# Stat cache fingerprint feedback for the caller - None as we usually
466
# don't generate one.
469
if content_summary[2] is None:
470
raise ValueError("Files must not have executable = None")
472
# We can't trust a check of the file length because of content
474
if (# if the exec bit has changed we have to store:
475
parent_entry.executable != content_summary[2]):
477
elif parent_entry.text_sha1 == content_summary[3]:
478
# all meta and content is unchanged (using a hash cache
479
# hit to check the sha)
480
ie.revision = parent_entry.revision
481
ie.text_size = parent_entry.text_size
482
ie.text_sha1 = parent_entry.text_sha1
483
ie.executable = parent_entry.executable
484
return self._get_delta(ie, basis_inv, path), False, None
486
# Either there is only a hash change(no hash cache entry,
487
# or same size content change), or there is no change on
489
# Provide the parent's hash to the store layer, so that the
490
# content is unchanged we will not store a new node.
491
nostore_sha = parent_entry.text_sha1
493
# We want to record a new node regardless of the presence or
494
# absence of a content change in the file.
496
ie.executable = content_summary[2]
497
file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
499
text = file_obj.read()
503
ie.text_sha1, ie.text_size = self._add_text_to_weave(
504
ie.file_id, text, heads, nostore_sha)
505
# Let the caller know we generated a stat fingerprint.
506
fingerprint = (ie.text_sha1, stat_value)
507
except errors.ExistingContent:
508
# Turns out that the file content was unchanged, and we were
509
# only going to store a new node if it was changed. Carry over
511
ie.revision = parent_entry.revision
512
ie.text_size = parent_entry.text_size
513
ie.text_sha1 = parent_entry.text_sha1
514
ie.executable = parent_entry.executable
515
return self._get_delta(ie, basis_inv, path), False, None
516
elif kind == 'directory':
518
# all data is meta here, nothing specific to directory, so
520
ie.revision = parent_entry.revision
521
return self._get_delta(ie, basis_inv, path), False, None
522
self._add_text_to_weave(ie.file_id, '', heads, None)
523
elif kind == 'symlink':
524
current_link_target = content_summary[3]
526
# symlink target is not generic metadata, check if it has
528
if current_link_target != parent_entry.symlink_target:
531
# unchanged, carry over.
532
ie.revision = parent_entry.revision
533
ie.symlink_target = parent_entry.symlink_target
534
return self._get_delta(ie, basis_inv, path), False, None
535
ie.symlink_target = current_link_target
536
self._add_text_to_weave(ie.file_id, '', heads, None)
537
elif kind == 'tree-reference':
539
if content_summary[3] != parent_entry.reference_revision:
542
# unchanged, carry over.
543
ie.reference_revision = parent_entry.reference_revision
544
ie.revision = parent_entry.revision
545
return self._get_delta(ie, basis_inv, path), False, None
546
ie.reference_revision = content_summary[3]
547
if ie.reference_revision is None:
548
raise AssertionError("invalid content_summary for nested tree: %r"
549
% (content_summary,))
550
self._add_text_to_weave(ie.file_id, '', heads, None)
552
raise NotImplementedError('unknown kind')
553
ie.revision = self._new_revision_id
554
# The initial commit adds a root directory, but this in itself is not
555
# a worthwhile commit.
556
if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
558
self._any_changes = True
559
return self._get_delta(ie, basis_inv, path), True, fingerprint
561
def record_iter_changes(self, tree, basis_revision_id, iter_changes,
562
_entry_factory=entry_factory):
563
"""Record a new tree via iter_changes.
565
:param tree: The tree to obtain text contents from for changed objects.
566
:param basis_revision_id: The revision id of the tree the iter_changes
567
has been generated against. Currently assumed to be the same
568
as self.parents[0] - if it is not, errors may occur.
569
:param iter_changes: An iter_changes iterator with the changes to apply
570
to basis_revision_id. The iterator must not include any items with
571
a current kind of None - missing items must be either filtered out
572
or errored-on before record_iter_changes sees the item.
573
:param _entry_factory: Private method to bind entry_factory locally for
575
:return: A generator of (file_id, relpath, fs_hash) tuples for use with
578
# Create an inventory delta based on deltas between all the parents and
579
# deltas between all the parent inventories. We use inventory delta's
580
# between the inventory objects because iter_changes masks
581
# last-changed-field only changes.
583
# file_id -> change map, change is fileid, paths, changed, versioneds,
584
# parents, names, kinds, executables
586
# {file_id -> revision_id -> inventory entry, for entries in parent
587
# trees that are not parents[0]
591
revtrees = list(self.repository.revision_trees(self.parents))
592
except errors.NoSuchRevision:
593
# one or more ghosts, slow path.
595
for revision_id in self.parents:
597
revtrees.append(self.repository.revision_tree(revision_id))
598
except errors.NoSuchRevision:
600
basis_revision_id = _mod_revision.NULL_REVISION
602
revtrees.append(self.repository.revision_tree(
603
_mod_revision.NULL_REVISION))
604
# The basis inventory from a repository
606
basis_tree = revtrees[0]
608
basis_tree = self.repository.revision_tree(
609
_mod_revision.NULL_REVISION)
610
basis_inv = basis_tree.root_inventory
611
if len(self.parents) > 0:
612
if basis_revision_id != self.parents[0] and not ghost_basis:
614
"arbitrary basis parents not yet supported with merges")
615
for revtree in revtrees[1:]:
616
for change in revtree.root_inventory._make_delta(basis_inv):
617
if change[1] is None:
618
# Not present in this parent.
620
if change[2] not in merged_ids:
621
if change[0] is not None:
622
basis_entry = basis_inv[change[2]]
623
merged_ids[change[2]] = [
625
basis_entry.revision,
628
parent_entries[change[2]] = {
630
basis_entry.revision:basis_entry,
632
change[3].revision:change[3],
635
merged_ids[change[2]] = [change[3].revision]
636
parent_entries[change[2]] = {change[3].revision:change[3]}
638
merged_ids[change[2]].append(change[3].revision)
639
parent_entries[change[2]][change[3].revision] = change[3]
642
# Setup the changes from the tree:
643
# changes maps file_id -> (change, [parent revision_ids])
645
for change in iter_changes:
646
# This probably looks up in basis_inv way to much.
647
if change[1][0] is not None:
648
head_candidate = [basis_inv[change[0]].revision]
651
changes[change[0]] = change, merged_ids.get(change[0],
653
unchanged_merged = set(merged_ids) - set(changes)
654
# Extend the changes dict with synthetic changes to record merges of
656
for file_id in unchanged_merged:
657
# Record a merged version of these items that did not change vs the
658
# basis. This can be either identical parallel changes, or a revert
659
# of a specific file after a merge. The recorded content will be
660
# that of the current tree (which is the same as the basis), but
661
# the per-file graph will reflect a merge.
662
# NB:XXX: We are reconstructing path information we had, this
663
# should be preserved instead.
664
# inv delta change: (file_id, (path_in_source, path_in_target),
665
# changed_content, versioned, parent, name, kind,
668
basis_entry = basis_inv[file_id]
669
except errors.NoSuchId:
670
# a change from basis->some_parents but file_id isn't in basis
671
# so was new in the merge, which means it must have changed
672
# from basis -> current, and as it hasn't the add was reverted
673
# by the user. So we discard this change.
677
(basis_inv.id2path(file_id), tree.id2path(file_id)),
679
(basis_entry.parent_id, basis_entry.parent_id),
680
(basis_entry.name, basis_entry.name),
681
(basis_entry.kind, basis_entry.kind),
682
(basis_entry.executable, basis_entry.executable))
683
changes[file_id] = (change, merged_ids[file_id])
684
# changes contains tuples with the change and a set of inventory
685
# candidates for the file.
687
# old_path, new_path, file_id, new_inventory_entry
688
seen_root = False # Is the root in the basis delta?
689
inv_delta = self._basis_delta
690
modified_rev = self._new_revision_id
691
for change, head_candidates in changes.values():
692
if change[3][1]: # versioned in target.
693
# Several things may be happening here:
694
# We may have a fork in the per-file graph
695
# - record a change with the content from tree
696
# We may have a change against < all trees
697
# - carry over the tree that hasn't changed
698
# We may have a change against all trees
699
# - record the change with the content from tree
702
entry = _entry_factory[kind](file_id, change[5][1],
704
head_set = self._heads(change[0], set(head_candidates))
707
for head_candidate in head_candidates:
708
if head_candidate in head_set:
709
heads.append(head_candidate)
710
head_set.remove(head_candidate)
713
# Could be a carry-over situation:
714
parent_entry_revs = parent_entries.get(file_id, None)
715
if parent_entry_revs:
716
parent_entry = parent_entry_revs.get(heads[0], None)
719
if parent_entry is None:
720
# The parent iter_changes was called against is the one
721
# that is the per-file head, so any change is relevant
722
# iter_changes is valid.
723
carry_over_possible = False
725
# could be a carry over situation
726
# A change against the basis may just indicate a merge,
727
# we need to check the content against the source of the
728
# merge to determine if it was changed after the merge
730
if (parent_entry.kind != entry.kind or
731
parent_entry.parent_id != entry.parent_id or
732
parent_entry.name != entry.name):
733
# Metadata common to all entries has changed
734
# against per-file parent
735
carry_over_possible = False
737
carry_over_possible = True
738
# per-type checks for changes against the parent_entry
741
# Cannot be a carry-over situation
742
carry_over_possible = False
743
# Populate the entry in the delta
745
# XXX: There is still a small race here: If someone reverts the content of a file
746
# after iter_changes examines and decides it has changed,
747
# we will unconditionally record a new version even if some
748
# other process reverts it while commit is running (with
749
# the revert happening after iter_changes did its
752
entry.executable = True
754
entry.executable = False
755
if (carry_over_possible and
756
parent_entry.executable == entry.executable):
757
# Check the file length, content hash after reading
759
nostore_sha = parent_entry.text_sha1
762
file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
764
text = file_obj.read()
768
entry.text_sha1, entry.text_size = self._add_text_to_weave(
769
file_id, text, heads, nostore_sha)
770
yield file_id, change[1][1], (entry.text_sha1, stat_value)
771
except errors.ExistingContent:
772
# No content change against a carry_over parent
773
# Perhaps this should also yield a fs hash update?
775
entry.text_size = parent_entry.text_size
776
entry.text_sha1 = parent_entry.text_sha1
777
elif kind == 'symlink':
779
entry.symlink_target = tree.get_symlink_target(file_id)
780
if (carry_over_possible and
781
parent_entry.symlink_target == entry.symlink_target):
784
self._add_text_to_weave(change[0], '', heads, None)
785
elif kind == 'directory':
786
if carry_over_possible:
789
# Nothing to set on the entry.
790
# XXX: split into the Root and nonRoot versions.
791
if change[1][1] != '' or self.repository.supports_rich_root():
792
self._add_text_to_weave(change[0], '', heads, None)
793
elif kind == 'tree-reference':
794
if not self.repository._format.supports_tree_reference:
795
# This isn't quite sane as an error, but we shouldn't
796
# ever see this code path in practice: tree's don't
797
# permit references when the repo doesn't support tree
799
raise errors.UnsupportedOperation(tree.add_reference,
801
reference_revision = tree.get_reference_revision(change[0])
802
entry.reference_revision = reference_revision
803
if (carry_over_possible and
804
parent_entry.reference_revision == reference_revision):
807
self._add_text_to_weave(change[0], '', heads, None)
809
raise AssertionError('unknown kind %r' % kind)
811
entry.revision = modified_rev
813
entry.revision = parent_entry.revision
816
new_path = change[1][1]
817
inv_delta.append((change[1][0], new_path, change[0], entry))
820
self.new_inventory = None
821
# The initial commit adds a root directory, but this in itself is not
822
# a worthwhile commit.
823
if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
824
(len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
825
# This should perhaps be guarded by a check that the basis we
826
# commit against is the basis for the commit and if not do a delta
828
self._any_changes = True
830
# housekeeping root entry changes do not affect no-change commits.
831
self._require_root_change(tree)
832
self.basis_delta_revision = basis_revision_id
834
def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
835
parent_keys = tuple([(file_id, parent) for parent in parents])
836
return self.repository.texts._add_text(
837
(file_id, self._new_revision_id), parent_keys, new_text,
838
nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
841
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
842
"""This commitbuilder actually records the root id"""
844
# the root entry gets versioned properly by this builder.
845
_versioned_root = True
847
def _check_root(self, ie, parent_invs, tree):
848
"""Helper for record_entry_contents.
850
:param ie: An entry being added.
851
:param parent_invs: The inventories of the parent revisions of the
853
:param tree: The tree that is being committed.
856
def _require_root_change(self, tree):
857
"""Enforce an appropriate root object change.
859
This is called once when record_iter_changes is called, if and only if
860
the root was not in the delta calculated by record_iter_changes.
862
:param tree: The tree which is being committed.
864
# versioned roots do not change unless the tree found a change.
867
class VersionedFileRepository(Repository):
868
"""Repository holding history for one or more branches.
870
The repository holds and retrieves historical information including
871
revisions and file history. It's normally accessed only by the Branch,
872
which views a particular line of development through that history.
874
The Repository builds on top of some byte storage facilies (the revisions,
875
signatures, inventories, texts and chk_bytes attributes) and a Transport,
876
which respectively provide byte storage and a means to access the (possibly
879
The byte storage facilities are addressed via tuples, which we refer to
880
as 'keys' throughout the code base. Revision_keys, inventory_keys and
881
signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
882
(file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
883
byte string made up of a hash identifier and a hash value.
884
We use this interface because it allows low friction with the underlying
885
code that implements disk indices, network encoding and other parts of
888
:ivar revisions: A breezy.versionedfile.VersionedFiles instance containing
889
the serialised revisions for the repository. This can be used to obtain
890
revision graph information or to access raw serialised revisions.
891
The result of trying to insert data into the repository via this store
892
is undefined: it should be considered read-only except for implementors
894
:ivar signatures: A breezy.versionedfile.VersionedFiles instance containing
895
the serialised signatures for the repository. This can be used to
896
obtain access to raw serialised signatures. The result of trying to
897
insert data into the repository via this store is undefined: it should
898
be considered read-only except for implementors of repositories.
899
:ivar inventories: A breezy.versionedfile.VersionedFiles instance containing
900
the serialised inventories for the repository. This can be used to
901
obtain unserialised inventories. The result of trying to insert data
902
into the repository via this store is undefined: it should be
903
considered read-only except for implementors of repositories.
904
:ivar texts: A breezy.versionedfile.VersionedFiles instance containing the
905
texts of files and directories for the repository. This can be used to
906
obtain file texts or file graphs. Note that Repository.iter_file_bytes
907
is usually a better interface for accessing file texts.
908
The result of trying to insert data into the repository via this store
909
is undefined: it should be considered read-only except for implementors
911
:ivar chk_bytes: A breezy.versionedfile.VersionedFiles instance containing
912
any data the repository chooses to store or have indexed by its hash.
913
The result of trying to insert data into the repository via this store
914
is undefined: it should be considered read-only except for implementors
916
:ivar _transport: Transport for file access to repository, typically
917
pointing to .bzr/repository.
920
# What class to use for a CommitBuilder. Often it's simpler to change this
921
# in a Repository class subclass rather than to override
922
# get_commit_builder.
923
_commit_builder_class = VersionedFileCommitBuilder
925
def add_fallback_repository(self, repository):
926
"""Add a repository to use for looking up data not held locally.
928
:param repository: A repository.
930
if not self._format.supports_external_lookups:
931
raise errors.UnstackableRepositoryFormat(self._format, self.base)
932
# This can raise an exception, so should be done before we lock the
933
# fallback repository.
934
self._check_fallback_repository(repository)
936
# This repository will call fallback.unlock() when we transition to
937
# the unlocked state, so we make sure to increment the lock count
938
repository.lock_read()
939
self._fallback_repositories.append(repository)
940
self.texts.add_fallback_versioned_files(repository.texts)
941
self.inventories.add_fallback_versioned_files(repository.inventories)
942
self.revisions.add_fallback_versioned_files(repository.revisions)
943
self.signatures.add_fallback_versioned_files(repository.signatures)
944
if self.chk_bytes is not None:
945
self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
947
@only_raises(errors.LockNotHeld, errors.LockBroken)
949
super(VersionedFileRepository, self).unlock()
950
if self.control_files._lock_count == 0:
951
self._inventory_entry_cache.clear()
953
def add_inventory(self, revision_id, inv, parents):
954
"""Add the inventory inv to the repository as revision_id.
956
:param parents: The revision ids of the parents that revision_id
957
is known to have and are in the repository already.
959
:returns: The validator(which is a sha1 digest, though what is sha'd is
960
repository format specific) of the serialized inventory.
962
if not self.is_in_write_group():
963
raise AssertionError("%r not in write group" % (self,))
964
_mod_revision.check_not_reserved_id(revision_id)
965
if not (inv.revision_id is None or inv.revision_id == revision_id):
966
raise AssertionError(
967
"Mismatch between inventory revision"
968
" id and insertion revid (%r, %r)"
969
% (inv.revision_id, revision_id))
971
raise errors.RootMissing()
972
return self._add_inventory_checked(revision_id, inv, parents)
974
def _add_inventory_checked(self, revision_id, inv, parents):
975
"""Add inv to the repository after checking the inputs.
977
This function can be overridden to allow different inventory styles.
979
:seealso: add_inventory, for the contract.
981
inv_lines = self._serializer.write_inventory_to_lines(inv)
982
return self._inventory_add_lines(revision_id, parents,
983
inv_lines, check_content=False)
985
def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
986
parents, basis_inv=None, propagate_caches=False):
987
"""Add a new inventory expressed as a delta against another revision.
989
See the inventory developers documentation for the theory behind
992
:param basis_revision_id: The inventory id the delta was created
993
against. (This does not have to be a direct parent.)
994
:param delta: The inventory delta (see Inventory.apply_delta for
996
:param new_revision_id: The revision id that the inventory is being
998
:param parents: The revision ids of the parents that revision_id is
999
known to have and are in the repository already. These are supplied
1000
for repositories that depend on the inventory graph for revision
1001
graph access, as well as for those that pun ancestry with delta
1003
:param basis_inv: The basis inventory if it is already known,
1005
:param propagate_caches: If True, the caches for this inventory are
1006
copied to and updated for the result if possible.
1008
:returns: (validator, new_inv)
1009
The validator(which is a sha1 digest, though what is sha'd is
1010
repository format specific) of the serialized inventory, and the
1011
resulting inventory.
1013
if not self.is_in_write_group():
1014
raise AssertionError("%r not in write group" % (self,))
1015
_mod_revision.check_not_reserved_id(new_revision_id)
1016
basis_tree = self.revision_tree(basis_revision_id)
1017
basis_tree.lock_read()
1019
# Note that this mutates the inventory of basis_tree, which not all
1020
# inventory implementations may support: A better idiom would be to
1021
# return a new inventory, but as there is no revision tree cache in
1022
# repository this is safe for now - RBC 20081013
1023
if basis_inv is None:
1024
basis_inv = basis_tree.root_inventory
1025
basis_inv.apply_delta(delta)
1026
basis_inv.revision_id = new_revision_id
1027
return (self.add_inventory(new_revision_id, basis_inv, parents),
1032
def _inventory_add_lines(self, revision_id, parents, lines,
1033
check_content=True):
1034
"""Store lines in inv_vf and return the sha1 of the inventory."""
1035
parents = [(parent,) for parent in parents]
1036
result = self.inventories.add_lines((revision_id,), parents, lines,
1037
check_content=check_content)[0]
1038
self.inventories._access.flush()
1041
def add_revision(self, revision_id, rev, inv=None):
1042
"""Add rev to the revision store as revision_id.
1044
:param revision_id: the revision id to use.
1045
:param rev: The revision object.
1046
:param inv: The inventory for the revision. if None, it will be looked
1047
up in the inventory storer
1049
# TODO: jam 20070210 Shouldn't we check rev.revision_id and
1051
_mod_revision.check_not_reserved_id(revision_id)
1052
# check inventory present
1053
if not self.inventories.get_parent_map([(revision_id,)]):
1055
raise errors.WeaveRevisionNotPresent(revision_id,
1058
# yes, this is not suitable for adding with ghosts.
1059
rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1062
key = (revision_id,)
1063
rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1064
self._add_revision(rev)
1066
def _add_revision(self, revision):
1067
text = self._serializer.write_revision_to_string(revision)
1068
key = (revision.revision_id,)
1069
parents = tuple((parent,) for parent in revision.parent_ids)
1070
self.revisions.add_lines(key, parents, osutils.split_lines(text))
1072
def _check_inventories(self, checker):
1073
"""Check the inventories found from the revision scan.
1075
This is responsible for verifying the sha1 of inventories and
1076
creating a pending_keys set that covers data referenced by inventories.
1078
bar = ui.ui_factory.nested_progress_bar()
1080
self._do_check_inventories(checker, bar)
1084
def _do_check_inventories(self, checker, bar):
1085
"""Helper for _check_inventories."""
1087
keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1088
kinds = ['chk_bytes', 'texts']
1089
count = len(checker.pending_keys)
1090
bar.update(gettext("inventories"), 0, 2)
1091
current_keys = checker.pending_keys
1092
checker.pending_keys = {}
1093
# Accumulate current checks.
1094
for key in current_keys:
1095
if key[0] != 'inventories' and key[0] not in kinds:
1096
checker._report_items.append('unknown key type %r' % (key,))
1097
keys[key[0]].add(key[1:])
1098
if keys['inventories']:
1099
# NB: output order *should* be roughly sorted - topo or
1100
# inverse topo depending on repository - either way decent
1101
# to just delta against. However, pre-CHK formats didn't
1102
# try to optimise inventory layout on disk. As such the
1103
# pre-CHK code path does not use inventory deltas.
1105
for record in self.inventories.check(keys=keys['inventories']):
1106
if record.storage_kind == 'absent':
1107
checker._report_items.append(
1108
'Missing inventory {%s}' % (record.key,))
1110
last_object = self._check_record('inventories', record,
1111
checker, last_object,
1112
current_keys[('inventories',) + record.key])
1113
del keys['inventories']
1116
bar.update(gettext("texts"), 1)
1117
while (checker.pending_keys or keys['chk_bytes']
1119
# Something to check.
1120
current_keys = checker.pending_keys
1121
checker.pending_keys = {}
1122
# Accumulate current checks.
1123
for key in current_keys:
1124
if key[0] not in kinds:
1125
checker._report_items.append('unknown key type %r' % (key,))
1126
keys[key[0]].add(key[1:])
1127
# Check the outermost kind only - inventories || chk_bytes || texts
1131
for record in getattr(self, kind).check(keys=keys[kind]):
1132
if record.storage_kind == 'absent':
1133
checker._report_items.append(
1134
'Missing %s {%s}' % (kind, record.key,))
1136
last_object = self._check_record(kind, record,
1137
checker, last_object, current_keys[(kind,) + record.key])
1141
def _check_record(self, kind, record, checker, last_object, item_data):
1142
"""Check a single text from this repository."""
1143
if kind == 'inventories':
1144
rev_id = record.key[0]
1145
inv = self._deserialise_inventory(rev_id,
1146
record.get_bytes_as('fulltext'))
1147
if last_object is not None:
1148
delta = inv._make_delta(last_object)
1149
for old_path, path, file_id, ie in delta:
1152
ie.check(checker, rev_id, inv)
1154
for path, ie in inv.iter_entries():
1155
ie.check(checker, rev_id, inv)
1156
if self._format.fast_deltas:
1158
elif kind == 'chk_bytes':
1159
# No code written to check chk_bytes for this repo format.
1160
checker._report_items.append(
1161
'unsupported key type chk_bytes for %s' % (record.key,))
1162
elif kind == 'texts':
1163
self._check_text(record, checker, item_data)
1165
checker._report_items.append(
1166
'unknown key type %s for %s' % (kind, record.key))
1168
def _check_text(self, record, checker, item_data):
1169
"""Check a single text."""
1170
# Check it is extractable.
1171
# TODO: check length.
1172
if record.storage_kind == 'chunked':
1173
chunks = record.get_bytes_as(record.storage_kind)
1174
sha1 = osutils.sha_strings(chunks)
1175
length = sum(map(len, chunks))
1177
content = record.get_bytes_as('fulltext')
1178
sha1 = osutils.sha_string(content)
1179
length = len(content)
1180
if item_data and sha1 != item_data[1]:
1181
checker._report_items.append(
1182
'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1183
(record.key, sha1, item_data[1], item_data[2]))
1186
def _eliminate_revisions_not_present(self, revision_ids):
1187
"""Check every revision id in revision_ids to see if we have it.
1189
Returns a set of the present revisions.
1192
graph = self.get_graph()
1193
parent_map = graph.get_parent_map(revision_ids)
1194
# The old API returned a list, should this actually be a set?
1195
return parent_map.keys()
1197
def __init__(self, _format, a_bzrdir, control_files):
1198
"""Instantiate a VersionedFileRepository.
1200
:param _format: The format of the repository on disk.
1201
:param controldir: The ControlDir of the repository.
1202
:param control_files: Control files to use for locking, etc.
1204
# In the future we will have a single api for all stores for
1205
# getting file texts, inventories and revisions, then
1206
# this construct will accept instances of those things.
1207
super(VersionedFileRepository, self).__init__(_format, a_bzrdir,
1209
self._transport = control_files._transport
1210
self.base = self._transport.base
1212
self._reconcile_does_inventory_gc = True
1213
self._reconcile_fixes_text_parents = False
1214
self._reconcile_backsup_inventory = True
1215
# An InventoryEntry cache, used during deserialization
1216
self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1217
# Is it safe to return inventory entries directly from the entry cache,
1218
# rather copying them?
1219
self._safe_to_return_from_cache = False
1221
def fetch(self, source, revision_id=None, find_ghosts=False,
1223
"""Fetch the content required to construct revision_id from source.
1225
If revision_id is None and fetch_spec is None, then all content is
1228
fetch() may not be used when the repository is in a write group -
1229
either finish the current write group before using fetch, or use
1230
fetch before starting the write group.
1232
:param find_ghosts: Find and copy revisions in the source that are
1233
ghosts in the target (and not reachable directly by walking out to
1234
the first-present revision in target from revision_id).
1235
:param revision_id: If specified, all the content needed for this
1236
revision ID will be copied to the target. Fetch will determine for
1237
itself which content needs to be copied.
1238
:param fetch_spec: If specified, a SearchResult or
1239
PendingAncestryResult that describes which revisions to copy. This
1240
allows copying multiple heads at once. Mutually exclusive with
1243
if fetch_spec is not None and revision_id is not None:
1244
raise AssertionError(
1245
"fetch_spec and revision_id are mutually exclusive.")
1246
if self.is_in_write_group():
1247
raise errors.InternalBzrError(
1248
"May not fetch while in a write group.")
1249
# fast path same-url fetch operations
1250
# TODO: lift out to somewhere common with RemoteRepository
1251
# <https://bugs.launchpad.net/bzr/+bug/401646>
1252
if (self.has_same_location(source)
1253
and fetch_spec is None
1254
and self._has_same_fallbacks(source)):
1255
# check that last_revision is in 'from' and then return a
1257
if (revision_id is not None and
1258
not _mod_revision.is_null(revision_id)):
1259
self.get_revision(revision_id)
1261
inter = InterRepository.get(source, self)
1262
if (fetch_spec is not None and
1263
not getattr(inter, "supports_fetch_spec", False)):
1264
raise errors.UnsupportedOperation(
1265
"fetch_spec not supported for %r" % inter)
1266
return inter.fetch(revision_id=revision_id,
1267
find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1270
def gather_stats(self, revid=None, committers=None):
1271
"""See Repository.gather_stats()."""
1272
result = super(VersionedFileRepository, self).gather_stats(revid, committers)
1273
# now gather global repository information
1274
# XXX: This is available for many repos regardless of listability.
1275
if self.user_transport.listable():
1276
# XXX: do we want to __define len__() ?
1277
# Maybe the versionedfiles object should provide a different
1278
# method to get the number of keys.
1279
result['revisions'] = len(self.revisions.keys())
1280
# result['size'] = t
1283
def get_commit_builder(self, branch, parents, config_stack, timestamp=None,
1284
timezone=None, committer=None, revprops=None,
1285
revision_id=None, lossy=False):
1286
"""Obtain a CommitBuilder for this repository.
1288
:param branch: Branch to commit to.
1289
:param parents: Revision ids of the parents of the new revision.
1290
:param config_stack: Configuration stack to use.
1291
:param timestamp: Optional timestamp recorded for commit.
1292
:param timezone: Optional timezone for timestamp.
1293
:param committer: Optional committer to set for commit.
1294
:param revprops: Optional dictionary of revision properties.
1295
:param revision_id: Optional revision id.
1296
:param lossy: Whether to discard data that can not be natively
1297
represented, when pushing to a foreign VCS
1299
if self._fallback_repositories and not self._format.supports_chks:
1300
raise errors.BzrError("Cannot commit directly to a stacked branch"
1301
" in pre-2a formats. See "
1302
"https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1303
result = self._commit_builder_class(self, parents, config_stack,
1304
timestamp, timezone, committer, revprops, revision_id,
1306
self.start_write_group()
1309
def get_missing_parent_inventories(self, check_for_missing_texts=True):
1310
"""Return the keys of missing inventory parents for revisions added in
1313
A revision is not complete if the inventory delta for that revision
1314
cannot be calculated. Therefore if the parent inventories of a
1315
revision are not present, the revision is incomplete, and e.g. cannot
1316
be streamed by a smart server. This method finds missing inventory
1317
parents for revisions added in this write group.
1319
if not self._format.supports_external_lookups:
1320
# This is only an issue for stacked repositories
1322
if not self.is_in_write_group():
1323
raise AssertionError('not in a write group')
1325
# XXX: We assume that every added revision already has its
1326
# corresponding inventory, so we only check for parent inventories that
1327
# might be missing, rather than all inventories.
1328
parents = set(self.revisions._index.get_missing_parents())
1329
parents.discard(_mod_revision.NULL_REVISION)
1330
unstacked_inventories = self.inventories._index
1331
present_inventories = unstacked_inventories.get_parent_map(
1332
key[-1:] for key in parents)
1333
parents.difference_update(present_inventories)
1334
if len(parents) == 0:
1335
# No missing parent inventories.
1337
if not check_for_missing_texts:
1338
return set(('inventories', rev_id) for (rev_id,) in parents)
1339
# Ok, now we have a list of missing inventories. But these only matter
1340
# if the inventories that reference them are missing some texts they
1341
# appear to introduce.
1342
# XXX: Texts referenced by all added inventories need to be present,
1343
# but at the moment we're only checking for texts referenced by
1344
# inventories at the graph's edge.
1345
key_deps = self.revisions._index._key_dependencies
1346
key_deps.satisfy_refs_for_keys(present_inventories)
1347
referrers = frozenset(r[0] for r in key_deps.get_referrers())
1348
file_ids = self.fileids_altered_by_revision_ids(referrers)
1349
missing_texts = set()
1350
for file_id, version_ids in file_ids.iteritems():
1351
missing_texts.update(
1352
(file_id, version_id) for version_id in version_ids)
1353
present_texts = self.texts.get_parent_map(missing_texts)
1354
missing_texts.difference_update(present_texts)
1355
if not missing_texts:
1356
# No texts are missing, so all revisions and their deltas are
1359
# Alternatively the text versions could be returned as the missing
1360
# keys, but this is likely to be less data.
1361
missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1365
def has_revisions(self, revision_ids):
1366
"""Probe to find out the presence of multiple revisions.
1368
:param revision_ids: An iterable of revision_ids.
1369
:return: A set of the revision_ids that were present.
1371
parent_map = self.revisions.get_parent_map(
1372
[(rev_id,) for rev_id in revision_ids])
1374
if _mod_revision.NULL_REVISION in revision_ids:
1375
result.add(_mod_revision.NULL_REVISION)
1376
result.update([key[0] for key in parent_map])
1380
def get_revision_reconcile(self, revision_id):
1381
"""'reconcile' helper routine that allows access to a revision always.
1383
This variant of get_revision does not cross check the weave graph
1384
against the revision one as get_revision does: but it should only
1385
be used by reconcile, or reconcile-alike commands that are correcting
1386
or testing the revision graph.
1388
return self._get_revisions([revision_id])[0]
1391
def get_revisions(self, revision_ids):
1392
"""Get many revisions at once.
1394
Repositories that need to check data on every revision read should
1395
subclass this method.
1397
return self._get_revisions(revision_ids)
1400
def _get_revisions(self, revision_ids):
1401
"""Core work logic to get many revisions without sanity checks."""
1403
for revid, rev in self._iter_revisions(revision_ids):
1405
raise errors.NoSuchRevision(self, revid)
1407
return [revs[revid] for revid in revision_ids]
1409
def _iter_revisions(self, revision_ids):
1410
"""Iterate over revision objects.
1412
:param revision_ids: An iterable of revisions to examine. None may be
1413
passed to request all revisions known to the repository. Note that
1414
not all repositories can find unreferenced revisions; for those
1415
repositories only referenced ones will be returned.
1416
:return: An iterator of (revid, revision) tuples. Absent revisions (
1417
those asked for but not available) are returned as (revid, None).
1419
if revision_ids is None:
1420
revision_ids = self.all_revision_ids()
1422
for rev_id in revision_ids:
1423
if not rev_id or not isinstance(rev_id, basestring):
1424
raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1425
keys = [(key,) for key in revision_ids]
1426
stream = self.revisions.get_record_stream(keys, 'unordered', True)
1427
for record in stream:
1428
revid = record.key[0]
1429
if record.storage_kind == 'absent':
1432
text = record.get_bytes_as('fulltext')
1433
rev = self._serializer.read_revision_from_string(text)
1437
def add_signature_text(self, revision_id, signature):
1438
"""Store a signature text for a revision.
1440
:param revision_id: Revision id of the revision
1441
:param signature: Signature text.
1443
self.signatures.add_lines((revision_id,), (),
1444
osutils.split_lines(signature))
1446
def find_text_key_references(self):
1447
"""Find the text key references within the repository.
1449
:return: A dictionary mapping text keys ((fileid, revision_id) tuples)
1450
to whether they were referred to by the inventory of the
1451
revision_id that they contain. The inventory texts from all present
1452
revision ids are assessed to generate this report.
1454
revision_keys = self.revisions.keys()
1455
w = self.inventories
1456
pb = ui.ui_factory.nested_progress_bar()
1458
return self._serializer._find_text_key_references(
1459
w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
1463
def _inventory_xml_lines_for_keys(self, keys):
1464
"""Get a line iterator of the sort needed for findind references.
1466
Not relevant for non-xml inventory repositories.
1468
Ghosts in revision_keys are ignored.
1470
:param revision_keys: The revision keys for the inventories to inspect.
1471
:return: An iterator over (inventory line, revid) for the fulltexts of
1472
all of the xml inventories specified by revision_keys.
1474
stream = self.inventories.get_record_stream(keys, 'unordered', True)
1475
for record in stream:
1476
if record.storage_kind != 'absent':
1477
chunks = record.get_bytes_as('chunked')
1478
revid = record.key[-1]
1479
lines = osutils.chunks_to_lines(chunks)
1483
def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
1485
"""Helper routine for fileids_altered_by_revision_ids.
1487
This performs the translation of xml lines to revision ids.
1489
:param line_iterator: An iterator of lines, origin_version_id
1490
:param revision_keys: The revision ids to filter for. This should be a
1491
set or other type which supports efficient __contains__ lookups, as
1492
the revision key from each parsed line will be looked up in the
1493
revision_keys filter.
1494
:return: a dictionary mapping altered file-ids to an iterable of
1495
revision_ids. Each altered file-ids has the exact revision_ids that
1496
altered it listed explicitly.
1498
seen = set(self._serializer._find_text_key_references(
1499
line_iterator).iterkeys())
1500
parent_keys = self._find_parent_keys_of_revisions(revision_keys)
1501
parent_seen = set(self._serializer._find_text_key_references(
1502
self._inventory_xml_lines_for_keys(parent_keys)))
1503
new_keys = seen - parent_seen
1505
setdefault = result.setdefault
1506
for key in new_keys:
1507
setdefault(key[0], set()).add(key[-1])
1510
def _find_parent_keys_of_revisions(self, revision_keys):
1511
"""Similar to _find_parent_ids_of_revisions, but used with keys.
1513
:param revision_keys: An iterable of revision_keys.
1514
:return: The parents of all revision_keys that are not already in
1517
parent_map = self.revisions.get_parent_map(revision_keys)
1518
parent_keys = set(itertools.chain.from_iterable(
1519
parent_map.itervalues()))
1520
parent_keys.difference_update(revision_keys)
1521
parent_keys.discard(_mod_revision.NULL_REVISION)
1524
def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
1525
"""Find the file ids and versions affected by revisions.
1527
:param revisions: an iterable containing revision ids.
1528
:param _inv_weave: The inventory weave from this repository or None.
1529
If None, the inventory weave will be opened automatically.
1530
:return: a dictionary mapping altered file-ids to an iterable of
1531
revision_ids. Each altered file-ids has the exact revision_ids that
1532
altered it listed explicitly.
1534
selected_keys = set((revid,) for revid in revision_ids)
1535
w = _inv_weave or self.inventories
1536
return self._find_file_ids_from_xml_inventory_lines(
1537
w.iter_lines_added_or_present_in_keys(
1538
selected_keys, pb=None),
1541
def iter_files_bytes(self, desired_files):
1542
"""Iterate through file versions.
1544
Files will not necessarily be returned in the order they occur in
1545
desired_files. No specific order is guaranteed.
1547
Yields pairs of identifier, bytes_iterator. identifier is an opaque
1548
value supplied by the caller as part of desired_files. It should
1549
uniquely identify the file version in the caller's context. (Examples:
1550
an index number or a TreeTransform trans_id.)
1552
bytes_iterator is an iterable of bytestrings for the file. The
1553
kind of iterable and length of the bytestrings are unspecified, but for
1554
this implementation, it is a list of bytes produced by
1555
VersionedFile.get_record_stream().
1557
:param desired_files: a list of (file_id, revision_id, identifier)
1561
for file_id, revision_id, callable_data in desired_files:
1562
text_keys[(file_id, revision_id)] = callable_data
1563
for record in self.texts.get_record_stream(text_keys, 'unordered', True):
1564
if record.storage_kind == 'absent':
1565
raise errors.RevisionNotPresent(record.key[1], record.key[0])
1566
yield text_keys[record.key], record.get_bytes_as('chunked')
1568
def _generate_text_key_index(self, text_key_references=None,
1570
"""Generate a new text key index for the repository.
1572
This is an expensive function that will take considerable time to run.
1574
:return: A dict mapping text keys ((file_id, revision_id) tuples) to a
1575
list of parents, also text keys. When a given key has no parents,
1576
the parents list will be [NULL_REVISION].
1578
# All revisions, to find inventory parents.
1579
if ancestors is None:
1580
graph = self.get_graph()
1581
ancestors = graph.get_parent_map(self.all_revision_ids())
1582
if text_key_references is None:
1583
text_key_references = self.find_text_key_references()
1584
pb = ui.ui_factory.nested_progress_bar()
1586
return self._do_generate_text_key_index(ancestors,
1587
text_key_references, pb)
1591
def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
1592
"""Helper for _generate_text_key_index to avoid deep nesting."""
1593
revision_order = tsort.topo_sort(ancestors)
1594
invalid_keys = set()
1596
for revision_id in revision_order:
1597
revision_keys[revision_id] = set()
1598
text_count = len(text_key_references)
1599
# a cache of the text keys to allow reuse; costs a dict of all the
1600
# keys, but saves a 2-tuple for every child of a given key.
1602
for text_key, valid in text_key_references.iteritems():
1604
invalid_keys.add(text_key)
1606
revision_keys[text_key[1]].add(text_key)
1607
text_key_cache[text_key] = text_key
1608
del text_key_references
1610
text_graph = graph.Graph(graph.DictParentsProvider(text_index))
1611
NULL_REVISION = _mod_revision.NULL_REVISION
1612
# Set a cache with a size of 10 - this suffices for bzr.dev but may be
1613
# too small for large or very branchy trees. However, for 55K path
1614
# trees, it would be easy to use too much memory trivially. Ideally we
1615
# could gauge this by looking at available real memory etc, but this is
1616
# always a tricky proposition.
1617
inventory_cache = lru_cache.LRUCache(10)
1618
batch_size = 10 # should be ~150MB on a 55K path tree
1619
batch_count = len(revision_order) / batch_size + 1
1621
pb.update(gettext("Calculating text parents"), processed_texts, text_count)
1622
for offset in xrange(batch_count):
1623
to_query = revision_order[offset * batch_size:(offset + 1) *
1627
for revision_id in to_query:
1628
parent_ids = ancestors[revision_id]
1629
for text_key in revision_keys[revision_id]:
1630
pb.update(gettext("Calculating text parents"), processed_texts)
1631
processed_texts += 1
1632
candidate_parents = []
1633
for parent_id in parent_ids:
1634
parent_text_key = (text_key[0], parent_id)
1636
check_parent = parent_text_key not in \
1637
revision_keys[parent_id]
1639
# the parent parent_id is a ghost:
1640
check_parent = False
1641
# truncate the derived graph against this ghost.
1642
parent_text_key = None
1644
# look at the parent commit details inventories to
1645
# determine possible candidates in the per file graph.
1648
inv = inventory_cache[parent_id]
1650
inv = self.revision_tree(parent_id).root_inventory
1651
inventory_cache[parent_id] = inv
1653
parent_entry = inv[text_key[0]]
1654
except (KeyError, errors.NoSuchId):
1656
if parent_entry is not None:
1658
text_key[0], parent_entry.revision)
1660
parent_text_key = None
1661
if parent_text_key is not None:
1662
candidate_parents.append(
1663
text_key_cache[parent_text_key])
1664
parent_heads = text_graph.heads(candidate_parents)
1665
new_parents = list(parent_heads)
1666
new_parents.sort(key=lambda x:candidate_parents.index(x))
1667
if new_parents == []:
1668
new_parents = [NULL_REVISION]
1669
text_index[text_key] = new_parents
1671
for text_key in invalid_keys:
1672
text_index[text_key] = [NULL_REVISION]
1675
def item_keys_introduced_by(self, revision_ids, _files_pb=None):
1676
"""Get an iterable listing the keys of all the data introduced by a set
1679
The keys will be ordered so that the corresponding items can be safely
1680
fetched and inserted in that order.
1682
:returns: An iterable producing tuples of (knit-kind, file-id,
1683
versions). knit-kind is one of 'file', 'inventory', 'signatures',
1684
'revisions'. file-id is None unless knit-kind is 'file'.
1686
for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
1689
for result in self._find_non_file_keys_to_fetch(revision_ids):
1692
def _find_file_keys_to_fetch(self, revision_ids, pb):
1693
# XXX: it's a bit weird to control the inventory weave caching in this
1694
# generator. Ideally the caching would be done in fetch.py I think. Or
1695
# maybe this generator should explicitly have the contract that it
1696
# should not be iterated until the previously yielded item has been
1698
inv_w = self.inventories
1700
# file ids that changed
1701
file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
1703
num_file_ids = len(file_ids)
1704
for file_id, altered_versions in file_ids.iteritems():
1706
pb.update(gettext("Fetch texts"), count, num_file_ids)
1708
yield ("file", file_id, altered_versions)
1710
def _find_non_file_keys_to_fetch(self, revision_ids):
1712
yield ("inventory", None, revision_ids)
1715
# XXX: Note ATM no callers actually pay attention to this return
1716
# instead they just use the list of revision ids and ignore
1717
# missing sigs. Consider removing this work entirely
1718
revisions_with_signatures = set(self.signatures.get_parent_map(
1719
[(r,) for r in revision_ids]))
1720
revisions_with_signatures = {r for (r,) in revisions_with_signatures}
1721
revisions_with_signatures.intersection_update(revision_ids)
1722
yield ("signatures", None, revisions_with_signatures)
1725
yield ("revisions", None, revision_ids)
1728
def get_inventory(self, revision_id):
1729
"""Get Inventory object by revision id."""
1730
return next(self.iter_inventories([revision_id]))
1732
def iter_inventories(self, revision_ids, ordering=None):
1733
"""Get many inventories by revision_ids.
1735
This will buffer some or all of the texts used in constructing the
1736
inventories in memory, but will only parse a single inventory at a
1739
:param revision_ids: The expected revision ids of the inventories.
1740
:param ordering: optional ordering, e.g. 'topological'. If not
1741
specified, the order of revision_ids will be preserved (by
1742
buffering if necessary).
1743
:return: An iterator of inventories.
1745
if ((None in revision_ids)
1746
or (_mod_revision.NULL_REVISION in revision_ids)):
1747
raise ValueError('cannot get null revision inventory')
1748
for inv, revid in self._iter_inventories(revision_ids, ordering):
1750
raise errors.NoSuchRevision(self, revid)
1753
def _iter_inventories(self, revision_ids, ordering):
1754
"""single-document based inventory iteration."""
1755
inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
1756
for text, revision_id in inv_xmls:
1758
yield None, revision_id
1760
yield self._deserialise_inventory(revision_id, text), revision_id
1762
def _iter_inventory_xmls(self, revision_ids, ordering):
1763
if ordering is None:
1764
order_as_requested = True
1765
ordering = 'unordered'
1767
order_as_requested = False
1768
keys = [(revision_id,) for revision_id in revision_ids]
1771
if order_as_requested:
1772
key_iter = iter(keys)
1773
next_key = next(key_iter)
1774
stream = self.inventories.get_record_stream(keys, ordering, True)
1776
for record in stream:
1777
if record.storage_kind != 'absent':
1778
chunks = record.get_bytes_as('chunked')
1779
if order_as_requested:
1780
text_chunks[record.key] = chunks
1782
yield ''.join(chunks), record.key[-1]
1784
yield None, record.key[-1]
1785
if order_as_requested:
1786
# Yield as many results as we can while preserving order.
1787
while next_key in text_chunks:
1788
chunks = text_chunks.pop(next_key)
1789
yield ''.join(chunks), next_key[-1]
1791
next_key = next(key_iter)
1792
except StopIteration:
1793
# We still want to fully consume the get_record_stream,
1794
# just in case it is not actually finished at this point
1798
def _deserialise_inventory(self, revision_id, xml):
1799
"""Transform the xml into an inventory object.
1801
:param revision_id: The expected revision id of the inventory.
1802
:param xml: A serialised inventory.
1804
result = self._serializer.read_inventory_from_string(xml, revision_id,
1805
entry_cache=self._inventory_entry_cache,
1806
return_from_cache=self._safe_to_return_from_cache)
1807
if result.revision_id != revision_id:
1808
raise AssertionError('revision id mismatch %s != %s' % (
1809
result.revision_id, revision_id))
1812
def get_serializer_format(self):
1813
return self._serializer.format_num
1816
def _get_inventory_xml(self, revision_id):
1817
"""Get serialized inventory as a string."""
1818
texts = self._iter_inventory_xmls([revision_id], 'unordered')
1819
text, revision_id = next(texts)
1821
raise errors.NoSuchRevision(self, revision_id)
1825
def revision_tree(self, revision_id):
1826
"""Return Tree for a revision on this branch.
1828
`revision_id` may be NULL_REVISION for the empty tree revision.
1830
revision_id = _mod_revision.ensure_null(revision_id)
1831
# TODO: refactor this to use an existing revision object
1832
# so we don't need to read it in twice.
1833
if revision_id == _mod_revision.NULL_REVISION:
1834
return InventoryRevisionTree(self,
1835
Inventory(root_id=None), _mod_revision.NULL_REVISION)
1837
inv = self.get_inventory(revision_id)
1838
return InventoryRevisionTree(self, inv, revision_id)
1840
def revision_trees(self, revision_ids):
1841
"""Return Trees for revisions in this repository.
1843
:param revision_ids: a sequence of revision-ids;
1844
a revision-id may not be None or 'null:'
1846
inventories = self.iter_inventories(revision_ids)
1847
for inv in inventories:
1848
yield InventoryRevisionTree(self, inv, inv.revision_id)
1850
def _filtered_revision_trees(self, revision_ids, file_ids):
1851
"""Return Tree for a revision on this branch with only some files.
1853
:param revision_ids: a sequence of revision-ids;
1854
a revision-id may not be None or 'null:'
1855
:param file_ids: if not None, the result is filtered
1856
so that only those file-ids, their parents and their
1857
children are included.
1859
inventories = self.iter_inventories(revision_ids)
1860
for inv in inventories:
1861
# Should we introduce a FilteredRevisionTree class rather
1862
# than pre-filter the inventory here?
1863
filtered_inv = inv.filter(file_ids)
1864
yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
1866
def get_parent_map(self, revision_ids):
1867
"""See graph.StackedParentsProvider.get_parent_map"""
1868
# revisions index works in keys; this just works in revisions
1869
# therefore wrap and unwrap
1872
for revision_id in revision_ids:
1873
if revision_id == _mod_revision.NULL_REVISION:
1874
result[revision_id] = ()
1875
elif revision_id is None:
1876
raise ValueError('get_parent_map(None) is not valid')
1878
query_keys.append((revision_id ,))
1879
for ((revision_id,), parent_keys) in \
1880
self.revisions.get_parent_map(query_keys).iteritems():
1882
result[revision_id] = tuple([parent_revid
1883
for (parent_revid,) in parent_keys])
1885
result[revision_id] = (_mod_revision.NULL_REVISION,)
1889
def get_known_graph_ancestry(self, revision_ids):
1890
"""Return the known graph for a set of revision ids and their ancestors.
1892
st = static_tuple.StaticTuple
1893
revision_keys = [st(r_id).intern() for r_id in revision_ids]
1894
known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
1895
return graph.GraphThunkIdsToKeys(known_graph)
1898
def get_file_graph(self):
1899
"""Return the graph walker for text revisions."""
1900
return graph.Graph(self.texts)
1902
def revision_ids_to_search_result(self, result_set):
1903
"""Convert a set of revision ids to a graph SearchResult."""
1904
result_parents = set()
1905
for parents in self.get_graph().get_parent_map(
1906
result_set).itervalues():
1907
result_parents.update(parents)
1908
included_keys = result_set.intersection(result_parents)
1909
start_keys = result_set.difference(included_keys)
1910
exclude_keys = result_parents.difference(result_set)
1911
result = vf_search.SearchResult(start_keys, exclude_keys,
1912
len(result_set), result_set)
1915
def _get_versioned_file_checker(self, text_key_references=None,
1917
"""Return an object suitable for checking versioned files.
1919
:param text_key_references: if non-None, an already built
1920
dictionary mapping text keys ((fileid, revision_id) tuples)
1921
to whether they were referred to by the inventory of the
1922
revision_id that they contain. If None, this will be
1924
:param ancestors: Optional result from
1925
self.get_graph().get_parent_map(self.all_revision_ids()) if already
1928
return _VersionedFileChecker(self,
1929
text_key_references=text_key_references, ancestors=ancestors)
1932
def has_signature_for_revision_id(self, revision_id):
1933
"""Query for a revision signature for revision_id in the repository."""
1934
if not self.has_revision(revision_id):
1935
raise errors.NoSuchRevision(self, revision_id)
1936
sig_present = (1 == len(
1937
self.signatures.get_parent_map([(revision_id,)])))
1941
def get_signature_text(self, revision_id):
1942
"""Return the text for a signature."""
1943
stream = self.signatures.get_record_stream([(revision_id,)],
1945
record = next(stream)
1946
if record.storage_kind == 'absent':
1947
raise errors.NoSuchRevision(self, revision_id)
1948
return record.get_bytes_as('fulltext')
1951
def _check(self, revision_ids, callback_refs, check_repo):
1952
result = check.VersionedFileCheck(self, check_repo=check_repo)
1953
result.check(callback_refs)
1956
def _find_inconsistent_revision_parents(self, revisions_iterator=None):
1957
"""Find revisions with different parent lists in the revision object
1958
and in the index graph.
1960
:param revisions_iterator: None, or an iterator of (revid,
1961
Revision-or-None). This iterator controls the revisions checked.
1962
:returns: an iterator yielding tuples of (revison-id, parents-in-index,
1963
parents-in-revision).
1965
if not self.is_locked():
1966
raise AssertionError()
1968
if revisions_iterator is None:
1969
revisions_iterator = self._iter_revisions(None)
1970
for revid, revision in revisions_iterator:
1971
if revision is None:
1973
parent_map = vf.get_parent_map([(revid,)])
1974
parents_according_to_index = tuple(parent[-1] for parent in
1975
parent_map[(revid,)])
1976
parents_according_to_revision = tuple(revision.parent_ids)
1977
if parents_according_to_index != parents_according_to_revision:
1978
yield (revid, parents_according_to_index,
1979
parents_according_to_revision)
1981
def _check_for_inconsistent_revision_parents(self):
1982
inconsistencies = list(self._find_inconsistent_revision_parents())
1984
raise errors.BzrCheckError(
1985
"Revision knit has inconsistent parents.")
1987
def _get_sink(self):
1988
"""Return a sink for streaming into this repository."""
1989
return StreamSink(self)
1991
def _get_source(self, to_format):
1992
"""Return a source for streaming from this repository."""
1993
return StreamSource(self, to_format)
1996
class MetaDirVersionedFileRepository(MetaDirRepository,
1997
VersionedFileRepository):
1998
"""Repositories in a meta-dir, that work via versioned file objects."""
2000
def __init__(self, _format, a_bzrdir, control_files):
2001
super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
2005
class MetaDirVersionedFileRepositoryFormat(RepositoryFormatMetaDir,
2006
VersionedFileRepositoryFormat):
2007
"""Base class for repository formats using versioned files in metadirs."""
2010
class StreamSink(object):
2011
"""An object that can insert a stream into a repository.
2013
This interface handles the complexity of reserialising inventories and
2014
revisions from different formats, and allows unidirectional insertion into
2015
stacked repositories without looking for the missing basis parents
2019
def __init__(self, target_repo):
2020
self.target_repo = target_repo
2022
def insert_stream(self, stream, src_format, resume_tokens):
2023
"""Insert a stream's content into the target repository.
2025
:param src_format: a bzr repository format.
2027
:return: a list of resume tokens and an iterable of keys additional
2028
items required before the insertion can be completed.
2030
self.target_repo.lock_write()
2033
self.target_repo.resume_write_group(resume_tokens)
2036
self.target_repo.start_write_group()
2039
# locked_insert_stream performs a commit|suspend.
2040
missing_keys = self.insert_stream_without_locking(stream,
2041
src_format, is_resume)
2043
# suspend the write group and tell the caller what we is
2044
# missing. We know we can suspend or else we would not have
2045
# entered this code path. (All repositories that can handle
2046
# missing keys can handle suspending a write group).
2047
write_group_tokens = self.target_repo.suspend_write_group()
2048
return write_group_tokens, missing_keys
2049
hint = self.target_repo.commit_write_group()
2050
to_serializer = self.target_repo._format._serializer
2051
src_serializer = src_format._serializer
2052
if (to_serializer != src_serializer and
2053
self.target_repo._format.pack_compresses):
2054
self.target_repo.pack(hint=hint)
2057
self.target_repo.abort_write_group(suppress_errors=True)
2060
self.target_repo.unlock()
2062
def insert_stream_without_locking(self, stream, src_format,
2064
"""Insert a stream's content into the target repository.
2066
This assumes that you already have a locked repository and an active
2069
:param src_format: a bzr repository format.
2070
:param is_resume: Passed down to get_missing_parent_inventories to
2071
indicate if we should be checking for missing texts at the same
2074
:return: A set of keys that are missing.
2076
if not self.target_repo.is_write_locked():
2077
raise errors.ObjectNotLocked(self)
2078
if not self.target_repo.is_in_write_group():
2079
raise errors.BzrError('you must already be in a write group')
2080
to_serializer = self.target_repo._format._serializer
2081
src_serializer = src_format._serializer
2083
if to_serializer == src_serializer:
2084
# If serializers match and the target is a pack repository, set the
2085
# write cache size on the new pack. This avoids poor performance
2086
# on transports where append is unbuffered (such as
2087
# RemoteTransport). This is safe to do because nothing should read
2088
# back from the target repository while a stream with matching
2089
# serialization is being inserted.
2090
# The exception is that a delta record from the source that should
2091
# be a fulltext may need to be expanded by the target (see
2092
# test_fetch_revisions_with_deltas_into_pack); but we take care to
2093
# explicitly flush any buffered writes first in that rare case.
2095
new_pack = self.target_repo._pack_collection._new_pack
2096
except AttributeError:
2097
# Not a pack repository
2100
new_pack.set_write_cache_size(1024*1024)
2101
for substream_type, substream in stream:
2102
if 'stream' in debug.debug_flags:
2103
mutter('inserting substream: %s', substream_type)
2104
if substream_type == 'texts':
2105
self.target_repo.texts.insert_record_stream(substream)
2106
elif substream_type == 'inventories':
2107
if src_serializer == to_serializer:
2108
self.target_repo.inventories.insert_record_stream(
2111
self._extract_and_insert_inventories(
2112
substream, src_serializer)
2113
elif substream_type == 'inventory-deltas':
2114
self._extract_and_insert_inventory_deltas(
2115
substream, src_serializer)
2116
elif substream_type == 'chk_bytes':
2117
# XXX: This doesn't support conversions, as it assumes the
2118
# conversion was done in the fetch code.
2119
self.target_repo.chk_bytes.insert_record_stream(substream)
2120
elif substream_type == 'revisions':
2121
# This may fallback to extract-and-insert more often than
2122
# required if the serializers are different only in terms of
2124
if src_serializer == to_serializer:
2125
self.target_repo.revisions.insert_record_stream(substream)
2127
self._extract_and_insert_revisions(substream,
2129
elif substream_type == 'signatures':
2130
self.target_repo.signatures.insert_record_stream(substream)
2132
raise AssertionError('kaboom! %s' % (substream_type,))
2133
# Done inserting data, and the missing_keys calculations will try to
2134
# read back from the inserted data, so flush the writes to the new pack
2135
# (if this is pack format).
2136
if new_pack is not None:
2137
new_pack._write_data('', flush=True)
2138
# Find all the new revisions (including ones from resume_tokens)
2139
missing_keys = self.target_repo.get_missing_parent_inventories(
2140
check_for_missing_texts=is_resume)
2142
for prefix, versioned_file in (
2143
('texts', self.target_repo.texts),
2144
('inventories', self.target_repo.inventories),
2145
('revisions', self.target_repo.revisions),
2146
('signatures', self.target_repo.signatures),
2147
('chk_bytes', self.target_repo.chk_bytes),
2149
if versioned_file is None:
2151
# TODO: key is often going to be a StaticTuple object
2152
# I don't believe we can define a method by which
2153
# (prefix,) + StaticTuple will work, though we could
2154
# define a StaticTuple.sq_concat that would allow you to
2155
# pass in either a tuple or a StaticTuple as the second
2156
# object, so instead we could have:
2157
# StaticTuple(prefix) + key here...
2158
missing_keys.update((prefix,) + key for key in
2159
versioned_file.get_missing_compression_parent_keys())
2160
except NotImplementedError:
2161
# cannot even attempt suspending, and missing would have failed
2162
# during stream insertion.
2163
missing_keys = set()
2166
def _extract_and_insert_inventory_deltas(self, substream, serializer):
2167
target_rich_root = self.target_repo._format.rich_root_data
2168
target_tree_refs = self.target_repo._format.supports_tree_reference
2169
for record in substream:
2170
# Insert the delta directly
2171
inventory_delta_bytes = record.get_bytes_as('fulltext')
2172
deserialiser = inventory_delta.InventoryDeltaDeserializer()
2174
parse_result = deserialiser.parse_text_bytes(
2175
inventory_delta_bytes)
2176
except inventory_delta.IncompatibleInventoryDelta as err:
2177
mutter("Incompatible delta: %s", err.msg)
2178
raise errors.IncompatibleRevision(self.target_repo._format)
2179
basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
2180
revision_id = new_id
2181
parents = [key[0] for key in record.parents]
2182
self.target_repo.add_inventory_by_delta(
2183
basis_id, inv_delta, revision_id, parents)
2185
def _extract_and_insert_inventories(self, substream, serializer,
2187
"""Generate a new inventory versionedfile in target, converting data.
2189
The inventory is retrieved from the source, (deserializing it), and
2190
stored in the target (reserializing it in a different format).
2192
target_rich_root = self.target_repo._format.rich_root_data
2193
target_tree_refs = self.target_repo._format.supports_tree_reference
2194
for record in substream:
2195
# It's not a delta, so it must be a fulltext in the source
2196
# serializer's format.
2197
bytes = record.get_bytes_as('fulltext')
2198
revision_id = record.key[0]
2199
inv = serializer.read_inventory_from_string(bytes, revision_id)
2200
parents = [key[0] for key in record.parents]
2201
self.target_repo.add_inventory(revision_id, inv, parents)
2202
# No need to keep holding this full inv in memory when the rest of
2203
# the substream is likely to be all deltas.
2206
def _extract_and_insert_revisions(self, substream, serializer):
2207
for record in substream:
2208
bytes = record.get_bytes_as('fulltext')
2209
revision_id = record.key[0]
2210
rev = serializer.read_revision_from_string(bytes)
2211
if rev.revision_id != revision_id:
2212
raise AssertionError('wtf: %s != %s' % (rev, revision_id))
2213
self.target_repo.add_revision(revision_id, rev)
2216
if self.target_repo._format._fetch_reconcile:
2217
self.target_repo.reconcile()
2220
class StreamSource(object):
2221
"""A source of a stream for fetching between repositories."""
2223
def __init__(self, from_repository, to_format):
2224
"""Create a StreamSource streaming from from_repository."""
2225
self.from_repository = from_repository
2226
self.to_format = to_format
2227
self._record_counter = RecordCounter()
2229
def delta_on_metadata(self):
2230
"""Return True if delta's are permitted on metadata streams.
2232
That is on revisions and signatures.
2234
src_serializer = self.from_repository._format._serializer
2235
target_serializer = self.to_format._serializer
2236
return (self.to_format._fetch_uses_deltas and
2237
src_serializer == target_serializer)
2239
def _fetch_revision_texts(self, revs):
2240
# fetch signatures first and then the revision texts
2241
# may need to be a InterRevisionStore call here.
2242
from_sf = self.from_repository.signatures
2243
# A missing signature is just skipped.
2244
keys = [(rev_id,) for rev_id in revs]
2245
signatures = versionedfile.filter_absent(from_sf.get_record_stream(
2247
self.to_format._fetch_order,
2248
not self.to_format._fetch_uses_deltas))
2249
# If a revision has a delta, this is actually expanded inside the
2250
# insert_record_stream code now, which is an alternate fix for
2252
from_rf = self.from_repository.revisions
2253
revisions = from_rf.get_record_stream(
2255
self.to_format._fetch_order,
2256
not self.delta_on_metadata())
2257
return [('signatures', signatures), ('revisions', revisions)]
2259
def _generate_root_texts(self, revs):
2260
"""This will be called by get_stream between fetching weave texts and
2261
fetching the inventory weave.
2263
if self._rich_root_upgrade():
2264
return _mod_fetch.Inter1and2Helper(
2265
self.from_repository).generate_root_texts(revs)
2269
def get_stream(self, search):
2271
revs = search.get_keys()
2272
graph = self.from_repository.get_graph()
2273
revs = tsort.topo_sort(graph.get_parent_map(revs))
2274
data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
2276
for knit_kind, file_id, revisions in data_to_fetch:
2277
if knit_kind != phase:
2279
# Make a new progress bar for this phase
2280
if knit_kind == "file":
2281
# Accumulate file texts
2282
text_keys.extend([(file_id, revision) for revision in
2284
elif knit_kind == "inventory":
2285
# Now copy the file texts.
2286
from_texts = self.from_repository.texts
2287
yield ('texts', from_texts.get_record_stream(
2288
text_keys, self.to_format._fetch_order,
2289
not self.to_format._fetch_uses_deltas))
2290
# Cause an error if a text occurs after we have done the
2293
# Before we process the inventory we generate the root
2294
# texts (if necessary) so that the inventories references
2296
for _ in self._generate_root_texts(revs):
2298
# we fetch only the referenced inventories because we do not
2299
# know for unselected inventories whether all their required
2300
# texts are present in the other repository - it could be
2302
for info in self._get_inventory_stream(revs):
2304
elif knit_kind == "signatures":
2305
# Nothing to do here; this will be taken care of when
2306
# _fetch_revision_texts happens.
2308
elif knit_kind == "revisions":
2309
for record in self._fetch_revision_texts(revs):
2312
raise AssertionError("Unknown knit kind %r" % knit_kind)
2314
def get_stream_for_missing_keys(self, missing_keys):
2315
# missing keys can only occur when we are byte copying and not
2316
# translating (because translation means we don't send
2317
# unreconstructable deltas ever).
2319
keys['texts'] = set()
2320
keys['revisions'] = set()
2321
keys['inventories'] = set()
2322
keys['chk_bytes'] = set()
2323
keys['signatures'] = set()
2324
for key in missing_keys:
2325
keys[key[0]].add(key[1:])
2326
if len(keys['revisions']):
2327
# If we allowed copying revisions at this point, we could end up
2328
# copying a revision without copying its required texts: a
2329
# violation of the requirements for repository integrity.
2330
raise AssertionError(
2331
'cannot copy revisions to fill in missing deltas %s' % (
2332
keys['revisions'],))
2333
for substream_kind, keys in keys.iteritems():
2334
vf = getattr(self.from_repository, substream_kind)
2335
if vf is None and keys:
2336
raise AssertionError(
2337
"cannot fill in keys for a versioned file we don't"
2338
" have: %s needs %s" % (substream_kind, keys))
2340
# No need to stream something we don't have
2342
if substream_kind == 'inventories':
2343
# Some missing keys are genuinely ghosts, filter those out.
2344
present = self.from_repository.inventories.get_parent_map(keys)
2345
revs = [key[0] for key in present]
2346
# Get the inventory stream more-or-less as we do for the
2347
# original stream; there's no reason to assume that records
2348
# direct from the source will be suitable for the sink. (Think
2349
# e.g. 2a -> 1.9-rich-root).
2350
for info in self._get_inventory_stream(revs, missing=True):
2354
# Ask for full texts always so that we don't need more round trips
2355
# after this stream.
2356
# Some of the missing keys are genuinely ghosts, so filter absent
2357
# records. The Sink is responsible for doing another check to
2358
# ensure that ghosts don't introduce missing data for future
2360
stream = versionedfile.filter_absent(vf.get_record_stream(keys,
2361
self.to_format._fetch_order, True))
2362
yield substream_kind, stream
2364
def inventory_fetch_order(self):
2365
if self._rich_root_upgrade():
2366
return 'topological'
2368
return self.to_format._fetch_order
2370
def _rich_root_upgrade(self):
2371
return (not self.from_repository._format.rich_root_data and
2372
self.to_format.rich_root_data)
2374
def _get_inventory_stream(self, revision_ids, missing=False):
2375
from_format = self.from_repository._format
2376
if (from_format.supports_chks and self.to_format.supports_chks and
2377
from_format.network_name() == self.to_format.network_name()):
2378
raise AssertionError(
2379
"this case should be handled by GroupCHKStreamSource")
2380
elif 'forceinvdeltas' in debug.debug_flags:
2381
return self._get_convertable_inventory_stream(revision_ids,
2382
delta_versus_null=missing)
2383
elif from_format.network_name() == self.to_format.network_name():
2385
return self._get_simple_inventory_stream(revision_ids,
2387
elif (not from_format.supports_chks and not self.to_format.supports_chks
2388
and from_format._serializer == self.to_format._serializer):
2389
# Essentially the same format.
2390
return self._get_simple_inventory_stream(revision_ids,
2393
# Any time we switch serializations, we want to use an
2394
# inventory-delta based approach.
2395
return self._get_convertable_inventory_stream(revision_ids,
2396
delta_versus_null=missing)
2398
def _get_simple_inventory_stream(self, revision_ids, missing=False):
2399
# NB: This currently reopens the inventory weave in source;
2400
# using a single stream interface instead would avoid this.
2401
from_weave = self.from_repository.inventories
2403
delta_closure = True
2405
delta_closure = not self.delta_on_metadata()
2406
yield ('inventories', from_weave.get_record_stream(
2407
[(rev_id,) for rev_id in revision_ids],
2408
self.inventory_fetch_order(), delta_closure))
2410
def _get_convertable_inventory_stream(self, revision_ids,
2411
delta_versus_null=False):
2412
# The two formats are sufficiently different that there is no fast
2413
# path, so we need to send just inventorydeltas, which any
2414
# sufficiently modern client can insert into any repository.
2415
# The StreamSink code expects to be able to
2416
# convert on the target, so we need to put bytes-on-the-wire that can
2417
# be converted. That means inventory deltas (if the remote is <1.19,
2418
# RemoteStreamSink will fallback to VFS to insert the deltas).
2419
yield ('inventory-deltas',
2420
self._stream_invs_as_deltas(revision_ids,
2421
delta_versus_null=delta_versus_null))
2423
def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
2424
"""Return a stream of inventory-deltas for the given rev ids.
2426
:param revision_ids: The list of inventories to transmit
2427
:param delta_versus_null: Don't try to find a minimal delta for this
2428
entry, instead compute the delta versus the NULL_REVISION. This
2429
effectively streams a complete inventory. Used for stuff like
2430
filling in missing parents, etc.
2432
from_repo = self.from_repository
2433
revision_keys = [(rev_id,) for rev_id in revision_ids]
2434
parent_map = from_repo.inventories.get_parent_map(revision_keys)
2435
# XXX: possibly repos could implement a more efficient iter_inv_deltas
2437
inventories = self.from_repository.iter_inventories(
2438
revision_ids, 'topological')
2439
format = from_repo._format
2440
invs_sent_so_far = {_mod_revision.NULL_REVISION}
2441
inventory_cache = lru_cache.LRUCache(50)
2442
null_inventory = from_repo.revision_tree(
2443
_mod_revision.NULL_REVISION).root_inventory
2444
# XXX: ideally the rich-root/tree-refs flags would be per-revision, not
2445
# per-repo (e.g. streaming a non-rich-root revision out of a rich-root
2446
# repo back into a non-rich-root repo ought to be allowed)
2447
serializer = inventory_delta.InventoryDeltaSerializer(
2448
versioned_root=format.rich_root_data,
2449
tree_references=format.supports_tree_reference)
2450
for inv in inventories:
2451
key = (inv.revision_id,)
2452
parent_keys = parent_map.get(key, ())
2454
if not delta_versus_null and parent_keys:
2455
# The caller did not ask for complete inventories and we have
2456
# some parents that we can delta against. Make a delta against
2457
# each parent so that we can find the smallest.
2458
parent_ids = [parent_key[0] for parent_key in parent_keys]
2459
for parent_id in parent_ids:
2460
if parent_id not in invs_sent_so_far:
2461
# We don't know that the remote side has this basis, so
2464
if parent_id == _mod_revision.NULL_REVISION:
2465
parent_inv = null_inventory
2467
parent_inv = inventory_cache.get(parent_id, None)
2468
if parent_inv is None:
2469
parent_inv = from_repo.get_inventory(parent_id)
2470
candidate_delta = inv._make_delta(parent_inv)
2471
if (delta is None or
2472
len(delta) > len(candidate_delta)):
2473
delta = candidate_delta
2474
basis_id = parent_id
2476
# Either none of the parents ended up being suitable, or we
2477
# were asked to delta against NULL
2478
basis_id = _mod_revision.NULL_REVISION
2479
delta = inv._make_delta(null_inventory)
2480
invs_sent_so_far.add(inv.revision_id)
2481
inventory_cache[inv.revision_id] = inv
2482
delta_serialized = ''.join(
2483
serializer.delta_to_lines(basis_id, key[-1], delta))
2484
yield versionedfile.FulltextContentFactory(
2485
key, parent_keys, None, delta_serialized)
2488
class _VersionedFileChecker(object):
2490
def __init__(self, repository, text_key_references=None, ancestors=None):
2491
self.repository = repository
2492
self.text_index = self.repository._generate_text_key_index(
2493
text_key_references=text_key_references, ancestors=ancestors)
2495
def calculate_file_version_parents(self, text_key):
2496
"""Calculate the correct parents for a file version according to
2499
parent_keys = self.text_index[text_key]
2500
if parent_keys == [_mod_revision.NULL_REVISION]:
2502
return tuple(parent_keys)
2504
def check_file_version_parents(self, texts, progress_bar=None):
2505
"""Check the parents stored in a versioned file are correct.
2507
It also detects file versions that are not referenced by their
2508
corresponding revision's inventory.
2510
:returns: A tuple of (wrong_parents, dangling_file_versions).
2511
wrong_parents is a dict mapping {revision_id: (stored_parents,
2512
correct_parents)} for each revision_id where the stored parents
2513
are not correct. dangling_file_versions is a set of (file_id,
2514
revision_id) tuples for versions that are present in this versioned
2515
file, but not used by the corresponding inventory.
2517
local_progress = None
2518
if progress_bar is None:
2519
local_progress = ui.ui_factory.nested_progress_bar()
2520
progress_bar = local_progress
2522
return self._check_file_version_parents(texts, progress_bar)
2525
local_progress.finished()
2527
def _check_file_version_parents(self, texts, progress_bar):
2528
"""See check_file_version_parents."""
2530
self.file_ids = {file_id for file_id, _ in
2531
self.text_index.iterkeys()}
2532
# text keys is now grouped by file_id
2533
n_versions = len(self.text_index)
2534
progress_bar.update(gettext('loading text store'), 0, n_versions)
2535
parent_map = self.repository.texts.get_parent_map(self.text_index)
2536
# On unlistable transports this could well be empty/error...
2537
text_keys = self.repository.texts.keys()
2538
unused_keys = frozenset(text_keys) - set(self.text_index)
2539
for num, key in enumerate(self.text_index.iterkeys()):
2540
progress_bar.update(gettext('checking text graph'), num, n_versions)
2541
correct_parents = self.calculate_file_version_parents(key)
2543
knit_parents = parent_map[key]
2544
except errors.RevisionNotPresent:
2547
if correct_parents != knit_parents:
2548
wrong_parents[key] = (knit_parents, correct_parents)
2549
return wrong_parents, unused_keys
2552
class InterVersionedFileRepository(InterRepository):
2554
_walk_to_common_revisions_batch_size = 50
2556
supports_fetch_spec = True
2559
def fetch(self, revision_id=None, find_ghosts=False,
2561
"""Fetch the content required to construct revision_id.
2563
The content is copied from self.source to self.target.
2565
:param revision_id: if None all content is copied, if NULL_REVISION no
2569
if self.target._format.experimental:
2570
ui.ui_factory.show_user_warning('experimental_format_fetch',
2571
from_format=self.source._format,
2572
to_format=self.target._format)
2573
from breezy.fetch import RepoFetcher
2574
# See <https://launchpad.net/bugs/456077> asking for a warning here
2575
if self.source._format.network_name() != self.target._format.network_name():
2576
ui.ui_factory.show_user_warning('cross_format_fetch',
2577
from_format=self.source._format,
2578
to_format=self.target._format)
2579
f = RepoFetcher(to_repository=self.target,
2580
from_repository=self.source,
2581
last_revision=revision_id,
2582
fetch_spec=fetch_spec,
2583
find_ghosts=find_ghosts)
2585
def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
2586
"""Walk out from revision_ids in source to revisions target has.
2588
:param revision_ids: The start point for the search.
2589
:return: A set of revision ids.
2591
target_graph = self.target.get_graph()
2592
revision_ids = frozenset(revision_ids)
2594
all_wanted_revs = revision_ids.union(if_present_ids)
2596
all_wanted_revs = revision_ids
2597
missing_revs = set()
2598
source_graph = self.source.get_graph()
2599
# ensure we don't pay silly lookup costs.
2600
searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
2601
null_set = frozenset([_mod_revision.NULL_REVISION])
2602
searcher_exhausted = False
2606
# Iterate the searcher until we have enough next_revs
2607
while len(next_revs) < self._walk_to_common_revisions_batch_size:
2609
next_revs_part, ghosts_part = searcher.next_with_ghosts()
2610
next_revs.update(next_revs_part)
2611
ghosts.update(ghosts_part)
2612
except StopIteration:
2613
searcher_exhausted = True
2615
# If there are ghosts in the source graph, and the caller asked for
2616
# them, make sure that they are present in the target.
2617
# We don't care about other ghosts as we can't fetch them and
2618
# haven't been asked to.
2619
ghosts_to_check = set(revision_ids.intersection(ghosts))
2620
revs_to_get = set(next_revs).union(ghosts_to_check)
2622
have_revs = set(target_graph.get_parent_map(revs_to_get))
2623
# we always have NULL_REVISION present.
2624
have_revs = have_revs.union(null_set)
2625
# Check if the target is missing any ghosts we need.
2626
ghosts_to_check.difference_update(have_revs)
2628
# One of the caller's revision_ids is a ghost in both the
2629
# source and the target.
2630
raise errors.NoSuchRevision(
2631
self.source, ghosts_to_check.pop())
2632
missing_revs.update(next_revs - have_revs)
2633
# Because we may have walked past the original stop point, make
2634
# sure everything is stopped
2635
stop_revs = searcher.find_seen_ancestors(have_revs)
2636
searcher.stop_searching_any(stop_revs)
2637
if searcher_exhausted:
2639
(started_keys, excludes, included_keys) = searcher.get_state()
2640
return vf_search.SearchResult(started_keys, excludes,
2641
len(included_keys), included_keys)
2644
def search_missing_revision_ids(self,
2645
find_ghosts=True, revision_ids=None, if_present_ids=None,
2647
"""Return the revision ids that source has that target does not.
2649
:param revision_ids: return revision ids included by these
2650
revision_ids. NoSuchRevision will be raised if any of these
2651
revisions are not present.
2652
:param if_present_ids: like revision_ids, but will not cause
2653
NoSuchRevision if any of these are absent, instead they will simply
2654
not be in the result. This is useful for e.g. finding revisions
2655
to fetch for tags, which may reference absent revisions.
2656
:param find_ghosts: If True find missing revisions in deep history
2657
rather than just finding the surface difference.
2658
:return: A breezy.graph.SearchResult.
2660
# stop searching at found target revisions.
2661
if not find_ghosts and (revision_ids is not None or if_present_ids is
2663
result = self._walk_to_common_revisions(revision_ids,
2664
if_present_ids=if_present_ids)
2667
result_set = result.get_keys()
2669
# generic, possibly worst case, slow code path.
2670
target_ids = set(self.target.all_revision_ids())
2671
source_ids = self._present_source_revisions_for(
2672
revision_ids, if_present_ids)
2673
result_set = set(source_ids).difference(target_ids)
2674
if limit is not None:
2675
topo_ordered = self.source.get_graph().iter_topo_order(result_set)
2676
result_set = set(itertools.islice(topo_ordered, limit))
2677
return self.source.revision_ids_to_search_result(result_set)
2679
def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
2680
"""Returns set of all revisions in ancestry of revision_ids present in
2683
:param revision_ids: if None, all revisions in source are returned.
2684
:param if_present_ids: like revision_ids, but if any/all of these are
2685
absent no error is raised.
2687
if revision_ids is not None or if_present_ids is not None:
2688
# First, ensure all specified revisions exist. Callers expect
2689
# NoSuchRevision when they pass absent revision_ids here.
2690
if revision_ids is None:
2691
revision_ids = set()
2692
if if_present_ids is None:
2693
if_present_ids = set()
2694
revision_ids = set(revision_ids)
2695
if_present_ids = set(if_present_ids)
2696
all_wanted_ids = revision_ids.union(if_present_ids)
2697
graph = self.source.get_graph()
2698
present_revs = set(graph.get_parent_map(all_wanted_ids))
2699
missing = revision_ids.difference(present_revs)
2701
raise errors.NoSuchRevision(self.source, missing.pop())
2702
found_ids = all_wanted_ids.intersection(present_revs)
2703
source_ids = [rev_id for (rev_id, parents) in
2704
graph.iter_ancestry(found_ids)
2705
if rev_id != _mod_revision.NULL_REVISION
2706
and parents is not None]
2708
source_ids = self.source.all_revision_ids()
2709
return set(source_ids)
2712
def _get_repo_format_to_test(self):
2716
def is_compatible(cls, source, target):
2717
# The default implementation is compatible with everything
2718
return (source._format.supports_full_versioned_files and
2719
target._format.supports_full_versioned_files)
2722
class InterDifferingSerializer(InterVersionedFileRepository):
2725
def _get_repo_format_to_test(self):
2729
def is_compatible(source, target):
2730
if not source._format.supports_full_versioned_files:
2732
if not target._format.supports_full_versioned_files:
2734
# This is redundant with format.check_conversion_target(), however that
2735
# raises an exception, and we just want to say "False" as in we won't
2736
# support converting between these formats.
2737
if 'IDS_never' in debug.debug_flags:
2739
if source.supports_rich_root() and not target.supports_rich_root():
2741
if (source._format.supports_tree_reference
2742
and not target._format.supports_tree_reference):
2744
if target._fallback_repositories and target._format.supports_chks:
2745
# IDS doesn't know how to copy CHKs for the parent inventories it
2746
# adds to stacked repos.
2748
if 'IDS_always' in debug.debug_flags:
2750
# Only use this code path for local source and target. IDS does far
2751
# too much IO (both bandwidth and roundtrips) over a network.
2752
if not source.bzrdir.transport.base.startswith('file:///'):
2754
if not target.bzrdir.transport.base.startswith('file:///'):
2758
def _get_trees(self, revision_ids, cache):
2760
for rev_id in revision_ids:
2762
possible_trees.append((rev_id, cache[rev_id]))
2764
# Not cached, but inventory might be present anyway.
2766
tree = self.source.revision_tree(rev_id)
2767
except errors.NoSuchRevision:
2768
# Nope, parent is ghost.
2771
cache[rev_id] = tree
2772
possible_trees.append((rev_id, tree))
2773
return possible_trees
2775
def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
2776
"""Get the best delta and base for this revision.
2778
:return: (basis_id, delta)
2781
# Generate deltas against each tree, to find the shortest.
2782
# FIXME: Support nested trees
2783
texts_possibly_new_in_tree = set()
2784
for basis_id, basis_tree in possible_trees:
2785
delta = tree.root_inventory._make_delta(basis_tree.root_inventory)
2786
for old_path, new_path, file_id, new_entry in delta:
2787
if new_path is None:
2788
# This file_id isn't present in the new rev, so we don't
2792
# Rich roots are handled elsewhere...
2794
kind = new_entry.kind
2795
if kind != 'directory' and kind != 'file':
2796
# No text record associated with this inventory entry.
2798
# This is a directory or file that has changed somehow.
2799
texts_possibly_new_in_tree.add((file_id, new_entry.revision))
2800
deltas.append((len(delta), basis_id, delta))
2802
return deltas[0][1:]
2804
def _fetch_parent_invs_for_stacking(self, parent_map, cache):
2805
"""Find all parent revisions that are absent, but for which the
2806
inventory is present, and copy those inventories.
2808
This is necessary to preserve correctness when the source is stacked
2809
without fallbacks configured. (Note that in cases like upgrade the
2810
source may be not have _fallback_repositories even though it is
2814
for parents in parent_map.values():
2815
parent_revs.update(parents)
2816
present_parents = self.source.get_parent_map(parent_revs)
2817
absent_parents = set(parent_revs).difference(present_parents)
2818
parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
2819
(rev_id,) for rev_id in absent_parents)
2820
parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
2821
for parent_tree in self.source.revision_trees(parent_inv_ids):
2822
current_revision_id = parent_tree.get_revision_id()
2823
parents_parents_keys = parent_invs_keys_for_stacking[
2824
(current_revision_id,)]
2825
parents_parents = [key[-1] for key in parents_parents_keys]
2826
basis_id = _mod_revision.NULL_REVISION
2827
basis_tree = self.source.revision_tree(basis_id)
2828
delta = parent_tree.root_inventory._make_delta(
2829
basis_tree.root_inventory)
2830
self.target.add_inventory_by_delta(
2831
basis_id, delta, current_revision_id, parents_parents)
2832
cache[current_revision_id] = parent_tree
2834
def _fetch_batch(self, revision_ids, basis_id, cache):
2835
"""Fetch across a few revisions.
2837
:param revision_ids: The revisions to copy
2838
:param basis_id: The revision_id of a tree that must be in cache, used
2839
as a basis for delta when no other base is available
2840
:param cache: A cache of RevisionTrees that we can use.
2841
:return: The revision_id of the last converted tree. The RevisionTree
2842
for it will be in cache
2844
# Walk though all revisions; get inventory deltas, copy referenced
2845
# texts that delta references, insert the delta, revision and
2847
root_keys_to_create = set()
2850
pending_revisions = []
2851
parent_map = self.source.get_parent_map(revision_ids)
2852
self._fetch_parent_invs_for_stacking(parent_map, cache)
2853
self.source._safe_to_return_from_cache = True
2854
for tree in self.source.revision_trees(revision_ids):
2855
# Find a inventory delta for this revision.
2856
# Find text entries that need to be copied, too.
2857
current_revision_id = tree.get_revision_id()
2858
parent_ids = parent_map.get(current_revision_id, ())
2859
parent_trees = self._get_trees(parent_ids, cache)
2860
possible_trees = list(parent_trees)
2861
if len(possible_trees) == 0:
2862
# There either aren't any parents, or the parents are ghosts,
2863
# so just use the last converted tree.
2864
possible_trees.append((basis_id, cache[basis_id]))
2865
basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
2867
revision = self.source.get_revision(current_revision_id)
2868
pending_deltas.append((basis_id, delta,
2869
current_revision_id, revision.parent_ids))
2870
if self._converting_to_rich_root:
2871
self._revision_id_to_root_id[current_revision_id] = \
2873
# Determine which texts are in present in this revision but not in
2874
# any of the available parents.
2875
texts_possibly_new_in_tree = set()
2876
for old_path, new_path, file_id, entry in delta:
2877
if new_path is None:
2878
# This file_id isn't present in the new rev
2882
if not self.target.supports_rich_root():
2883
# The target doesn't support rich root, so we don't
2886
if self._converting_to_rich_root:
2887
# This can't be copied normally, we have to insert
2889
root_keys_to_create.add((file_id, entry.revision))
2892
texts_possibly_new_in_tree.add((file_id, entry.revision))
2893
for basis_id, basis_tree in possible_trees:
2894
basis_inv = basis_tree.root_inventory
2895
for file_key in list(texts_possibly_new_in_tree):
2896
file_id, file_revision = file_key
2898
entry = basis_inv[file_id]
2899
except errors.NoSuchId:
2901
if entry.revision == file_revision:
2902
texts_possibly_new_in_tree.remove(file_key)
2903
text_keys.update(texts_possibly_new_in_tree)
2904
pending_revisions.append(revision)
2905
cache[current_revision_id] = tree
2906
basis_id = current_revision_id
2907
self.source._safe_to_return_from_cache = False
2909
from_texts = self.source.texts
2910
to_texts = self.target.texts
2911
if root_keys_to_create:
2912
root_stream = _mod_fetch._new_root_data_stream(
2913
root_keys_to_create, self._revision_id_to_root_id, parent_map,
2915
to_texts.insert_record_stream(root_stream)
2916
to_texts.insert_record_stream(from_texts.get_record_stream(
2917
text_keys, self.target._format._fetch_order,
2918
not self.target._format._fetch_uses_deltas))
2919
# insert inventory deltas
2920
for delta in pending_deltas:
2921
self.target.add_inventory_by_delta(*delta)
2922
if self.target._fallback_repositories:
2923
# Make sure this stacked repository has all the parent inventories
2924
# for the new revisions that we are about to insert. We do this
2925
# before adding the revisions so that no revision is added until
2926
# all the inventories it may depend on are added.
2927
# Note that this is overzealous, as we may have fetched these in an
2930
revision_ids = set()
2931
for revision in pending_revisions:
2932
revision_ids.add(revision.revision_id)
2933
parent_ids.update(revision.parent_ids)
2934
parent_ids.difference_update(revision_ids)
2935
parent_ids.discard(_mod_revision.NULL_REVISION)
2936
parent_map = self.source.get_parent_map(parent_ids)
2937
# we iterate over parent_map and not parent_ids because we don't
2938
# want to try copying any revision which is a ghost
2939
for parent_tree in self.source.revision_trees(parent_map):
2940
current_revision_id = parent_tree.get_revision_id()
2941
parents_parents = parent_map[current_revision_id]
2942
possible_trees = self._get_trees(parents_parents, cache)
2943
if len(possible_trees) == 0:
2944
# There either aren't any parents, or the parents are
2945
# ghosts, so just use the last converted tree.
2946
possible_trees.append((basis_id, cache[basis_id]))
2947
basis_id, delta = self._get_delta_for_revision(parent_tree,
2948
parents_parents, possible_trees)
2949
self.target.add_inventory_by_delta(
2950
basis_id, delta, current_revision_id, parents_parents)
2951
# insert signatures and revisions
2952
for revision in pending_revisions:
2954
signature = self.source.get_signature_text(
2955
revision.revision_id)
2956
self.target.add_signature_text(revision.revision_id,
2958
except errors.NoSuchRevision:
2960
self.target.add_revision(revision.revision_id, revision)
2963
def _fetch_all_revisions(self, revision_ids, pb):
2964
"""Fetch everything for the list of revisions.
2966
:param revision_ids: The list of revisions to fetch. Must be in
2968
:param pb: A ProgressTask
2971
basis_id, basis_tree = self._get_basis(revision_ids[0])
2973
cache = lru_cache.LRUCache(100)
2974
cache[basis_id] = basis_tree
2975
del basis_tree # We don't want to hang on to it here
2979
for offset in range(0, len(revision_ids), batch_size):
2980
self.target.start_write_group()
2982
pb.update(gettext('Transferring revisions'), offset,
2984
batch = revision_ids[offset:offset+batch_size]
2985
basis_id = self._fetch_batch(batch, basis_id, cache)
2987
self.source._safe_to_return_from_cache = False
2988
self.target.abort_write_group()
2991
hint = self.target.commit_write_group()
2994
if hints and self.target._format.pack_compresses:
2995
self.target.pack(hint=hints)
2996
pb.update(gettext('Transferring revisions'), len(revision_ids),
3000
def fetch(self, revision_id=None, find_ghosts=False,
3002
"""See InterRepository.fetch()."""
3003
if fetch_spec is not None:
3004
revision_ids = fetch_spec.get_keys()
3007
if self.source._format.experimental:
3008
ui.ui_factory.show_user_warning('experimental_format_fetch',
3009
from_format=self.source._format,
3010
to_format=self.target._format)
3011
if (not self.source.supports_rich_root()
3012
and self.target.supports_rich_root()):
3013
self._converting_to_rich_root = True
3014
self._revision_id_to_root_id = {}
3016
self._converting_to_rich_root = False
3017
# See <https://launchpad.net/bugs/456077> asking for a warning here
3018
if self.source._format.network_name() != self.target._format.network_name():
3019
ui.ui_factory.show_user_warning('cross_format_fetch',
3020
from_format=self.source._format,
3021
to_format=self.target._format)
3022
if revision_ids is None:
3024
search_revision_ids = [revision_id]
3026
search_revision_ids = None
3027
revision_ids = self.target.search_missing_revision_ids(self.source,
3028
revision_ids=search_revision_ids,
3029
find_ghosts=find_ghosts).get_keys()
3030
if not revision_ids:
3032
revision_ids = tsort.topo_sort(
3033
self.source.get_graph().get_parent_map(revision_ids))
3034
if not revision_ids:
3036
# Walk though all revisions; get inventory deltas, copy referenced
3037
# texts that delta references, insert the delta, revision and
3039
pb = ui.ui_factory.nested_progress_bar()
3041
self._fetch_all_revisions(revision_ids, pb)
3044
return len(revision_ids), 0
3046
def _get_basis(self, first_revision_id):
3047
"""Get a revision and tree which exists in the target.
3049
This assumes that first_revision_id is selected for transmission
3050
because all other ancestors are already present. If we can't find an
3051
ancestor we fall back to NULL_REVISION since we know that is safe.
3053
:return: (basis_id, basis_tree)
3055
first_rev = self.source.get_revision(first_revision_id)
3057
basis_id = first_rev.parent_ids[0]
3058
# only valid as a basis if the target has it
3059
self.target.get_revision(basis_id)
3060
# Try to get a basis tree - if it's a ghost it will hit the
3061
# NoSuchRevision case.
3062
basis_tree = self.source.revision_tree(basis_id)
3063
except (IndexError, errors.NoSuchRevision):
3064
basis_id = _mod_revision.NULL_REVISION
3065
basis_tree = self.source.revision_tree(basis_id)
3066
return basis_id, basis_tree
3069
class InterSameDataRepository(InterVersionedFileRepository):
3070
"""Code for converting between repositories that represent the same data.
3072
Data format and model must match for this to work.
3076
def _get_repo_format_to_test(self):
3077
"""Repository format for testing with.
3079
InterSameData can pull from subtree to subtree and from non-subtree to
3080
non-subtree, so we test this with the richest repository format.
3082
from breezy.repofmt import knitrepo
3083
return knitrepo.RepositoryFormatKnit3()
3086
def is_compatible(source, target):
3088
InterRepository._same_model(source, target) and
3089
source._format.supports_full_versioned_files and
3090
target._format.supports_full_versioned_files)
3093
InterRepository.register_optimiser(InterVersionedFileRepository)
3094
InterRepository.register_optimiser(InterDifferingSerializer)
3095
InterRepository.register_optimiser(InterSameDataRepository)
3098
def install_revisions(repository, iterable, num_revisions=None, pb=None):
3099
"""Install all revision data into a repository.
3101
Accepts an iterable of revision, tree, signature tuples. The signature
3104
repository.start_write_group()
3106
inventory_cache = lru_cache.LRUCache(10)
3107
for n, (revision, revision_tree, signature) in enumerate(iterable):
3108
_install_revision(repository, revision, revision_tree, signature,
3111
pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
3113
repository.abort_write_group()
3116
repository.commit_write_group()
3119
def _install_revision(repository, rev, revision_tree, signature,
3121
"""Install all revision data into a repository."""
3122
present_parents = []
3124
for p_id in rev.parent_ids:
3125
if repository.has_revision(p_id):
3126
present_parents.append(p_id)
3127
parent_trees[p_id] = repository.revision_tree(p_id)
3129
parent_trees[p_id] = repository.revision_tree(
3130
_mod_revision.NULL_REVISION)
3132
# FIXME: Support nested trees
3133
inv = revision_tree.root_inventory
3134
entries = inv.iter_entries()
3135
# backwards compatibility hack: skip the root id.
3136
if not repository.supports_rich_root():
3137
path, root = next(entries)
3138
if root.revision != rev.revision_id:
3139
raise errors.IncompatibleRevision(repr(repository))
3141
for path, ie in entries:
3142
text_keys[(ie.file_id, ie.revision)] = ie
3143
text_parent_map = repository.texts.get_parent_map(text_keys)
3144
missing_texts = set(text_keys) - set(text_parent_map)
3145
# Add the texts that are not already present
3146
for text_key in missing_texts:
3147
ie = text_keys[text_key]
3149
# FIXME: TODO: The following loop overlaps/duplicates that done by
3150
# commit to determine parents. There is a latent/real bug here where
3151
# the parents inserted are not those commit would do - in particular
3152
# they are not filtered by heads(). RBC, AB
3153
for revision, tree in parent_trees.iteritems():
3154
if not tree.has_id(ie.file_id):
3156
parent_id = tree.get_file_revision(ie.file_id)
3157
if parent_id in text_parents:
3159
text_parents.append((ie.file_id, parent_id))
3160
lines = revision_tree.get_file(ie.file_id).readlines()
3161
repository.texts.add_lines(text_key, text_parents, lines)
3163
# install the inventory
3164
if repository._format._commit_inv_deltas and len(rev.parent_ids):
3165
# Cache this inventory
3166
inventory_cache[rev.revision_id] = inv
3168
basis_inv = inventory_cache[rev.parent_ids[0]]
3170
repository.add_inventory(rev.revision_id, inv, present_parents)
3172
delta = inv._make_delta(basis_inv)
3173
repository.add_inventory_by_delta(rev.parent_ids[0], delta,
3174
rev.revision_id, present_parents)
3176
repository.add_inventory(rev.revision_id, inv, present_parents)
3177
except errors.RevisionAlreadyPresent:
3179
if signature is not None:
3180
repository.add_signature_text(rev.revision_id, signature)
3181
repository.add_revision(rev.revision_id, rev, inv)
3184
def install_revision(repository, rev, revision_tree):
3185
"""Install all revision data into a repository."""
3186
install_revisions(repository, [(rev, revision_tree, None)])