/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/vf_repository.py

  • Committer: Jelmer Vernooij
  • Date: 2011-12-05 15:16:52 UTC
  • mto: This revision was merged to the branch mainline in revision 6348.
  • Revision ID: jelmer@samba.org-20111205151652-8y6qgvv1qkbv5f71
Fix get_state().

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
    MetaDirRepositoryFormat,
 
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
        return self._iter_inventories(revision_ids, ordering)
 
1753
 
 
1754
    def _iter_inventories(self, revision_ids, ordering):
 
1755
        """single-document based inventory iteration."""
 
1756
        inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
 
1757
        for text, revision_id in inv_xmls:
 
1758
            yield self._deserialise_inventory(revision_id, text)
 
1759
 
 
1760
    def _iter_inventory_xmls(self, revision_ids, ordering):
 
1761
        if ordering is None:
 
1762
            order_as_requested = True
 
1763
            ordering = 'unordered'
 
1764
        else:
 
1765
            order_as_requested = False
 
1766
        keys = [(revision_id,) for revision_id in revision_ids]
 
1767
        if not keys:
 
1768
            return
 
1769
        if order_as_requested:
 
1770
            key_iter = iter(keys)
 
1771
            next_key = key_iter.next()
 
1772
        stream = self.inventories.get_record_stream(keys, ordering, True)
 
1773
        text_chunks = {}
 
1774
        for record in stream:
 
1775
            if record.storage_kind != 'absent':
 
1776
                chunks = record.get_bytes_as('chunked')
 
1777
                if order_as_requested:
 
1778
                    text_chunks[record.key] = chunks
 
1779
                else:
 
1780
                    yield ''.join(chunks), record.key[-1]
 
1781
            else:
 
1782
                raise errors.NoSuchRevision(self, record.key)
 
1783
            if order_as_requested:
 
1784
                # Yield as many results as we can while preserving order.
 
1785
                while next_key in text_chunks:
 
1786
                    chunks = text_chunks.pop(next_key)
 
1787
                    yield ''.join(chunks), next_key[-1]
 
1788
                    try:
 
1789
                        next_key = key_iter.next()
 
1790
                    except StopIteration:
 
1791
                        # We still want to fully consume the get_record_stream,
 
1792
                        # just in case it is not actually finished at this point
 
1793
                        next_key = None
 
1794
                        break
 
1795
 
 
1796
    def _deserialise_inventory(self, revision_id, xml):
 
1797
        """Transform the xml into an inventory object.
 
1798
 
 
1799
        :param revision_id: The expected revision id of the inventory.
 
1800
        :param xml: A serialised inventory.
 
1801
        """
 
1802
        result = self._serializer.read_inventory_from_string(xml, revision_id,
 
1803
                    entry_cache=self._inventory_entry_cache,
 
1804
                    return_from_cache=self._safe_to_return_from_cache)
 
1805
        if result.revision_id != revision_id:
 
1806
            raise AssertionError('revision id mismatch %s != %s' % (
 
1807
                result.revision_id, revision_id))
 
1808
        return result
 
1809
 
 
1810
    def get_serializer_format(self):
 
1811
        return self._serializer.format_num
 
1812
 
 
1813
    @needs_read_lock
 
1814
    def _get_inventory_xml(self, revision_id):
 
1815
        """Get serialized inventory as a string."""
 
1816
        texts = self._iter_inventory_xmls([revision_id], 'unordered')
 
1817
        try:
 
1818
            text, revision_id = texts.next()
 
1819
        except StopIteration:
 
1820
            raise errors.HistoryMissing(self, 'inventory', revision_id)
 
1821
        return text
 
1822
 
 
1823
    @needs_read_lock
 
1824
    def revision_tree(self, revision_id):
 
1825
        """Return Tree for a revision on this branch.
 
1826
 
 
1827
        `revision_id` may be NULL_REVISION for the empty tree revision.
 
1828
        """
 
1829
        revision_id = _mod_revision.ensure_null(revision_id)
 
1830
        # TODO: refactor this to use an existing revision object
 
1831
        # so we don't need to read it in twice.
 
1832
        if revision_id == _mod_revision.NULL_REVISION:
 
1833
            return InventoryRevisionTree(self,
 
1834
                Inventory(root_id=None), _mod_revision.NULL_REVISION)
 
1835
        else:
 
1836
            inv = self.get_inventory(revision_id)
 
1837
            return InventoryRevisionTree(self, inv, revision_id)
 
1838
 
 
1839
    def revision_trees(self, revision_ids):
 
1840
        """Return Trees for revisions in this repository.
 
1841
 
 
1842
        :param revision_ids: a sequence of revision-ids;
 
1843
          a revision-id may not be None or 'null:'
 
1844
        """
 
1845
        inventories = self.iter_inventories(revision_ids)
 
1846
        for inv in inventories:
 
1847
            yield InventoryRevisionTree(self, inv, inv.revision_id)
 
1848
 
 
1849
    def _filtered_revision_trees(self, revision_ids, file_ids):
 
1850
        """Return Tree for a revision on this branch with only some files.
 
1851
 
 
1852
        :param revision_ids: a sequence of revision-ids;
 
1853
          a revision-id may not be None or 'null:'
 
1854
        :param file_ids: if not None, the result is filtered
 
1855
          so that only those file-ids, their parents and their
 
1856
          children are included.
 
1857
        """
 
1858
        inventories = self.iter_inventories(revision_ids)
 
1859
        for inv in inventories:
 
1860
            # Should we introduce a FilteredRevisionTree class rather
 
1861
            # than pre-filter the inventory here?
 
1862
            filtered_inv = inv.filter(file_ids)
 
1863
            yield InventoryRevisionTree(self, filtered_inv, filtered_inv.revision_id)
 
1864
 
 
1865
    def get_parent_map(self, revision_ids):
 
1866
        """See graph.StackedParentsProvider.get_parent_map"""
 
1867
        # revisions index works in keys; this just works in revisions
 
1868
        # therefore wrap and unwrap
 
1869
        query_keys = []
 
1870
        result = {}
 
1871
        for revision_id in revision_ids:
 
1872
            if revision_id == _mod_revision.NULL_REVISION:
 
1873
                result[revision_id] = ()
 
1874
            elif revision_id is None:
 
1875
                raise ValueError('get_parent_map(None) is not valid')
 
1876
            else:
 
1877
                query_keys.append((revision_id ,))
 
1878
        for ((revision_id,), parent_keys) in \
 
1879
                self.revisions.get_parent_map(query_keys).iteritems():
 
1880
            if parent_keys:
 
1881
                result[revision_id] = tuple([parent_revid
 
1882
                    for (parent_revid,) in parent_keys])
 
1883
            else:
 
1884
                result[revision_id] = (_mod_revision.NULL_REVISION,)
 
1885
        return result
 
1886
 
 
1887
    @needs_read_lock
 
1888
    def get_known_graph_ancestry(self, revision_ids):
 
1889
        """Return the known graph for a set of revision ids and their ancestors.
 
1890
        """
 
1891
        st = static_tuple.StaticTuple
 
1892
        revision_keys = [st(r_id).intern() for r_id in revision_ids]
 
1893
        known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
 
1894
        return graph.GraphThunkIdsToKeys(known_graph)
 
1895
 
 
1896
    @needs_read_lock
 
1897
    def get_file_graph(self):
 
1898
        """Return the graph walker for text revisions."""
 
1899
        return graph.Graph(self.texts)
 
1900
 
 
1901
    def revision_ids_to_search_result(self, result_set):
 
1902
        """Convert a set of revision ids to a graph SearchResult."""
 
1903
        result_parents = set()
 
1904
        for parents in self.get_graph().get_parent_map(
 
1905
            result_set).itervalues():
 
1906
            result_parents.update(parents)
 
1907
        included_keys = result_set.intersection(result_parents)
 
1908
        start_keys = result_set.difference(included_keys)
 
1909
        exclude_keys = result_parents.difference(result_set)
 
1910
        result = vf_search.SearchResult(start_keys, exclude_keys,
 
1911
            len(result_set), result_set)
 
1912
        return result
 
1913
 
 
1914
    def _get_versioned_file_checker(self, text_key_references=None,
 
1915
        ancestors=None):
 
1916
        """Return an object suitable for checking versioned files.
 
1917
        
 
1918
        :param text_key_references: if non-None, an already built
 
1919
            dictionary mapping text keys ((fileid, revision_id) tuples)
 
1920
            to whether they were referred to by the inventory of the
 
1921
            revision_id that they contain. If None, this will be
 
1922
            calculated.
 
1923
        :param ancestors: Optional result from
 
1924
            self.get_graph().get_parent_map(self.all_revision_ids()) if already
 
1925
            available.
 
1926
        """
 
1927
        return _VersionedFileChecker(self,
 
1928
            text_key_references=text_key_references, ancestors=ancestors)
 
1929
 
 
1930
    @needs_read_lock
 
