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