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