1931
    def has_signature_for_revision_id(self, revision_id):
 
1932
        """Query for a revision signature for revision_id in the repository."""
 
1933
        if not self.has_revision(revision_id):
 
1934
            raise errors.NoSuchRevision(self, revision_id)
 
1935
        sig_present = (1 == len(
 
1936
            self.signatures.get_parent_map([(revision_id,)])))
 
1937
        return sig_present
 
1938
 
 
1939
    @needs_read_lock
 
1940
    def get_signature_text(self, revision_id):
 
1941
        """Return the text for a signature."""
 
1942
        stream = self.signatures.get_record_stream([(revision_id,)],
 
1943
            'unordered', True)
 
1944
        record = stream.next()
 
1945
        if record.storage_kind == 'absent':
 
1946
            raise errors.NoSuchRevision(self, revision_id)
 
1947
        return record.get_bytes_as('fulltext')
 
1948
 
 
1949
    @needs_read_lock
 
1950
    def _check(self, revision_ids, callback_refs, check_repo):
 
1951
        result = check.VersionedFileCheck(self, check_repo=check_repo)
 
1952
        result.check(callback_refs)
 
1953
        return result
 
1954
 
 
1955
    def _find_inconsistent_revision_parents(self, revisions_iterator=None):
 
1956
        """Find revisions with different parent lists in the revision object
 
1957
        and in the index graph.
 
1958
 
 
1959
        :param revisions_iterator: None, or an iterator of (revid,
 
1960
            Revision-or-None). This iterator controls the revisions checked.
 
1961
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1962
            parents-in-revision).
 
1963
        """
 
1964
        if not self.is_locked():
 
1965
            raise AssertionError()
 
1966
        vf = self.revisions
 
1967
        if revisions_iterator is None:
 
1968
            revisions_iterator = self._iter_revisions(None)
 
1969
        for revid, revision in revisions_iterator:
 
1970
            if revision is None:
 
1971
                pass
 
1972
            parent_map = vf.get_parent_map([(revid,)])
 
1973
            parents_according_to_index = tuple(parent[-1] for parent in
 
1974
                parent_map[(revid,)])
 
1975
            parents_according_to_revision = tuple(revision.parent_ids)
 
1976
            if parents_according_to_index != parents_according_to_revision:
 
1977
                yield (revid, parents_according_to_index,
 
1978
                    parents_according_to_revision)
 
1979
 
 
1980
    def _check_for_inconsistent_revision_parents(self):
 
1981
        inconsistencies = list(self._find_inconsistent_revision_parents())
 
1982
        if inconsistencies:
 
1983
            raise errors.BzrCheckError(
 
1984
                "Revision knit has inconsistent parents.")
 
1985
 
 
1986
    def _get_sink(self):
 
1987
        """Return a sink for streaming into this repository."""
 
1988
        return StreamSink(self)
 
1989
 
 
1990
    def _get_source(self, to_format):
 
1991
        """Return a source for streaming from this repository."""
 
1992
        return StreamSource(self, to_format)
 
1993
 
 
1994
 
 
1995
class MetaDirVersionedFileRepository(MetaDirRepository,
 
1996
                                     VersionedFileRepository):
 
1997
    """Repositories in a meta-dir, that work via versioned file objects."""
 
1998
 
 
1999
    def __init__(self, _format, a_bzrdir, control_files):
 
2000
        super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
 
2001
            control_files)
 
2002
 
 
2003
 
 
2004
class MetaDirVersionedFileRepositoryFormat(MetaDirRepositoryFormat,
 
2005
        VersionedFileRepositoryFormat):
 
2006
    """Base class for repository formats using versioned files in metadirs."""
 
2007
 
 
2008
 
 
2009
class StreamSink(object):
 
2010
    """An object that can insert a stream into a repository.
 
2011
 
 
2012
    This interface handles the complexity of reserialising inventories and
 
2013
    revisions from different formats, and allows unidirectional insertion into
 
2014
    stacked repositories without looking for the missing basis parents
 
2015
    beforehand.
 
2016
    """
 
2017
 
 
2018
    def __init__(self, target_repo):
 
2019
        self.target_repo = target_repo
 
2020
 
 
2021
    def insert_stream(self, stream, src_format, resume_tokens):
 
2022
        """Insert a stream's content into the target repository.
 
2023
 
 
2024
        :param src_format: a bzr repository format.
 
2025
 
 
2026
        :return: a list of resume tokens and an  iterable of keys additional
 
2027
            items required before the insertion can be completed.
 
2028
        """
 
2029
        self.target_repo.lock_write()
 
2030
        try:
 
2031
            if resume_tokens:
 
2032
                self.target_repo.resume_write_group(resume_tokens)
 
2033
                is_resume = True
 
2034
            else:
 
2035
                self.target_repo.start_write_group()
 
2036
                is_resume = False
 
2037
            try:
 
2038
                # locked_insert_stream performs a commit|suspend.
 
2039
                missing_keys = self.insert_stream_without_locking(stream,
 
2040
                                    src_format, is_resume)
 
2041
                if missing_keys:
 
2042
                    # suspend the write group and tell the caller what we is
 
2043
                    # missing. We know we can suspend or else we would not have
 
2044
                    # entered this code path. (All repositories that can handle
 
2045
                    # missing keys can handle suspending a write group).
 
2046
                    write_group_tokens = self.target_repo.suspend_write_group()
 
2047
                    return write_group_tokens, missing_keys
 
2048
                hint = self.target_repo.commit_write_group()
 
2049
                to_serializer = self.target_repo._format._serializer
 
2050
                src_serializer = src_format._serializer
 
2051
                if (to_serializer != src_serializer and
 
2052
                    self.target_repo._format.pack_compresses):
 
2053
                    self.target_repo.pack(hint=hint)
 
2054
                return [], set()
 
2055
            except:
 
2056
                self.target_repo.abort_write_group(suppress_errors=True)
 
2057
                raise
 
2058
        finally:
 
2059
            self.target_repo.unlock()
 
2060
 
 
2061
    def insert_stream_without_locking(self, stream, src_format,
 
2062
                                      is_resume=False):
 
2063
        """Insert a stream's content into the target repository.
 
2064
 
 
2065
        This assumes that you already have a locked repository and an active
 
2066
        write group.
 
2067
 
 
2068
        :param src_format: a bzr repository format.
 
2069
        :param is_resume: Passed down to get_missing_parent_inventories to
 
2070
            indicate if we should be checking for missing texts at the same
 
2071
            time.
 
2072
 
 
2073
        :return: A set of keys that are missing.
 
2074
        """
 
2075
        if not self.target_repo.is_write_locked():
 
2076
            raise errors.ObjectNotLocked(self)
 
2077
        if not self.target_repo.is_in_write_group():
 
2078
            raise errors.BzrError('you must already be in a write group')
 
2079
        to_serializer = self.target_repo._format._serializer
 
2080
        src_serializer = src_format._serializer
 
2081
        new_pack = None
 
2082
        if to_serializer == src_serializer:
 
2083
            # If serializers match and the target is a pack repository, set the
 
2084
            # write cache size on the new pack.  This avoids poor performance
 
2085
            # on transports where append is unbuffered (such as
 
2086
            # RemoteTransport).  This is safe to do because nothing should read
 
2087
            # back from the target repository while a stream with matching
 
2088
            # serialization is being inserted.
 
2089
            # The exception is that a delta record from the source that should
 
2090
            # be a fulltext may need to be expanded by the target (see
 
2091
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
 
2092
            # explicitly flush any buffered writes first in that rare case.
 
2093
            try:
 
2094
                new_pack = self.target_repo._pack_collection._new_pack
 
2095
            except AttributeError:
 
2096
                # Not a pack repository
 
2097
                pass
 
2098
            else:
 
2099
                new_pack.set_write_cache_size(1024*1024)
 
2100
        for substream_type, substream in stream:
 
2101
            if 'stream' in debug.debug_flags:
 
2102
                mutter('inserting substream: %s', substream_type)
 
2103
            if substream_type == 'texts':
 
2104
                self.target_repo.texts.insert_record_stream(substream)
 
2105
            elif substream_type == 'inventories':
 
2106
                if src_serializer == to_serializer:
 
2107
                    self.target_repo.inventories.insert_record_stream(
 
2108
                        substream)
 
2109
                else:
 
2110
                    self._extract_and_insert_inventories(
 
2111
                        substream, src_serializer)
 
2112
            elif substream_type == 'inventory-deltas':
 
2113
                self._extract_and_insert_inventory_deltas(
 
2114
                    substream, src_serializer)
 
2115
            elif substream_type == 'chk_bytes':
 
2116
                # XXX: This doesn't support conversions, as it assumes the
 
2117
                #      conversion was done in the fetch code.
 
2118
                self.target_repo.chk_bytes.insert_record_stream(substream)
 
2119
            elif substream_type == 'revisions':
 
2120
                # This may fallback to extract-and-insert more often than
 
