/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-10 01:57:00 UTC
  • mto: This revision was merged to the branch mainline in revision 6679.
  • Revision ID: gzlist@googlemail.com-20170610015700-o3xeuyaqry2obiay
Go back to native str for urls and many other py3 changes

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