~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/vf_repository.py

  • Committer: Vincent Ladeuil
  • Date: 2011-06-27 15:52:06 UTC
  • mto: (5993.1.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 5994.
  • Revision ID: v.ladeuil+lp@free.fr-20110627155206-erxoqocysuv4oskj
Fix more test failures.

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005-2011 Canonical Ltd
 
2
#
 
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.
 
7
#
 
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.
 
12
#
 
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
 
16
 
 
17
"""Repository formats built around versioned files."""
 
18
 
 
19
 
 
20
from bzrlib.lazy_import import lazy_import
 
21
lazy_import(globals(), """
 
22
import itertools
 
23
 
 
24
from bzrlib import (
 
25
    check,
 
26
    debug,
 
27
    fetch as _mod_fetch,
 
28
    fifo_cache,
 
29
    gpg,
 
30
    graph,
 
31
    inventory_delta,
 
32
    lru_cache,
 
33
    osutils,
 
34
    revision as _mod_revision,
 
35
    serializer as _mod_serializer,
 
36
    static_tuple,
 
37
    symbol_versioning,
 
38
    tsort,
 
39
    ui,
 
40
    versionedfile,
 
41
    )
 
42
 
 
43
from bzrlib.recordcounter import RecordCounter
 
44
from bzrlib.revisiontree import InventoryRevisionTree
 
45
from bzrlib.testament import Testament
 
46
""")
 
47
 
 
48
from bzrlib import (
 
49
    errors,
 
50
    )
 
51
from bzrlib.decorators import (
 
52
    needs_read_lock,
 
53
    needs_write_lock,
 
54
    only_raises,
 
55
    )
 
56
from bzrlib.inventory import (
 
57
    Inventory,
 
58
    InventoryDirectory,
 
59
    ROOT_ID,
 
60
    entry_factory,
 
61
    )
 
62
 
 
63
from bzrlib.repository import (
 
64
    CommitBuilder,
 
65
    InterRepository,
 
66
    MetaDirRepository,
 
67
    MetaDirRepositoryFormat,
 
68
    Repository,
 
69
    RepositoryFormat,
 
70
    )
 
71
 
 
72
from bzrlib.trace import (
 
73
    mutter,
 
74
    )
 
75
 
 
76
 
 
77
class VersionedFileRepositoryFormat(RepositoryFormat):
 
78
    """Base class for all repository formats that are VersionedFiles-based."""
 
79
 
 
80
    supports_full_versioned_files = True
 
81
 
 
82
    # Should commit add an inventory, or an inventory delta to the repository.
 
83
    _commit_inv_deltas = True
 
84
    # What order should fetch operations request streams in?
 
85
    # The default is unordered as that is the cheapest for an origin to
 
86
    # provide.
 
87
    _fetch_order = 'unordered'
 
88
    # Does this repository format use deltas that can be fetched as-deltas ?
 
89
    # (E.g. knits, where the knit deltas can be transplanted intact.
 
90
    # We default to False, which will ensure that enough data to get
 
91
    # a full text out of any fetch stream will be grabbed.
 
92
    _fetch_uses_deltas = False
 
93
 
 
94
 
 
95
class VersionedFileCommitBuilder(CommitBuilder):
 
96
    """Commit builder implementation for versioned files based repositories.
 
97
    """
 
98
 
 
99
    # this commit builder supports the record_entry_contents interface
 
100
    supports_record_entry_contents = True
 
101
 
 
102
    # the default CommitBuilder does not manage trees whose root is versioned.
 
103
    _versioned_root = False
 
104
 
 
105
    def __init__(self, repository, parents, config, timestamp=None,
 
106
                 timezone=None, committer=None, revprops=None,
 
107
                 revision_id=None, lossy=False):
 
108
        super(VersionedFileCommitBuilder, self).__init__(repository,
 
109
            parents, config, timestamp, timezone, committer, revprops,
 
110
            revision_id, lossy)
 
111
        try:
 
112
            basis_id = self.parents[0]
 
113
        except IndexError:
 
114
            basis_id = _mod_revision.NULL_REVISION
 
115
        self.basis_delta_revision = basis_id
 
116
        self.new_inventory = Inventory(None)
 
117
        self._basis_delta = []
 
118
        self.__heads = graph.HeadsCache(repository.get_graph()).heads
 
119
        # memo'd check for no-op commits.
 
120
        self._any_changes = False
 
121
        # API compatibility, older code that used CommitBuilder did not call
 
122
        # .record_delete(), which means the delta that is computed would not be
 
123
        # valid. Callers that will call record_delete() should call
 
124
        # .will_record_deletes() to indicate that.
 
125
        self._recording_deletes = False
 
126
 
 
127
    def will_record_deletes(self):
 
128
        """Tell the commit builder that deletes are being notified.
 
129
 
 
130
        This enables the accumulation of an inventory delta; for the resulting
 
131
        commit to be valid, deletes against the basis MUST be recorded via
 
132
        builder.record_delete().
 
133
        """
 
134
        self._recording_deletes = True
 
135
 
 
136
    def any_changes(self):
 
137
        """Return True if any entries were changed.
 
138
 
 
139
        This includes merge-only changes. It is the core for the --unchanged
 
140
        detection in commit.
 
141
 
 
142
        :return: True if any changes have occured.
 
143
        """
 
144
        return self._any_changes
 
145
 
 
146
    def _ensure_fallback_inventories(self):
 
147
        """Ensure that appropriate inventories are available.
 
148
 
 
149
        This only applies to repositories that are stacked, and is about
 
150
        enusring the stacking invariants. Namely, that for any revision that is
 
151
        present, we either have all of the file content, or we have the parent
 
152
        inventory and the delta file content.
 
153
        """
 
154
        if not self.repository._fallback_repositories:
 
155
            return
 
156
        if not self.repository._format.supports_chks:
 
157
            raise errors.BzrError("Cannot commit directly to a stacked branch"
 
158
                " in pre-2a formats. See "
 
159
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
 
160
        # This is a stacked repo, we need to make sure we have the parent
 
161
        # inventories for the parents.
 
162
        parent_keys = [(p,) for p in self.parents]
 
163
        parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
 
164
        missing_parent_keys = set([pk for pk in parent_keys
 
165
                                       if pk not in parent_map])
 
166
        fallback_repos = list(reversed(self.repository._fallback_repositories))
 
167
        missing_keys = [('inventories', pk[0])
 
168
                        for pk in missing_parent_keys]
 
169
        resume_tokens = []
 
170
        while missing_keys and fallback_repos:
 
171
            fallback_repo = fallback_repos.pop()
 
172
            source = fallback_repo._get_source(self.repository._format)
 
173
            sink = self.repository._get_sink()
 
174
            stream = source.get_stream_for_missing_keys(missing_keys)
 
175
            missing_keys = sink.insert_stream_without_locking(stream,
 
176
                self.repository._format)
 
177
        if missing_keys:
 
178
            raise errors.BzrError('Unable to fill in parent inventories for a'
 
179
                                  ' stacked branch')
 
180
 
 
181
    def commit(self, message):
 
182
        """Make the actual commit.
 
183
 
 
184
        :return: The revision id of the recorded revision.
 
185
        """
 
186
        self._validate_unicode_text(message, 'commit message')
 
187
        rev = _mod_revision.Revision(
 
188
                       timestamp=self._timestamp,
 
189
                       timezone=self._timezone,
 
190
                       committer=self._committer,
 
191
                       message=message,
 
192
                       inventory_sha1=self.inv_sha1,
 
193
                       revision_id=self._new_revision_id,
 
194
                       properties=self._revprops)
 
195
        rev.parent_ids = self.parents
 
196
        self.repository.add_revision(self._new_revision_id, rev,
 
197
            self.new_inventory, self._config)
 
198
        self._ensure_fallback_inventories()
 
199
        self.repository.commit_write_group()
 
200
        return self._new_revision_id
 
201
 
 
202
    def abort(self):
 
203
        """Abort the commit that is being built.
 
204
        """
 
205
        self.repository.abort_write_group()
 
206
 
 
207
    def revision_tree(self):
 
208
        """Return the tree that was just committed.
 
209
 
 
210
        After calling commit() this can be called to get a
 
211
        RevisionTree representing the newly committed tree. This is
 
212
        preferred to calling Repository.revision_tree() because that may
 
213
        require deserializing the inventory, while we already have a copy in
 
214
        memory.
 
215
        """
 
216
        if self.new_inventory is None:
 
217
            self.new_inventory = self.repository.get_inventory(
 
218
                self._new_revision_id)
 
219
        return InventoryRevisionTree(self.repository, self.new_inventory,
 
220
            self._new_revision_id)
 
221
 
 
222
    def finish_inventory(self):
 
223
        """Tell the builder that the inventory is finished.
 
224
 
 
225
        :return: The inventory id in the repository, which can be used with
 
226
            repository.get_inventory.
 
227
        """
 
228
        if self.new_inventory is None:
 
229
            # an inventory delta was accumulated without creating a new
 
230
            # inventory.
 
231
            basis_id = self.basis_delta_revision
 
232
            # We ignore the 'inventory' returned by add_inventory_by_delta
 
233
            # because self.new_inventory is used to hint to the rest of the
 
234
            # system what code path was taken
 
235
            self.inv_sha1, _ = self.repository.add_inventory_by_delta(
 
236
                basis_id, self._basis_delta, self._new_revision_id,
 
237
                self.parents)
 
238
        else:
 
239
            if self.new_inventory.root is None:
 
240
                raise AssertionError('Root entry should be supplied to'
 
241
                    ' record_entry_contents, as of bzr 0.10.')
 
242
                self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
 
243
            self.new_inventory.revision_id = self._new_revision_id
 
244
            self.inv_sha1 = self.repository.add_inventory(
 
245
                self._new_revision_id,
 
246
                self.new_inventory,
 
247
                self.parents
 
248
                )
 
249
        return self._new_revision_id
 
250
 
 
251
    def _check_root(self, ie, parent_invs, tree):
 
252
        """Helper for record_entry_contents.
 
253
 
 
254
        :param ie: An entry being added.
 
255
        :param parent_invs: The inventories of the parent revisions of the
 
256
            commit.
 
257
        :param tree: The tree that is being committed.
 
258
        """
 
259
        # In this revision format, root entries have no knit or weave When
 
260
        # serializing out to disk and back in root.revision is always
 
261
        # _new_revision_id
 
262
        ie.revision = self._new_revision_id
 
263
 
 
264
    def _require_root_change(self, tree):
 
265
        """Enforce an appropriate root object change.
 
266
 
 
267
        This is called once when record_iter_changes is called, if and only if
 
268
        the root was not in the delta calculated by record_iter_changes.
 
269
 
 
270
        :param tree: The tree which is being committed.
 
271
        """
 
272
        if len(self.parents) == 0:
 
273
            raise errors.RootMissing()
 
274
        entry = entry_factory['directory'](tree.path2id(''), '',
 
275
            None)
 
276
        entry.revision = self._new_revision_id
 
277
        self._basis_delta.append(('', '', entry.file_id, entry))
 
278
 
 
279
    def _get_delta(self, ie, basis_inv, path):
 
280
        """Get a delta against the basis inventory for ie."""
 
281
        if ie.file_id not in basis_inv:
 
282
            # add
 
283
            result = (None, path, ie.file_id, ie)
 
284
            self._basis_delta.append(result)
 
285
            return result
 
286
        elif ie != basis_inv[ie.file_id]:
 
287
            # common but altered
 
288
            # TODO: avoid tis id2path call.
 
289
            result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
 
290
            self._basis_delta.append(result)
 
291
            return result
 
292
        else:
 
293
            # common, unaltered
 
294
            return None
 
295
 
 
296
    def _heads(self, file_id, revision_ids):
 
297
        """Calculate the graph heads for revision_ids in the graph of file_id.
 
298
 
 
299
        This can use either a per-file graph or a global revision graph as we
 
300
        have an identity relationship between the two graphs.
 
301
        """
 
302
        return self.__heads(revision_ids)
 
303
 
 
304
    def get_basis_delta(self):
 
305
        """Return the complete inventory delta versus the basis inventory.
 
306
 
 
307
        This has been built up with the calls to record_delete and
 
308
        record_entry_contents. The client must have already called
 
309
        will_record_deletes() to indicate that they will be generating a
 
310
        complete delta.
 
311
 
 
312
        :return: An inventory delta, suitable for use with apply_delta, or
 
313
            Repository.add_inventory_by_delta, etc.
 
314
        """
 
315
        if not self._recording_deletes:
 
316
            raise AssertionError("recording deletes not activated.")
 
317
        return self._basis_delta
 
318
 
 
319
    def record_delete(self, path, file_id):
 
320
        """Record that a delete occured against a basis tree.
 
321
 
 
322
        This is an optional API - when used it adds items to the basis_delta
 
323
        being accumulated by the commit builder. It cannot be called unless the
 
324
        method will_record_deletes() has been called to inform the builder that
 
325
        a delta is being supplied.
 
326
 
 
327
        :param path: The path of the thing deleted.
 
328
        :param file_id: The file id that was deleted.
 
329
        """
 
330
        if not self._recording_deletes:
 
331
            raise AssertionError("recording deletes not activated.")
 
332
        delta = (path, None, file_id, None)
 
333
        self._basis_delta.append(delta)
 
334
        self._any_changes = True
 
335
        return delta
 
336
 
 
337
    def record_entry_contents(self, ie, parent_invs, path, tree,
 
338
        content_summary):
 
339
        """Record the content of ie from tree into the commit if needed.
 
340
 
 
341
        Side effect: sets ie.revision when unchanged
 
342
 
 
343
        :param ie: An inventory entry present in the commit.
 
344
        :param parent_invs: The inventories of the parent revisions of the
 
345
            commit.
 
346
        :param path: The path the entry is at in the tree.
 
347
        :param tree: The tree which contains this entry and should be used to
 
348
            obtain content.
 
349
        :param content_summary: Summary data from the tree about the paths
 
350
            content - stat, length, exec, sha/link target. This is only
 
351
            accessed when the entry has a revision of None - that is when it is
 
352
            a candidate to commit.
 
353
        :return: A tuple (change_delta, version_recorded, fs_hash).
 
354
            change_delta is an inventory_delta change for this entry against
 
355
            the basis tree of the commit, or None if no change occured against
 
356
            the basis tree.
 
357
            version_recorded is True if a new version of the entry has been
 
358
            recorded. For instance, committing a merge where a file was only
 
359
            changed on the other side will return (delta, False).
 
360
            fs_hash is either None, or the hash details for the path (currently
 
361
            a tuple of the contents sha1 and the statvalue returned by
 
362
            tree.get_file_with_stat()).
 
363
        """
 
364
        if self.new_inventory.root is None:
 
365
            if ie.parent_id is not None:
 
366
                raise errors.RootMissing()
 
367
            self._check_root(ie, parent_invs, tree)
 
368
        if ie.revision is None:
 
369
            kind = content_summary[0]
 
370
        else:
 
371
            # ie is carried over from a prior commit
 
372
            kind = ie.kind
 
373
        # XXX: repository specific check for nested tree support goes here - if
 
374
        # the repo doesn't want nested trees we skip it ?
 
375
        if (kind == 'tree-reference' and
 
376
            not self.repository._format.supports_tree_reference):
 
377
            # mismatch between commit builder logic and repository:
 
378
            # this needs the entry creation pushed down into the builder.
 
379
            raise NotImplementedError('Missing repository subtree support.')
 
380
        self.new_inventory.add(ie)
 
381
 
 
382
        # TODO: slow, take it out of the inner loop.
 
383
        try:
 
384
            basis_inv = parent_invs[0]
 
385
        except IndexError:
 
386
            basis_inv = Inventory(root_id=None)
 
387
 
 
388
        # ie.revision is always None if the InventoryEntry is considered
 
389
        # for committing. We may record the previous parents revision if the
 
390
        # content is actually unchanged against a sole head.
 
391
        if ie.revision is not None:
 
392
            if not self._versioned_root and path == '':
 
393
                # repositories that do not version the root set the root's
 
394
                # revision to the new commit even when no change occurs (more
 
395
                # specifically, they do not record a revision on the root; and
 
396
                # the rev id is assigned to the root during deserialisation -
 
397
                # this masks when a change may have occurred against the basis.
 
398
                # To match this we always issue a delta, because the revision
 
399
                # of the root will always be changing.
 
400
                if ie.file_id in basis_inv:
 
401
                    delta = (basis_inv.id2path(ie.file_id), path,
 
402
                        ie.file_id, ie)
 
403
                else:
 
404
                    # add
 
405
                    delta = (None, path, ie.file_id, ie)
 
406
                self._basis_delta.append(delta)
 
407
                return delta, False, None
 
408
            else:
 
409
                # we don't need to commit this, because the caller already
 
410
                # determined that an existing revision of this file is
 
411
                # appropriate. If it's not being considered for committing then
 
412
                # it and all its parents to the root must be unaltered so
 
413
                # no-change against the basis.
 
414
                if ie.revision == self._new_revision_id:
 
415
                    raise AssertionError("Impossible situation, a skipped "
 
416
                        "inventory entry (%r) claims to be modified in this "
 
417
                        "commit (%r).", (ie, self._new_revision_id))
 
418
                return None, False, None
 
419
        # XXX: Friction: parent_candidates should return a list not a dict
 
420
        #      so that we don't have to walk the inventories again.
 
421
        parent_candiate_entries = ie.parent_candidates(parent_invs)
 
422
        head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
 
423
        heads = []
 
424
        for inv in parent_invs:
 
425
            if ie.file_id in inv:
 
426
                old_rev = inv[ie.file_id].revision
 
427
                if old_rev in head_set:
 
428
                    heads.append(inv[ie.file_id].revision)
 
429
                    head_set.remove(inv[ie.file_id].revision)
 
430
 
 
431
        store = False
 
432
        # now we check to see if we need to write a new record to the
 
433
        # file-graph.
 
434
        # We write a new entry unless there is one head to the ancestors, and
 
435
        # the kind-derived content is unchanged.
 
436
 
 
437
        # Cheapest check first: no ancestors, or more the one head in the
 
438
        # ancestors, we write a new node.
 
439
        if len(heads) != 1:
 
440
            store = True
 
441
        if not store:
 
442
            # There is a single head, look it up for comparison
 
443
            parent_entry = parent_candiate_entries[heads[0]]
 
444
            # if the non-content specific data has changed, we'll be writing a
 
445
            # node:
 
446
            if (parent_entry.parent_id != ie.parent_id or
 
447
                parent_entry.name != ie.name):
 
448
                store = True
 
449
        # now we need to do content specific checks:
 
450
        if not store:
 
451
            # if the kind changed the content obviously has
 
452
            if kind != parent_entry.kind:
 
453
                store = True
 
454
        # Stat cache fingerprint feedback for the caller - None as we usually
 
455
        # don't generate one.
 
456
        fingerprint = None
 
457
        if kind == 'file':
 
458
            if content_summary[2] is None:
 
459
                raise ValueError("Files must not have executable = None")
 
460
            if not store:
 
461
                # We can't trust a check of the file length because of content
 
462
                # filtering...
 
463
                if (# if the exec bit has changed we have to store:
 
464
                    parent_entry.executable != content_summary[2]):
 
465
                    store = True
 
466
                elif parent_entry.text_sha1 == content_summary[3]:
 
467
                    # all meta and content is unchanged (using a hash cache
 
468
                    # hit to check the sha)
 
469
                    ie.revision = parent_entry.revision
 
470
                    ie.text_size = parent_entry.text_size
 
471
                    ie.text_sha1 = parent_entry.text_sha1
 
472
                    ie.executable = parent_entry.executable
 
473
                    return self._get_delta(ie, basis_inv, path), False, None
 
474
                else:
 
475
                    # Either there is only a hash change(no hash cache entry,
 
476
                    # or same size content change), or there is no change on
 
477
                    # this file at all.
 
478
                    # Provide the parent's hash to the store layer, so that the
 
479
                    # content is unchanged we will not store a new node.
 
480
                    nostore_sha = parent_entry.text_sha1
 
481
            if store:
 
482
                # We want to record a new node regardless of the presence or
 
483
                # absence of a content change in the file.
 
484
                nostore_sha = None
 
485
            ie.executable = content_summary[2]
 
486
            file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
 
487
            try:
 
488
                text = file_obj.read()
 
489
            finally:
 
490
                file_obj.close()
 
491
            try:
 
492
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
 
493
                    ie.file_id, text, heads, nostore_sha)
 
494
                # Let the caller know we generated a stat fingerprint.
 
495
                fingerprint = (ie.text_sha1, stat_value)
 
496
            except errors.ExistingContent:
 
497
                # Turns out that the file content was unchanged, and we were
 
498
                # only going to store a new node if it was changed. Carry over
 
499
                # the entry.
 
500
                ie.revision = parent_entry.revision
 
501
                ie.text_size = parent_entry.text_size
 
502
                ie.text_sha1 = parent_entry.text_sha1
 
503
                ie.executable = parent_entry.executable
 
504
                return self._get_delta(ie, basis_inv, path), False, None
 
505
        elif kind == 'directory':
 
506
            if not store:
 
507
                # all data is meta here, nothing specific to directory, so
 
508
                # carry over:
 
509
                ie.revision = parent_entry.revision
 
510
                return self._get_delta(ie, basis_inv, path), False, None
 
511
            self._add_text_to_weave(ie.file_id, '', heads, None)
 
512
        elif kind == 'symlink':
 
513
            current_link_target = content_summary[3]
 
514
            if not store:
 
515
                # symlink target is not generic metadata, check if it has
 
516
                # changed.
 
517
                if current_link_target != parent_entry.symlink_target:
 
518
                    store = True
 
519
            if not store:
 
520
                # unchanged, carry over.
 
521
                ie.revision = parent_entry.revision
 
522
                ie.symlink_target = parent_entry.symlink_target
 
523
                return self._get_delta(ie, basis_inv, path), False, None
 
524
            ie.symlink_target = current_link_target
 
525
            self._add_text_to_weave(ie.file_id, '', heads, None)
 
526
        elif kind == 'tree-reference':
 
527
            if not store:
 
528
                if content_summary[3] != parent_entry.reference_revision:
 
529
                    store = True
 
530
            if not store:
 
531
                # unchanged, carry over.
 
532
                ie.reference_revision = parent_entry.reference_revision
 
533
                ie.revision = parent_entry.revision
 
534
                return self._get_delta(ie, basis_inv, path), False, None
 
535
            ie.reference_revision = content_summary[3]
 
536
            if ie.reference_revision is None:
 
537
                raise AssertionError("invalid content_summary for nested tree: %r"
 
538
                    % (content_summary,))
 
539
            self._add_text_to_weave(ie.file_id, '', heads, None)
 
540
        else:
 
541
            raise NotImplementedError('unknown kind')
 
542
        ie.revision = self._new_revision_id
 
543
        # The initial commit adds a root directory, but this in itself is not
 
544
        # a worthwhile commit.
 
545
        if (self.basis_delta_revision != _mod_revision.NULL_REVISION or
 
546
            path != ""):
 
547
            self._any_changes = True
 
548
        return self._get_delta(ie, basis_inv, path), True, fingerprint
 
549
 
 
550
    def record_iter_changes(self, tree, basis_revision_id, iter_changes,
 
551
        _entry_factory=entry_factory):
 
552
        """Record a new tree via iter_changes.
 
553
 
 
554
        :param tree: The tree to obtain text contents from for changed objects.
 
555
        :param basis_revision_id: The revision id of the tree the iter_changes
 
556
            has been generated against. Currently assumed to be the same
 
557
            as self.parents[0] - if it is not, errors may occur.
 
558
        :param iter_changes: An iter_changes iterator with the changes to apply
 
559
            to basis_revision_id. The iterator must not include any items with
 
560
            a current kind of None - missing items must be either filtered out
 
561
            or errored-on beefore record_iter_changes sees the item.
 
562
        :param _entry_factory: Private method to bind entry_factory locally for
 
563
            performance.
 
564
        :return: A generator of (file_id, relpath, fs_hash) tuples for use with
 
565
            tree._observed_sha1.
 
566
        """
 
567
        # Create an inventory delta based on deltas between all the parents and
 
568
        # deltas between all the parent inventories. We use inventory delta's 
 
569
        # between the inventory objects because iter_changes masks
 
570
        # last-changed-field only changes.
 
571
        # Working data:
 
572
        # file_id -> change map, change is fileid, paths, changed, versioneds,
 
573
        # parents, names, kinds, executables
 
574
        merged_ids = {}
 
575
        # {file_id -> revision_id -> inventory entry, for entries in parent
 
576
        # trees that are not parents[0]
 
577
        parent_entries = {}
 
578
        ghost_basis = False
 
579
        try:
 
580
            revtrees = list(self.repository.revision_trees(self.parents))
 
581
        except errors.NoSuchRevision:
 
582
            # one or more ghosts, slow path.
 
583
            revtrees = []
 
584
            for revision_id in self.parents:
 
585
                try:
 
586
                    revtrees.append(self.repository.revision_tree(revision_id))
 
587
                except errors.NoSuchRevision:
 
588
                    if not revtrees:
 
589
                        basis_revision_id = _mod_revision.NULL_REVISION
 
590
                        ghost_basis = True
 
591
                    revtrees.append(self.repository.revision_tree(
 
592
                        _mod_revision.NULL_REVISION))
 
593
        # The basis inventory from a repository 
 
594
        if revtrees:
 
595
            basis_inv = revtrees[0].inventory
 
596
        else:
 
597
            basis_inv = self.repository.revision_tree(
 
598
                _mod_revision.NULL_REVISION).inventory
 
599
        if len(self.parents) > 0:
 
600
            if basis_revision_id != self.parents[0] and not ghost_basis:
 
601
                raise Exception(
 
602
                    "arbitrary basis parents not yet supported with merges")
 
603
            for revtree in revtrees[1:]:
 
604
                for change in revtree.inventory._make_delta(basis_inv):
 
605
                    if change[1] is None:
 
606
                        # Not present in this parent.
 
607
                        continue
 
608
                    if change[2] not in merged_ids:
 
609
                        if change[0] is not None:
 
610
                            basis_entry = basis_inv[change[2]]
 
611
                            merged_ids[change[2]] = [
 
612
                                # basis revid
 
613
                                basis_entry.revision,
 
614
                                # new tree revid
 
615
                                change[3].revision]
 
616
                            parent_entries[change[2]] = {
 
617
                                # basis parent
 
618
                                basis_entry.revision:basis_entry,
 
619
                                # this parent 
 
620
                                change[3].revision:change[3],
 
621
                                }
 
622
                        else:
 
623
                            merged_ids[change[2]] = [change[3].revision]
 
624
                            parent_entries[change[2]] = {change[3].revision:change[3]}
 
625
                    else:
 
626
                        merged_ids[change[2]].append(change[3].revision)
 
627
                        parent_entries[change[2]][change[3].revision] = change[3]
 
628
        else:
 
629
            merged_ids = {}
 
630
        # Setup the changes from the tree:
 
631
        # changes maps file_id -> (change, [parent revision_ids])
 
632
        changes= {}
 
633
        for change in iter_changes:
 
634
            # This probably looks up in basis_inv way to much.
 
635
            if change[1][0] is not None:
 
636
                head_candidate = [basis_inv[change[0]].revision]
 
637
            else:
 
638
                head_candidate = []
 
639
            changes[change[0]] = change, merged_ids.get(change[0],
 
640
                head_candidate)
 
641
        unchanged_merged = set(merged_ids) - set(changes)
 
642
        # Extend the changes dict with synthetic changes to record merges of
 
643
        # texts.
 
644
        for file_id in unchanged_merged:
 
645
            # Record a merged version of these items that did not change vs the
 
646
            # basis. This can be either identical parallel changes, or a revert
 
647
            # of a specific file after a merge. The recorded content will be
 
648
            # that of the current tree (which is the same as the basis), but
 
649
            # the per-file graph will reflect a merge.
 
650
            # NB:XXX: We are reconstructing path information we had, this
 
651
            # should be preserved instead.
 
652
            # inv delta  change: (file_id, (path_in_source, path_in_target),
 
653
            #   changed_content, versioned, parent, name, kind,
 
654
            #   executable)
 
655
            try:
 
656
                basis_entry = basis_inv[file_id]
 
657
            except errors.NoSuchId:
 
658
                # a change from basis->some_parents but file_id isn't in basis
 
659
                # so was new in the merge, which means it must have changed
 
660
                # from basis -> current, and as it hasn't the add was reverted
 
661
                # by the user. So we discard this change.
 
662
                pass
 
663
            else:
 
664
                change = (file_id,
 
665
                    (basis_inv.id2path(file_id), tree.id2path(file_id)),
 
666
                    False, (True, True),
 
667
                    (basis_entry.parent_id, basis_entry.parent_id),
 
668
                    (basis_entry.name, basis_entry.name),
 
669
                    (basis_entry.kind, basis_entry.kind),
 
670
                    (basis_entry.executable, basis_entry.executable))
 
671
                changes[file_id] = (change, merged_ids[file_id])
 
672
        # changes contains tuples with the change and a set of inventory
 
673
        # candidates for the file.
 
674
        # inv delta is:
 
675
        # old_path, new_path, file_id, new_inventory_entry
 
676
        seen_root = False # Is the root in the basis delta?
 
677
        inv_delta = self._basis_delta
 
678
        modified_rev = self._new_revision_id
 
679
        for change, head_candidates in changes.values():
 
680
            if change[3][1]: # versioned in target.
 
681
                # Several things may be happening here:
 
682
                # We may have a fork in the per-file graph
 
683
                #  - record a change with the content from tree
 
684
                # We may have a change against < all trees  
 
685
                #  - carry over the tree that hasn't changed
 
686
                # We may have a change against all trees
 
687
                #  - record the change with the content from tree
 
688
                kind = change[6][1]
 
689
                file_id = change[0]
 
690
                entry = _entry_factory[kind](file_id, change[5][1],
 
691
                    change[4][1])
 
692
                head_set = self._heads(change[0], set(head_candidates))
 
693
                heads = []
 
694
                # Preserve ordering.
 
695
                for head_candidate in head_candidates:
 
696
                    if head_candidate in head_set:
 
697
                        heads.append(head_candidate)
 
698
                        head_set.remove(head_candidate)
 
699
                carried_over = False
 
700
                if len(heads) == 1:
 
701
                    # Could be a carry-over situation:
 
702
                    parent_entry_revs = parent_entries.get(file_id, None)
 
703
                    if parent_entry_revs:
 
704
                        parent_entry = parent_entry_revs.get(heads[0], None)
 
705
                    else:
 
706
                        parent_entry = None
 
707
                    if parent_entry is None:
 
708
                        # The parent iter_changes was called against is the one
 
709
                        # that is the per-file head, so any change is relevant
 
710
                        # iter_changes is valid.
 
711
                        carry_over_possible = False
 
712
                    else:
 
713
                        # could be a carry over situation
 
714
                        # A change against the basis may just indicate a merge,
 
715
                        # we need to check the content against the source of the
 
716
                        # merge to determine if it was changed after the merge
 
717
                        # or carried over.
 
718
                        if (parent_entry.kind != entry.kind or
 
719
                            parent_entry.parent_id != entry.parent_id or
 
720
                            parent_entry.name != entry.name):
 
721
                            # Metadata common to all entries has changed
 
722
                            # against per-file parent
 
723
                            carry_over_possible = False
 
724
                        else:
 
725
                            carry_over_possible = True
 
726
                        # per-type checks for changes against the parent_entry
 
727
                        # are done below.
 
728
                else:
 
729
                    # Cannot be a carry-over situation
 
730
                    carry_over_possible = False
 
731
                # Populate the entry in the delta
 
732
                if kind == 'file':
 
733
                    # XXX: There is still a small race here: If someone reverts the content of a file
 
734
                    # after iter_changes examines and decides it has changed,
 
735
                    # we will unconditionally record a new version even if some
 
736
                    # other process reverts it while commit is running (with
 
737
                    # the revert happening after iter_changes did its
 
738
                    # examination).
 
739
                    if change[7][1]:
 
740
                        entry.executable = True
 
741
                    else:
 
742
                        entry.executable = False
 
743
                    if (carry_over_possible and
 
744
                        parent_entry.executable == entry.executable):
 
745
                            # Check the file length, content hash after reading
 
746
                            # the file.
 
747
                            nostore_sha = parent_entry.text_sha1
 
748
                    else:
 
749
                        nostore_sha = None
 
750
                    file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
 
751
                    try:
 
752
                        text = file_obj.read()
 
753
                    finally:
 
754
                        file_obj.close()
 
755
                    try:
 
756
                        entry.text_sha1, entry.text_size = self._add_text_to_weave(
 
757
                            file_id, text, heads, nostore_sha)
 
758
                        yield file_id, change[1][1], (entry.text_sha1, stat_value)
 
759
                    except errors.ExistingContent:
 
760
                        # No content change against a carry_over parent
 
761
                        # Perhaps this should also yield a fs hash update?
 
762
                        carried_over = True
 
763
                        entry.text_size = parent_entry.text_size
 
764
                        entry.text_sha1 = parent_entry.text_sha1
 
765
                elif kind == 'symlink':
 
766
                    # Wants a path hint?
 
767
                    entry.symlink_target = tree.get_symlink_target(file_id)
 
768
                    if (carry_over_possible and
 
769
                        parent_entry.symlink_target == entry.symlink_target):
 
770
                        carried_over = True
 
771
                    else:
 
772
                        self._add_text_to_weave(change[0], '', heads, None)
 
773
                elif kind == 'directory':
 
774
                    if carry_over_possible:
 
775
                        carried_over = True
 
776
                    else:
 
777
                        # Nothing to set on the entry.
 
778
                        # XXX: split into the Root and nonRoot versions.
 
779
                        if change[1][1] != '' or self.repository.supports_rich_root():
 
780
                            self._add_text_to_weave(change[0], '', heads, None)
 
781
                elif kind == 'tree-reference':
 
782
                    if not self.repository._format.supports_tree_reference:
 
783
                        # This isn't quite sane as an error, but we shouldn't
 
784
                        # ever see this code path in practice: tree's don't
 
785
                        # permit references when the repo doesn't support tree
 
786
                        # references.
 
787
                        raise errors.UnsupportedOperation(tree.add_reference,
 
788
                            self.repository)
 
789
                    reference_revision = tree.get_reference_revision(change[0])
 
790
                    entry.reference_revision = reference_revision
 
791
                    if (carry_over_possible and
 
792
                        parent_entry.reference_revision == reference_revision):
 
793
                        carried_over = True
 
794
                    else:
 
795
                        self._add_text_to_weave(change[0], '', heads, None)
 
796
                else:
 
797
                    raise AssertionError('unknown kind %r' % kind)
 
798
                if not carried_over:
 
799
                    entry.revision = modified_rev
 
800
                else:
 
801
                    entry.revision = parent_entry.revision
 
802
            else:
 
803
                entry = None
 
804
            new_path = change[1][1]
 
805
            inv_delta.append((change[1][0], new_path, change[0], entry))
 
806
            if new_path == '':
 
807
                seen_root = True
 
808
        self.new_inventory = None
 
809
        # The initial commit adds a root directory, but this in itself is not
 
810
        # a worthwhile commit.
 
811
        if ((len(inv_delta) > 0 and basis_revision_id != _mod_revision.NULL_REVISION) or
 
812
            (len(inv_delta) > 1 and basis_revision_id == _mod_revision.NULL_REVISION)):
 
813
            # This should perhaps be guarded by a check that the basis we
 
814
            # commit against is the basis for the commit and if not do a delta
 
815
            # against the basis.
 
816
            self._any_changes = True
 
817
        if not seen_root:
 
818
            # housekeeping root entry changes do not affect no-change commits.
 
819
            self._require_root_change(tree)
 
820
        self.basis_delta_revision = basis_revision_id
 
821
 
 
822
    def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
 
823
        parent_keys = tuple([(file_id, parent) for parent in parents])
 
824
        return self.repository.texts._add_text(
 
825
            (file_id, self._new_revision_id), parent_keys, new_text,
 
826
            nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
 
827
 
 
828
 
 
829
class VersionedFileRootCommitBuilder(VersionedFileCommitBuilder):
 
830
    """This commitbuilder actually records the root id"""
 
831
 
 
832
    # the root entry gets versioned properly by this builder.
 
833
    _versioned_root = True
 
834
 
 
835
    def _check_root(self, ie, parent_invs, tree):
 
836
        """Helper for record_entry_contents.
 
837
 
 
838
        :param ie: An entry being added.
 
839
        :param parent_invs: The inventories of the parent revisions of the
 
840
            commit.
 
841
        :param tree: The tree that is being committed.
 
842
        """
 
843
 
 
844
    def _require_root_change(self, tree):
 
845
        """Enforce an appropriate root object change.
 
846
 
 
847
        This is called once when record_iter_changes is called, if and only if
 
848
        the root was not in the delta calculated by record_iter_changes.
 
849
 
 
850
        :param tree: The tree which is being committed.
 
851
        """
 
852
        # versioned roots do not change unless the tree found a change.
 
853
 
 
854
 
 
855
class VersionedFileRepository(Repository):
 
856
    """Repository holding history for one or more branches.
 
857
 
 
858
    The repository holds and retrieves historical information including
 
859
    revisions and file history.  It's normally accessed only by the Branch,
 
860
    which views a particular line of development through that history.
 
861
 
 
862
    The Repository builds on top of some byte storage facilies (the revisions,
 
863
    signatures, inventories, texts and chk_bytes attributes) and a Transport,
 
864
    which respectively provide byte storage and a means to access the (possibly
 
865
    remote) disk.
 
866
 
 
867
    The byte storage facilities are addressed via tuples, which we refer to
 
868
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
 
869
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
 
870
    (file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
 
871
    byte string made up of a hash identifier and a hash value.
 
872
    We use this interface because it allows low friction with the underlying
 
873
    code that implements disk indices, network encoding and other parts of
 
874
    bzrlib.
 
875
 
 
876
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
 
877
        the serialised revisions for the repository. This can be used to obtain
 
878
        revision graph information or to access raw serialised revisions.
 
879
        The result of trying to insert data into the repository via this store
 
880
        is undefined: it should be considered read-only except for implementors
 
881
        of repositories.
 
882
    :ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
 
883
        the serialised signatures for the repository. This can be used to
 
884
        obtain access to raw serialised signatures.  The result of trying to
 
885
        insert data into the repository via this store is undefined: it should
 
886
        be considered read-only except for implementors of repositories.
 
887
    :ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
 
888
        the serialised inventories for the repository. This can be used to
 
889
        obtain unserialised inventories.  The result of trying to insert data
 
890
        into the repository via this store is undefined: it should be
 
891
        considered read-only except for implementors of repositories.
 
892
    :ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
 
893
        texts of files and directories for the repository. This can be used to
 
894
        obtain file texts or file graphs. Note that Repository.iter_file_bytes
 
895
        is usually a better interface for accessing file texts.
 
896
        The result of trying to insert data into the repository via this store
 
897
        is undefined: it should be considered read-only except for implementors
 
898
        of repositories.
 
899
    :ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
 
900
        any data the repository chooses to store or have indexed by its hash.
 
901
        The result of trying to insert data into the repository via this store
 
902
        is undefined: it should be considered read-only except for implementors
 
903
        of repositories.
 
904
    :ivar _transport: Transport for file access to repository, typically
 
905
        pointing to .bzr/repository.
 
906
    """
 
907
 
 
908
    # What class to use for a CommitBuilder. Often it's simpler to change this
 
909
    # in a Repository class subclass rather than to override
 
910
    # get_commit_builder.
 
911
    _commit_builder_class = VersionedFileCommitBuilder
 
912
 
 
913
    def add_fallback_repository(self, repository):
 
914
        """Add a repository to use for looking up data not held locally.
 
915
 
 
916
        :param repository: A repository.
 
917
        """
 
918
        if not self._format.supports_external_lookups:
 
919
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
 
920
        if self.is_locked():
 
921
            # This repository will call fallback.unlock() when we transition to
 
922
            # the unlocked state, so we make sure to increment the lock count
 
923
            repository.lock_read()
 
924
        self._check_fallback_repository(repository)
 
925
        self._fallback_repositories.append(repository)
 
926
        self.texts.add_fallback_versioned_files(repository.texts)
 
927
        self.inventories.add_fallback_versioned_files(repository.inventories)
 
928
        self.revisions.add_fallback_versioned_files(repository.revisions)
 
929
        self.signatures.add_fallback_versioned_files(repository.signatures)
 
930
        if self.chk_bytes is not None:
 
931
            self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
 
932
 
 
933
    @only_raises(errors.LockNotHeld, errors.LockBroken)
 
934
    def unlock(self):
 
935
        super(VersionedFileRepository, self).unlock()
 
936
        if self.control_files._lock_count == 0:
 
937
            self._inventory_entry_cache.clear()
 
938
 
 
939
    def add_inventory(self, revision_id, inv, parents):
 
940
        """Add the inventory inv to the repository as revision_id.
 
941
 
 
942
        :param parents: The revision ids of the parents that revision_id
 
943
                        is known to have and are in the repository already.
 
944
 
 
945
        :returns: The validator(which is a sha1 digest, though what is sha'd is
 
946
            repository format specific) of the serialized inventory.
 
947
        """
 
948
        if not self.is_in_write_group():
 
949
            raise AssertionError("%r not in write group" % (self,))
 
950
        _mod_revision.check_not_reserved_id(revision_id)
 
951
        if not (inv.revision_id is None or inv.revision_id == revision_id):
 
952
            raise AssertionError(
 
953
                "Mismatch between inventory revision"
 
954
                " id and insertion revid (%r, %r)"
 
955
                % (inv.revision_id, revision_id))
 
956
        if inv.root is None:
 
957
            raise errors.RootMissing()
 
958
        return self._add_inventory_checked(revision_id, inv, parents)
 
959
 
 
960
    def _add_inventory_checked(self, revision_id, inv, parents):
 
961
        """Add inv to the repository after checking the inputs.
 
962
 
 
963
        This function can be overridden to allow different inventory styles.
 
964
 
 
965
        :seealso: add_inventory, for the contract.
 
966
        """
 
967
        inv_lines = self._serializer.write_inventory_to_lines(inv)
 
968
        return self._inventory_add_lines(revision_id, parents,
 
969
            inv_lines, check_content=False)
 
970
 
 
971
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
 
972
                               parents, basis_inv=None, propagate_caches=False):
 
973
        """Add a new inventory expressed as a delta against another revision.
 
974
 
 
975
        See the inventory developers documentation for the theory behind
 
976
        inventory deltas.
 
977
 
 
978
        :param basis_revision_id: The inventory id the delta was created
 
979
            against. (This does not have to be a direct parent.)
 
980
        :param delta: The inventory delta (see Inventory.apply_delta for
 
981
            details).
 
982
        :param new_revision_id: The revision id that the inventory is being
 
983
            added for.
 
984
        :param parents: The revision ids of the parents that revision_id is
 
985
            known to have and are in the repository already. These are supplied
 
986
            for repositories that depend on the inventory graph for revision
 
987
            graph access, as well as for those that pun ancestry with delta
 
988
            compression.
 
989
        :param basis_inv: The basis inventory if it is already known,
 
990
            otherwise None.
 
991
        :param propagate_caches: If True, the caches for this inventory are
 
992
          copied to and updated for the result if possible.
 
993
 
 
994
        :returns: (validator, new_inv)
 
995
            The validator(which is a sha1 digest, though what is sha'd is
 
996
            repository format specific) of the serialized inventory, and the
 
997
            resulting inventory.
 
998
        """
 
999
        if not self.is_in_write_group():
 
1000
            raise AssertionError("%r not in write group" % (self,))
 
1001
        _mod_revision.check_not_reserved_id(new_revision_id)
 
1002
        basis_tree = self.revision_tree(basis_revision_id)
 
1003
        basis_tree.lock_read()
 
1004
        try:
 
1005
            # Note that this mutates the inventory of basis_tree, which not all
 
1006
            # inventory implementations may support: A better idiom would be to
 
1007
            # return a new inventory, but as there is no revision tree cache in
 
1008
            # repository this is safe for now - RBC 20081013
 
1009
            if basis_inv is None:
 
1010
                basis_inv = basis_tree.inventory
 
1011
            basis_inv.apply_delta(delta)
 
1012
            basis_inv.revision_id = new_revision_id
 
1013
            return (self.add_inventory(new_revision_id, basis_inv, parents),
 
1014
                    basis_inv)
 
1015
        finally:
 
1016
            basis_tree.unlock()
 
1017
 
 
1018
    def _inventory_add_lines(self, revision_id, parents, lines,
 
1019
        check_content=True):
 
1020
        """Store lines in inv_vf and return the sha1 of the inventory."""
 
1021
        parents = [(parent,) for parent in parents]
 
1022
        result = self.inventories.add_lines((revision_id,), parents, lines,
 
1023
            check_content=check_content)[0]
 
1024
        self.inventories._access.flush()
 
1025
        return result
 
1026
 
 
1027
    def add_revision(self, revision_id, rev, inv=None, config=None):
 
1028
        """Add rev to the revision store as revision_id.
 
1029
 
 
1030
        :param revision_id: the revision id to use.
 
1031
        :param rev: The revision object.
 
1032
        :param inv: The inventory for the revision. if None, it will be looked
 
1033
                    up in the inventory storer
 
1034
        :param config: If None no digital signature will be created.
 
1035
                       If supplied its signature_needed method will be used
 
1036
                       to determine if a signature should be made.
 
1037
        """
 
1038
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
 
1039
        #       rev.parent_ids?
 
1040
        _mod_revision.check_not_reserved_id(revision_id)
 
1041
        if config is not None and config.signature_needed():
 
1042
            if inv is None:
 
1043
                inv = self.get_inventory(revision_id)
 
1044
            tree = InventoryRevisionTree(self, inv, revision_id)
 
1045
            testament = Testament(rev, tree)
 
1046
            plaintext = testament.as_short_text()
 
1047
            self.store_revision_signature(
 
1048
                gpg.GPGStrategy(config), plaintext, revision_id)
 
1049
        # check inventory present
 
1050
        if not self.inventories.get_parent_map([(revision_id,)]):
 
1051
            if inv is None:
 
1052
                raise errors.WeaveRevisionNotPresent(revision_id,
 
1053
                                                     self.inventories)
 
1054
            else:
 
1055
                # yes, this is not suitable for adding with ghosts.
 
1056
                rev.inventory_sha1 = self.add_inventory(revision_id, inv,
 
1057
                                                        rev.parent_ids)
 
1058
        else:
 
1059
            key = (revision_id,)
 
1060
            rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
 
1061
        self._add_revision(rev)
 
1062
 
 
1063
    def _add_revision(self, revision):
 
1064
        text = self._serializer.write_revision_to_string(revision)
 
1065
        key = (revision.revision_id,)
 
1066
        parents = tuple((parent,) for parent in revision.parent_ids)
 
1067
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
 
1068
 
 
1069
    def _check_inventories(self, checker):
 
1070
        """Check the inventories found from the revision scan.
 
1071
        
 
1072
        This is responsible for verifying the sha1 of inventories and
 
1073
        creating a pending_keys set that covers data referenced by inventories.
 
1074
        """
 
1075
        bar = ui.ui_factory.nested_progress_bar()
 
1076
        try:
 
1077
            self._do_check_inventories(checker, bar)
 
1078
        finally:
 
1079
            bar.finished()
 
1080
 
 
1081
    def _do_check_inventories(self, checker, bar):
 
1082
        """Helper for _check_inventories."""
 
1083
        revno = 0
 
1084
        keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
 
1085
        kinds = ['chk_bytes', 'texts']
 
1086
        count = len(checker.pending_keys)
 
1087
        bar.update("inventories", 0, 2)
 
1088
        current_keys = checker.pending_keys
 
1089
        checker.pending_keys = {}
 
1090
        # Accumulate current checks.
 
1091
        for key in current_keys:
 
1092
            if key[0] != 'inventories' and key[0] not in kinds:
 
1093
                checker._report_items.append('unknown key type %r' % (key,))
 
1094
            keys[key[0]].add(key[1:])
 
1095
        if keys['inventories']:
 
1096
            # NB: output order *should* be roughly sorted - topo or
 
1097
            # inverse topo depending on repository - either way decent
 
1098
            # to just delta against. However, pre-CHK formats didn't
 
1099
            # try to optimise inventory layout on disk. As such the
 
1100
            # pre-CHK code path does not use inventory deltas.
 
1101
            last_object = None
 
1102
            for record in self.inventories.check(keys=keys['inventories']):
 
1103
                if record.storage_kind == 'absent':
 
1104
                    checker._report_items.append(
 
1105
                        'Missing inventory {%s}' % (record.key,))
 
1106
                else:
 
1107
                    last_object = self._check_record('inventories', record,
 
1108
                        checker, last_object,
 
1109
                        current_keys[('inventories',) + record.key])
 
1110
            del keys['inventories']
 
1111
        else:
 
1112
            return
 
1113
        bar.update("texts", 1)
 
1114
        while (checker.pending_keys or keys['chk_bytes']
 
1115
            or keys['texts']):
 
1116
            # Something to check.
 
1117
            current_keys = checker.pending_keys
 
1118
            checker.pending_keys = {}
 
1119
            # Accumulate current checks.
 
1120
            for key in current_keys:
 
1121
                if key[0] not in kinds:
 
1122
                    checker._report_items.append('unknown key type %r' % (key,))
 
1123
                keys[key[0]].add(key[1:])
 
1124
            # Check the outermost kind only - inventories || chk_bytes || texts
 
1125
            for kind in kinds:
 
1126
                if keys[kind]:
 
1127
                    last_object = None
 
1128
                    for record in getattr(self, kind).check(keys=keys[kind]):
 
1129
                        if record.storage_kind == 'absent':
 
1130
                            checker._report_items.append(
 
1131
                                'Missing %s {%s}' % (kind, record.key,))
 
1132
                        else:
 
1133
                            last_object = self._check_record(kind, record,
 
1134
                                checker, last_object, current_keys[(kind,) + record.key])
 
1135
                    keys[kind] = set()
 
1136
                    break
 
1137
 
 
1138
    def _check_record(self, kind, record, checker, last_object, item_data):
 
1139
        """Check a single text from this repository."""
 
1140
        if kind == 'inventories':
 
1141
            rev_id = record.key[0]
 
1142
            inv = self._deserialise_inventory(rev_id,
 
1143
                record.get_bytes_as('fulltext'))
 
1144
            if last_object is not None:
 
1145
                delta = inv._make_delta(last_object)
 
1146
                for old_path, path, file_id, ie in delta:
 
1147
                    if ie is None:
 
1148
                        continue
 
1149
                    ie.check(checker, rev_id, inv)
 
1150
            else:
 
1151
                for path, ie in inv.iter_entries():
 
1152
                    ie.check(checker, rev_id, inv)
 
1153
            if self._format.fast_deltas:
 
1154
                return inv
 
1155
        elif kind == 'chk_bytes':
 
1156
            # No code written to check chk_bytes for this repo format.
 
1157
            checker._report_items.append(
 
1158
                'unsupported key type chk_bytes for %s' % (record.key,))
 
1159
        elif kind == 'texts':
 
1160
            self._check_text(record, checker, item_data)
 
1161
        else:
 
1162
            checker._report_items.append(
 
1163
                'unknown key type %s for %s' % (kind, record.key))
 
1164
 
 
1165
    def _check_text(self, record, checker, item_data):
 
1166
        """Check a single text."""
 
1167
        # Check it is extractable.
 
1168
        # TODO: check length.
 
1169
        if record.storage_kind == 'chunked':
 
1170
            chunks = record.get_bytes_as(record.storage_kind)
 
1171
            sha1 = osutils.sha_strings(chunks)
 
1172
            length = sum(map(len, chunks))
 
1173
        else:
 
1174
            content = record.get_bytes_as('fulltext')
 
1175
            sha1 = osutils.sha_string(content)
 
1176
            length = len(content)
 
1177
        if item_data and sha1 != item_data[1]:
 
1178
            checker._report_items.append(
 
1179
                'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
 
1180
                (record.key, sha1, item_data[1], item_data[2]))
 
1181
 
 
1182
    def __init__(self, _format, a_bzrdir, control_files):
 
1183
        """Instantiate a VersionedFileRepository.
 
1184
 
 
1185
        :param _format: The format of the repository on disk.
 
1186
        :param a_bzrdir: The BzrDir of the repository.
 
1187
        :param control_files: Control files to use for locking, etc.
 
1188
        """
 
1189
        # In the future we will have a single api for all stores for
 
1190
        # getting file texts, inventories and revisions, then
 
1191
        # this construct will accept instances of those things.
 
1192
        super(VersionedFileRepository, self).__init__(_format, a_bzrdir,
 
1193
            control_files)
 
1194
        # for tests
 
1195
        self._reconcile_does_inventory_gc = True
 
1196
        self._reconcile_fixes_text_parents = False
 
1197
        self._reconcile_backsup_inventory = True
 
1198
        # An InventoryEntry cache, used during deserialization
 
1199
        self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
 
1200
        # Is it safe to return inventory entries directly from the entry cache,
 
1201
        # rather copying them?
 
1202
        self._safe_to_return_from_cache = False
 
1203
 
 
1204
    @needs_read_lock
 
1205
    def gather_stats(self, revid=None, committers=None):
 
1206
        """See Repository.gather_stats()."""
 
1207
        result = super(VersionedFileRepository, self).gather_stats(revid, committers)
 
1208
        # now gather global repository information
 
1209
        # XXX: This is available for many repos regardless of listability.
 
1210
        if self.user_transport.listable():
 
1211
            # XXX: do we want to __define len__() ?
 
1212
            # Maybe the versionedfiles object should provide a different
 
1213
            # method to get the number of keys.
 
1214
            result['revisions'] = len(self.revisions.keys())
 
1215
            # result['size'] = t
 
1216
        return result
 
1217
 
 
1218
    def get_commit_builder(self, branch, parents, config, timestamp=None,
 
1219
                           timezone=None, committer=None, revprops=None,
 
1220
                           revision_id=None, lossy=False):
 
1221
        """Obtain a CommitBuilder for this repository.
 
1222
 
 
1223
        :param branch: Branch to commit to.
 
1224
        :param parents: Revision ids of the parents of the new revision.
 
1225
        :param config: Configuration to use.
 
1226
        :param timestamp: Optional timestamp recorded for commit.
 
1227
        :param timezone: Optional timezone for timestamp.
 
1228
        :param committer: Optional committer to set for commit.
 
1229
        :param revprops: Optional dictionary of revision properties.
 
1230
        :param revision_id: Optional revision id.
 
1231
        :param lossy: Whether to discard data that can not be natively
 
1232
            represented, when pushing to a foreign VCS
 
1233
        """
 
1234
        if self._fallback_repositories and not self._format.supports_chks:
 
1235
            raise errors.BzrError("Cannot commit directly to a stacked branch"
 
1236
                " in pre-2a formats. See "
 
1237
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
 
1238
        result = self._commit_builder_class(self, parents, config,
 
1239
            timestamp, timezone, committer, revprops, revision_id,
 
1240
            lossy)
 
1241
        self.start_write_group()
 
1242
        return result
 
1243
 
 
1244
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
 
1245
        """Return the keys of missing inventory parents for revisions added in
 
1246
        this write group.
 
1247
 
 
1248
        A revision is not complete if the inventory delta for that revision
 
1249
        cannot be calculated.  Therefore if the parent inventories of a
 
1250
        revision are not present, the revision is incomplete, and e.g. cannot
 
1251
        be streamed by a smart server.  This method finds missing inventory
 
1252
        parents for revisions added in this write group.
 
1253
        """
 
1254
        if not self._format.supports_external_lookups:
 
1255
            # This is only an issue for stacked repositories
 
1256
            return set()
 
1257
        if not self.is_in_write_group():
 
1258
            raise AssertionError('not in a write group')
 
1259
 
 
1260
        # XXX: We assume that every added revision already has its
 
1261
        # corresponding inventory, so we only check for parent inventories that
 
1262
        # might be missing, rather than all inventories.
 
1263
        parents = set(self.revisions._index.get_missing_parents())
 
1264
        parents.discard(_mod_revision.NULL_REVISION)
 
1265
        unstacked_inventories = self.inventories._index
 
1266
        present_inventories = unstacked_inventories.get_parent_map(
 
1267
            key[-1:] for key in parents)
 
1268
        parents.difference_update(present_inventories)
 
1269
        if len(parents) == 0:
 
1270
            # No missing parent inventories.
 
1271
            return set()
 
1272
        if not check_for_missing_texts:
 
1273
            return set(('inventories', rev_id) for (rev_id,) in parents)
 
1274
        # Ok, now we have a list of missing inventories.  But these only matter
 
1275
        # if the inventories that reference them are missing some texts they
 
1276
        # appear to introduce.
 
1277
        # XXX: Texts referenced by all added inventories need to be present,
 
1278
        # but at the moment we're only checking for texts referenced by
 
1279
        # inventories at the graph's edge.
 
1280
        key_deps = self.revisions._index._key_dependencies
 
1281
        key_deps.satisfy_refs_for_keys(present_inventories)
 
1282
        referrers = frozenset(r[0] for r in key_deps.get_referrers())
 
1283
        file_ids = self.fileids_altered_by_revision_ids(referrers)
 
1284
        missing_texts = set()
 
1285
        for file_id, version_ids in file_ids.iteritems():
 
1286
            missing_texts.update(
 
1287
                (file_id, version_id) for version_id in version_ids)
 
1288
        present_texts = self.texts.get_parent_map(missing_texts)
 
1289
        missing_texts.difference_update(present_texts)
 
1290
        if not missing_texts:
 
1291
            # No texts are missing, so all revisions and their deltas are
 
1292
            # reconstructable.
 
1293
            return set()
 
1294
        # Alternatively the text versions could be returned as the missing
 
1295
        # keys, but this is likely to be less data.
 
1296
        missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
 
1297
        return missing_keys
 
1298
 
 
1299
    @needs_read_lock
 
1300
    def has_revisions(self, revision_ids):
 
1301
        """Probe to find out the presence of multiple revisions.
 
1302
 
 
1303
        :param revision_ids: An iterable of revision_ids.
 
1304
        :return: A set of the revision_ids that were present.
 
1305
        """
 
1306
        parent_map = self.revisions.get_parent_map(
 
1307
            [(rev_id,) for rev_id in revision_ids])
 
1308
        result = set()
 
1309
        if _mod_revision.NULL_REVISION in revision_ids:
 
1310
            result.add(_mod_revision.NULL_REVISION)
 
1311
        result.update([key[0] for key in parent_map])
 
1312
        return result
 
1313
 
 
1314
    @needs_read_lock
 
1315
    def get_revision_reconcile(self, revision_id):
 
1316
        """'reconcile' helper routine that allows access to a revision always.
 
1317
 
 
1318
        This variant of get_revision does not cross check the weave graph
 
1319
        against the revision one as get_revision does: but it should only
 
1320
        be used by reconcile, or reconcile-alike commands that are correcting
 
1321
        or testing the revision graph.
 
1322
        """
 
1323
        return self._get_revisions([revision_id])[0]
 
1324
 
 
1325
    @needs_read_lock
 
1326
    def get_revisions(self, revision_ids):
 
1327
        """Get many revisions at once.
 
1328
        
 
1329
        Repositories that need to check data on every revision read should 
 
1330
        subclass this method.
 
1331
        """
 
1332
        return self._get_revisions(revision_ids)
 
1333
 
 
1334
    @needs_read_lock
 
1335
    def _get_revisions(self, revision_ids):
 
1336
        """Core work logic to get many revisions without sanity checks."""
 
1337
        revs = {}
 
1338
        for revid, rev in self._iter_revisions(revision_ids):
 
1339
            if rev is None:
 
1340
                raise errors.NoSuchRevision(self, revid)
 
1341
            revs[revid] = rev
 
1342
        return [revs[revid] for revid in revision_ids]
 
1343
 
 
1344
    def _iter_revisions(self, revision_ids):
 
1345
        """Iterate over revision objects.
 
1346
 
 
1347
        :param revision_ids: An iterable of revisions to examine. None may be
 
1348
            passed to request all revisions known to the repository. Note that
 
1349
            not all repositories can find unreferenced revisions; for those
 
1350
            repositories only referenced ones will be returned.
 
1351
        :return: An iterator of (revid, revision) tuples. Absent revisions (
 
1352
            those asked for but not available) are returned as (revid, None).
 
1353
        """
 
1354
        if revision_ids is None:
 
1355
            revision_ids = self.all_revision_ids()
 
1356
        else:
 
1357
            for rev_id in revision_ids:
 
1358
                if not rev_id or not isinstance(rev_id, basestring):
 
1359
                    raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
 
1360
        keys = [(key,) for key in revision_ids]
 
1361
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
 
1362
        for record in stream:
 
1363
            revid = record.key[0]
 
1364
            if record.storage_kind == 'absent':
 
1365
                yield (revid, None)
 
1366
            else:
 
1367
                text = record.get_bytes_as('fulltext')
 
1368
                rev = self._serializer.read_revision_from_string(text)
 
1369
                yield (revid, rev)
 
1370
 
 
1371
    @needs_write_lock
 
1372
    def add_signature_text(self, revision_id, signature):
 
1373
        """Store a signature text for a revision.
 
1374
 
 
1375
        :param revision_id: Revision id of the revision
 
1376
        :param signature: Signature text.
 
1377
        """
 
1378
        self.signatures.add_lines((revision_id,), (),
 
1379
            osutils.split_lines(signature))
 
1380
 
 
1381
    def find_text_key_references(self):
 
1382
        """Find the text key references within the repository.
 
1383
 
 
1384
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
 
1385
            to whether they were referred to by the inventory of the
 
1386
            revision_id that they contain. The inventory texts from all present
 
1387
            revision ids are assessed to generate this report.
 
1388
        """
 
1389
        revision_keys = self.revisions.keys()
 
1390
        w = self.inventories
 
1391
        pb = ui.ui_factory.nested_progress_bar()
 
1392
        try:
 
1393
            return self._serializer._find_text_key_references(
 
1394
                w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
 
1395
        finally:
 
1396
            pb.finished()
 
1397
 
 
1398
    def _inventory_xml_lines_for_keys(self, keys):
 
1399
        """Get a line iterator of the sort needed for findind references.
 
1400
 
 
1401
        Not relevant for non-xml inventory repositories.
 
1402
 
 
1403
        Ghosts in revision_keys are ignored.
 
1404
 
 
1405
        :param revision_keys: The revision keys for the inventories to inspect.
 
1406
        :return: An iterator over (inventory line, revid) for the fulltexts of
 
1407
            all of the xml inventories specified by revision_keys.
 
1408
        """
 
1409
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
 
1410
        for record in stream:
 
1411
            if record.storage_kind != 'absent':
 
1412
                chunks = record.get_bytes_as('chunked')
 
1413
                revid = record.key[-1]
 
1414
                lines = osutils.chunks_to_lines(chunks)
 
1415
                for line in lines:
 
1416
                    yield line, revid
 
1417
 
 
1418
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
 
1419
        revision_keys):
 
1420
        """Helper routine for fileids_altered_by_revision_ids.
 
1421
 
 
1422
        This performs the translation of xml lines to revision ids.
 
1423
 
 
1424
        :param line_iterator: An iterator of lines, origin_version_id
 
1425
        :param revision_keys: The revision ids to filter for. This should be a
 
1426
            set or other type which supports efficient __contains__ lookups, as
 
1427
            the revision key from each parsed line will be looked up in the
 
1428
            revision_keys filter.
 
1429
        :return: a dictionary mapping altered file-ids to an iterable of
 
1430
            revision_ids. Each altered file-ids has the exact revision_ids that
 
1431
            altered it listed explicitly.
 
1432
        """
 
1433
        seen = set(self._serializer._find_text_key_references(
 
1434
                line_iterator).iterkeys())
 
1435
        parent_keys = self._find_parent_keys_of_revisions(revision_keys)
 
1436
        parent_seen = set(self._serializer._find_text_key_references(
 
1437
            self._inventory_xml_lines_for_keys(parent_keys)))
 
1438
        new_keys = seen - parent_seen
 
1439
        result = {}
 
1440
        setdefault = result.setdefault
 
1441
        for key in new_keys:
 
1442
            setdefault(key[0], set()).add(key[-1])
 
1443
        return result
 
1444
 
 
1445
    def _find_parent_keys_of_revisions(self, revision_keys):
 
1446
        """Similar to _find_parent_ids_of_revisions, but used with keys.
 
1447
 
 
1448
        :param revision_keys: An iterable of revision_keys.
 
1449
        :return: The parents of all revision_keys that are not already in
 
1450
            revision_keys
 
1451
        """
 
1452
        parent_map = self.revisions.get_parent_map(revision_keys)
 
1453
        parent_keys = set()
 
1454
        map(parent_keys.update, parent_map.itervalues())
 
1455
        parent_keys.difference_update(revision_keys)
 
1456
        parent_keys.discard(_mod_revision.NULL_REVISION)
 
1457
        return parent_keys
 
1458
 
 
1459
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
 
1460
        """Find the file ids and versions affected by revisions.
 
1461
 
 
1462
        :param revisions: an iterable containing revision ids.
 
1463
        :param _inv_weave: The inventory weave from this repository or None.
 
1464
            If None, the inventory weave will be opened automatically.
 
1465
        :return: a dictionary mapping altered file-ids to an iterable of
 
1466
            revision_ids. Each altered file-ids has the exact revision_ids that
 
1467
            altered it listed explicitly.
 
1468
        """
 
1469
        selected_keys = set((revid,) for revid in revision_ids)
 
1470
        w = _inv_weave or self.inventories
 
1471
        return self._find_file_ids_from_xml_inventory_lines(
 
1472
            w.iter_lines_added_or_present_in_keys(
 
1473
                selected_keys, pb=None),
 
1474
            selected_keys)
 
1475
 
 
1476
    def iter_files_bytes(self, desired_files):
 
1477
        """Iterate through file versions.
 
1478
 
 
1479
        Files will not necessarily be returned in the order they occur in
 
1480
        desired_files.  No specific order is guaranteed.
 
1481
 
 
1482
        Yields pairs of identifier, bytes_iterator.  identifier is an opaque
 
1483
        value supplied by the caller as part of desired_files.  It should
 
1484
        uniquely identify the file version in the caller's context.  (Examples:
 
1485
        an index number or a TreeTransform trans_id.)
 
1486
 
 
1487
        bytes_iterator is an iterable of bytestrings for the file.  The
 
1488
        kind of iterable and length of the bytestrings are unspecified, but for
 
1489
        this implementation, it is a list of bytes produced by
 
1490
        VersionedFile.get_record_stream().
 
1491
 
 
1492
        :param desired_files: a list of (file_id, revision_id, identifier)
 
1493
            triples
 
1494
        """
 
1495
        text_keys = {}
 
1496
        for file_id, revision_id, callable_data in desired_files:
 
1497
            text_keys[(file_id, revision_id)] = callable_data
 
1498
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
 
1499
            if record.storage_kind == 'absent':
 
1500
                raise errors.RevisionNotPresent(record.key, self)
 
1501
            yield text_keys[record.key], record.get_bytes_as('chunked')
 
1502
 
 
1503
    def _generate_text_key_index(self, text_key_references=None,
 
1504
        ancestors=None):
 
1505
        """Generate a new text key index for the repository.
 
1506
 
 
1507
        This is an expensive function that will take considerable time to run.
 
1508
 
 
1509
        :return: A dict mapping text keys ((file_id, revision_id) tuples) to a
 
1510
            list of parents, also text keys. When a given key has no parents,
 
1511
            the parents list will be [NULL_REVISION].
 
1512
        """
 
1513
        # All revisions, to find inventory parents.
 
1514
        if ancestors is None:
 
1515
            graph = self.get_graph()
 
1516
            ancestors = graph.get_parent_map(self.all_revision_ids())
 
1517
        if text_key_references is None:
 
1518
            text_key_references = self.find_text_key_references()
 
1519
        pb = ui.ui_factory.nested_progress_bar()
 
1520
        try:
 
1521
            return self._do_generate_text_key_index(ancestors,
 
1522
                text_key_references, pb)
 
1523
        finally:
 
1524
            pb.finished()
 
1525
 
 
1526
    def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
 
1527
        """Helper for _generate_text_key_index to avoid deep nesting."""
 
1528
        revision_order = tsort.topo_sort(ancestors)
 
1529
        invalid_keys = set()
 
1530
        revision_keys = {}
 
1531
        for revision_id in revision_order:
 
1532
            revision_keys[revision_id] = set()
 
1533
        text_count = len(text_key_references)
 
1534
        # a cache of the text keys to allow reuse; costs a dict of all the
 
1535
        # keys, but saves a 2-tuple for every child of a given key.
 
1536
        text_key_cache = {}
 
1537
        for text_key, valid in text_key_references.iteritems():
 
1538
            if not valid:
 
1539
                invalid_keys.add(text_key)
 
1540
            else:
 
1541
                revision_keys[text_key[1]].add(text_key)
 
1542
            text_key_cache[text_key] = text_key
 
1543
        del text_key_references
 
1544
        text_index = {}
 
1545
        text_graph = graph.Graph(graph.DictParentsProvider(text_index))
 
1546
        NULL_REVISION = _mod_revision.NULL_REVISION
 
1547
        # Set a cache with a size of 10 - this suffices for bzr.dev but may be
 
1548
        # too small for large or very branchy trees. However, for 55K path
 
1549
        # trees, it would be easy to use too much memory trivially. Ideally we
 
1550
        # could gauge this by looking at available real memory etc, but this is
 
1551
        # always a tricky proposition.
 
1552
        inventory_cache = lru_cache.LRUCache(10)
 
1553
        batch_size = 10 # should be ~150MB on a 55K path tree
 
1554
        batch_count = len(revision_order) / batch_size + 1
 
1555
        processed_texts = 0
 
1556
        pb.update("Calculating text parents", processed_texts, text_count)
 
1557
        for offset in xrange(batch_count):
 
1558
            to_query = revision_order[offset * batch_size:(offset + 1) *
 
1559
                batch_size]
 
1560
            if not to_query:
 
1561
                break
 
1562
            for revision_id in to_query:
 
1563
                parent_ids = ancestors[revision_id]
 
1564
                for text_key in revision_keys[revision_id]:
 
1565
                    pb.update("Calculating text parents", processed_texts)
 
1566
                    processed_texts += 1
 
1567
                    candidate_parents = []
 
1568
                    for parent_id in parent_ids:
 
1569
                        parent_text_key = (text_key[0], parent_id)
 
1570
                        try:
 
1571
                            check_parent = parent_text_key not in \
 
1572
                                revision_keys[parent_id]
 
1573
                        except KeyError:
 
1574
                            # the parent parent_id is a ghost:
 
1575
                            check_parent = False
 
1576
                            # truncate the derived graph against this ghost.
 
1577
                            parent_text_key = None
 
1578
                        if check_parent:
 
1579
                            # look at the parent commit details inventories to
 
1580
                            # determine possible candidates in the per file graph.
 
1581
                            # TODO: cache here.
 
1582
                            try:
 
1583
                                inv = inventory_cache[parent_id]
 
1584
                            except KeyError:
 
1585
                                inv = self.revision_tree(parent_id).inventory
 
1586
                                inventory_cache[parent_id] = inv
 
1587
                            try:
 
1588
                                parent_entry = inv[text_key[0]]
 
1589
                            except (KeyError, errors.NoSuchId):
 
1590
                                parent_entry = None
 
1591
                            if parent_entry is not None:
 
1592
                                parent_text_key = (
 
1593
                                    text_key[0], parent_entry.revision)
 
1594
                            else:
 
1595
                                parent_text_key = None
 
1596
                        if parent_text_key is not None:
 
1597
                            candidate_parents.append(
 
1598
                                text_key_cache[parent_text_key])
 
1599
                    parent_heads = text_graph.heads(candidate_parents)
 
1600
                    new_parents = list(parent_heads)
 
1601
                    new_parents.sort(key=lambda x:candidate_parents.index(x))
 
1602
                    if new_parents == []:
 
1603
                        new_parents = [NULL_REVISION]
 
1604
                    text_index[text_key] = new_parents
 
1605
 
 
1606
        for text_key in invalid_keys:
 
1607
            text_index[text_key] = [NULL_REVISION]
 
1608
        return text_index
 
1609
 
 
1610
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
 
1611
        """Get an iterable listing the keys of all the data introduced by a set
 
1612
        of revision IDs.
 
1613
 
 
1614
        The keys will be ordered so that the corresponding items can be safely
 
1615
        fetched and inserted in that order.
 
1616
 
 
1617
        :returns: An iterable producing tuples of (knit-kind, file-id,
 
1618
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
 
1619
            'revisions'.  file-id is None unless knit-kind is 'file'.
 
1620
        """
 
1621
        for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
 
1622
            yield result
 
1623
        del _files_pb
 
1624
        for result in self._find_non_file_keys_to_fetch(revision_ids):
 
1625
            yield result
 
1626
 
 
1627
    def _find_file_keys_to_fetch(self, revision_ids, pb):
 
1628
        # XXX: it's a bit weird to control the inventory weave caching in this
 
1629
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
 
1630
        # maybe this generator should explicitly have the contract that it
 
1631
        # should not be iterated until the previously yielded item has been
 
1632
        # processed?
 
1633
        inv_w = self.inventories
 
1634
 
 
1635
        # file ids that changed
 
1636
        file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
 
1637
        count = 0
 
1638
        num_file_ids = len(file_ids)
 
1639
        for file_id, altered_versions in file_ids.iteritems():
 
1640
            if pb is not None:
 
1641
                pb.update("Fetch texts", count, num_file_ids)
 
1642
            count += 1
 
1643
            yield ("file", file_id, altered_versions)
 
1644
 
 
1645
    def _find_non_file_keys_to_fetch(self, revision_ids):
 
1646
        # inventory
 
1647
        yield ("inventory", None, revision_ids)
 
1648
 
 
1649
        # signatures
 
1650
        # XXX: Note ATM no callers actually pay attention to this return
 
1651
        #      instead they just use the list of revision ids and ignore
 
1652
        #      missing sigs. Consider removing this work entirely
 
1653
        revisions_with_signatures = set(self.signatures.get_parent_map(
 
1654
            [(r,) for r in revision_ids]))
 
1655
        revisions_with_signatures = set(
 
1656
            [r for (r,) in revisions_with_signatures])
 
1657
        revisions_with_signatures.intersection_update(revision_ids)
 
1658
        yield ("signatures", None, revisions_with_signatures)
 
1659
 
 
1660
        # revisions
 
1661
        yield ("revisions", None, revision_ids)
 
1662
 
 
1663
    @needs_read_lock
 
1664
    def get_inventory(self, revision_id):
 
1665
        """Get Inventory object by revision id."""
 
1666
        return self.iter_inventories([revision_id]).next()
 
1667
 
 
1668
    def iter_inventories(self, revision_ids, ordering=None):
 
1669
        """Get many inventories by revision_ids.
 
1670
 
 
1671
        This will buffer some or all of the texts used in constructing the
 
1672
        inventories in memory, but will only parse a single inventory at a
 
1673
        time.
 
1674
 
 
1675
        :param revision_ids: The expected revision ids of the inventories.
 
1676
        :param ordering: optional ordering, e.g. 'topological'.  If not
 
1677
            specified, the order of revision_ids will be preserved (by
 
1678
            buffering if necessary).
 
1679
        :return: An iterator of inventories.
 
1680
        """
 
1681
        if ((None in revision_ids)
 
1682
            or (_mod_revision.NULL_REVISION in revision_ids)):
 
1683
            raise ValueError('cannot get null revision inventory')
 
1684
        return self._iter_inventories(revision_ids, ordering)
 
1685
 
 
1686
    def _iter_inventories(self, revision_ids, ordering):
 
1687
        """single-document based inventory iteration."""
 
1688
        inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
 
1689
        for text, revision_id in inv_xmls:
 
1690
            yield self._deserialise_inventory(revision_id, text)
 
1691
 
 
1692
    def _iter_inventory_xmls(self, revision_ids, ordering):
 
1693
        if ordering is None:
 
1694
            order_as_requested = True
 
1695
            ordering = 'unordered'
 
1696
        else:
 
1697
            order_as_requested = False
 
1698
        keys = [(revision_id,) for revision_id in revision_ids]
 
1699
        if not keys:
 
1700
            return
 
1701
        if order_as_requested:
 
1702
            key_iter = iter(keys)
 
1703
            next_key = key_iter.next()
 
1704
        stream = self.inventories.get_record_stream(keys, ordering, True)
 
1705
        text_chunks = {}
 
1706
        for record in stream:
 
1707
            if record.storage_kind != 'absent':
 
1708
                chunks = record.get_bytes_as('chunked')
 
1709
                if order_as_requested:
 
1710
                    text_chunks[record.key] = chunks
 
1711
                else:
 
1712
                    yield ''.join(chunks), record.key[-1]
 
1713
            else:
 
1714
                raise errors.NoSuchRevision(self, record.key)
 
1715
            if order_as_requested:
 
1716
                # Yield as many results as we can while preserving order.
 
1717
                while next_key in text_chunks:
 
1718
                    chunks = text_chunks.pop(next_key)
 
1719
                    yield ''.join(chunks), next_key[-1]
 
1720
                    try:
 
1721
                        next_key = key_iter.next()
 
1722
                    except StopIteration:
 
1723
                        # We still want to fully consume the get_record_stream,
 
1724
                        # just in case it is not actually finished at this point
 
1725
                        next_key = None
 
1726
                        break
 
1727
 
 
1728
    def _deserialise_inventory(self, revision_id, xml):
 
1729
        """Transform the xml into an inventory object.
 
1730
 
 
1731
        :param revision_id: The expected revision id of the inventory.
 
1732
        :param xml: A serialised inventory.
 
1733
        """
 
1734
        result = self._serializer.read_inventory_from_string(xml, revision_id,
 
1735
                    entry_cache=self._inventory_entry_cache,
 
1736
                    return_from_cache=self._safe_to_return_from_cache)
 
1737
        if result.revision_id != revision_id:
 
1738
            raise AssertionError('revision id mismatch %s != %s' % (
 
1739
                result.revision_id, revision_id))
 
1740
        return result
 
1741
 
 
1742
    def get_serializer_format(self):
 
1743
        return self._serializer.format_num
 
1744
 
 
1745
    @needs_read_lock
 
1746
    def _get_inventory_xml(self, revision_id):
 
1747
        """Get serialized inventory as a string."""
 
1748
        texts = self._iter_inventory_xmls([revision_id], 'unordered')
 
1749
        try:
 
1750
            text, revision_id = texts.next()
 
1751
        except StopIteration:
 
1752
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
1753
        return text
 
1754
 
 
1755
    @needs_read_lock
 
1756
    def revision_tree(self, revision_id):
 
1757
        """Return Tree for a revision on this branch.
 
1758
 
 
1759
        `revision_id` may be NULL_REVISION for the empty tree revision.
 
1760
        """
 
1761
        revision_id = _mod_revision.ensure_null(revision_id)
 
1762
        # TODO: refactor this to use an existing revision object
 
1763
        # so we don't need to read it in twice.
 
1764
        if revision_id == _mod_revision.NULL_REVISION:
 
1765
            return InventoryRevisionTree(self,
 
1766
                Inventory(root_id=None), _mod_revision.NULL_REVISION)
 
1767
        else:
 
1768
            inv = self.get_inventory(revision_id)
 
1769
            return InventoryRevisionTree(self, inv, revision_id)
 
1770
 
 
1771
    def revision_trees(self, revision_ids):
 
1772
        """Return Trees for revisions in this repository.
 
1773
 
 
1774
        :param revision_ids: a sequence of revision-ids;
 
1775
          a revision-id may not be None or 'null:'
 
1776
        """
 
1777
        inventories = self.iter_inventories(revision_ids)
 
1778
        for inv in inventories:
 
1779
            yield InventoryRevisionTree(self, inv, inv.revision_id)
 
1780
 
 
1781
    def _filtered_revision_trees(self, revision_ids, file_ids):
 
1782
        """Return Tree for a revision on this branch with only some files.
 
1783
 
 
1784
        :param revision_ids: a sequence of revision-ids;
 
1785
          a revision-id may not be None or 'null:'
 
1786
        :param file_ids: if not None, the result is filtered
 
1787
          so that only those file-ids, their parents and their
 
1788
          children are included.
 
1789
        """
 
1790
        inventories = self.iter_inventories(revision_ids)
 
1791
        for inv in inventories:
 
1792
            # Should we introduce a FilteredRevisionTree class rather
 
1793
            # than pre-filter the inventory here?
 
1794
            filtered_inv = inv.filter(file_ids)
 
1795
            yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
 
1796
 
 
1797
    def get_parent_map(self, revision_ids):
 
1798
        """See graph.StackedParentsProvider.get_parent_map"""
 
1799
        # revisions index works in keys; this just works in revisions
 
1800
        # therefore wrap and unwrap
 
1801
        query_keys = []
 
1802
        result = {}
 
1803
        for revision_id in revision_ids:
 
1804
            if revision_id == _mod_revision.NULL_REVISION:
 
1805
                result[revision_id] = ()
 
1806
            elif revision_id is None:
 
1807
                raise ValueError('get_parent_map(None) is not valid')
 
1808
            else:
 
1809
                query_keys.append((revision_id ,))
 
1810
        for ((revision_id,), parent_keys) in \
 
1811
                self.revisions.get_parent_map(query_keys).iteritems():
 
1812
            if parent_keys:
 
1813
                result[revision_id] = tuple([parent_revid
 
1814
                    for (parent_revid,) in parent_keys])
 
1815
            else:
 
1816
                result[revision_id] = (_mod_revision.NULL_REVISION,)
 
1817
        return result
 
1818
 
 
1819
    @needs_read_lock
 
1820
    def get_known_graph_ancestry(self, revision_ids):
 
1821
        """Return the known graph for a set of revision ids and their ancestors.
 
1822
        """
 
1823
        st = static_tuple.StaticTuple
 
1824
        revision_keys = [st(r_id).intern() for r_id in revision_ids]
 
1825
        known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
 
1826
        return graph.GraphThunkIdsToKeys(known_graph)
 
1827
 
 
1828
    @needs_read_lock
 
1829
    def get_file_graph(self):
 
1830
        """Return the graph walker for text revisions."""
 
1831
        return graph.Graph(self.texts)
 
1832
 
 
1833
    def _get_versioned_file_checker(self, text_key_references=None,
 
1834
        ancestors=None):
 
1835
        """Return an object suitable for checking versioned files.
 
1836
        
 
1837
        :param text_key_references: if non-None, an already built
 
1838
            dictionary mapping text keys ((fileid, revision_id) tuples)
 
1839
            to whether they were referred to by the inventory of the
 
1840
            revision_id that they contain. If None, this will be
 
1841
            calculated.
 
1842
        :param ancestors: Optional result from
 
1843
            self.get_graph().get_parent_map(self.all_revision_ids()) if already
 
1844
            available.
 
1845
        """
 
1846
        return _VersionedFileChecker(self,
 
1847
            text_key_references=text_key_references, ancestors=ancestors)
 
1848
 
 
1849
    @needs_read_lock
 
1850
    def has_signature_for_revision_id(self, revision_id):
 
1851
        """Query for a revision signature for revision_id in the repository."""
 
1852
        if not self.has_revision(revision_id):
 
1853
            raise errors.NoSuchRevision(self, revision_id)
 
1854
        sig_present = (1 == len(
 
1855
            self.signatures.get_parent_map([(revision_id,)])))
 
1856
        return sig_present
 
1857
 
 
1858
    @needs_read_lock
 
1859
    def get_signature_text(self, revision_id):
 
1860
        """Return the text for a signature."""
 
1861
        stream = self.signatures.get_record_stream([(revision_id,)],
 
1862
            'unordered', True)
 
1863
        record = stream.next()
 
1864
        if record.storage_kind == 'absent':
 
1865
            raise errors.NoSuchRevision(self, revision_id)
 
1866
        return record.get_bytes_as('fulltext')
 
1867
 
 
1868
    @needs_read_lock
 
1869
    def _check(self, revision_ids, callback_refs, check_repo):
 
1870
        result = check.VersionedFileCheck(self, check_repo=check_repo)
 
1871
        result.check(callback_refs)
 
1872
        return result
 
1873
 
 
1874
    def _find_inconsistent_revision_parents(self, revisions_iterator=None):
 
1875
        """Find revisions with different parent lists in the revision object
 
1876
        and in the index graph.
 
1877
 
 
1878
        :param revisions_iterator: None, or an iterator of (revid,
 
1879
            Revision-or-None). This iterator controls the revisions checked.
 
1880
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1881
            parents-in-revision).
 
1882
        """
 
1883
        if not self.is_locked():
 
1884
            raise AssertionError()
 
1885
        vf = self.revisions
 
1886
        if revisions_iterator is None:
 
1887
            revisions_iterator = self._iter_revisions(None)
 
1888
        for revid, revision in revisions_iterator:
 
1889
            if revision is None:
 
1890
                pass
 
1891
            parent_map = vf.get_parent_map([(revid,)])
 
1892
            parents_according_to_index = tuple(parent[-1] for parent in
 
1893
                parent_map[(revid,)])
 
1894
            parents_according_to_revision = tuple(revision.parent_ids)
 
1895
            if parents_according_to_index != parents_according_to_revision:
 
1896
                yield (revid, parents_according_to_index,
 
1897
                    parents_according_to_revision)
 
1898
 
 
1899
    def _check_for_inconsistent_revision_parents(self):
 
1900
        inconsistencies = list(self._find_inconsistent_revision_parents())
 
1901
        if inconsistencies:
 
1902
            raise errors.BzrCheckError(
 
1903
                "Revision knit has inconsistent parents.")
 
1904
 
 
1905
    def _get_sink(self):
 
1906
        """Return a sink for streaming into this repository."""
 
1907
        return StreamSink(self)
 
1908
 
 
1909
    def _get_source(self, to_format):
 
1910
        """Return a source for streaming from this repository."""
 
1911
        return StreamSource(self, to_format)
 
1912
 
 
1913
 
 
1914
class MetaDirVersionedFileRepository(MetaDirRepository,
 
1915
                                     VersionedFileRepository):
 
1916
    """Repositories in a meta-dir, that work via versioned file objects."""
 
1917
 
 
1918
    def __init__(self, _format, a_bzrdir, control_files):
 
1919
        super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
 
1920
            control_files)
 
1921
 
 
1922
 
 
1923
class MetaDirVersionedFileRepositoryFormat(MetaDirRepositoryFormat,
 
1924
        VersionedFileRepositoryFormat):
 
1925
    """Base class for repository formats using versioned files in metadirs."""
 
1926
 
 
1927
 
 
1928
class StreamSink(object):
 
1929
    """An object that can insert a stream into a repository.
 
1930
 
 
1931
    This interface handles the complexity of reserialising inventories and
 
1932
    revisions from different formats, and allows unidirectional insertion into
 
1933
    stacked repositories without looking for the missing basis parents
 
1934
    beforehand.
 
1935
    """
 
1936
 
 
1937
    def __init__(self, target_repo):
 
1938
        self.target_repo = target_repo
 
1939
 
 
1940
    def insert_stream(self, stream, src_format, resume_tokens):
 
1941
        """Insert a stream's content into the target repository.
 
1942
 
 
1943
        :param src_format: a bzr repository format.
 
1944
 
 
1945
        :return: a list of resume tokens and an  iterable of keys additional
 
1946
            items required before the insertion can be completed.
 
1947
        """
 
1948
        self.target_repo.lock_write()
 
1949
        try:
 
1950
            if resume_tokens:
 
1951
                self.target_repo.resume_write_group(resume_tokens)
 
1952
                is_resume = True
 
1953
            else:
 
1954
                self.target_repo.start_write_group()
 
1955
                is_resume = False
 
1956
            try:
 
1957
                # locked_insert_stream performs a commit|suspend.
 
1958
                missing_keys = self.insert_stream_without_locking(stream,
 
1959
                                    src_format, is_resume)
 
1960
                if missing_keys:
 
1961
                    # suspend the write group and tell the caller what we is
 
1962
                    # missing. We know we can suspend or else we would not have
 
1963
                    # entered this code path. (All repositories that can handle
 
1964
                    # missing keys can handle suspending a write group).
 
1965
                    write_group_tokens = self.target_repo.suspend_write_group()
 
1966
                    return write_group_tokens, missing_keys
 
1967
                hint = self.target_repo.commit_write_group()
 
1968
                to_serializer = self.target_repo._format._serializer
 
1969
                src_serializer = src_format._serializer
 
1970
                if (to_serializer != src_serializer and
 
1971
                    self.target_repo._format.pack_compresses):
 
1972
                    self.target_repo.pack(hint=hint)
 
1973
                return [], set()
 
1974
            except:
 
1975
                self.target_repo.abort_write_group(suppress_errors=True)
 
1976
                raise
 
1977
        finally:
 
1978
            self.target_repo.unlock()
 
1979
 
 
1980
    def insert_stream_without_locking(self, stream, src_format,
 
1981
                                      is_resume=False):
 
1982
        """Insert a stream's content into the target repository.
 
1983
 
 
1984
        This assumes that you already have a locked repository and an active
 
1985
        write group.
 
1986
 
 
1987
        :param src_format: a bzr repository format.
 
1988
        :param is_resume: Passed down to get_missing_parent_inventories to
 
1989
            indicate if we should be checking for missing texts at the same
 
1990
            time.
 
1991
 
 
1992
        :return: A set of keys that are missing.
 
1993
        """
 
1994
        if not self.target_repo.is_write_locked():
 
1995
            raise errors.ObjectNotLocked(self)
 
1996
        if not self.target_repo.is_in_write_group():
 
1997
            raise errors.BzrError('you must already be in a write group')
 
1998
        to_serializer = self.target_repo._format._serializer
 
1999
        src_serializer = src_format._serializer
 
2000
        new_pack = None
 
2001
        if to_serializer == src_serializer:
 
2002
            # If serializers match and the target is a pack repository, set the
 
2003
            # write cache size on the new pack.  This avoids poor performance
 
2004
            # on transports where append is unbuffered (such as
 
2005
            # RemoteTransport).  This is safe to do because nothing should read
 
2006
            # back from the target repository while a stream with matching
 
2007
            # serialization is being inserted.
 
2008
            # The exception is that a delta record from the source that should
 
2009
            # be a fulltext may need to be expanded by the target (see
 
2010
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
 
2011
            # explicitly flush any buffered writes first in that rare case.
 
2012
            try:
 
2013
                new_pack = self.target_repo._pack_collection._new_pack
 
2014
            except AttributeError:
 
2015
                # Not a pack repository
 
2016
                pass
 
2017
            else:
 
2018
                new_pack.set_write_cache_size(1024*1024)
 
2019
        for substream_type, substream in stream:
 
2020
            if 'stream' in debug.debug_flags:
 
2021
                mutter('inserting substream: %s', substream_type)
 
2022
            if substream_type == 'texts':
 
2023
                self.target_repo.texts.insert_record_stream(substream)
 
2024
            elif substream_type == 'inventories':
 
2025
                if src_serializer == to_serializer:
 
2026
                    self.target_repo.inventories.insert_record_stream(
 
2027
                        substream)
 
2028
                else:
 
2029
                    self._extract_and_insert_inventories(
 
2030
                        substream, src_serializer)
 
2031
            elif substream_type == 'inventory-deltas':
 
2032
                self._extract_and_insert_inventory_deltas(
 
2033
                    substream, src_serializer)
 
2034
            elif substream_type == 'chk_bytes':
 
2035
                # XXX: This doesn't support conversions, as it assumes the
 
2036
                #      conversion was done in the fetch code.
 
2037
                self.target_repo.chk_bytes.insert_record_stream(substream)
 
2038
            elif substream_type == 'revisions':
 
2039
                # This may fallback to extract-and-insert more often than
 
2040
                # required if the serializers are different only in terms of
 
2041
                # the inventory.
 
2042
                if src_serializer == to_serializer:
 
2043
                    self.target_repo.revisions.insert_record_stream(substream)
 
2044
                else:
 
2045
                    self._extract_and_insert_revisions(substream,
 
2046
                        src_serializer)
 
2047
            elif substream_type == 'signatures':
 
2048
                self.target_repo.signatures.insert_record_stream(substream)
 
2049
            else:
 
2050
                raise AssertionError('kaboom! %s' % (substream_type,))
 
2051
        # Done inserting data, and the missing_keys calculations will try to
 
2052
        # read back from the inserted data, so flush the writes to the new pack
 
2053
        # (if this is pack format).
 
2054
        if new_pack is not None:
 
2055
            new_pack._write_data('', flush=True)
 
2056
        # Find all the new revisions (including ones from resume_tokens)
 
2057
        missing_keys = self.target_repo.get_missing_parent_inventories(
 
2058
            check_for_missing_texts=is_resume)
 
2059
        try:
 
2060
            for prefix, versioned_file in (
 
2061
                ('texts', self.target_repo.texts),
 
2062
                ('inventories', self.target_repo.inventories),
 
2063
                ('revisions', self.target_repo.revisions),
 
2064
                ('signatures', self.target_repo.signatures),
 
2065
                ('chk_bytes', self.target_repo.chk_bytes),
 
2066
                ):
 
2067
                if versioned_file is None:
 
2068
                    continue
 
2069
                # TODO: key is often going to be a StaticTuple object
 
2070
                #       I don't believe we can define a method by which
 
2071
                #       (prefix,) + StaticTuple will work, though we could
 
2072
                #       define a StaticTuple.sq_concat that would allow you to
 
2073
                #       pass in either a tuple or a StaticTuple as the second
 
2074
                #       object, so instead we could have:
 
2075
                #       StaticTuple(prefix) + key here...
 
2076
                missing_keys.update((prefix,) + key for key in
 
2077
                    versioned_file.get_missing_compression_parent_keys())
 
2078
        except NotImplementedError:
 
2079
            # cannot even attempt suspending, and missing would have failed
 
2080
            # during stream insertion.
 
2081
            missing_keys = set()
 
2082
        return missing_keys
 
2083
 
 
2084
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
 
2085
        target_rich_root = self.target_repo._format.rich_root_data
 
2086
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
2087
        for record in substream:
 
2088
            # Insert the delta directly
 
2089
            inventory_delta_bytes = record.get_bytes_as('fulltext')
 
2090
            deserialiser = inventory_delta.InventoryDeltaDeserializer()
 
2091
            try:
 
2092
                parse_result = deserialiser.parse_text_bytes(
 
2093
                    inventory_delta_bytes)
 
2094
            except inventory_delta.IncompatibleInventoryDelta, err:
 
2095
                mutter("Incompatible delta: %s", err.msg)
 
2096
                raise errors.IncompatibleRevision(self.target_repo._format)
 
2097
            basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
 
2098
            revision_id = new_id
 
2099
            parents = [key[0] for key in record.parents]
 
2100
            self.target_repo.add_inventory_by_delta(
 
2101
                basis_id, inv_delta, revision_id, parents)
 
2102
 
 
2103
    def _extract_and_insert_inventories(self, substream, serializer,
 
2104
            parse_delta=None):
 
2105
        """Generate a new inventory versionedfile in target, converting data.
 
2106
 
 
2107
        The inventory is retrieved from the source, (deserializing it), and
 
2108
        stored in the target (reserializing it in a different format).
 
2109
        """
 
2110
        target_rich_root = self.target_repo._format.rich_root_data
 
2111
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
2112
        for record in substream:
 
2113
            # It's not a delta, so it must be a fulltext in the source
 
2114
            # serializer's format.
 
2115
            bytes = record.get_bytes_as('fulltext')
 
2116
            revision_id = record.key[0]
 
2117
            inv = serializer.read_inventory_from_string(bytes, revision_id)
 
2118
            parents = [key[0] for key in record.parents]
 
2119
            self.target_repo.add_inventory(revision_id, inv, parents)
 
2120
            # No need to keep holding this full inv in memory when the rest of
 
2121
            # the substream is likely to be all deltas.
 
2122
            del inv
 
2123
 
 
2124
    def _extract_and_insert_revisions(self, substream, serializer):
 
2125
        for record in substream:
 
2126
            bytes = record.get_bytes_as('fulltext')
 
2127
            revision_id = record.key[0]
 
2128
            rev = serializer.read_revision_from_string(bytes)
 
2129
            if rev.revision_id != revision_id:
 
2130
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
 
2131
            self.target_repo.add_revision(revision_id, rev)
 
2132
 
 
2133
    def finished(self):
 
2134
        if self.target_repo._format._fetch_reconcile:
 
2135
            self.target_repo.reconcile()
 
2136
 
 
2137
 
 
2138
class StreamSource(object):
 
2139
    """A source of a stream for fetching between repositories."""
 
2140
 
 
2141
    def __init__(self, from_repository, to_format):
 
2142
        """Create a StreamSource streaming from from_repository."""
 
2143
        self.from_repository = from_repository
 
2144
        self.to_format = to_format
 
2145
        self._record_counter = RecordCounter()
 
2146
 
 
2147
    def delta_on_metadata(self):
 
2148
        """Return True if delta's are permitted on metadata streams.
 
2149
 
 
2150
        That is on revisions and signatures.
 
2151
        """
 
2152
        src_serializer = self.from_repository._format._serializer
 
2153
        target_serializer = self.to_format._serializer
 
2154
        return (self.to_format._fetch_uses_deltas and
 
2155
            src_serializer == target_serializer)
 
2156
 
 
2157
    def _fetch_revision_texts(self, revs):
 
2158
        # fetch signatures first and then the revision texts
 
2159
        # may need to be a InterRevisionStore call here.
 
2160
        from_sf = self.from_repository.signatures
 
2161
        # A missing signature is just skipped.
 
2162
        keys = [(rev_id,) for rev_id in revs]
 
2163
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
 
2164
            keys,
 
2165
            self.to_format._fetch_order,
 
2166
            not self.to_format._fetch_uses_deltas))
 