2121
                # required if the serializers are different only in terms of
 
2122
                # the inventory.
 
2123
                if src_serializer == to_serializer:
 
2124
                    self.target_repo.revisions.insert_record_stream(substream)
 
2125
                else:
 
2126
                    self._extract_and_insert_revisions(substream,
 
2127
                        src_serializer)
 
2128
            elif substream_type == 'signatures':
 
2129
                self.target_repo.signatures.insert_record_stream(substream)
 
2130
            else:
 
2131
                raise AssertionError('kaboom! %s' % (substream_type,))
 
2132
        # Done inserting data, and the missing_keys calculations will try to
 
2133
        # read back from the inserted data, so flush the writes to the new pack
 
2134
        # (if this is pack format).
 
2135
        if new_pack is not None:
 
2136
            new_pack._write_data('', flush=True)
 
2137
        # Find all the new revisions (including ones from resume_tokens)
 
2138
        missing_keys = self.target_repo.get_missing_parent_inventories(
 
2139
            check_for_missing_texts=is_resume)
 
2140
        try:
 
2141
            for prefix, versioned_file in (
 
2142
                ('texts', self.target_repo.texts),
 
2143
                ('inventories', self.target_repo.inventories),
 
2144
                ('revisions', self.target_repo.revisions),
 
2145
                ('signatures', self.target_repo.signatures),
 
2146
                ('chk_bytes', self.target_repo.chk_bytes),
 
2147
                ):
 
2148
                if versioned_file is None:
 
2149
                    continue
 
2150
                # TODO: key is often going to be a StaticTuple object
 
2151
                #       I don't believe we can define a method by which
 
2152
                #       (prefix,) + StaticTuple will work, though we could
 
2153
                #       define a StaticTuple.sq_concat that would allow you to
 
2154
                #       pass in either a tuple or a StaticTuple as the second
 
2155
                #       object, so instead we could have:
 
2156
                #       StaticTuple(prefix) + key here...
 
2157
                missing_keys.update((prefix,) + key for key in
 
2158
                    versioned_file.get_missing_compression_parent_keys())
 
2159
        except NotImplementedError:
 
2160
            # cannot even attempt suspending, and missing would have failed
 
2161
            # during stream insertion.
 
2162
            missing_keys = set()
 
2163
        return missing_keys
 
2164
 
 
2165
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
 
2166
        target_rich_root = self.target_repo._format.rich_root_data
 
2167
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
2168
        for record in substream:
 
2169
            # Insert the delta directly
 
2170
            inventory_delta_bytes = record.get_bytes_as('fulltext')
 
2171
            deserialiser = inventory_delta.InventoryDeltaDeserializer()
 
2172
            try:
 
2173
                parse_result = deserialiser.parse_text_bytes(
 
2174
                    inventory_delta_bytes)
 
2175
            except inventory_delta.IncompatibleInventoryDelta, err:
 
2176
                mutter("Incompatible delta: %s", err.msg)
 
2177
                raise errors.IncompatibleRevision(self.target_repo._format)
 
2178
            basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
 
2179
            revision_id = new_id
 
2180
            parents = [key[0] for key in record.parents]
 
2181
            self.target_repo.add_inventory_by_delta(
 
2182
                basis_id, inv_delta, revision_id, parents)
 
2183
 
 
2184
    def _extract_and_insert_inventories(self, substream, serializer,
 
2185
            parse_delta=None):
 
2186
        """Generate a new inventory versionedfile in target, converting data.
 
2187
 
 
2188
        The inventory is retrieved from the source, (deserializing it), and
 
2189
        stored in the target (reserializing it in a different format).
 
2190
        """
 
2191
        target_rich_root = self.target_repo._format.rich_root_data
 
2192
        target_tree_refs = self.target_repo._format.supports_tree_reference
 
2193
        for record in substream:
 
2194
            # It's not a delta, so it must be a fulltext in the source
 
2195
            # serializer's format.
 
2196
            bytes = record.get_bytes_as('fulltext')
 
2197
            revision_id = record.key[0]
 
2198
            inv = serializer.read_inventory_from_string(bytes, revision_id)
 
2199
            parents = [key[0] for key in record.parents]
 
2200
            self.target_repo.add_inventory(revision_id, inv, parents)
 
2201
            # No need to keep holding this full inv in memory when the rest of
 
2202
            # the substream is likely to be all deltas.
 
2203
            del inv
 
2204
 
 
2205
    def _extract_and_insert_revisions(self, substream, serializer):
 
2206
        for record in substream:
 
2207
            bytes = record.get_bytes_as('fulltext')
 
2208
            revision_id = record.key[0]
 
2209
            rev = serializer.read_revision_from_string(bytes)
 
2210
            if rev.revision_id != revision_id:
 
2211
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
 
2212
            self.target_repo.add_revision(revision_id, rev)
 
2213
 
 
2214
    def finished(self):
 
2215
        if self.target_repo._format._fetch_reconcile:
 
2216
            self.target_repo.reconcile()
 
2217
 
 
2218
 
 
2219
class StreamSource(object):
 
2220
    """A source of a stream for fetching between repositories."""
 
2221
 
 
2222
    def __init__(self, from_repository, to_format):
 
2223
        """Create a StreamSource streaming from from_repository."""
 
2224
        self.from_repository = from_repository
 
2225
        self.to_format = to_format
 
2226
        self._record_counter = RecordCounter()
 
2227
 
 
2228
    def delta_on_metadata(self):
 
2229
        """Return True if delta's are permitted on metadata streams.
 
2230
 
 
2231
        That is on revisions and signatures.
 
2232
        """
 
2233
        src_serializer = self.from_repository._format._serializer
 
2234
        target_serializer = self.to_format._serializer
 
2235
        return (self.to_format._fetch_uses_deltas and
 
2236
            src_serializer == target_serializer)
 
2237
 
 
2238
    def _fetch_revision_texts(self, revs):
 
2239
        # fetch signatures first and then the revision texts
 
2240
        # may need to be a InterRevisionStore call here.
 
2241
        from_sf = self.from_repository.signatures
 
2242
        # A missing signature is just skipped.
 
2243
        keys = [(rev_id,) for rev_id in revs]
 
2244
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
 
2245
            keys,
 
2246
            self.to_format._fetch_order,
 
2247
            not self.to_format._fetch_uses_deltas))
 
2248
        # If a revision has a delta, this is actually expanded inside the
 
2249
        # insert_record_stream code now, which is an alternate fix for
 
2250
        # bug #261339
 
2251
        from_rf = self.from_repository.revisions
 
2252
        revisions = from_rf.get_record_stream(
 
2253
            keys,
 
2254
            self.to_format._fetch_order,
 
2255
            not self.delta_on_metadata())
 
2256
        return [('signatures', signatures), ('revisions', revisions)]
 
2257
 
 
2258
    def _generate_root_texts(self, revs):
 
2259
        """This will be called by get_stream between fetching weave texts and
 
2260
        fetching the inventory weave.
 
2261
        """
 
2262
        if self._rich_root_upgrade():
 
2263
            return _mod_fetch.Inter1and2Helper(
 
2264
                self.from_repository).generate_root_texts(revs)
 
2265
        else:
 
2266
            return []
 
2267
 
 
2268
    def get_stream(self, search):
 
2269
        phase = 'file'
 
2270
        revs = search.get_keys()
 
2271
        graph = self.from_repository.get_graph()
 
2272
        revs = tsort.topo_sort(graph.get_parent_map(revs))
 
2273
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
 
2274
        text_keys = []
 
2275
        for knit_kind, file_id, revisions in data_to_fetch:
 
2276
            if knit_kind != phase:
 
2277
                phase = knit_kind
 
2278
                # Make a new progress bar for this phase
 
2279
            if knit_kind == "file":
 
2280
                # Accumulate file texts
 
2281
                text_keys.extend([(file_id, revision) for revision in
 
2282
                    revisions])
 
2283
            elif knit_kind == "inventory":
 
2284
                # Now copy the file texts.
 
2285
                from_texts = self.from_repository.texts
 
2286
                yield ('texts', from_texts.get_record_stream(
 
2287
                    text_keys, self.to_format._fetch_order,
 
2288
                    not self.to_format._fetch_uses_deltas))
 
2289
                # Cause an error if a text occurs after we have done the
 
2290
                # copy.
 
2291
                text_keys = None
 
2292
                # Before we process the inventory we generate the root
 
2293
                # texts (if necessary) so that the inventories references
 
2294
                # will be valid.
 
2295
                for _ in self._generate_root_texts(revs):
 
2296
                    yield _
 
2297
                # we fetch only the referenced inventories because we do not
 
2298
                # know for unselected inventories whether all their required
 
2299
                # texts are present in the other repository - it could be
 
2300
                # corrupt.
 
2301
                for info in self._get_inventory_stream(revs):
 
2302
                    yield info
 
2303
            elif knit_kind == "signatures":
 
2304
                # Nothing to do here; this will be taken care of when
 
