~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/vf_repository.py

  • Committer: Martin Packman
  • Date: 2011-12-23 19:38:22 UTC
  • mto: This revision was merged to the branch mainline in revision 6405.
  • Revision ID: martin.packman@canonical.com-20111223193822-hesheea4o8aqwexv
Accept and document passing the medium rather than transport for smart connections

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