/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/vf_repository.py

  • Committer: Jonathan Riddell
  • Date: 2011-09-16 10:08:09 UTC
  • mto: This revision was merged to the branch mainline in revision 6145.
  • Revision ID: jriddell@canonical.com-20110916100809-uii7a1h5tp8qguhy
add gettext to progress bar strings

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