2305
                # _fetch_revision_texts happens.
 
2306
                pass
 
2307
            elif knit_kind == "revisions":
 
2308
                for record in self._fetch_revision_texts(revs):
 
2309
                    yield record
 
2310
            else:
 
2311
                raise AssertionError("Unknown knit kind %r" % knit_kind)
 
2312
 
 
2313
    def get_stream_for_missing_keys(self, missing_keys):
 
2314
        # missing keys can only occur when we are byte copying and not
 
2315
        # translating (because translation means we don't send
 
2316
        # unreconstructable deltas ever).
 
2317
        keys = {}
 
2318
        keys['texts'] = set()
 
2319
        keys['revisions'] = set()
 
2320
        keys['inventories'] = set()
 
2321
        keys['chk_bytes'] = set()
 
2322
        keys['signatures'] = set()
 
2323
        for key in missing_keys:
 
2324
            keys[key[0]].add(key[1:])
 
2325
        if len(keys['revisions']):
 
2326
            # If we allowed copying revisions at this point, we could end up
 
2327
            # copying a revision without copying its required texts: a
 
2328
            # violation of the requirements for repository integrity.
 
2329
            raise AssertionError(
 
2330
                'cannot copy revisions to fill in missing deltas %s' % (
 
2331
                    keys['revisions'],))
 
2332
        for substream_kind, keys in keys.iteritems():
 
2333
            vf = getattr(self.from_repository, substream_kind)
 
2334
            if vf is None and keys:
 
2335
                    raise AssertionError(
 
2336
                        "cannot fill in keys for a versioned file we don't"
 
2337
                        " have: %s needs %s" % (substream_kind, keys))
 
2338
            if not keys:
 
2339
                # No need to stream something we don't have
 
2340
                continue
 
2341
            if substream_kind == 'inventories':
 
2342
                # Some missing keys are genuinely ghosts, filter those out.
 
2343
                present = self.from_repository.inventories.get_parent_map(keys)
 
2344
                revs = [key[0] for key in present]
 
2345
                # Get the inventory stream more-or-less as we do for the
 
2346
                # original stream; there's no reason to assume that records
 
2347
                # direct from the source will be suitable for the sink.  (Think
 
2348
                # e.g. 2a -> 1.9-rich-root).
 
2349
                for info in self._get_inventory_stream(revs, missing=True):
 
2350
                    yield info
 
2351
                continue
 
2352
 
 
2353
            # Ask for full texts always so that we don't need more round trips
 
2354
            # after this stream.
 
2355
            # Some of the missing keys are genuinely ghosts, so filter absent
 
2356
            # records. The Sink is responsible for doing another check to
 
2357
            # ensure that ghosts don't introduce missing data for future
 
2358
            # fetches.
 
2359
            stream = versionedfile.filter_absent(vf.get_record_stream(keys,
 
2360
                self.to_format._fetch_order, True))
 
2361
            yield substream_kind, stream
 
2362
 
 
2363
    def inventory_fetch_order(self):
 
2364
        if self._rich_root_upgrade():
 
2365
            return 'topological'
 
2366
        else:
 
2367
            return self.to_format._fetch_order
 
2368
 
 
2369
    def _rich_root_upgrade(self):
 
2370
        return (not self.from_repository._format.rich_root_data and
 
2371
            self.to_format.rich_root_data)
 
2372
 
 
2373
    def _get_inventory_stream(self, revision_ids, missing=False):
 
2374
        from_format = self.from_repository._format
 
2375
        if (from_format.supports_chks and self.to_format.supports_chks and
 
2376
            from_format.network_name() == self.to_format.network_name()):
 
2377
            raise AssertionError(
 
2378
                "this case should be handled by GroupCHKStreamSource")
 
2379
        elif 'forceinvdeltas' in debug.debug_flags:
 
2380
            return self._get_convertable_inventory_stream(revision_ids,
 
2381
                    delta_versus_null=missing)
 
2382
        elif from_format.network_name() == self.to_format.network_name():
 
2383
            # Same format.
 
2384
            return self._get_simple_inventory_stream(revision_ids,
 
2385
                    missing=missing)
 
2386
        elif (not from_format.supports_chks and not self.to_format.supports_chks
 
2387
                and from_format._serializer == self.to_format._serializer):
 
2388
            # Essentially the same format.
 
2389
            return self._get_simple_inventory_stream(revision_ids,
 
2390
                    missing=missing)
 
2391
        else:
 
2392
            # Any time we switch serializations, we want to use an
 
2393
            # inventory-delta based approach.
 
2394
            return self._get_convertable_inventory_stream(revision_ids,
 
2395
                    delta_versus_null=missing)
 
2396
 
 
2397
    def _get_simple_inventory_stream(self, revision_ids, missing=False):
 
2398
        # NB: This currently reopens the inventory weave in source;
 
2399
        # using a single stream interface instead would avoid this.
 
2400
        from_weave = self.from_repository.inventories
 
2401
        if missing:
 
2402
            delta_closure = True
 
2403
        else:
 
2404
            delta_closure = not self.delta_on_metadata()
 
2405
        yield ('inventories', from_weave.get_record_stream(
 
2406
            [(rev_id,) for rev_id in revision_ids],
 
2407
            self.inventory_fetch_order(), delta_closure))
 
2408
 
 
2409
    def _get_convertable_inventory_stream(self, revision_ids,
 
2410
                                          delta_versus_null=False):
 
2411
        # The two formats are sufficiently different that there is no fast
 
2412
        # path, so we need to send just inventorydeltas, which any
 
2413
        # sufficiently modern client can insert into any repository.
 
2414
        # The StreamSink code expects to be able to
 
2415
        # convert on the target, so we need to put bytes-on-the-wire that can
 
2416
        # be converted.  That means inventory deltas (if the remote is <1.19,
 
2417
        # RemoteStreamSink will fallback to VFS to insert the deltas).
 
2418
        yield ('inventory-deltas',
 
2419
           self._stream_invs_as_deltas(revision_ids,
 
2420
                                       delta_versus_null=delta_versus_null))
 
2421
 
 
2422
    def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
 
2423
        """Return a stream of inventory-deltas for the given rev ids.
 
2424
 
 
2425
        :param revision_ids: The list of inventories to transmit
 
2426
        :param delta_versus_null: Don't try to find a minimal delta for this
 
2427
            entry, instead compute the delta versus the NULL_REVISION. This
 
2428
            effectively streams a complete inventory. Used for stuff like
 
2429
            filling in missing parents, etc.
 
2430
        """
 
2431
        from_repo = self.from_repository
 
2432
        revision_keys = [(rev_id,) for rev_id in revision_ids]
 
2433
        parent_map = from_repo.inventories.get_parent_map(revision_keys)
 
2434
        # XXX: possibly repos could implement a more efficient iter_inv_deltas
 
2435
        # method...
 
2436
        inventories = self.from_repository.iter_inventories(
 
2437
            revision_ids, 'topological')
 
2438
        format = from_repo._format
 
2439
        invs_sent_so_far = set([_mod_revision.NULL_REVISION])
 
2440
        inventory_cache = lru_cache.LRUCache(50)
 
2441
        null_inventory = from_repo.revision_tree(
 
2442
            _mod_revision.NULL_REVISION).inventory
 
2443
        # XXX: ideally the rich-root/tree-refs flags would be per-revision, not
 
2444
        # per-repo (e.g.  streaming a non-rich-root revision out of a rich-root
 
2445
        # repo back into a non-rich-root repo ought to be allowed)
 
2446
        serializer = inventory_delta.InventoryDeltaSerializer(
 
2447
            versioned_root=format.rich_root_data,
 
2448
            tree_references=format.supports_tree_reference)
 
2449
        for inv in inventories:
 
2450
            key = (inv.revision_id,)
 
2451
            parent_keys = parent_map.get(key, ())
 
2452
            delta = None
 
2453
            if not delta_versus_null and parent_keys:
 
2454
                # The caller did not ask for complete inventories and we have
 
2455
                # some parents that we can delta against.  Make a delta against
 
2456
                # each parent so that we can find the smallest.
 
2457
                parent_ids = [parent_key[0] for parent_key in parent_keys]
 
2458
                for parent_id in parent_ids:
 
2459
                    if parent_id not in invs_sent_so_far:
 
2460
                        # We don't know that the remote side has this basis, so
 
2461
                        # we can't use it.
 
2462
                        continue
 
2463
                    if parent_id == _mod_revision.NULL_REVISION:
 
2464
                        parent_inv = null_inventory
 
2465
                    else:
 
2466
                        parent_inv = inventory_cache.get(parent_id, None)
 
2467
                        if parent_inv is None:
 
2468
                            parent_inv = from_repo.get_inventory(parent_id)
 
2469
                    candidate_delta = inv._make_delta(parent_inv)
 
2470
                    if (delta is None or
 
2471
                        len(delta) > len(candidate_delta)):
 
