~bzr-pqm/bzr/bzr.dev

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