2167
        # If a revision has a delta, this is actually expanded inside the
 
2168
        # insert_record_stream code now, which is an alternate fix for
 
2169
        # bug #261339
 
2170
        from_rf = self.from_repository.revisions
 
2171
        revisions = from_rf.get_record_stream(
 
2172
            keys,
 
2173
            self.to_format._fetch_order,
 
2174
            not self.delta_on_metadata())
 
2175
        return [('signatures', signatures), ('revisions', revisions)]
 
2176
 
 
2177
    def _generate_root_texts(self, revs):
 
2178
        """This will be called by get_stream between fetching weave texts and
 
2179
        fetching the inventory weave.
 
2180
        """
 
2181
        if self._rich_root_upgrade():
 
2182
            return _mod_fetch.Inter1and2Helper(
 
2183
                self.from_repository).generate_root_texts(revs)
 
2184
        else:
 
2185
            return []
 
2186
 
 
2187
    def get_stream(self, search):
 
2188
        phase = 'file'
 
2189
        revs = search.get_keys()
 
2190
        graph = self.from_repository.get_graph()
 
2191
        revs = tsort.topo_sort(graph.get_parent_map(revs))
 
2192
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
 
2193
        text_keys = []
 
2194
        for knit_kind, file_id, revisions in data_to_fetch:
 