2472
                        delta = candidate_delta
 
2473
                        basis_id = parent_id
 
2474
            if delta is None:
 
2475
                # Either none of the parents ended up being suitable, or we
 
2476
                # were asked to delta against NULL
 
2477
                basis_id = _mod_revision.NULL_REVISION
 
2478
                delta = inv._make_delta(null_inventory)
 
2479
            invs_sent_so_far.add(inv.revision_id)
 
2480
            inventory_cache[inv.revision_id] = inv
 
2481
            delta_serialized = ''.join(
 
2482
                serializer.delta_to_lines(basis_id, key[-1], delta))
 
2483
            yield versionedfile.FulltextContentFactory(
 
2484
                key, parent_keys, None, delta_serialized)
 
2485
 
 
2486
 
 
2487
class _VersionedFileChecker(object):
 
2488
 
 
2489
    def __init__(self, repository, text_key_references=None, ancestors=None):
 
2490
        self.repository = repository
 
2491
        self.text_index = self.repository._generate_text_key_index(
 
2492
            text_key_references=text_key_references, ancestors=ancestors)
 
2493
 
 
2494
    def calculate_file_version_parents(self, text_key):
 
2495
        """Calculate the correct parents for a file version according to
 
2496
        the inventories.
 
2497
        """
 
2498
        parent_keys = self.text_index[text_key]
 
2499
        if parent_keys == [_mod_revision.NULL_REVISION]:
 
2500
            return ()
 
2501
        return tuple(parent_keys)
 
2502
 
 
2503
    def check_file_version_parents(self, texts, progress_bar=None):
 
2504
        """Check the parents stored in a versioned file are correct.
 
2505
 
 
2506
        It also detects file versions that are not referenced by their
 
2507
        corresponding revision's inventory.
 
2508
 
 
2509
        :returns: A tuple of (wrong_parents, dangling_file_versions).
 
2510
            wrong_parents is a dict mapping {revision_id: (stored_parents,
 
2511
            correct_parents)} for each revision_id where the stored parents
 
2512
            are not correct.  dangling_file_versions is a set of (file_id,
 
2513
            revision_id) tuples for versions that are present in this versioned
 
2514
            file, but not used by the corresponding inventory.
 
2515
        """
 
2516
        local_progress = None
 
2517
        if progress_bar is None:
 
2518
            local_progress = ui.ui_factory.nested_progress_bar()
 
2519
            progress_bar = local_progress
 
2520
        try:
 
2521
            return self._check_file_version_parents(texts, progress_bar)
 
2522
        finally:
 
2523
            if local_progress:
 
2524
                local_progress.finished()
 
2525
 
 
2526
    def _check_file_version_parents(self, texts, progress_bar):
 
2527
        """See check_file_version_parents."""
 
2528
        wrong_parents = {}
 
2529
        self.file_ids = set([file_id for file_id, _ in
 
2530
            self.text_index.iterkeys()])
 
2531
        # text keys is now grouped by file_id
 
2532
        n_versions = len(self.text_index)
 
2533
        progress_bar.update(gettext('loading text store'), 0, n_versions)
 
2534
        parent_map = self.repository.texts.get_parent_map(self.text_index)
 
2535
        # On unlistable transports this could well be empty/error...
 
2536
        text_keys = self.repository.texts.keys()
 
2537
        unused_keys = frozenset(text_keys) - set(self.text_index)
 
2538
        for num, key in enumerate(self.text_index.iterkeys()):
 
2539
            progress_bar.update(gettext('checking text graph'), num, n_versions)
 
2540
            correct_parents = self.calculate_file_version_parents(key)
 
2541
            try:
 
2542
                knit_parents = parent_map[key]
 
2543
            except errors.RevisionNotPresent:
 
2544
                # Missing text!
 
2545
                knit_parents = None
 
2546
            if correct_parents != knit_parents:
 
2547
                wrong_parents[key] = (knit_parents, correct_parents)
 
2548
        return wrong_parents, unused_keys
 
2549
 
 
2550
 
 
2551
class InterVersionedFileRepository(InterRepository):
 
2552
 
 
2553
    _walk_to_common_revisions_batch_size = 50
 
2554
 
 
2555
    supports_fetch_spec = True
 
2556
 
 
2557
    @needs_write_lock
 
2558
    def fetch(self, revision_id=None, find_ghosts=False,
 
2559
            fetch_spec=None):
 
2560
        """Fetch the content required to construct revision_id.
 
2561
 
 
2562
        The content is copied from self.source to self.target.
 
2563
 
 
2564
        :param revision_id: if None all content is copied, if NULL_REVISION no
 
2565
                            content is copied.
 
2566
        :return: None.
 
2567
        """
 
2568
        if self.target._format.experimental:
 
2569
            ui.ui_factory.show_user_warning('experimental_format_fetch',
 
2570
                from_format=self.source._format,
 
2571
                to_format=self.target._format)
 
2572
        from bzrlib.fetch import RepoFetcher
 
2573
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
2574
        if self.source._format.network_name() != self.target._format.network_name():
 
2575
            ui.ui_factory.show_user_warning('cross_format_fetch',
 
2576
                from_format=self.source._format,
 
2577
                to_format=self.target._format)
 
2578
        f = RepoFetcher(to_repository=self.target,
 
2579
                               from_repository=self.source,
 
2580
                               last_revision=revision_id,
 
2581
                               fetch_spec=fetch_spec,
 
2582
                               find_ghosts=find_ghosts)
 
2583
 
 
2584
    def _walk_to_common_revisions(self, revision_ids, if_present_ids=None):
 
2585
        """Walk out from revision_ids in source to revisions target has.
 
2586
 
 
2587
        :param revision_ids: The start point for the search.
 
2588
        :return: A set of revision ids.
 
2589
        """
 
2590
        target_graph = self.target.get_graph()
 
2591
        revision_ids = frozenset(revision_ids)
 
2592
        if if_present_ids:
 
2593
            all_wanted_revs = revision_ids.union(if_present_ids)
 
2594
        else:
 
2595
            all_wanted_revs = revision_ids
 
2596
        missing_revs = set()
 
2597
        source_graph = self.source.get_graph()
 
2598
        # ensure we don't pay silly lookup costs.
 
2599
        searcher = source_graph._make_breadth_first_searcher(all_wanted_revs)
 
2600
        null_set = frozenset([_mod_revision.NULL_REVISION])
 
2601
        searcher_exhausted = False
 
2602
        while True:
 
2603
            next_revs = set()
 
2604
            ghosts = set()
 
2605
            # Iterate the searcher until we have enough next_revs
 
2606
            while len(next_revs) < self._walk_to_common_revisions_batch_size:
 
2607
                try:
 
2608
                    next_revs_part, ghosts_part = searcher.next_with_ghosts()
 
2609
                    next_revs.update(next_revs_part)
 
2610
                    ghosts.update(ghosts_part)
 
2611
                except StopIteration:
 
2612
                    searcher_exhausted = True
 
2613
                    break
 
2614
            # If there are ghosts in the source graph, and the caller asked for
 
2615
            # them, make sure that they are present in the target.
 
2616
            # We don't care about other ghosts as we can't fetch them and
 
2617
            # haven't been asked to.
 
2618
            ghosts_to_check = set(revision_ids.intersection(ghosts))
 
2619
            revs_to_get = set(next_revs).union(ghosts_to_check)
 
2620
            if revs_to_get:
 
2621
                have_revs = set(target_graph.get_parent_map(revs_to_get))
 
2622
                # we always have NULL_REVISION present.
 
2623
                have_revs = have_revs.union(null_set)
 
2624
                # Check if the target is missing any ghosts we need.
 
2625
                ghosts_to_check.difference_update(have_revs)
 
2626
                if ghosts_to_check:
 
2627
                    # One of the caller's revision_ids is a ghost in both the
 
2628
                    # source and the target.
 
2629
                    raise errors.NoSuchRevision(
 
2630
                        self.source, ghosts_to_check.pop())
 
2631
                missing_revs.update(next_revs - have_revs)
 
2632
                # Because we may have walked past the original stop point, make
 
2633
                # sure everything is stopped
 
2634
                stop_revs = searcher.find_seen_ancestors(have_revs)
 
2635
                searcher.stop_searching_any(stop_revs)
 
2636
            if searcher_exhausted:
 
2637
                break
 
2638
        (started_keys, excludes, included_keys) = searcher.get_state()
 
2639
        return vf_search.SearchResult(started_keys, excludes,
 
2640
            len(included_keys), included_keys)
 
2641
 
 
2642
    @needs_read_lock
 
2643
    def search_missing_revision_ids(self,
 
2644
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
 
2645
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
2646
            limit=None):
 
