/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 breezy/vf_repository.py

  • Committer: Martin
  • Date: 2017-06-05 20:48:31 UTC
  • mto: This revision was merged to the branch mainline in revision 6658.
  • Revision ID: gzlist@googlemail.com-20170605204831-20accykspjcrx0a8
Apply 2to3 dict fixer and clean up resulting mess using view helpers

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