2195
            if knit_kind != phase:
 
2196
                phase = knit_kind
 
2197
                # Make a new progress bar for this phase
 
2198
            if knit_kind == "file":
 
2199
                # Accumulate file texts
 
2200
                text_keys.extend([(file_id, revision) for revision in
 
2201
                    revisions])
 
2202
            elif knit_kind == "inventory":
 
2203
                # Now copy the file texts.
 
2204
                from_texts = self.from_repository.texts
 
2205
                yield ('texts', from_texts.get_record_stream(
 
2206
                    text_keys, self.to_format._fetch_order,
 
2207
                    not self.to_format._fetch_uses_deltas))
 
2208
                # Cause an error if a text occurs after we have done the
 
2209
                # copy.
 
2210
                text_keys = None
 
2211
                # Before we process the inventory we generate the root
 
2212
                # texts (if necessary) so that the inventories references
 
2213
                # will be valid.
 
2214
                for _ in self._generate_root_texts(revs):
 
2215
                    yield _
 
2216
                # we fetch only the referenced inventories because we do not
 
2217
                # know for unselected inventories whether all their required
 
2218
                # texts are present in the other repository - it could be
 
2219
                # corrupt.
 
2220
                for info in self._get_inventory_stream(revs):
 
2221
                    yield info
 