2647
        """Return the revision ids that source has that target does not.
 
2648
 
 
2649
        :param revision_id: only return revision ids included by this
 
2650
            revision_id.
 
2651
        :param revision_ids: return revision ids included by these
 
2652
            revision_ids.  NoSuchRevision will be raised if any of these
 
2653
            revisions are not present.
 
2654
        :param if_present_ids: like revision_ids, but will not cause
 
2655
            NoSuchRevision if any of these are absent, instead they will simply
 
2656
            not be in the result.  This is useful for e.g. finding revisions
 
2657
            to fetch for tags, which may reference absent revisions.
 
2658
        :param find_ghosts: If True find missing revisions in deep history
 
2659
            rather than just finding the surface difference.
 
2660
        :return: A bzrlib.graph.SearchResult.
 
2661
        """
 
2662
        if symbol_versioning.deprecated_passed(revision_id):
 
2663
            symbol_versioning.warn(
 
2664
                'search_missing_revision_ids(revision_id=...) was '
 
2665
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
 
2666
                DeprecationWarning, stacklevel=2)
 
2667
            if revision_ids is not None:
 
2668
                raise AssertionError(
 
2669
                    'revision_ids is mutually exclusive with revision_id')
 
2670
            if revision_id is not None:
 
2671
                revision_ids = [revision_id]
 
2672
        del revision_id
 
2673
        # stop searching at found target revisions.
 
2674
        if not find_ghosts and (revision_ids is not None or if_present_ids is
 
2675
                not None):
 
2676
            result = self._walk_to_common_revisions(revision_ids,
 
2677
                    if_present_ids=if_present_ids)
 
2678
            if limit is None:
 
2679
                return result
 
2680
            result_set = result.get_keys()
 
2681
        else:
 
2682
            # generic, possibly worst case, slow code path.
 
2683
            target_ids = set(self.target.all_revision_ids())
 
2684
            source_ids = self._present_source_revisions_for(
 
2685
                revision_ids, if_present_ids)
 
2686
            result_set = set(source_ids).difference(target_ids)
 
2687
        if limit is not None:
 
2688
            topo_ordered = self.source.get_graph().iter_topo_order(result_set)
 
2689
            result_set = set(itertools.islice(topo_ordered, limit))
 
2690
        return self.source.revision_ids_to_search_result(result_set)
 
2691
 
 
2692
    def _present_source_revisions_for(self, revision_ids, if_present_ids=None):
 
2693
        """Returns set of all revisions in ancestry of revision_ids present in
 
2694
        the source repo.
 
2695
 
 
2696
        :param revision_ids: if None, all revisions in source are returned.
 
2697
        :param if_present_ids: like revision_ids, but if any/all of these are
 
2698
            absent no error is raised.
 
2699
        """
 
2700
        if revision_ids is not None or if_present_ids is not None:
 
2701
            # First, ensure all specified revisions exist.  Callers expect
 
2702
            # NoSuchRevision when they pass absent revision_ids here.
 
2703
            if revision_ids is None:
 
2704
                revision_ids = set()
 
2705
            if if_present_ids is None:
 
2706
                if_present_ids = set()
 
2707
            revision_ids = set(revision_ids)
 
2708
            if_present_ids = set(if_present_ids)
 
2709
            all_wanted_ids = revision_ids.union(if_present_ids)
 
2710
            graph = self.source.get_graph()
 
2711
            present_revs = set(graph.get_parent_map(all_wanted_ids))
 
2712
            missing = revision_ids.difference(present_revs)
 
2713
            if missing:
 
2714
                raise errors.NoSuchRevision(self.source, missing.pop())
 
2715
            found_ids = all_wanted_ids.intersection(present_revs)
 
2716
            source_ids = [rev_id for (rev_id, parents) in
 
2717
                          graph.iter_ancestry(found_ids)
 
2718
                          if rev_id != _mod_revision.NULL_REVISION
 
2719
                          and parents is not None]
 
2720
        else:
 
2721
            source_ids = self.source.all_revision_ids()
 
2722
        return set(source_ids)
 
2723
 
 
2724
    @classmethod
 
2725
    def _get_repo_format_to_test(self):
 
2726
        return None
 
2727
 
 
2728
    @classmethod
 
2729
    def is_compatible(cls, source, target):
 
2730
        # The default implementation is compatible with everything
 
2731
        return (source._format.supports_full_versioned_files and
 
2732
                target._format.supports_full_versioned_files)
 
2733
 
 
2734
 
 
2735
class InterDifferingSerializer(InterVersionedFileRepository):
 
2736
 
 
2737
    @classmethod
 
2738
    def _get_repo_format_to_test(self):
 
2739
        return None
 
2740
 
 
2741
    @staticmethod
 
2742
    def is_compatible(source, target):
 
2743
        if not source._format.supports_full_versioned_files:
 
2744
            return False
 
2745
        if not target._format.supports_full_versioned_files:
 
2746
            return False
 
2747
        # This is redundant with format.check_conversion_target(), however that
 
2748
        # raises an exception, and we just want to say "False" as in we won't
 
2749
        # support converting between these formats.
 
2750
        if 'IDS_never' in debug.debug_flags:
 
2751
            return False
 
2752
        if source.supports_rich_root() and not target.supports_rich_root():
 
2753
            return False
 
2754
        if (source._format.supports_tree_reference
 
2755
            and not target._format.supports_tree_reference):
 
2756
            return False
 
2757
        if target._fallback_repositories and target._format.supports_chks:
 
2758
            # IDS doesn't know how to copy CHKs for the parent inventories it
 
2759
            # adds to stacked repos.
 
2760
            return False
 
2761
        if 'IDS_always' in debug.debug_flags:
 
2762
            return True
 
2763
        # Only use this code path for local source and target.  IDS does far
 
2764
        # too much IO (both bandwidth and roundtrips) over a network.
 
2765
        if not source.bzrdir.transport.base.startswith('file:///'):
 
2766
            return False
 
2767
        if not target.bzrdir.transport.base.startswith('file:///'):
 
2768
            return False
 
2769
        return True
 
2770
 
 
2771
    def _get_trees(self, revision_ids, cache):
 
2772
        possible_trees = []
 
2773
        for rev_id in revision_ids:
 
2774
            if rev_id in cache:
 
2775
                possible_trees.append((rev_id, cache[rev_id]))
 
2776
            else:
 
2777
                # Not cached, but inventory might be present anyway.
 
2778
                try:
 
2779
                    tree = self.source.revision_tree(rev_id)
 
2780
                except errors.NoSuchRevision:
 
2781
                    # Nope, parent is ghost.
 
2782
                    pass
 
2783
                else:
 
2784
                    cache[rev_id] = tree
 
2785
                    possible_trees.append((rev_id, tree))
 
2786
        return possible_trees
 
2787
 
 
2788
    def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
 
2789
        """Get the best delta and base for this revision.
 
2790
 
 
2791
        :return: (basis_id, delta)
 
2792
        """
 
2793
        deltas = []
 
2794
        # Generate deltas against each tree, to find the shortest.
 
2795
        texts_possibly_new_in_tree = set()
 
2796
        for basis_id, basis_tree in possible_trees:
 
2797
            delta = tree.inventory._make_delta(basis_tree.inventory)
 
2798
            for old_path, new_path, file_id, new_entry in delta:
 
2799
                if new_path is None:
 
2800
                    # This file_id isn't present in the new rev, so we don't
 
2801
                    # care about it.
 
2802
                    continue
 
2803
                if not new_path:
 
2804
                    # Rich roots are handled elsewhere...
 
2805
                    continue
 
2806
                kind = new_entry.kind
 
2807
                if kind != 'directory' and kind != 'file':
 
2808
                    # No text record associated with this inventory entry.
 
2809
                    continue
 
2810
                # This is a directory or file that has changed somehow.
 
2811
                texts_possibly_new_in_tree.add((file_id, new_entry.revision))
 
2812
            deltas.append((len(delta), basis_id, delta))
 
2813
        deltas.sort()
 
2814
        return deltas[0][1:]
 
2815
 
 
2816
    def _fetch_parent_invs_for_stacking(self, parent_map, cache):
 
2817
        """Find all parent revisions that are absent, but for which the
 
2818
        inventory is present, and copy those inventories.
 
2819
 
 
2820
        This is necessary to preserve correctness when the source is stacked
 
2821
        without fallbacks configured.  (Note that in cases like upgrade the
 
2822
        source may be not have _fallback_repositories even though it is
 
2823
        stacked.)
 
2824
        """
 
2825
        parent_revs = set()
 
2826
        for parents in parent_map.values():
 
2827
            parent_revs.update(parents)
 
2828
        present_parents = self.source.get_parent_map(parent_revs)
 
2829
        absent_parents = set(parent_revs).difference(present_parents)
 
2830
        parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
 
2831
            (rev_id,) for rev_id in absent_parents)
 
2832
        parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
 
2833
        for parent_tree in self.source.revision_trees(parent_inv_ids):
 
2834
            current_revision_id = parent_tree.get_revision_id()
 
2835
            parents_parents_keys = parent_invs_keys_for_stacking[
 
2836
                (current_revision_id,)]
 
