/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to breezy/bzr/vf_repository.py

  • Committer: Jelmer Vernooij
  • Date: 2018-11-21 03:39:28 UTC
  • mto: This revision was merged to the branch mainline in revision 7206.
  • Revision ID: jelmer@jelmer.uk-20181121033928-ck4sb5zfdwosw35b
Fix test.

Show diffs side-by-side

added added

removed removed

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