2222
            elif knit_kind == "signatures":
 
2223
                # Nothing to do here; this will be taken care of when
 
2224
                # _fetch_revision_texts happens.
 
2225
                pass
 
2226
            elif knit_kind == "revisions":
 
2227
                for record in self._fetch_revision_texts(revs):
 
2228
                    yield record
 
2229
            else:
 
2230
                raise AssertionError("Unknown knit kind %r" % knit_kind)
 
2231
 
 
2232
    def get_stream_for_missing_keys(self, missing_keys):
 
2233
        # missing keys can only occur when we are byte copying and not
 
2234
        # translating (because translation means we don't send
 
2235
        # unreconstructable deltas ever).
 
2236
        keys = {}
 
2237
        keys['texts'] = set()
 
2238
        keys['revisions'] = set()
 
2239
        keys['inventories'] = set()
 
2240
        keys['chk_bytes'] = set()
 
2241
        keys['signatures'] = set()
 
2242
        for key in missing_keys:
 
2243
            keys[key[0]].add(key[1:])
 
2244
        if len(keys['revisions']):
 
2245
            # If we allowed copying revisions at this point, we could end up
 
2246
            # copying a revision without copying its required texts: a
 
2247
            # violation of the requirements for repository integrity.
 
2248
            raise AssertionError(
 
2249
                'cannot copy revisions to fill in missing deltas %s' % (
 
2250
                    keys['revisions'],))
 