2837
            parents_parents = [key[-1] for key in parents_parents_keys]
 
2838
            basis_id = _mod_revision.NULL_REVISION
 
2839
            basis_tree = self.source.revision_tree(basis_id)
 
2840
            delta = parent_tree.inventory._make_delta(basis_tree.inventory)
 
2841
            self.target.add_inventory_by_delta(
 
2842
                basis_id, delta, current_revision_id, parents_parents)
 
2843
            cache[current_revision_id] = parent_tree
 
2844
 
 
2845
    def _fetch_batch(self, revision_ids, basis_id, cache):
 
2846
        """Fetch across a few revisions.
 
2847
 
 
2848
        :param revision_ids: The revisions to copy
 
2849
        :param basis_id: The revision_id of a tree that must be in cache, used
 
2850
            as a basis for delta when no other base is available
 
2851
        :param cache: A cache of RevisionTrees that we can use.
 
2852
        :return: The revision_id of the last converted tree. The RevisionTree
 
2853
            for it will be in cache
 
2854
        """
 
2855
        # Walk though all revisions; get inventory deltas, copy referenced
 
2856
        # texts that delta references, insert the delta, revision and
 
2857
        # signature.
 
2858
        root_keys_to_create = set()
 
2859
        text_keys = set()
 
2860
        pending_deltas = []
 
2861
        pending_revisions = []
 
2862
        parent_map = self.source.get_parent_map(revision_ids)
 
2863
        self._fetch_parent_invs_for_stacking(parent_map, cache)
 
2864
        self.source._safe_to_return_from_cache = True
 
2865
        for tree in self.source.revision_trees(revision_ids):
 
2866
            # Find a inventory delta for this revision.
 
2867
            # Find text entries that need to be copied, too.
 
2868
            current_revision_id = tree.get_revision_id()
 
2869
            parent_ids = parent_map.get(current_revision_id, ())
 
2870
            parent_trees = self._get_trees(parent_ids, cache)
 
2871
            possible_trees = list(parent_trees)
 
2872
            if len(possible_trees) == 0:
 
2873
                # There either aren't any parents, or the parents are ghosts,
 
2874
                # so just use the last converted tree.
 
2875
                possible_trees.append((basis_id, cache[basis_id]))
 
2876
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
 
2877
                                                           possible_trees)
 
2878
            revision = self.source.get_revision(current_revision_id)
 
2879
            pending_deltas.append((basis_id, delta,
 
2880
                current_revision_id, revision.parent_ids))
 
2881
            if self._converting_to_rich_root:
 
2882
                self._revision_id_to_root_id[current_revision_id] = \
 
2883
                    tree.get_root_id()
 
2884
            # Determine which texts are in present in this revision but not in
 
2885
            # any of the available parents.
 
2886
            texts_possibly_new_in_tree = set()
 
2887
            for old_path, new_path, file_id, entry in delta:
 
2888
                if new_path is None:
 
2889
                    # This file_id isn't present in the new rev
 
2890
                    continue
 
2891
                if not new_path:
 
2892
                    # This is the root
 
2893
                    if not self.target.supports_rich_root():
 
2894
                        # The target doesn't support rich root, so we don't
 
2895
                        # copy
 
2896
                        continue
 
2897
                    if self._converting_to_rich_root:
 
2898
                        # This can't be copied normally, we have to insert
 
2899
                        # it specially
 
2900
                        root_keys_to_create.add((file_id, entry.revision))
 
2901
                        continue
 
2902
                kind = entry.kind
 
2903
                texts_possibly_new_in_tree.add((file_id, entry.revision))
 
2904
            for basis_id, basis_tree in possible_trees:
 
2905
                basis_inv = basis_tree.inventory
 
2906
                for file_key in list(texts_possibly_new_in_tree):
 
2907
                    file_id, file_revision = file_key
 
2908
                    try:
 
2909
                        entry = basis_inv[file_id]
 
2910
                    except errors.NoSuchId:
 
2911
                        continue
 
2912
                    if entry.revision == file_revision:
 
2913
                        texts_possibly_new_in_tree.remove(file_key)
 
2914
            text_keys.update(texts_possibly_new_in_tree)
 
2915
            pending_revisions.append(revision)
 
2916
            cache[current_revision_id] = tree
 
2917
            basis_id = current_revision_id
 
2918
        self.source._safe_to_return_from_cache = False
 
2919
        # Copy file texts
 
2920
        from_texts = self.source.texts
 
2921
        to_texts = self.target.texts
 
2922
        if root_keys_to_create:
 
2923
            root_stream = _mod_fetch._new_root_data_stream(
 
2924
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
 
2925
                self.source)
 
2926
            to_texts.insert_record_stream(root_stream)
 
2927
        to_texts.insert_record_stream(from_texts.get_record_stream(
 
2928
            text_keys, self.target._format._fetch_order,
 
2929
            not self.target._format._fetch_uses_deltas))
 
2930
        # insert inventory deltas
 
2931
        for delta in pending_deltas:
 
2932
            self.target.add_inventory_by_delta(*delta)
 
2933
        if self.target._fallback_repositories:
 
2934
            # Make sure this stacked repository has all the parent inventories
 
2935
            # for the new revisions that we are about to insert.  We do this
 
2936
            # before adding the revisions so that no revision is added until
 
2937
            # all the inventories it may depend on are added.
 
2938
            # Note that this is overzealous, as we may have fetched these in an
 
2939
            # earlier batch.
 
2940
            parent_ids = set()
 
2941
            revision_ids = set()
 
2942
            for revision in pending_revisions:
 
2943
                revision_ids.add(revision.revision_id)
 
2944
                parent_ids.update(revision.parent_ids)
 
2945
            parent_ids.difference_update(revision_ids)
 
2946
            parent_ids.discard(_mod_revision.NULL_REVISION)
 
2947
            parent_map = self.source.get_parent_map(parent_ids)
 
2948
            # we iterate over parent_map and not parent_ids because we don't
 
2949
            # want to try copying any revision which is a ghost
 
2950
            for parent_tree in self.source.revision_trees(parent_map):
 
2951
                current_revision_id = parent_tree.get_revision_id()
 
2952
                parents_parents = parent_map[current_revision_id]
 
2953
                possible_trees = self._get_trees(parents_parents, cache)
 
2954
                if len(possible_trees) == 0:
 
2955
                    # There either aren't any parents, or the parents are
 
2956
                    # ghosts, so just use the last converted tree.
 
2957
                    possible_trees.append((basis_id, cache[basis_id]))
 
2958
                basis_id, delta = self._get_delta_for_revision(parent_tree,
 
2959
                    parents_parents, possible_trees)
 
2960
                self.target.add_inventory_by_delta(
 
2961
                    basis_id, delta, current_revision_id, parents_parents)
 
2962
        # insert signatures and revisions
 
2963
        for revision in pending_revisions:
 
2964
            try:
 
2965
                signature = self.source.get_signature_text(
 
2966
                    revision.revision_id)
 
2967
                self.target.add_signature_text(revision.revision_id,
 
2968
                    signature)
 
2969
            except errors.NoSuchRevision:
 
2970
                pass
 
2971
            self.target.add_revision(revision.revision_id, revision)
 
2972
        return basis_id
 
2973
 
 
2974
    def _fetch_all_revisions(self, revision_ids, pb):
 
2975
        """Fetch everything for the list of revisions.
 
2976
 
 
2977
        :param revision_ids: The list of revisions to fetch. Must be in
 
2978
            topological order.
 
2979
        :param pb: A ProgressTask
 
2980
        :return: None
 
2981
        """
 
2982
        basis_id, basis_tree = self._get_basis(revision_ids[0])
 
2983
        batch_size = 100
 
2984
        cache = lru_cache.LRUCache(100)
 
2985
        cache[basis_id] = basis_tree
 
2986
        del basis_tree # We don't want to hang on to it here
 
2987
        hints = []
 
2988
        a_graph = None
 
2989
 
 
2990
        for offset in range(0, len(revision_ids), batch_size):
 
2991
            self.target.start_write_group()
 
2992
            try:
 
2993
                pb.update(gettext('Transferring revisions'), offset,
 
2994
                          len(revision_ids))
 
2995
                batch = revision_ids[offset:offset+batch_size]
 
2996
                basis_id = self._fetch_batch(batch, basis_id, cache)
 
2997
            except:
 
2998
                self.source._safe_to_return_from_cache = False
 
2999
                self.target.abort_write_group()
 
3000
                raise
 
3001
            else:
 
3002
                hint = self.target.commit_write_group()
 
3003
                if hint:
 
3004
                    hints.extend(hint)
 
3005
        if hints and self.target._format.pack_compresses:
 
3006
            self.target.pack(hint=hints)
 
3007
        pb.update(gettext('Transferring revisions'), len(revision_ids),
 
3008
                  len(revision_ids))
 
3009
 
 
3010
    @needs_write_lock
 
3011
    def fetch(self, revision_id=None, find_ghosts=False,
 
3012
            fetch_spec=None):
 
3013
        """See InterRepository.fetch()."""
 
3014
        if fetch_spec is not None:
 
3015
            revision_ids = fetch_spec.get_keys()
 
3016
        else:
 
3017
            revision_ids = None
 
3018
        if self.source._format.experimental:
 
3019
            ui.ui_factory.show_user_warning('experimental_format_fetch',
 
3020
                from_format=self.source._format,
 
3021
                to_format=self.target._format)
 
3022
        if (not self.source.supports_rich_root()
 
3023
            and self.target.supports_rich_root()):
 
3024
            self._converting_to_rich_root = True
 
3025
            self._revision_id_to_root_id = {}
 
3026
        else:
 
3027
            self._converting_to_rich_root = False
 
3028
        # See <https://launchpad.net/bugs/456077> asking for a warning here
 
3029
        if self.source._format.network_name() != self.target._format.network_name():
 
3030
            ui.ui_factory.show_user_warning('cross_format_fetch',
 
3031
                from_format=self.source._format,
 
3032
                to_format=self.target._format)
 
3033
        if revision_ids is None:
 
3034
            if revision_id:
 
3035
                search_revision_ids = [revision_id]
 
3036
            else:
 
3037
                search_revision_ids = None
 
3038
            revision_ids = self.target.search_missing_revision_ids(self.source,
 
3039
                revision_ids=search_revision_ids,
 
3040
                find_ghosts=find_ghosts).get_keys()
 
3041
        if not revision_ids:
 
3042
            return 0, 0
 
3043
        revision_ids = tsort.topo_sort(
 
3044
            self.source.get_graph().get_parent_map(revision_ids))
 
3045
        if not revision_ids:
 
3046
            return 0, 0
 
3047
        # Walk though all revisions; get inventory deltas, copy referenced
 
3048
        # texts that delta references, insert the delta, revision and
 
3049
        # signature.
 
3050
        pb = ui.ui_factory.nested_progress_bar()
 
3051
        try:
 
3052
            self._fetch_all_revisions(revision_ids, pb)
 
3053
        finally:
 
3054
            pb.finished()
 
3055
        return len(revision_ids), 0
 
3056
 
 
3057
    def _get_basis(self, first_revision_id):
 
3058
        """Get a revision and tree which exists in the target.
 
3059
 
 
3060
        This assumes that first_revision_id is selected for transmission
 
3061
        because all other ancestors are already present. If we can't find an
 
3062
        ancestor we fall back to NULL_REVISION since we know that is safe.
 
3063
 
 
3064
        :return: (basis_id, basis_tree)
 
3065
        """
 
3066
        first_rev = self.source.get_revision(first_revision_id)
 
3067
        try:
 
3068
            basis_id = first_rev.parent_ids[0]
 
3069
            # only valid as a basis if the target has it
 
3070
            self.target.get_revision(basis_id)
 
3071
            # Try to get a basis tree - if it's a ghost it will hit the
 
3072
            # NoSuchRevision case.
 
3073
            basis_tree = self.source.revision_tree(basis_id)
 
3074
        except (IndexError, errors.NoSuchRevision):
 
3075
            basis_id = _mod_revision.NULL_REVISION
 
3076
            basis_tree = self.source.revision_tree(basis_id)
 
3077
        return basis_id, basis_tree
 
3078
 
 
3079
 
 
3080
class InterSameDataRepository(InterVersionedFileRepository):
 
3081
    """Code for converting between repositories that represent the same data.
 
3082
 
 
3083
    Data format and model must match for this to work.
 
3084
    """
 
3085
 
 
3086
    @classmethod
 
3087
    def _get_repo_format_to_test(self):
 
3088
        """Repository format for testing with.
 
3089
 
 
3090
        InterSameData can pull from subtree to subtree and from non-subtree to
 
3091
        non-subtree, so we test this with the richest repository format.
 
3092
        """
 
3093
        from bzrlib.repofmt import knitrepo
 
3094
        return knitrepo.RepositoryFormatKnit3()
 
3095
 
 
3096
    @staticmethod
 
3097
    def is_compatible(source, target):
 
3098
        return (
 
3099
            InterRepository._same_model(source, target) and
 
3100
            source._format.supports_full_versioned_files and
 
3101
            target._format.supports_full_versioned_files)
 
3102
 
 
3103
 
 
3104
InterRepository.register_optimiser(InterVersionedFileRepository)
 
3105
InterRepository.register_optimiser(InterDifferingSerializer)
 
3106
InterRepository.register_optimiser(InterSameDataRepository)
 
3107
 
 
3108
 
 
3109
def install_revisions(repository, iterable, num_revisions=None, pb=None):
 
3110
    """Install all revision data into a repository.
 
3111
 
 
3112
    Accepts an iterable of revision, tree, signature tuples.  The signature
 
3113
    may be None.
 
3114
    """
 
3115
    repository.start_write_group()
 
3116
    try:
 
3117
        inventory_cache = lru_cache.LRUCache(10)
 
3118
        for n, (revision, revision_tree, signature) in enumerate(iterable):
 
3119
            _install_revision(repository, revision, revision_tree, signature,
 
3120
                inventory_cache)
 
3121
            if pb is not None:
 
3122
                pb.update(gettext('Transferring revisions'), n + 1, num_revisions)
 
3123
    except:
 
3124
        repository.abort_write_group()
 
3125
        raise
 
3126
    else:
 
3127
        repository.commit_write_group()
 
3128
 
 
3129
 
 
3130
def _install_revision(repository, rev, revision_tree, signature,
 
3131
    inventory_cache):
 
3132
    """Install all revision data into a repository."""
 
3133
    present_parents = []
 
3134
    parent_trees = {}
 
3135
    for p_id in rev.parent_ids:
 
3136
        if repository.has_revision(p_id):
 
3137
            present_parents.append(p_id)
 
3138
            parent_trees[p_id] = repository.revision_tree(p_id)
 
3139
        else:
 
3140
            parent_trees[p_id] = repository.revision_tree(
 
3141
                                     _mod_revision.NULL_REVISION)
 
3142
 
 
3143
    inv = revision_tree.inventory
 
3144
    entries = inv.iter_entries()
 
3145
    # backwards compatibility hack: skip the root id.
 
3146
    if not repository.supports_rich_root():
 
3147
        path, root = entries.next()
 
3148
        if root.revision != rev.revision_id:
 
3149
            raise errors.IncompatibleRevision(repr(repository))
 
3150
    text_keys = {}
 
3151
    for path, ie in entries:
 
3152
        text_keys[(ie.file_id, ie.revision)] = ie
 
3153
    text_parent_map = repository.texts.get_parent_map(text_keys)
 
3154
    missing_texts = set(text_keys) - set(text_parent_map)
 
3155
    # Add the texts that are not already present
 
3156
    for text_key in missing_texts:
 
3157
        ie = text_keys[text_key]
 
3158
        text_parents = []
 
3159
        # FIXME: TODO: The following loop overlaps/duplicates that done by
 
3160
        # commit to determine parents. There is a latent/real bug here where
 
3161
        # the parents inserted are not those commit would do - in particular
 
3162
        # they are not filtered by heads(). RBC, AB
 
3163
        for revision, tree in parent_trees.iteritems():
 
3164
            if not tree.has_id(ie.file_id):
 
3165
                continue
 
3166
            parent_id = tree.get_file_revision(ie.file_id)
 
3167
            if parent_id in text_parents:
 
3168
                continue
 
3169
            text_parents.append((ie.file_id, parent_id))
 
3170
        lines = revision_tree.get_file(ie.file_id).readlines()
 
3171
        repository.texts.add_lines(text_key, text_parents, lines)
 
3172
    try:
 
3173
        # install the inventory
 
3174
        if repository._format._commit_inv_deltas and len(rev.parent_ids):
 
3175
            # Cache this inventory
 
3176
            inventory_cache[rev.revision_id] = inv
 
3177
            try:
 
3178
                basis_inv = inventory_cache[rev.parent_ids[0]]
 
3179
            except KeyError:
 
3180
                repository.add_inventory(rev.revision_id, inv, present_parents)
 
3181
            else:
 
3182
                delta = inv._make_delta(basis_inv)
 
3183
                repository.add_inventory_by_delta(rev.parent_ids[0], delta,
 
3184
                    rev.revision_id, present_parents)
 
3185
        else:
 
3186
            repository.add_inventory(rev.revision_id, inv, present_parents)
 
3187
    except errors.RevisionAlreadyPresent:
 
3188
        pass
 
3189
    if signature is not None:
 
3190
        repository.add_signature_text(rev.revision_id, signature)
 
3191
    repository.add_revision(rev.revision_id, rev, inv)
 
3192
 
 
3193
 
 
3194
def install_revision(repository, rev, revision_tree):
 
3195
    """Install all revision data into a repository."""
 
3196
    install_revisions(repository, [(rev, revision_tree, None)])