2251
        for substream_kind, keys in keys.iteritems():
 
2252
            vf = getattr(self.from_repository, substream_kind)
 
2253
            if vf is None and keys:
 
2254
                    raise AssertionError(
 
2255
                        "cannot fill in keys for a versioned file we don't"
 
2256
                        " have: %s needs %s" % (substream_kind, keys))
 
2257
            if not keys:
 
2258
                # No need to stream something we don't have
 
2259
                continue
 
2260
            if substream_kind == 'inventories':
 
2261
                # Some missing keys are genuinely ghosts, filter those out.
 
2262
                present = self.from_repository.inventories.get_parent_map(keys)
 
2263
                revs = [key[0] for key in present]
 
2264
                # Get the inventory stream more-or-less as we do for the
 
2265
                # original stream; there's no reason to assume that records
 
2266
                # direct from the source will be suitable for the sink.  (Think
 
2267
                # e.g. 2a -> 1.9-rich-root).
 
2268
                for info in self._get_inventory_stream(revs, missing=True):
 
2269
                    yield info
 
2270
                continue
 
2271
 
 
2272
            # Ask for full texts always so that we don't need more round trips
 
2273
            # after this stream.
 
2274
            # Some of the missing keys are genuinely ghosts, so filter absent
 
2275
            # records. The Sink is responsible for doing another check to
 
2276
            # ensure that ghosts don't introduce missing data for future
 
2277
            # fetches.
 
2278
            stream = versionedfile.filter_absent(vf.get_record_stream(keys,
 
2279
                self.to_format._fetch_order, True))
 
2280
            yield substream_kind, stream
 
2281
 
 
2282
    def inventory_fetch_order(self):
 
2283
        if self._rich_root_upgrade():
 
2284
            return 'topological'
 
2285
        else:
 
2286
            return self.to_format._fetch_order
 
2287
 
 
2288
    def _rich_root_upgrade(self):
 
2289
        return (not self.from_repository._format.rich_root_data and
 
2290
            self.to_format.rich_root_data)
 
2291
 
 
2292
    def _get_inventory_stream(self, revision_ids, missing=False):
 
2293
        from_format = self.from_repository._format
 
2294
        if (from_format.supports_chks and self.to_format.supports_chks and
 
2295
            from_format.network_name() == self.to_format.network_name()):
 
2296
            raise AssertionError(
 
2297
                "this case should be handled by GroupCHKStreamSource")
 
2298
        elif 'forceinvdeltas' in debug.debug_flags:
 
2299
            return self._get_convertable_inventory_stream(revision_ids,
 
2300
                    delta_versus_null=missing)
 
2301
        elif from_format.network_name() == self.to_format.network_name():
 
2302
            # Same format.
 
2303
            return self._get_simple_inventory_stream(revision_ids,
 
2304
                    missing=missing)
 
2305
        elif (not from_format.supports_chks and not self.to_format.supports_chks
 
2306
                and from_format._serializer == self.to_format._serializer):
 
2307
            # Essentially the same format.
 
2308
            return self._get_simple_inventory_stream(revision_ids,
 
2309
                    missing=missing)
 
2310
        else:
 
2311
            # Any time we switch serializations, we want to use an
 
2312
            # inventory-delta based approach.
 
2313
            return self._get_convertable_inventory_stream(revision_ids,
 
2314
                    delta_versus_null=missing)
 
2315
 
 
2316
    def _get_simple_inventory_stream(self, revision_ids, missing=False):
 
2317
        # NB: This currently reopens the inventory weave in source;
 
2318
        # using a single stream interface instead would avoid this.
 
2319
        from_weave = self.from_repository.inventories
 
2320
        if missing:
 
2321
            delta_closure = True
 
2322
        else:
 
2323
            delta_closure = not self.delta_on_metadata()
 
2324
        yield ('inventories', from_weave.get_record_stream(
 
2325
            [(rev_id,) for rev_id in revision_ids],
 
2326
            self.inventory_fetch_order(), delta_closure))
 
2327
 
 
2328
    def _get_convertable_inventory_stream(self, revision_ids,
 
2329
                                          delta_versus_null=False):
 
2330
        # The two formats are sufficiently different that there is no fast
 
2331
        # path, so we need to send just inventorydeltas, which any
 
2332
        # sufficiently modern client can insert into any repository.
 
2333
        # The StreamSink code expects to be able to
 
2334
        # convert on the target, so we need to put bytes-on-the-wire that can
 
2335
        # be converted.  That means inventory deltas (if the remote is <1.19,
 
2336
        # RemoteStreamSink will fallback to VFS to insert the deltas).
 
2337
        yield ('inventory-deltas',
 
2338
           self._stream_invs_as_deltas(revision_ids,
 
2339
                                       delta_versus_null=delta_versus_null))
 
2340
 
 
2341
    def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
 
2342
        """Return a stream of inventory-deltas for the given rev ids.
 
2343
 
 
2344
        :param revision_ids: The list of inventories to transmit
 
2345
        :param delta_versus_null: Don't try to find a minimal delta for this
 
2346
            entry, instead compute the delta versus the NULL_REVISION. This
 
2347
            effectively streams a complete inventory. Used for stuff like
 
2348
            filling in missing parents, etc.
 
2349
        """
 
2350
        from_repo = self.from_repository
 
2351
        revision_keys = [(rev_id,) for rev_id in revision_ids]
 
2352
        parent_map = from_repo.inventories.get_parent_map(revision_keys)
 
2353
        # XXX: possibly repos could implement a more efficient iter_inv_deltas
 
2354
        # method...
 
2355
        inventories = self.from_repository.iter_inventories(
 
2356
            revision_ids, 'topological')
 
2357
        format = from_repo._format
 
2358
        invs_sent_so_far = set([_mod_revision.NULL_REVISION])
 
2359
        inventory_cache = lru_cache.LRUCache(50)
 
2360
        null_inventory = from_repo.revision_tree(
 
2361
            _mod_revision.NULL_REVISION).inventory
 
2362
        # XXX: ideally the rich-root/tree-refs flags would be per-revision, not
 
2363
        # per-repo (e.g.  streaming a non-rich-root revision out of a rich-root
 
2364
        # repo back into a non-rich-root repo ought to be allowed)
 
2365
        serializer = inventory_delta.InventoryDeltaSerializer(
 
2366
            versioned_root=format.rich_root_data,
 
2367
            tree_references=format.supports_tree_reference)
 
2368
        for inv in inventories:
 
2369
            key = (inv.revision_id,)
 
2370
            parent_keys = parent_map.get(key, ())
 
2371
            delta = None
 
2372
            if not delta_versus_null and parent_keys:
 
2373
                # The caller did not ask for complete inventories and we have
 
2374
                # some parents that we can delta against.  Make a delta against
 
2375
                # each parent so that we can find the smallest.
 
2376
                parent_ids = [parent_key[0] for parent_key in parent_keys]
 
2377
                for parent_id in parent_ids:
 
2378
                    if parent_id not in invs_sent_so_far:
 
2379
                        # We don't know that the remote side has this basis, so
 
2380
                        # we can't use it.
 
2381
                        continue
 
2382
                    if parent_id == _mod_revision.NULL_REVISION:
 
2383
                        parent_inv = null_inventory
 
2384
                    else:
 
2385
                        parent_inv = inventory_cache.get(parent_id, None)
 
2386
                        if parent_inv is None:
 
2387
                            parent_inv = from_repo.get_inventory(parent_id)
 
2388
                    candidate_delta = inv._make_delta(parent_inv)
 
2389
                    if (delta is None or
 
2390
                        len(delta) > len(candidate_delta)):
 
2391
                        delta = candidate_delta
 
2392
                        basis_id = parent_id
 
2393
            if delta is None:
 
2394
                # Either none of the parents ended up being suitable, or we
 
2395
                # were asked to delta against NULL
 
2396
                basis_id = _mod_revision.NULL_REVISION
 
2397
                delta = inv._make_delta(null_inventory)
 
2398
            invs_sent_so_far.add(inv.revision_id)
 
2399
            inventory_cache[inv.revision_id] = inv
 
2400
            delta_serialized = ''.join(
 
2401
                serializer.delta_to_lines(basis_id, key[-1], delta))
 
2402
            yield versionedfile.FulltextContentFactory(
 
2403
                key, parent_keys, None, delta_serialized)
 
2404
 
 
2405
 
 
2406
class _VersionedFileChecker(object):
 
2407
 
 
2408
    def __init__(self, repository, text_key_references=None, ancestors=None):
 
2409
        self.repository = repository
 
2410
        self.text_index = self.repository._generate_text_key_index(
 
2411
            text_key_references=text_key_references, ancestors=ancestors)
 
2412
 
 
2413
    def calculate_file_version_parents(self, text_key):
 
2414
        """Calculate the correct parents for a file version according to
 
2415
        the inventories.
 
2416
        """
 
2417
        parent_keys = self.text_index[text_key]
 
2418
        if parent_keys == [_mod_revision.NULL_REVISION]:
 
2419
            return ()
 
2420
        return tuple(parent_keys)
 
2421
 
 
2422
    def check_file_version_parents(self, texts, progress_bar=None):
 
2423
        """Check the parents stored in a versioned file are correct.
 
2424
 
 
2425
        It also detects file versions that are not referenced by their
 
2426
        corresponding revision's inventory.
 
2427
 
 
2428
        :returns: A tuple of (wrong_parents, dangling_file_versions).
 
2429
            wrong_parents is a dict mapping {revision_id: (stored_parents,
 
2430
            correct_parents)} for each revision_id where the stored parents
 
2431
            are not correct.  dangling_file_versions is a set of (file_id,
 
2432
            revision_id) tuples for versions that are present in this versioned
 
2433
            file, but not used by the corresponding inventory.
 
2434
        """
 
2435
        local_progress = None
 
2436
        if progress_bar is None:
 
2437
            local_progress = ui.ui_factory.nested_progress_bar()
 
2438
            progress_bar = local_progress
 
2439
        try:
 
2440
            return self._check_file_version_parents(texts, progress_bar)
 
2441
        finally:
 
2442
            if local_progress:
 
2443
                local_progress.finished()
 
2444
 
 
2445
    def _check_file_version_parents(self, texts, progress_bar):
 
2446
        """See check_file_version_parents."""
 
2447
        wrong_parents = {}
 
2448
        self.file_ids = set([file_id for file_id, _ in
 
2449
            self.text_index.iterkeys()])
 
2450
        # text keys is now grouped by file_id
 
2451
        n_versions = len(self.text_index)
 
2452
        progress_bar.update('loading text store', 0, n_versions)
 
2453
        parent_map = self.repository.texts.get_parent_map(self.text_index)
 
2454
        # On unlistable transports this could well be empty/error...
 
2455
        text_keys = self.repository.texts.keys()
 
2456
        unused_keys = frozenset(text_keys) - set(self.text_index)
 
2457
        for num, key in enumerate(self.text_index.iterkeys()):
 
2458
            progress_bar.update('checking text graph', num, n_versions)
 
2459
            correct_parents = self.calculate_file_version_parents(key)
 
2460
            try:
 
2461
                knit_parents = parent_map[key]
 
2462
            except errors.RevisionNotPresent:
 
2463
                # Missing text!
 
2464
                knit_parents = None
 
2465
            if correct_parents != knit_parents:
 
2466
                wrong_parents[key] = (knit_parents, correct_parents)
 
2467
        return wrong_parents, unused_keys
 
2468
 
 
2469
 
 
2470
class InterVersionedFileRepository(InterRepository):
 
2471
 
 
2472
    _walk_to_common_revisions_batch_size = 50
 
2473
 
 
2474
    @needs_write_lock
 
2475
    def fetch(self, revision_id=None, find_ghosts=False,
 
2476
            fetch_spec=None):
 
2477
        """Fetch the content required to construct revision_id.
 
2478
 
 
2479
        The content is copied from self.source to self.target.
 
2480
 
 
2481
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
2482
                            content is copied.
 
2483
        :return: None.
 
2484
        """
 
2485
        ui.ui_factory.warn_experimental_format_fetch(self)
 
2486
        from bzrlib.fetch import RepoFetcher
 
2487
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
2488
        if self.source._format.network_name() != self.target._format.network_name():
 
2489
            ui.ui_factory.show_user_warning('cross_format_fetch',
 
2490
                from_format=self.source._format,
 
2491
                to_format=self.target._format)
 
2492
        f = RepoFetcher(to_repository=self.target,
 
2493
                               from_repository=self.source,
 
2494
                               last_revision=revision_id,
 
2495
                               fetch_spec=fetch_spec,
 
2496
                               find_ghosts=find_ghosts)
 
2497
 
 
2498
    def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
 
2499
        """Walk out from revision_ids in source to revisions target has.
 
2500
 
 
2501
        :param revision_ids: The start point for the search.
 
2502
        :return: A set of revision ids.
 
2503
        """
 
2504
        target_graph = self.target.get_graph()
 
2505
        revision_ids = frozenset(revision_ids)
 
2506
        if if_present_ids:
 
2507
            all_wanted_revs = revision_ids.union(if_present_ids)
 
2508
        else:
 
2509
            all_wanted_revs = revision_ids
 
2510
        missing_revs = set()
 
2511
        source_graph = self.source.get_graph()
 
2512
        # ensure we don't pay silly lookup costs.
 
2513
        searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
 
2514
        null_set = frozenset([_mod_revision.NULL_REVISION])
 
2515
        searcher_exhausted = False
 
2516
        while True:
 
2517
            next_revs = set()
 
2518
            ghosts = set()
 
2519
            # Iterate the searcher until we have enough next_revs
 
2520
            while len(next_revs) < self._walk_to_common_revisions_batch_size:
 
2521
                try:
 
2522
                    next_revs_part, ghosts_part = searcher.next_with_ghosts()
 
2523
                    next_revs.update(next_revs_part)
 
2524
                    ghosts.update(ghosts_part)
 
2525
                except StopIteration:
 
2526
                    searcher_exhausted = True
 
2527
                    break
 
2528
            # If there are ghosts in the source graph, and the caller asked for
 
2529
            # them, make sure that they are present in the target.
 
2530
            # We don't care about other ghosts as we can't fetch them and
 
2531
            # haven't been asked to.
 
2532
            ghosts_to_check = set(revision_ids.intersection(ghosts))
 
2533
            revs_to_get = set(next_revs).union(ghosts_to_check)
 
2534
            if revs_to_get:
 
2535
                have_revs = set(target_graph.get_parent_map(revs_to_get))
 
2536
                # we always have NULL_REVISION present.
 
2537
                have_revs = have_revs.union(null_set)
 
2538
                # Check if the target is missing any ghosts we need.
 
2539
                ghosts_to_check.difference_update(have_revs)
 
2540
                if ghosts_to_check:
 
2541
                    # One of the caller's revision_ids is a ghost in both the
 
2542
                    # source and the target.
 
2543
                    raise errors.NoSuchRevision(
 
2544
                        self.source, ghosts_to_check.pop())
 
2545
                missing_revs.update(next_revs - have_revs)
 
2546
                # Because we may have walked past the original stop point, make
 
2547
                # sure everything is stopped
 
2548
                stop_revs = searcher.find_seen_ancestors(have_revs)
 
2549
                searcher.stop_searching_any(stop_revs)
 
2550
            if searcher_exhausted:
 
2551
                break
 
2552
        return searcher.get_result()
 
2553
 
 
2554
    @needs_read_lock
 
2555
    def search_missing_revision_ids(self,
 
2556
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
 
2557
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
2558
            limit=None):
 
2559
        """Return the revision ids that source has that target does not.
 
2560
 
 
2561
        :param revision_id: only return revision ids included by this
 
2562
            revision_id.
 
2563
        :param revision_ids: return revision ids included by these
 
2564
            revision_ids.  NoSuchRevision will be raised if any of these
 
2565
            revisions are not present.
 
2566
        :param if_present_ids: like revision_ids, but will not cause
 
2567
            NoSuchRevision if any of these are absent, instead they will simply
 
2568
            not be in the result.  This is useful for e.g. finding revisions
 
2569
            to fetch for tags, which may reference absent revisions.
 
2570
        :param find_ghosts: If True find missing revisions in deep history
 
2571
            rather than just finding the surface difference.
 
2572
        :return: A bzrlib.graph.SearchResult.
 
2573
        """
 
2574
        if symbol_versioning.deprecated_passed(revision_id):
 
2575
            symbol_versioning.warn(
 
2576
                'search_missing_revision_ids(revision_id=...) was '
 
2577
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
 
2578
                DeprecationWarning, stacklevel=2)
 
2579
            if revision_ids is not None:
 
2580
                raise AssertionError(
 
2581
                    'revision_ids is mutually exclusive with revision_id')
 
2582
            if revision_id is not None:
 
2583
                revision_ids = [revision_id]
 
2584
        del revision_id
 
2585
        # stop searching at found target revisions.
 
2586
        if not find_ghosts and (revision_ids is not None or if_present_ids is
 
2587
                not None):
 
2588
            result = self._walk_to_common_revisions(revision_ids,
 
2589
                    if_present_ids=if_present_ids)
 
2590
            if limit is None:
 
2591
                return result
 
2592
            result_set = result.get_keys()
 
2593
        else:
 
2594
            # generic, possibly worst case, slow code path.
 
2595
            target_ids = set(self.target.all_revision_ids())
 
2596
            source_ids = self._present_source_revisions_for(
 
2597
                revision_ids, if_present_ids)
 
2598
            result_set = set(source_ids).difference(target_ids)
 
2599
        if limit is not None:
 
2600
            topo_ordered = self.source.get_graph().iter_topo_order(result_set)
 
2601
            result_set = set(itertools.islice(topo_ordered, limit))
 
2602
        return self.source.revision_ids_to_search_result(result_set)
 
2603
 
 
2604
    def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
 
2605
        """Returns set of all revisions in ancestry of revision_ids present in
 
2606
        the source repo.
 
2607
 
 
2608
        :param revision_ids: if None, all revisions in source are returned.
 
2609
        :param if_present_ids: like revision_ids, but if any/all of these are
 
2610
            absent no error is raised.
 
2611
        """
 
2612
        if revision_ids is not None or if_present_ids is not None:
 
2613
            # First, ensure all specified revisions exist.  Callers expect
 
2614
            # NoSuchRevision when they pass absent revision_ids here.
 
2615
            if revision_ids is None:
 
2616
                revision_ids = set()
 
2617
            if if_present_ids is None:
 
2618
                if_present_ids = set()
 
2619
            revision_ids = set(revision_ids)
 
2620
            if_present_ids = set(if_present_ids)
 
2621
            all_wanted_ids = revision_ids.union(if_present_ids)
 
2622
            graph = self.source.get_graph()
 
2623
            present_revs = set(graph.get_parent_map(all_wanted_ids))
 
2624
            missing = revision_ids.difference(present_revs)
 
2625
            if missing:
 
2626
                raise errors.NoSuchRevision(self.source, missing.pop())
 
2627
            found_ids = all_wanted_ids.intersection(present_revs)
 
2628
            source_ids = [rev_id for (rev_id, parents) in
 
2629
                          graph.iter_ancestry(found_ids)
 
2630
                          if rev_id != _mod_revision.NULL_REVISION
 
2631
                          and parents is not None]
 
2632
        else:
 
2633
            source_ids = self.source.all_revision_ids()
 
2634
        return set(source_ids)
 
2635
 
 
2636
    @classmethod
 
2637
    def _get_repo_format_to_test(self):
 
2638
        return None
 
2639
 
 
2640
    @classmethod
 
2641
    def is_compatible(cls, source, target):
 
2642
        # The default implementation is compatible with everything
 
2643
        return (source._format.supports_full_versioned_files and
 
2644
                target._format.supports_full_versioned_files)
 
2645
 
 
2646
 
 
2647
class InterDifferingSerializer(InterVersionedFileRepository):
 
2648
 
 
2649
    @classmethod
 
2650
    def _get_repo_format_to_test(self):
 
2651
        return None
 
2652
 
 
2653
    @staticmethod
 
2654
    def is_compatible(source, target):
 
2655
        if not source._format.supports_full_versioned_files:
 
2656
            return False
 
2657
        if not target._format.supports_full_versioned_files:
 
2658
            return False
 
2659
        # This is redundant with format.check_conversion_target(), however that
 
2660
        # raises an exception, and we just want to say "False" as in we won't
 
2661
        # support converting between these formats.
 
2662
        if 'IDS_never' in debug.debug_flags:
 
2663
            return False
 
2664
        if source.supports_rich_root() and not target.supports_rich_root():
 
2665
            return False
 
2666
        if (source._format.supports_tree_reference
 
2667
            and not target._format.supports_tree_reference):
 
2668
            return False
 
2669
        if target._fallback_repositories and target._format.supports_chks:
 
2670
            # IDS doesn't know how to copy CHKs for the parent inventories it
 
2671
            # adds to stacked repos.
 
2672
            return False
 
2673
        if 'IDS_always' in debug.debug_flags:
 
2674
            return True
 
2675
        # Only use this code path for local source and target.  IDS does far
 
2676
        # too much IO (both bandwidth and roundtrips) over a network.
 
2677
        if not source.bzrdir.transport.base.startswith('file:///'):
 
2678
            return False
 
2679
        if not target.bzrdir.transport.base.startswith('file:///'):
 
2680
            return False
 
2681
        return True
 
2682
 
 
2683
    def _get_trees(self, revision_ids, cache):
 
2684
        possible_trees = []
 
2685
        for rev_id in revision_ids:
 
2686
            if rev_id in cache:
 
2687
                possible_trees.append((rev_id, cache[rev_id]))
 
2688
            else:
 
2689
                # Not cached, but inventory might be present anyway.
 
2690
                try:
 
2691
                    tree = self.source.revision_tree(rev_id)
 
2692
                except errors.NoSuchRevision:
 
2693
                    # Nope, parent is ghost.
 
2694
                    pass
 
2695
                else:
 
2696
                    cache[rev_id] = tree
 
2697
                    possible_trees.append((rev_id, tree))
 
2698
        return possible_trees
 
2699
 
 
2700
    def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
 
2701
        """Get the best delta and base for this revision.
 
2702
 
 
2703
        :return: (basis_id, delta)
 
2704
        """
 
2705
        deltas = []
 
2706
        # Generate deltas against each tree, to find the shortest.
 
2707
        texts_possibly_new_in_tree = set()
 
2708
        for basis_id, basis_tree in possible_trees:
 
2709
            delta = tree.inventory._make_delta(basis_tree.inventory)
 
2710
            for old_path, new_path, file_id, new_entry in delta:
 
2711
                if new_path is None:
 
2712
                    # This file_id isn't present in the new rev, so we don't
 
2713
                    # care about it.
 
2714
                    continue
 
2715
                if not new_path:
 
2716
                    # Rich roots are handled elsewhere...
 
2717
                    continue
 
2718
                kind = new_entry.kind
 
2719
                if kind != 'directory' and kind != 'file':
 
2720
                    # No text record associated with this inventory entry.
 
2721
                    continue
 
2722
                # This is a directory or file that has changed somehow.
 
2723
                texts_possibly_new_in_tree.add((file_id, new_entry.revision))
 
2724
            deltas.append((len(delta), basis_id, delta))
 
2725
        deltas.sort()
 
2726
        return deltas[0][1:]
 
2727
 
 
2728
    def _fetch_parent_invs_for_stacking(self, parent_map, cache):
 
2729
        """Find all parent revisions that are absent, but for which the
 
2730
        inventory is present, and copy those inventories.
 
2731
 
 
2732
        This is necessary to preserve correctness when the source is stacked
 
2733
        without fallbacks configured.  (Note that in cases like upgrade the
 
2734
        source may be not have _fallback_repositories even though it is
 
2735
        stacked.)
 
2736
        """
 
2737
        parent_revs = set()
 
2738
        for parents in parent_map.values():
 
2739
            parent_revs.update(parents)
 
2740
        present_parents = self.source.get_parent_map(parent_revs)
 
2741
        absent_parents = set(parent_revs).difference(present_parents)
 
2742
        parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
 
2743
            (rev_id,) for rev_id in absent_parents)
 
2744
        parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
 
2745
        for parent_tree in self.source.revision_trees(parent_inv_ids):
 
2746
            current_revision_id = parent_tree.get_revision_id()
 
2747
            parents_parents_keys = parent_invs_keys_for_stacking[
 
2748
                (current_revision_id,)]
 
2749
            parents_parents = [key[-1] for key in parents_parents_keys]
 
2750
            basis_id = _mod_revision.NULL_REVISION
 
2751
            basis_tree = self.source.revision_tree(basis_id)
 
2752
            delta = parent_tree.inventory._make_delta(basis_tree.inventory)
 
2753
            self.target.add_inventory_by_delta(
 
2754
                basis_id, delta, current_revision_id, parents_parents)
 
2755
            cache[current_revision_id] = parent_tree
 
2756
 
 
2757
    def _fetch_batch(self, revision_ids, basis_id, cache):
 
2758
        """Fetch across a few revisions.
 
2759
 
 
2760
        :param revision_ids: The revisions to copy
 
2761
        :param basis_id: The revision_id of a tree that must be in cache, used
 
2762
            as a basis for delta when no other base is available
 
2763
        :param cache: A cache of RevisionTrees that we can use.
 
2764
        :return: The revision_id of the last converted tree. The RevisionTree
 
2765
            for it will be in cache
 
2766
        """
 
2767
        # Walk though all revisions; get inventory deltas, copy referenced
 
2768
        # texts that delta references, insert the delta, revision and
 
2769
        # signature.
 
2770
        root_keys_to_create = set()
 
2771
        text_keys = set()
 
2772
        pending_deltas = []
 
2773
        pending_revisions = []
 
2774
        parent_map = self.source.get_parent_map(revision_ids)
 
2775
        self._fetch_parent_invs_for_stacking(parent_map, cache)
 
2776
        self.source._safe_to_return_from_cache = True
 
2777
        for tree in self.source.revision_trees(revision_ids):
 
2778
            # Find a inventory delta for this revision.
 
2779
            # Find text entries that need to be copied, too.
 
2780
            current_revision_id = tree.get_revision_id()
 
2781
            parent_ids = parent_map.get(current_revision_id, ())
 
2782
            parent_trees = self._get_trees(parent_ids, cache)
 
2783
            possible_trees = list(parent_trees)
 
2784
            if len(possible_trees) == 0:
 
2785
                # There either aren't any parents, or the parents are ghosts,
 
2786
                # so just use the last converted tree.
 
2787
                possible_trees.append((basis_id, cache[basis_id]))
 
2788
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
 
2789
                                                           possible_trees)
 
2790
            revision = self.source.get_revision(current_revision_id)
 
2791
            pending_deltas.append((basis_id, delta,
 
2792
                current_revision_id, revision.parent_ids))
 
2793
            if self._converting_to_rich_root:
 
2794
                self._revision_id_to_root_id[current_revision_id] = \
 
2795
                    tree.get_root_id()
 
2796
            # Determine which texts are in present in this revision but not in
 
2797
            # any of the available parents.
 
2798
            texts_possibly_new_in_tree = set()
 
2799
            for old_path, new_path, file_id, entry in delta:
 
2800
                if new_path is None:
 
2801
                    # This file_id isn't present in the new rev
 
2802
                    continue
 
2803
                if not new_path:
 
2804
                    # This is the root
 
2805
                    if not self.target.supports_rich_root():
 
2806
                        # The target doesn't support rich root, so we don't
 
2807
                        # copy
 
2808
                        continue
 
2809
                    if self._converting_to_rich_root:
 
2810
                        # This can't be copied normally, we have to insert
 
2811
                        # it specially
 
2812
                        root_keys_to_create.add((file_id, entry.revision))
 
2813
                        continue
 
2814
                kind = entry.kind
 
2815
                texts_possibly_new_in_tree.add((file_id, entry.revision))
 
2816
            for basis_id, basis_tree in possible_trees:
 
2817
                basis_inv = basis_tree.inventory
 
2818
                for file_key in list(texts_possibly_new_in_tree):
 
2819
                    file_id, file_revision = file_key
 
2820
                    try:
 
2821
                        entry = basis_inv[file_id]
 
2822
                    except errors.NoSuchId:
 
2823
                        continue
 
2824
                    if entry.revision == file_revision:
 
2825
                        texts_possibly_new_in_tree.remove(file_key)
 
2826
            text_keys.update(texts_possibly_new_in_tree)
 
2827
            pending_revisions.append(revision)
 
2828
            cache[current_revision_id] = tree
 
2829
            basis_id = current_revision_id
 
2830
        self.source._safe_to_return_from_cache = False
 
2831
        # Copy file texts
 
2832
        from_texts = self.source.texts
 
2833
        to_texts = self.target.texts
 
2834
        if root_keys_to_create:
 
2835
            root_stream = _mod_fetch._new_root_data_stream(
 
2836
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
 
2837
                self.source)
 
2838
            to_texts.insert_record_stream(root_stream)
 
2839
        to_texts.insert_record_stream(from_texts.get_record_stream(
 
2840
            text_keys, self.target._format._fetch_order,
 
2841
            not self.target._format._fetch_uses_deltas))
 
2842
        # insert inventory deltas
 
2843
        for delta in pending_deltas:
 
2844
            self.target.add_inventory_by_delta(*delta)
 
2845
        if self.target._fallback_repositories:
 
2846
            # Make sure this stacked repository has all the parent inventories
 
2847
            # for the new revisions that we are about to insert.  We do this
 
2848
            # before adding the revisions so that no revision is added until
 
2849
            # all the inventories it may depend on are added.
 
2850
            # Note that this is overzealous, as we may have fetched these in an
 
2851
            # earlier batch.
 
2852
            parent_ids = set()
 
2853
            revision_ids = set()
 
2854
            for revision in pending_revisions:
 
2855
                revision_ids.add(revision.revision_id)
 
2856
                parent_ids.update(revision.parent_ids)
 
2857
            parent_ids.difference_update(revision_ids)
 
2858
            parent_ids.discard(_mod_revision.NULL_REVISION)
 
2859
            parent_map = self.source.get_parent_map(parent_ids)
 
2860
            # we iterate over parent_map and not parent_ids because we don't
 
2861
            # want to try copying any revision which is a ghost
 
2862
            for parent_tree in self.source.revision_trees(parent_map):
 
2863
                current_revision_id = parent_tree.get_revision_id()
 
2864
                parents_parents = parent_map[current_revision_id]
 
2865
                possible_trees = self._get_trees(parents_parents, cache)
 
2866
                if len(possible_trees) == 0:
 
2867
                    # There either aren't any parents, or the parents are
 
2868
                    # ghosts, so just use the last converted tree.
 
2869
                    possible_trees.append((basis_id, cache[basis_id]))
 
2870
                basis_id, delta = self._get_delta_for_revision(parent_tree,
 
2871
                    parents_parents, possible_trees)
 
2872
                self.target.add_inventory_by_delta(
 
2873
                    basis_id, delta, current_revision_id, parents_parents)
 
2874
        # insert signatures and revisions
 
2875
        for revision in pending_revisions:
 
2876
            try:
 
2877
                signature = self.source.get_signature_text(
 
2878
                    revision.revision_id)
 
2879
                self.target.add_signature_text(revision.revision_id,
 
2880
                    signature)
 
2881
            except errors.NoSuchRevision:
 
2882
                pass
 
2883
            self.target.add_revision(revision.revision_id, revision)
 
2884
        return basis_id
 
2885
 
 
2886
    def _fetch_all_revisions(self, revision_ids, pb):
 
2887
        """Fetch everything for the list of revisions.
 
2888
 
 
2889
        :param revision_ids: The list of revisions to fetch. Must be in
 
2890
            topological order.
 
2891
        :param pb: A ProgressTask
 
2892
        :return: None
 
2893
        """
 
2894
        basis_id, basis_tree = self._get_basis(revision_ids[0])
 
2895
        batch_size = 100
 
2896
        cache = lru_cache.LRUCache(100)
 
2897
        cache[basis_id] = basis_tree
 
2898
        del basis_tree # We don't want to hang on to it here
 
2899
        hints = []
 
2900
        a_graph = None
 
2901
 
 
2902
        for offset in range(0, len(revision_ids), batch_size):
 
2903
            self.target.start_write_group()
 
2904
            try:
 
2905
                pb.update('Transferring revisions', offset,
 
2906
                          len(revision_ids))
 
2907
                batch = revision_ids[offset:offset+batch_size]
 
2908
                basis_id = self._fetch_batch(batch, basis_id, cache)
 
2909
            except:
 
2910
                self.source._safe_to_return_from_cache = False
 
2911
                self.target.abort_write_group()
 
2912
                raise
 
2913
            else:
 
2914
                hint = self.target.commit_write_group()
 
2915
                if hint:
 
2916
                    hints.extend(hint)
 
2917
        if hints and self.target._format.pack_compresses:
 
2918
            self.target.pack(hint=hints)
 
2919
        pb.update('Transferring revisions', len(revision_ids),
 
2920
                  len(revision_ids))
 
2921
 
 
2922
    @needs_write_lock
 
2923
    def fetch(self, revision_id=None, find_ghosts=False,
 
2924
            fetch_spec=None):
 
2925
        """See InterRepository.fetch()."""
 
2926
        if fetch_spec is not None:
 
2927
            revision_ids = fetch_spec.get_keys()
 
2928
        else:
 
2929
            revision_ids = None
 
2930
        ui.ui_factory.warn_experimental_format_fetch(self)
 
2931
        if (not self.source.supports_rich_root()
 
2932
            and self.target.supports_rich_root()):
 
2933
            self._converting_to_rich_root = True
 
2934
            self._revision_id_to_root_id = {}
 
2935
        else:
 
2936
            self._converting_to_rich_root = False
 
2937
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
2938
        if self.source._format.network_name() != self.target._format.network_name():
 
2939
            ui.ui_factory.show_user_warning('cross_format_fetch',
 
2940
                from_format=self.source._format,
 
2941
                to_format=self.target._format)
 
2942
        if revision_ids is None:
 
2943
            if revision_id:
 
2944
                search_revision_ids = [revision_id]
 
2945
            else:
 
2946
                search_revision_ids = None
 
2947
            revision_ids = self.target.search_missing_revision_ids(self.source,
 
2948
                revision_ids=search_revision_ids,
 
2949
                find_ghosts=find_ghosts).get_keys()
 
2950
        if not revision_ids:
 
2951
            return 0, 0
 
2952
        revision_ids = tsort.topo_sort(
 
2953
            self.source.get_graph().get_parent_map(revision_ids))
 
2954
        if not revision_ids:
 
2955
            return 0, 0
 
2956
        # Walk though all revisions; get inventory deltas, copy referenced
 
2957
        # texts that delta references, insert the delta, revision and
 
2958
        # signature.
 
2959
        pb = ui.ui_factory.nested_progress_bar()
 
2960
        try:
 
2961
            self._fetch_all_revisions(revision_ids, pb)
 
2962
        finally:
 
2963
            pb.finished()
 
2964
        return len(revision_ids), 0
 
2965
 
 
2966
    def _get_basis(self, first_revision_id):
 
2967
        """Get a revision and tree which exists in the target.
 
2968
 
 
2969
        This assumes that first_revision_id is selected for transmission
 
2970
        because all other ancestors are already present. If we can't find an
 
2971
        ancestor we fall back to NULL_REVISION since we know that is safe.
 
2972
 
 
2973
        :return: (basis_id, basis_tree)
 
2974
        """
 
2975
        first_rev = self.source.get_revision(first_revision_id)
 
2976
        try:
 
2977
            basis_id = first_rev.parent_ids[0]
 
2978
            # only valid as a basis if the target has it
 
2979
            self.target.get_revision(basis_id)
 
2980
            # Try to get a basis tree - if it's a ghost it will hit the
 
2981
            # NoSuchRevision case.
 
2982
            basis_tree = self.source.revision_tree(basis_id)
 
2983
        except (IndexError, errors.NoSuchRevision):
 
2984
            basis_id = _mod_revision.NULL_REVISION
 
2985
            basis_tree = self.source.revision_tree(basis_id)
 
2986
        return basis_id, basis_tree
 
2987
 
 
2988
 
 
2989
class InterSameDataRepository(InterVersionedFileRepository):
 
2990
    """Code for converting between repositories that represent the same data.
 
2991
 
 
2992
    Data format and model must match for this to work.
 
2993
    """
 
2994
 
 
2995
    @classmethod
 
2996
    def _get_repo_format_to_test(self):
 
2997
        """Repository format for testing with.
 
2998
 
 
2999
        InterSameData can pull from subtree to subtree and from non-subtree to
 
3000
        non-subtree, so we test this with the richest repository format.
 
3001
        """
 
3002
        from bzrlib.repofmt import knitrepo
 
3003
        return knitrepo.RepositoryFormatKnit3()
 
3004
 
 
3005
    @staticmethod
 
3006
    def is_compatible(source, target):
 
3007
        return (
 
3008
            InterRepository._same_model(source, target) and
 
3009
            source._format.supports_full_versioned_files and
 
3010
            target._format.supports_full_versioned_files)
 
3011
 
 
3012
 
 
3013
InterRepository.register_optimiser(InterVersionedFileRepository)
 
3014
InterRepository.register_optimiser(InterDifferingSerializer)
 
3015
InterRepository.register_optimiser(InterSameDataRepository)
 
3016
 
 
3017
 
 
3018
def install_revisions(repository, iterable, num_revisions=None, pb=None):
 
3019
    """Install all revision data into a repository.
 
3020
 
 
3021
    Accepts an iterable of revision, tree, signature tuples.  The signature
 
3022
    may be None.
 
3023
    """
 
3024
    repository.start_write_group()
 
3025
    try:
 
3026
        inventory_cache = lru_cache.LRUCache(10)
 
3027
        for n, (revision, revision_tree, signature) in enumerate(iterable):
 
3028
            _install_revision(repository, revision, revision_tree, signature,
 
3029
                inventory_cache)
 
3030
            if pb is not None:
 
3031
                pb.update('Transferring revisions', n + 1, num_revisions)
 
3032
    except:
 
3033
        repository.abort_write_group()
 
3034
        raise
 
3035
    else:
 
3036
        repository.commit_write_group()
 
3037
 
 
3038
 
 
3039
def _install_revision(repository, rev, revision_tree, signature,
 
3040
    inventory_cache):
 
3041
    """Install all revision data into a repository."""
 
3042
    present_parents = []
 
3043
    parent_trees = {}
 
3044
    for p_id in rev.parent_ids:
 
3045
        if repository.has_revision(p_id):
 
3046
            present_parents.append(p_id)
 
3047
            parent_trees[p_id] = repository.revision_tree(p_id)
 
3048
        else:
 
3049
            parent_trees[p_id] = repository.revision_tree(
 
3050
                                     _mod_revision.NULL_REVISION)
 
3051
 
 
3052
    inv = revision_tree.inventory
 
3053
    entries = inv.iter_entries()
 
3054
    # backwards compatibility hack: skip the root id.
 
3055
    if not repository.supports_rich_root():
 
3056
        path, root = entries.next()
 
3057
        if root.revision != rev.revision_id:
 
3058
            raise errors.IncompatibleRevision(repr(repository))
 
3059
    text_keys = {}
 
3060
    for path, ie in entries:
 
3061
        text_keys[(ie.file_id, ie.revision)] = ie
 
3062
    text_parent_map = repository.texts.get_parent_map(text_keys)
 
3063
    missing_texts = set(text_keys) - set(text_parent_map)
 
3064
    # Add the texts that are not already present
 
3065
    for text_key in missing_texts:
 
3066
        ie = text_keys[text_key]
 
3067
        text_parents = []
 
3068
        # FIXME: TODO: The following loop overlaps/duplicates that done by
 
3069
        # commit to determine parents. There is a latent/real bug here where
 
3070
        # the parents inserted are not those commit would do - in particular
 
3071
        # they are not filtered by heads(). RBC, AB
 
3072
        for revision, tree in parent_trees.iteritems():
 
3073
            if ie.file_id not in tree:
 
3074
                continue
 
3075
            parent_id = tree.get_file_revision(ie.file_id)
 
3076
            if parent_id in text_parents:
 
3077
                continue
 
3078
            text_parents.append((ie.file_id, parent_id))
 
3079
        lines = revision_tree.get_file(ie.file_id).readlines()
 
3080
        repository.texts.add_lines(text_key, text_parents, lines)
 
3081
    try:
 
3082
        # install the inventory
 
3083
        if repository._format._commit_inv_deltas and len(rev.parent_ids):
 
3084
            # Cache this inventory
 
3085
            inventory_cache[rev.revision_id] = inv
 
3086
            try:
 
3087
                basis_inv = inventory_cache[rev.parent_ids[0]]
 
3088
            except KeyError:
 
3089
                repository.add_inventory(rev.revision_id, inv, present_parents)
 
3090
            else:
 
3091
                delta = inv._make_delta(basis_inv)
 
3092
                repository.add_inventory_by_delta(rev.parent_ids[0], delta,
 
3093
                    rev.revision_id, present_parents)
 
3094
        else:
 
3095
            repository.add_inventory(rev.revision_id, inv, present_parents)
 
3096
    except errors.RevisionAlreadyPresent:
 
3097
        pass
 
3098
    if signature is not None:
 
3099
        repository.add_signature_text(rev.revision_id, signature)
 
3100
    repository.add_revision(rev.revision_id, rev, inv)
 
3101
 
 
3102
 
 
3103
def install_revision(repository, rev, revision_tree):
 
3104
    """Install all revision data into a repository."""
 
3105
    install_revisions(repository, [(rev, revision_tree, None)])