~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repository.py

  • Committer: Vincent Ladeuil
  • Date: 2011-07-06 09:22:00 UTC
  • mfrom: (6008 +trunk)
  • mto: (6012.1.1 trunk)
  • mto: This revision was merged to the branch mainline in revision 6013.
  • Revision ID: v.ladeuil+lp@free.fr-20110706092200-7iai2mwzc0sqdsvf
MergingĀ inĀ trunk

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
from bzrlib.lazy_import import lazy_import
18
18
lazy_import(globals(), """
19
 
import cStringIO
20
 
import re
 
19
import itertools
21
20
import time
22
21
 
23
22
from bzrlib import (
24
23
    bzrdir,
25
 
    check,
26
 
    chk_map,
27
24
    config,
28
25
    controldir,
29
26
    debug,
30
 
    fetch as _mod_fetch,
31
 
    fifo_cache,
32
27
    generate_ids,
33
 
    gpg,
34
28
    graph,
35
 
    inventory,
36
 
    inventory_delta,
37
 
    lazy_regex,
38
29
    lockable_files,
39
30
    lockdir,
40
 
    lru_cache,
41
31
    osutils,
42
 
    pyutils,
43
32
    revision as _mod_revision,
44
 
    static_tuple,
45
 
    symbol_versioning,
46
 
    trace,
 
33
    testament as _mod_testament,
47
34
    tsort,
48
 
    versionedfile,
 
35
    gpg,
49
36
    )
50
37
from bzrlib.bundle import serializer
51
 
from bzrlib.revisiontree import RevisionTree
52
 
from bzrlib.store.versioned import VersionedFileStore
53
 
from bzrlib.testament import Testament
54
38
""")
55
39
 
56
 
import sys
57
40
from bzrlib import (
58
41
    errors,
59
42
    registry,
 
43
    symbol_versioning,
60
44
    ui,
61
45
    )
62
46
from bzrlib.decorators import needs_read_lock, needs_write_lock, only_raises
63
47
from bzrlib.inter import InterObject
64
 
from bzrlib.inventory import (
65
 
    Inventory,
66
 
    InventoryDirectory,
67
 
    ROOT_ID,
68
 
    entry_factory,
69
 
    )
70
 
from bzrlib.recordcounter import RecordCounter
71
48
from bzrlib.lock import _RelockDebugMixin, LogicalLockResult
72
49
from bzrlib.trace import (
73
50
    log_exception_quietly, note, mutter, mutter_callsite, warning)
94
71
 
95
72
    # all clients should supply tree roots.
96
73
    record_root_entry = True
97
 
    # the default CommitBuilder does not manage trees whose root is versioned.
98
 
    _versioned_root = False
 
74
    # whether this commit builder supports the record_entry_contents interface
 
75
    supports_record_entry_contents = False
99
76
 
100
77
    def __init__(self, repository, parents, config, timestamp=None,
101
78
                 timezone=None, committer=None, revprops=None,
102
 
                 revision_id=None):
 
79
                 revision_id=None, lossy=False):
103
80
        """Initiate a CommitBuilder.
104
81
 
105
82
        :param repository: Repository to commit to.
106
83
        :param parents: Revision ids of the parents of the new revision.
107
 
        :param config: Configuration to use.
108
84
        :param timestamp: Optional timestamp recorded for commit.
109
85
        :param timezone: Optional timezone for timestamp.
110
86
        :param committer: Optional committer to set for commit.
111
87
        :param revprops: Optional dictionary of revision properties.
112
88
        :param revision_id: Optional revision id.
 
89
        :param lossy: Whether to discard data that can not be natively
 
90
            represented, when pushing to a foreign VCS 
113
91
        """
114
92
        self._config = config
 
93
        self._lossy = lossy
115
94
 
116
95
        if committer is None:
117
96
            self._committer = self._config.username()
120
99
        else:
121
100
            self._committer = committer
122
101
 
123
 
        self.new_inventory = Inventory(None)
124
102
        self._new_revision_id = revision_id
125
103
        self.parents = parents
126
104
        self.repository = repository
141
119
            self._timezone = int(timezone)
142
120
 
143
121
        self._generate_revision_if_needed()
144
 
        self.__heads = graph.HeadsCache(repository.get_graph()).heads
145
 
        self._basis_delta = []
146
 
        # API compatibility, older code that used CommitBuilder did not call
147
 
        # .record_delete(), which means the delta that is computed would not be
148
 
        # valid. Callers that will call record_delete() should call
149
 
        # .will_record_deletes() to indicate that.
150
 
        self._recording_deletes = False
151
 
        # memo'd check for no-op commits.
152
 
        self._any_changes = False
153
122
 
154
123
    def any_changes(self):
155
124
        """Return True if any entries were changed.
156
 
        
 
125
 
157
126
        This includes merge-only changes. It is the core for the --unchanged
158
127
        detection in commit.
159
128
 
160
129
        :return: True if any changes have occured.
161
130
        """
162
 
        return self._any_changes
 
131
        raise NotImplementedError(self.any_changes)
163
132
 
164
133
    def _validate_unicode_text(self, text, context):
165
134
        """Verify things like commit messages don't have bogus characters."""
176
145
            self._validate_unicode_text(value,
177
146
                                        'revision property (%s)' % (key,))
178
147
 
179
 
    def _ensure_fallback_inventories(self):
180
 
        """Ensure that appropriate inventories are available.
181
 
 
182
 
        This only applies to repositories that are stacked, and is about
183
 
        enusring the stacking invariants. Namely, that for any revision that is
184
 
        present, we either have all of the file content, or we have the parent
185
 
        inventory and the delta file content.
186
 
        """
187
 
        if not self.repository._fallback_repositories:
188
 
            return
189
 
        if not self.repository._format.supports_chks:
190
 
            raise errors.BzrError("Cannot commit directly to a stacked branch"
191
 
                " in pre-2a formats. See "
192
 
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
193
 
        # This is a stacked repo, we need to make sure we have the parent
194
 
        # inventories for the parents.
195
 
        parent_keys = [(p,) for p in self.parents]
196
 
        parent_map = self.repository.inventories._index.get_parent_map(parent_keys)
197
 
        missing_parent_keys = set([pk for pk in parent_keys
198
 
                                       if pk not in parent_map])
199
 
        fallback_repos = list(reversed(self.repository._fallback_repositories))
200
 
        missing_keys = [('inventories', pk[0])
201
 
                        for pk in missing_parent_keys]
202
 
        resume_tokens = []
203
 
        while missing_keys and fallback_repos:
204
 
            fallback_repo = fallback_repos.pop()
205
 
            source = fallback_repo._get_source(self.repository._format)
206
 
            sink = self.repository._get_sink()
207
 
            stream = source.get_stream_for_missing_keys(missing_keys)
208
 
            missing_keys = sink.insert_stream_without_locking(stream,
209
 
                self.repository._format)
210
 
        if missing_keys:
211
 
            raise errors.BzrError('Unable to fill in parent inventories for a'
212
 
                                  ' stacked branch')
213
 
 
214
148
    def commit(self, message):
215
149
        """Make the actual commit.
216
150
 
217
151
        :return: The revision id of the recorded revision.
218
152
        """
219
 
        self._validate_unicode_text(message, 'commit message')
220
 
        rev = _mod_revision.Revision(
221
 
                       timestamp=self._timestamp,
222
 
                       timezone=self._timezone,
223
 
                       committer=self._committer,
224
 
                       message=message,
225
 
                       inventory_sha1=self.inv_sha1,
226
 
                       revision_id=self._new_revision_id,
227
 
                       properties=self._revprops)
228
 
        rev.parent_ids = self.parents
229
 
        self.repository.add_revision(self._new_revision_id, rev,
230
 
            self.new_inventory, self._config)
231
 
        self._ensure_fallback_inventories()
232
 
        self.repository.commit_write_group()
233
 
        return self._new_revision_id
 
153
        raise NotImplementedError(self.commit)
234
154
 
235
155
    def abort(self):
236
156
        """Abort the commit that is being built.
237
157
        """
238
 
        self.repository.abort_write_group()
 
158
        raise NotImplementedError(self.abort)
239
159
 
240
160
    def revision_tree(self):
241
161
        """Return the tree that was just committed.
242
162
 
243
 
        After calling commit() this can be called to get a RevisionTree
244
 
        representing the newly committed tree. This is preferred to
245
 
        calling Repository.revision_tree() because that may require
246
 
        deserializing the inventory, while we already have a copy in
 
163
        After calling commit() this can be called to get a
 
164
        RevisionTree representing the newly committed tree. This is
 
165
        preferred to calling Repository.revision_tree() because that may
 
166
        require deserializing the inventory, while we already have a copy in
247
167
        memory.
248
168
        """
249
 
        if self.new_inventory is None:
250
 
            self.new_inventory = self.repository.get_inventory(
251
 
                self._new_revision_id)
252
 
        return RevisionTree(self.repository, self.new_inventory,
253
 
            self._new_revision_id)
 
169
        raise NotImplementedError(self.revision_tree)
254
170
 
255
171
    def finish_inventory(self):
256
172
        """Tell the builder that the inventory is finished.
258
174
        :return: The inventory id in the repository, which can be used with
259
175
            repository.get_inventory.
260
176
        """
261
 
        if self.new_inventory is None:
262
 
            # an inventory delta was accumulated without creating a new
263
 
            # inventory.
264
 
            basis_id = self.basis_delta_revision
265
 
            # We ignore the 'inventory' returned by add_inventory_by_delta
266
 
            # because self.new_inventory is used to hint to the rest of the
267
 
            # system what code path was taken
268
 
            self.inv_sha1, _ = self.repository.add_inventory_by_delta(
269
 
                basis_id, self._basis_delta, self._new_revision_id,
270
 
                self.parents)
271
 
        else:
272
 
            if self.new_inventory.root is None:
273
 
                raise AssertionError('Root entry should be supplied to'
274
 
                    ' record_entry_contents, as of bzr 0.10.')
275
 
                self.new_inventory.add(InventoryDirectory(ROOT_ID, '', None))
276
 
            self.new_inventory.revision_id = self._new_revision_id
277
 
            self.inv_sha1 = self.repository.add_inventory(
278
 
                self._new_revision_id,
279
 
                self.new_inventory,
280
 
                self.parents
281
 
                )
282
 
        return self._new_revision_id
 
177
        raise NotImplementedError(self.finish_inventory)
283
178
 
284
179
    def _gen_revision_id(self):
285
180
        """Return new revision-id."""
300
195
        else:
301
196
            self.random_revid = False
302
197
 
303
 
    def _heads(self, file_id, revision_ids):
304
 
        """Calculate the graph heads for revision_ids in the graph of file_id.
305
 
 
306
 
        This can use either a per-file graph or a global revision graph as we
307
 
        have an identity relationship between the two graphs.
308
 
        """
309
 
        return self.__heads(revision_ids)
310
 
 
311
 
    def _check_root(self, ie, parent_invs, tree):
312
 
        """Helper for record_entry_contents.
313
 
 
314
 
        :param ie: An entry being added.
315
 
        :param parent_invs: The inventories of the parent revisions of the
316
 
            commit.
317
 
        :param tree: The tree that is being committed.
318
 
        """
319
 
        # In this revision format, root entries have no knit or weave When
320
 
        # serializing out to disk and back in root.revision is always
321
 
        # _new_revision_id
322
 
        ie.revision = self._new_revision_id
323
 
 
324
 
    def _require_root_change(self, tree):
325
 
        """Enforce an appropriate root object change.
326
 
 
327
 
        This is called once when record_iter_changes is called, if and only if
328
 
        the root was not in the delta calculated by record_iter_changes.
329
 
 
330
 
        :param tree: The tree which is being committed.
331
 
        """
332
 
        if len(self.parents) == 0:
333
 
            raise errors.RootMissing()
334
 
        entry = entry_factory['directory'](tree.path2id(''), '',
335
 
            None)
336
 
        entry.revision = self._new_revision_id
337
 
        self._basis_delta.append(('', '', entry.file_id, entry))
338
 
 
339
 
    def _get_delta(self, ie, basis_inv, path):
340
 
        """Get a delta against the basis inventory for ie."""
341
 
        if ie.file_id not in basis_inv:
342
 
            # add
343
 
            result = (None, path, ie.file_id, ie)
344
 
            self._basis_delta.append(result)
345
 
            return result
346
 
        elif ie != basis_inv[ie.file_id]:
347
 
            # common but altered
348
 
            # TODO: avoid tis id2path call.
349
 
            result = (basis_inv.id2path(ie.file_id), path, ie.file_id, ie)
350
 
            self._basis_delta.append(result)
351
 
            return result
352
 
        else:
353
 
            # common, unaltered
354
 
            return None
355
 
 
356
 
    def get_basis_delta(self):
357
 
        """Return the complete inventory delta versus the basis inventory.
358
 
 
359
 
        This has been built up with the calls to record_delete and
360
 
        record_entry_contents. The client must have already called
361
 
        will_record_deletes() to indicate that they will be generating a
362
 
        complete delta.
363
 
 
364
 
        :return: An inventory delta, suitable for use with apply_delta, or
365
 
            Repository.add_inventory_by_delta, etc.
366
 
        """
367
 
        if not self._recording_deletes:
368
 
            raise AssertionError("recording deletes not activated.")
369
 
        return self._basis_delta
370
 
 
371
 
    def record_delete(self, path, file_id):
372
 
        """Record that a delete occured against a basis tree.
373
 
 
374
 
        This is an optional API - when used it adds items to the basis_delta
375
 
        being accumulated by the commit builder. It cannot be called unless the
376
 
        method will_record_deletes() has been called to inform the builder that
377
 
        a delta is being supplied.
378
 
 
379
 
        :param path: The path of the thing deleted.
380
 
        :param file_id: The file id that was deleted.
381
 
        """
382
 
        if not self._recording_deletes:
383
 
            raise AssertionError("recording deletes not activated.")
384
 
        delta = (path, None, file_id, None)
385
 
        self._basis_delta.append(delta)
386
 
        self._any_changes = True
387
 
        return delta
388
 
 
389
198
    def will_record_deletes(self):
390
199
        """Tell the commit builder that deletes are being notified.
391
200
 
393
202
        commit to be valid, deletes against the basis MUST be recorded via
394
203
        builder.record_delete().
395
204
        """
396
 
        self._recording_deletes = True
397
 
        try:
398
 
            basis_id = self.parents[0]
399
 
        except IndexError:
400
 
            basis_id = _mod_revision.NULL_REVISION
401
 
        self.basis_delta_revision = basis_id
402
 
 
403
 
    def record_entry_contents(self, ie, parent_invs, path, tree,
404
 
        content_summary):
405
 
        """Record the content of ie from tree into the commit if needed.
406
 
 
407
 
        Side effect: sets ie.revision when unchanged
408
 
 
409
 
        :param ie: An inventory entry present in the commit.
410
 
        :param parent_invs: The inventories of the parent revisions of the
411
 
            commit.
412
 
        :param path: The path the entry is at in the tree.
413
 
        :param tree: The tree which contains this entry and should be used to
414
 
            obtain content.
415
 
        :param content_summary: Summary data from the tree about the paths
416
 
            content - stat, length, exec, sha/link target. This is only
417
 
            accessed when the entry has a revision of None - that is when it is
418
 
            a candidate to commit.
419
 
        :return: A tuple (change_delta, version_recorded, fs_hash).
420
 
            change_delta is an inventory_delta change for this entry against
421
 
            the basis tree of the commit, or None if no change occured against
422
 
            the basis tree.
423
 
            version_recorded is True if a new version of the entry has been
424
 
            recorded. For instance, committing a merge where a file was only
425
 
            changed on the other side will return (delta, False).
426
 
            fs_hash is either None, or the hash details for the path (currently
427
 
            a tuple of the contents sha1 and the statvalue returned by
428
 
            tree.get_file_with_stat()).
429
 
        """
430
 
        if self.new_inventory.root is None:
431
 
            if ie.parent_id is not None:
432
 
                raise errors.RootMissing()
433
 
            self._check_root(ie, parent_invs, tree)
434
 
        if ie.revision is None:
435
 
            kind = content_summary[0]
436
 
        else:
437
 
            # ie is carried over from a prior commit
438
 
            kind = ie.kind
439
 
        # XXX: repository specific check for nested tree support goes here - if
440
 
        # the repo doesn't want nested trees we skip it ?
441
 
        if (kind == 'tree-reference' and
442
 
            not self.repository._format.supports_tree_reference):
443
 
            # mismatch between commit builder logic and repository:
444
 
            # this needs the entry creation pushed down into the builder.
445
 
            raise NotImplementedError('Missing repository subtree support.')
446
 
        self.new_inventory.add(ie)
447
 
 
448
 
        # TODO: slow, take it out of the inner loop.
449
 
        try:
450
 
            basis_inv = parent_invs[0]
451
 
        except IndexError:
452
 
            basis_inv = Inventory(root_id=None)
453
 
 
454
 
        # ie.revision is always None if the InventoryEntry is considered
455
 
        # for committing. We may record the previous parents revision if the
456
 
        # content is actually unchanged against a sole head.
457
 
        if ie.revision is not None:
458
 
            if not self._versioned_root and path == '':
459
 
                # repositories that do not version the root set the root's
460
 
                # revision to the new commit even when no change occurs (more
461
 
                # specifically, they do not record a revision on the root; and
462
 
                # the rev id is assigned to the root during deserialisation -
463
 
                # this masks when a change may have occurred against the basis.
464
 
                # To match this we always issue a delta, because the revision
465
 
                # of the root will always be changing.
466
 
                if ie.file_id in basis_inv:
467
 
                    delta = (basis_inv.id2path(ie.file_id), path,
468
 
                        ie.file_id, ie)
469
 
                else:
470
 
                    # add
471
 
                    delta = (None, path, ie.file_id, ie)
472
 
                self._basis_delta.append(delta)
473
 
                return delta, False, None
474
 
            else:
475
 
                # we don't need to commit this, because the caller already
476
 
                # determined that an existing revision of this file is
477
 
                # appropriate. If it's not being considered for committing then
478
 
                # it and all its parents to the root must be unaltered so
479
 
                # no-change against the basis.
480
 
                if ie.revision == self._new_revision_id:
481
 
                    raise AssertionError("Impossible situation, a skipped "
482
 
                        "inventory entry (%r) claims to be modified in this "
483
 
                        "commit (%r).", (ie, self._new_revision_id))
484
 
                return None, False, None
485
 
        # XXX: Friction: parent_candidates should return a list not a dict
486
 
        #      so that we don't have to walk the inventories again.
487
 
        parent_candiate_entries = ie.parent_candidates(parent_invs)
488
 
        head_set = self._heads(ie.file_id, parent_candiate_entries.keys())
489
 
        heads = []
490
 
        for inv in parent_invs:
491
 
            if ie.file_id in inv:
492
 
                old_rev = inv[ie.file_id].revision
493
 
                if old_rev in head_set:
494
 
                    heads.append(inv[ie.file_id].revision)
495
 
                    head_set.remove(inv[ie.file_id].revision)
496
 
 
497
 
        store = False
498
 
        # now we check to see if we need to write a new record to the
499
 
        # file-graph.
500
 
        # We write a new entry unless there is one head to the ancestors, and
501
 
        # the kind-derived content is unchanged.
502
 
 
503
 
        # Cheapest check first: no ancestors, or more the one head in the
504
 
        # ancestors, we write a new node.
505
 
        if len(heads) != 1:
506
 
            store = True
507
 
        if not store:
508
 
            # There is a single head, look it up for comparison
509
 
            parent_entry = parent_candiate_entries[heads[0]]
510
 
            # if the non-content specific data has changed, we'll be writing a
511
 
            # node:
512
 
            if (parent_entry.parent_id != ie.parent_id or
513
 
                parent_entry.name != ie.name):
514
 
                store = True
515
 
        # now we need to do content specific checks:
516
 
        if not store:
517
 
            # if the kind changed the content obviously has
518
 
            if kind != parent_entry.kind:
519
 
                store = True
520
 
        # Stat cache fingerprint feedback for the caller - None as we usually
521
 
        # don't generate one.
522
 
        fingerprint = None
523
 
        if kind == 'file':
524
 
            if content_summary[2] is None:
525
 
                raise ValueError("Files must not have executable = None")
526
 
            if not store:
527
 
                # We can't trust a check of the file length because of content
528
 
                # filtering...
529
 
                if (# if the exec bit has changed we have to store:
530
 
                    parent_entry.executable != content_summary[2]):
531
 
                    store = True
532
 
                elif parent_entry.text_sha1 == content_summary[3]:
533
 
                    # all meta and content is unchanged (using a hash cache
534
 
                    # hit to check the sha)
535
 
                    ie.revision = parent_entry.revision
536
 
                    ie.text_size = parent_entry.text_size
537
 
                    ie.text_sha1 = parent_entry.text_sha1
538
 
                    ie.executable = parent_entry.executable
539
 
                    return self._get_delta(ie, basis_inv, path), False, None
540
 
                else:
541
 
                    # Either there is only a hash change(no hash cache entry,
542
 
                    # or same size content change), or there is no change on
543
 
                    # this file at all.
544
 
                    # Provide the parent's hash to the store layer, so that the
545
 
                    # content is unchanged we will not store a new node.
546
 
                    nostore_sha = parent_entry.text_sha1
547
 
            if store:
548
 
                # We want to record a new node regardless of the presence or
549
 
                # absence of a content change in the file.
550
 
                nostore_sha = None
551
 
            ie.executable = content_summary[2]
552
 
            file_obj, stat_value = tree.get_file_with_stat(ie.file_id, path)
553
 
            try:
554
 
                text = file_obj.read()
555
 
            finally:
556
 
                file_obj.close()
557
 
            try:
558
 
                ie.text_sha1, ie.text_size = self._add_text_to_weave(
559
 
                    ie.file_id, text, heads, nostore_sha)
560
 
                # Let the caller know we generated a stat fingerprint.
561
 
                fingerprint = (ie.text_sha1, stat_value)
562
 
            except errors.ExistingContent:
563
 
                # Turns out that the file content was unchanged, and we were
564
 
                # only going to store a new node if it was changed. Carry over
565
 
                # the entry.
566
 
                ie.revision = parent_entry.revision
567
 
                ie.text_size = parent_entry.text_size
568
 
                ie.text_sha1 = parent_entry.text_sha1
569
 
                ie.executable = parent_entry.executable
570
 
                return self._get_delta(ie, basis_inv, path), False, None
571
 
        elif kind == 'directory':
572
 
            if not store:
573
 
                # all data is meta here, nothing specific to directory, so
574
 
                # carry over:
575
 
                ie.revision = parent_entry.revision
576
 
                return self._get_delta(ie, basis_inv, path), False, None
577
 
            self._add_text_to_weave(ie.file_id, '', heads, None)
578
 
        elif kind == 'symlink':
579
 
            current_link_target = content_summary[3]
580
 
            if not store:
581
 
                # symlink target is not generic metadata, check if it has
582
 
                # changed.
583
 
                if current_link_target != parent_entry.symlink_target:
584
 
                    store = True
585
 
            if not store:
586
 
                # unchanged, carry over.
587
 
                ie.revision = parent_entry.revision
588
 
                ie.symlink_target = parent_entry.symlink_target
589
 
                return self._get_delta(ie, basis_inv, path), False, None
590
 
            ie.symlink_target = current_link_target
591
 
            self._add_text_to_weave(ie.file_id, '', heads, None)
592
 
        elif kind == 'tree-reference':
593
 
            if not store:
594
 
                if content_summary[3] != parent_entry.reference_revision:
595
 
                    store = True
596
 
            if not store:
597
 
                # unchanged, carry over.
598
 
                ie.reference_revision = parent_entry.reference_revision
599
 
                ie.revision = parent_entry.revision
600
 
                return self._get_delta(ie, basis_inv, path), False, None
601
 
            ie.reference_revision = content_summary[3]
602
 
            if ie.reference_revision is None:
603
 
                raise AssertionError("invalid content_summary for nested tree: %r"
604
 
                    % (content_summary,))
605
 
            self._add_text_to_weave(ie.file_id, '', heads, None)
606
 
        else:
607
 
            raise NotImplementedError('unknown kind')
608
 
        ie.revision = self._new_revision_id
609
 
        self._any_changes = True
610
 
        return self._get_delta(ie, basis_inv, path), True, fingerprint
611
 
 
612
 
    def record_iter_changes(self, tree, basis_revision_id, iter_changes,
613
 
        _entry_factory=entry_factory):
 
205
        raise NotImplementedError(self.will_record_deletes)
 
206
 
 
207
    def record_iter_changes(self, tree, basis_revision_id, iter_changes):
614
208
        """Record a new tree via iter_changes.
615
209
 
616
210
        :param tree: The tree to obtain text contents from for changed objects.
621
215
            to basis_revision_id. The iterator must not include any items with
622
216
            a current kind of None - missing items must be either filtered out
623
217
            or errored-on beefore record_iter_changes sees the item.
624
 
        :param _entry_factory: Private method to bind entry_factory locally for
625
 
            performance.
626
218
        :return: A generator of (file_id, relpath, fs_hash) tuples for use with
627
219
            tree._observed_sha1.
628
220
        """
629
 
        # Create an inventory delta based on deltas between all the parents and
630
 
        # deltas between all the parent inventories. We use inventory delta's 
631
 
        # between the inventory objects because iter_changes masks
632
 
        # last-changed-field only changes.
633
 
        # Working data:
634
 
        # file_id -> change map, change is fileid, paths, changed, versioneds,
635
 
        # parents, names, kinds, executables
636
 
        merged_ids = {}
637
 
        # {file_id -> revision_id -> inventory entry, for entries in parent
638
 
        # trees that are not parents[0]
639
 
        parent_entries = {}
640
 
        ghost_basis = False
641
 
        try:
642
 
            revtrees = list(self.repository.revision_trees(self.parents))
643
 
        except errors.NoSuchRevision:
644
 
            # one or more ghosts, slow path.
645
 
            revtrees = []
646
 
            for revision_id in self.parents:
647
 
                try:
648
 
                    revtrees.append(self.repository.revision_tree(revision_id))
649
 
                except errors.NoSuchRevision:
650
 
                    if not revtrees:
651
 
                        basis_revision_id = _mod_revision.NULL_REVISION
652
 
                        ghost_basis = True
653
 
                    revtrees.append(self.repository.revision_tree(
654
 
                        _mod_revision.NULL_REVISION))
655
 
        # The basis inventory from a repository 
656
 
        if revtrees:
657
 
            basis_inv = revtrees[0].inventory
658
 
        else:
659
 
            basis_inv = self.repository.revision_tree(
660
 
                _mod_revision.NULL_REVISION).inventory
661
 
        if len(self.parents) > 0:
662
 
            if basis_revision_id != self.parents[0] and not ghost_basis:
663
 
                raise Exception(
664
 
                    "arbitrary basis parents not yet supported with merges")
665
 
            for revtree in revtrees[1:]:
666
 
                for change in revtree.inventory._make_delta(basis_inv):
667
 
                    if change[1] is None:
668
 
                        # Not present in this parent.
669
 
                        continue
670
 
                    if change[2] not in merged_ids:
671
 
                        if change[0] is not None:
672
 
                            basis_entry = basis_inv[change[2]]
673
 
                            merged_ids[change[2]] = [
674
 
                                # basis revid
675
 
                                basis_entry.revision,
676
 
                                # new tree revid
677
 
                                change[3].revision]
678
 
                            parent_entries[change[2]] = {
679
 
                                # basis parent
680
 
                                basis_entry.revision:basis_entry,
681
 
                                # this parent 
682
 
                                change[3].revision:change[3],
683
 
                                }
684
 
                        else:
685
 
                            merged_ids[change[2]] = [change[3].revision]
686
 
                            parent_entries[change[2]] = {change[3].revision:change[3]}
687
 
                    else:
688
 
                        merged_ids[change[2]].append(change[3].revision)
689
 
                        parent_entries[change[2]][change[3].revision] = change[3]
690
 
        else:
691
 
            merged_ids = {}
692
 
        # Setup the changes from the tree:
693
 
        # changes maps file_id -> (change, [parent revision_ids])
694
 
        changes= {}
695
 
        for change in iter_changes:
696
 
            # This probably looks up in basis_inv way to much.
697
 
            if change[1][0] is not None:
698
 
                head_candidate = [basis_inv[change[0]].revision]
699
 
            else:
700
 
                head_candidate = []
701
 
            changes[change[0]] = change, merged_ids.get(change[0],
702
 
                head_candidate)
703
 
        unchanged_merged = set(merged_ids) - set(changes)
704
 
        # Extend the changes dict with synthetic changes to record merges of
705
 
        # texts.
706
 
        for file_id in unchanged_merged:
707
 
            # Record a merged version of these items that did not change vs the
708
 
            # basis. This can be either identical parallel changes, or a revert
709
 
            # of a specific file after a merge. The recorded content will be
710
 
            # that of the current tree (which is the same as the basis), but
711
 
            # the per-file graph will reflect a merge.
712
 
            # NB:XXX: We are reconstructing path information we had, this
713
 
            # should be preserved instead.
714
 
            # inv delta  change: (file_id, (path_in_source, path_in_target),
715
 
            #   changed_content, versioned, parent, name, kind,
716
 
            #   executable)
717
 
            try:
718
 
                basis_entry = basis_inv[file_id]
719
 
            except errors.NoSuchId:
720
 
                # a change from basis->some_parents but file_id isn't in basis
721
 
                # so was new in the merge, which means it must have changed
722
 
                # from basis -> current, and as it hasn't the add was reverted
723
 
                # by the user. So we discard this change.
724
 
                pass
725
 
            else:
726
 
                change = (file_id,
727
 
                    (basis_inv.id2path(file_id), tree.id2path(file_id)),
728
 
                    False, (True, True),
729
 
                    (basis_entry.parent_id, basis_entry.parent_id),
730
 
                    (basis_entry.name, basis_entry.name),
731
 
                    (basis_entry.kind, basis_entry.kind),
732
 
                    (basis_entry.executable, basis_entry.executable))
733
 
                changes[file_id] = (change, merged_ids[file_id])
734
 
        # changes contains tuples with the change and a set of inventory
735
 
        # candidates for the file.
736
 
        # inv delta is:
737
 
        # old_path, new_path, file_id, new_inventory_entry
738
 
        seen_root = False # Is the root in the basis delta?
739
 
        inv_delta = self._basis_delta
740
 
        modified_rev = self._new_revision_id
741
 
        for change, head_candidates in changes.values():
742
 
            if change[3][1]: # versioned in target.
743
 
                # Several things may be happening here:
744
 
                # We may have a fork in the per-file graph
745
 
                #  - record a change with the content from tree
746
 
                # We may have a change against < all trees  
747
 
                #  - carry over the tree that hasn't changed
748
 
                # We may have a change against all trees
749
 
                #  - record the change with the content from tree
750
 
                kind = change[6][1]
751
 
                file_id = change[0]
752
 
                entry = _entry_factory[kind](file_id, change[5][1],
753
 
                    change[4][1])
754
 
                head_set = self._heads(change[0], set(head_candidates))
755
 
                heads = []
756
 
                # Preserve ordering.
757
 
                for head_candidate in head_candidates:
758
 
                    if head_candidate in head_set:
759
 
                        heads.append(head_candidate)
760
 
                        head_set.remove(head_candidate)
761
 
                carried_over = False
762
 
                if len(heads) == 1:
763
 
                    # Could be a carry-over situation:
764
 
                    parent_entry_revs = parent_entries.get(file_id, None)
765
 
                    if parent_entry_revs:
766
 
                        parent_entry = parent_entry_revs.get(heads[0], None)
767
 
                    else:
768
 
                        parent_entry = None
769
 
                    if parent_entry is None:
770
 
                        # The parent iter_changes was called against is the one
771
 
                        # that is the per-file head, so any change is relevant
772
 
                        # iter_changes is valid.
773
 
                        carry_over_possible = False
774
 
                    else:
775
 
                        # could be a carry over situation
776
 
                        # A change against the basis may just indicate a merge,
777
 
                        # we need to check the content against the source of the
778
 
                        # merge to determine if it was changed after the merge
779
 
                        # or carried over.
780
 
                        if (parent_entry.kind != entry.kind or
781
 
                            parent_entry.parent_id != entry.parent_id or
782
 
                            parent_entry.name != entry.name):
783
 
                            # Metadata common to all entries has changed
784
 
                            # against per-file parent
785
 
                            carry_over_possible = False
786
 
                        else:
787
 
                            carry_over_possible = True
788
 
                        # per-type checks for changes against the parent_entry
789
 
                        # are done below.
790
 
                else:
791
 
                    # Cannot be a carry-over situation
792
 
                    carry_over_possible = False
793
 
                # Populate the entry in the delta
794
 
                if kind == 'file':
795
 
                    # XXX: There is still a small race here: If someone reverts the content of a file
796
 
                    # after iter_changes examines and decides it has changed,
797
 
                    # we will unconditionally record a new version even if some
798
 
                    # other process reverts it while commit is running (with
799
 
                    # the revert happening after iter_changes did its
800
 
                    # examination).
801
 
                    if change[7][1]:
802
 
                        entry.executable = True
803
 
                    else:
804
 
                        entry.executable = False
805
 
                    if (carry_over_possible and
806
 
                        parent_entry.executable == entry.executable):
807
 
                            # Check the file length, content hash after reading
808
 
                            # the file.
809
 
                            nostore_sha = parent_entry.text_sha1
810
 
                    else:
811
 
                        nostore_sha = None
812
 
                    file_obj, stat_value = tree.get_file_with_stat(file_id, change[1][1])
813
 
                    try:
814
 
                        text = file_obj.read()
815
 
                    finally:
816
 
                        file_obj.close()
817
 
                    try:
818
 
                        entry.text_sha1, entry.text_size = self._add_text_to_weave(
819
 
                            file_id, text, heads, nostore_sha)
820
 
                        yield file_id, change[1][1], (entry.text_sha1, stat_value)
821
 
                    except errors.ExistingContent:
822
 
                        # No content change against a carry_over parent
823
 
                        # Perhaps this should also yield a fs hash update?
824
 
                        carried_over = True
825
 
                        entry.text_size = parent_entry.text_size
826
 
                        entry.text_sha1 = parent_entry.text_sha1
827
 
                elif kind == 'symlink':
828
 
                    # Wants a path hint?
829
 
                    entry.symlink_target = tree.get_symlink_target(file_id)
830
 
                    if (carry_over_possible and
831
 
                        parent_entry.symlink_target == entry.symlink_target):
832
 
                        carried_over = True
833
 
                    else:
834
 
                        self._add_text_to_weave(change[0], '', heads, None)
835
 
                elif kind == 'directory':
836
 
                    if carry_over_possible:
837
 
                        carried_over = True
838
 
                    else:
839
 
                        # Nothing to set on the entry.
840
 
                        # XXX: split into the Root and nonRoot versions.
841
 
                        if change[1][1] != '' or self.repository.supports_rich_root():
842
 
                            self._add_text_to_weave(change[0], '', heads, None)
843
 
                elif kind == 'tree-reference':
844
 
                    if not self.repository._format.supports_tree_reference:
845
 
                        # This isn't quite sane as an error, but we shouldn't
846
 
                        # ever see this code path in practice: tree's don't
847
 
                        # permit references when the repo doesn't support tree
848
 
                        # references.
849
 
                        raise errors.UnsupportedOperation(tree.add_reference,
850
 
                            self.repository)
851
 
                    reference_revision = tree.get_reference_revision(change[0])
852
 
                    entry.reference_revision = reference_revision
853
 
                    if (carry_over_possible and
854
 
                        parent_entry.reference_revision == reference_revision):
855
 
                        carried_over = True
856
 
                    else:
857
 
                        self._add_text_to_weave(change[0], '', heads, None)
858
 
                else:
859
 
                    raise AssertionError('unknown kind %r' % kind)
860
 
                if not carried_over:
861
 
                    entry.revision = modified_rev
862
 
                else:
863
 
                    entry.revision = parent_entry.revision
864
 
            else:
865
 
                entry = None
866
 
            new_path = change[1][1]
867
 
            inv_delta.append((change[1][0], new_path, change[0], entry))
868
 
            if new_path == '':
869
 
                seen_root = True
870
 
        self.new_inventory = None
871
 
        if len(inv_delta):
872
 
            # This should perhaps be guarded by a check that the basis we
873
 
            # commit against is the basis for the commit and if not do a delta
874
 
            # against the basis.
875
 
            self._any_changes = True
876
 
        if not seen_root:
877
 
            # housekeeping root entry changes do not affect no-change commits.
878
 
            self._require_root_change(tree)
879
 
        self.basis_delta_revision = basis_revision_id
880
 
 
881
 
    def _add_text_to_weave(self, file_id, new_text, parents, nostore_sha):
882
 
        parent_keys = tuple([(file_id, parent) for parent in parents])
883
 
        return self.repository.texts._add_text(
884
 
            (file_id, self._new_revision_id), parent_keys, new_text,
885
 
            nostore_sha=nostore_sha, random_id=self.random_revid)[0:2]
886
 
 
887
 
 
888
 
class RootCommitBuilder(CommitBuilder):
889
 
    """This commitbuilder actually records the root id"""
890
 
 
891
 
    # the root entry gets versioned properly by this builder.
892
 
    _versioned_root = True
893
 
 
894
 
    def _check_root(self, ie, parent_invs, tree):
895
 
        """Helper for record_entry_contents.
896
 
 
897
 
        :param ie: An entry being added.
898
 
        :param parent_invs: The inventories of the parent revisions of the
899
 
            commit.
900
 
        :param tree: The tree that is being committed.
901
 
        """
902
 
 
903
 
    def _require_root_change(self, tree):
904
 
        """Enforce an appropriate root object change.
905
 
 
906
 
        This is called once when record_iter_changes is called, if and only if
907
 
        the root was not in the delta calculated by record_iter_changes.
908
 
 
909
 
        :param tree: The tree which is being committed.
910
 
        """
911
 
        # versioned roots do not change unless the tree found a change.
 
221
        raise NotImplementedError(self.record_iter_changes)
912
222
 
913
223
 
914
224
class RepositoryWriteLockResult(LogicalLockResult):
939
249
    revisions and file history.  It's normally accessed only by the Branch,
940
250
    which views a particular line of development through that history.
941
251
 
942
 
    The Repository builds on top of some byte storage facilies (the revisions,
943
 
    signatures, inventories, texts and chk_bytes attributes) and a Transport,
944
 
    which respectively provide byte storage and a means to access the (possibly
945
 
    remote) disk.
946
 
 
947
 
    The byte storage facilities are addressed via tuples, which we refer to
948
 
    as 'keys' throughout the code base. Revision_keys, inventory_keys and
949
 
    signature_keys are all 1-tuples: (revision_id,). text_keys are two-tuples:
950
 
    (file_id, revision_id). chk_bytes uses CHK keys - a 1-tuple with a single
951
 
    byte string made up of a hash identifier and a hash value.
952
 
    We use this interface because it allows low friction with the underlying
953
 
    code that implements disk indices, network encoding and other parts of
954
 
    bzrlib.
955
 
 
956
 
    :ivar revisions: A bzrlib.versionedfile.VersionedFiles instance containing
957
 
        the serialised revisions for the repository. This can be used to obtain
958
 
        revision graph information or to access raw serialised revisions.
959
 
        The result of trying to insert data into the repository via this store
960
 
        is undefined: it should be considered read-only except for implementors
961
 
        of repositories.
962
 
    :ivar signatures: A bzrlib.versionedfile.VersionedFiles instance containing
963
 
        the serialised signatures for the repository. This can be used to
964
 
        obtain access to raw serialised signatures.  The result of trying to
965
 
        insert data into the repository via this store is undefined: it should
966
 
        be considered read-only except for implementors of repositories.
967
 
    :ivar inventories: A bzrlib.versionedfile.VersionedFiles instance containing
968
 
        the serialised inventories for the repository. This can be used to
969
 
        obtain unserialised inventories.  The result of trying to insert data
970
 
        into the repository via this store is undefined: it should be
971
 
        considered read-only except for implementors of repositories.
972
 
    :ivar texts: A bzrlib.versionedfile.VersionedFiles instance containing the
973
 
        texts of files and directories for the repository. This can be used to
974
 
        obtain file texts or file graphs. Note that Repository.iter_file_bytes
975
 
        is usually a better interface for accessing file texts.
976
 
        The result of trying to insert data into the repository via this store
977
 
        is undefined: it should be considered read-only except for implementors
978
 
        of repositories.
979
 
    :ivar chk_bytes: A bzrlib.versionedfile.VersionedFiles instance containing
980
 
        any data the repository chooses to store or have indexed by its hash.
981
 
        The result of trying to insert data into the repository via this store
982
 
        is undefined: it should be considered read-only except for implementors
983
 
        of repositories.
984
 
    :ivar _transport: Transport for file access to repository, typically
985
 
        pointing to .bzr/repository.
 
252
    See VersionedFileRepository in bzrlib.vf_repository for the
 
253
    base class for most Bazaar repositories.
986
254
    """
987
255
 
988
 
    # What class to use for a CommitBuilder. Often it's simpler to change this
989
 
    # in a Repository class subclass rather than to override
990
 
    # get_commit_builder.
991
 
    _commit_builder_class = CommitBuilder
992
 
    # The search regex used by xml based repositories to determine what things
993
 
    # where changed in a single commit.
994
 
    _file_ids_altered_regex = lazy_regex.lazy_compile(
995
 
        r'file_id="(?P<file_id>[^"]+)"'
996
 
        r'.* revision="(?P<revision_id>[^"]+)"'
997
 
        )
998
 
 
999
256
    def abort_write_group(self, suppress_errors=False):
1000
257
        """Commit the contents accrued within the current write group.
1001
258
 
1044
301
 
1045
302
        :param repository: A repository.
1046
303
        """
1047
 
        if not self._format.supports_external_lookups:
1048
 
            raise errors.UnstackableRepositoryFormat(self._format, self.base)
1049
 
        if self.is_locked():
1050
 
            # This repository will call fallback.unlock() when we transition to
1051
 
            # the unlocked state, so we make sure to increment the lock count
1052
 
            repository.lock_read()
1053
 
        self._check_fallback_repository(repository)
1054
 
        self._fallback_repositories.append(repository)
1055
 
        self.texts.add_fallback_versioned_files(repository.texts)
1056
 
        self.inventories.add_fallback_versioned_files(repository.inventories)
1057
 
        self.revisions.add_fallback_versioned_files(repository.revisions)
1058
 
        self.signatures.add_fallback_versioned_files(repository.signatures)
1059
 
        if self.chk_bytes is not None:
1060
 
            self.chk_bytes.add_fallback_versioned_files(repository.chk_bytes)
 
304
        raise NotImplementedError(self.add_fallback_repository)
1061
305
 
1062
306
    def _check_fallback_repository(self, repository):
1063
307
        """Check that this repository can fallback to repository safely.
1068
312
        """
1069
313
        return InterRepository._assert_same_model(self, repository)
1070
314
 
1071
 
    def add_inventory(self, revision_id, inv, parents):
1072
 
        """Add the inventory inv to the repository as revision_id.
1073
 
 
1074
 
        :param parents: The revision ids of the parents that revision_id
1075
 
                        is known to have and are in the repository already.
1076
 
 
1077
 
        :returns: The validator(which is a sha1 digest, though what is sha'd is
1078
 
            repository format specific) of the serialized inventory.
1079
 
        """
1080
 
        if not self.is_in_write_group():
1081
 
            raise AssertionError("%r not in write group" % (self,))
1082
 
        _mod_revision.check_not_reserved_id(revision_id)
1083
 
        if not (inv.revision_id is None or inv.revision_id == revision_id):
1084
 
            raise AssertionError(
1085
 
                "Mismatch between inventory revision"
1086
 
                " id and insertion revid (%r, %r)"
1087
 
                % (inv.revision_id, revision_id))
1088
 
        if inv.root is None:
1089
 
            raise errors.RootMissing()
1090
 
        return self._add_inventory_checked(revision_id, inv, parents)
1091
 
 
1092
 
    def _add_inventory_checked(self, revision_id, inv, parents):
1093
 
        """Add inv to the repository after checking the inputs.
1094
 
 
1095
 
        This function can be overridden to allow different inventory styles.
1096
 
 
1097
 
        :seealso: add_inventory, for the contract.
1098
 
        """
1099
 
        inv_lines = self._serializer.write_inventory_to_lines(inv)
1100
 
        return self._inventory_add_lines(revision_id, parents,
1101
 
            inv_lines, check_content=False)
1102
 
 
1103
 
    def add_inventory_by_delta(self, basis_revision_id, delta, new_revision_id,
1104
 
                               parents, basis_inv=None, propagate_caches=False):
1105
 
        """Add a new inventory expressed as a delta against another revision.
1106
 
 
1107
 
        See the inventory developers documentation for the theory behind
1108
 
        inventory deltas.
1109
 
 
1110
 
        :param basis_revision_id: The inventory id the delta was created
1111
 
            against. (This does not have to be a direct parent.)
1112
 
        :param delta: The inventory delta (see Inventory.apply_delta for
1113
 
            details).
1114
 
        :param new_revision_id: The revision id that the inventory is being
1115
 
            added for.
1116
 
        :param parents: The revision ids of the parents that revision_id is
1117
 
            known to have and are in the repository already. These are supplied
1118
 
            for repositories that depend on the inventory graph for revision
1119
 
            graph access, as well as for those that pun ancestry with delta
1120
 
            compression.
1121
 
        :param basis_inv: The basis inventory if it is already known,
1122
 
            otherwise None.
1123
 
        :param propagate_caches: If True, the caches for this inventory are
1124
 
          copied to and updated for the result if possible.
1125
 
 
1126
 
        :returns: (validator, new_inv)
1127
 
            The validator(which is a sha1 digest, though what is sha'd is
1128
 
            repository format specific) of the serialized inventory, and the
1129
 
            resulting inventory.
1130
 
        """
1131
 
        if not self.is_in_write_group():
1132
 
            raise AssertionError("%r not in write group" % (self,))
1133
 
        _mod_revision.check_not_reserved_id(new_revision_id)
1134
 
        basis_tree = self.revision_tree(basis_revision_id)
1135
 
        basis_tree.lock_read()
1136
 
        try:
1137
 
            # Note that this mutates the inventory of basis_tree, which not all
1138
 
            # inventory implementations may support: A better idiom would be to
1139
 
            # return a new inventory, but as there is no revision tree cache in
1140
 
            # repository this is safe for now - RBC 20081013
1141
 
            if basis_inv is None:
1142
 
                basis_inv = basis_tree.inventory
1143
 
            basis_inv.apply_delta(delta)
1144
 
            basis_inv.revision_id = new_revision_id
1145
 
            return (self.add_inventory(new_revision_id, basis_inv, parents),
1146
 
                    basis_inv)
1147
 
        finally:
1148
 
            basis_tree.unlock()
1149
 
 
1150
 
    def _inventory_add_lines(self, revision_id, parents, lines,
1151
 
        check_content=True):
1152
 
        """Store lines in inv_vf and return the sha1 of the inventory."""
1153
 
        parents = [(parent,) for parent in parents]
1154
 
        result = self.inventories.add_lines((revision_id,), parents, lines,
1155
 
            check_content=check_content)[0]
1156
 
        self.inventories._access.flush()
1157
 
        return result
1158
 
 
1159
 
    def add_revision(self, revision_id, rev, inv=None, config=None):
1160
 
        """Add rev to the revision store as revision_id.
1161
 
 
1162
 
        :param revision_id: the revision id to use.
1163
 
        :param rev: The revision object.
1164
 
        :param inv: The inventory for the revision. if None, it will be looked
1165
 
                    up in the inventory storer
1166
 
        :param config: If None no digital signature will be created.
1167
 
                       If supplied its signature_needed method will be used
1168
 
                       to determine if a signature should be made.
1169
 
        """
1170
 
        # TODO: jam 20070210 Shouldn't we check rev.revision_id and
1171
 
        #       rev.parent_ids?
1172
 
        _mod_revision.check_not_reserved_id(revision_id)
1173
 
        if config is not None and config.signature_needed():
1174
 
            if inv is None:
1175
 
                inv = self.get_inventory(revision_id)
1176
 
            plaintext = Testament(rev, inv).as_short_text()
1177
 
            self.store_revision_signature(
1178
 
                gpg.GPGStrategy(config), plaintext, revision_id)
1179
 
        # check inventory present
1180
 
        if not self.inventories.get_parent_map([(revision_id,)]):
1181
 
            if inv is None:
1182
 
                raise errors.WeaveRevisionNotPresent(revision_id,
1183
 
                                                     self.inventories)
1184
 
            else:
1185
 
                # yes, this is not suitable for adding with ghosts.
1186
 
                rev.inventory_sha1 = self.add_inventory(revision_id, inv,
1187
 
                                                        rev.parent_ids)
1188
 
        else:
1189
 
            key = (revision_id,)
1190
 
            rev.inventory_sha1 = self.inventories.get_sha1s([key])[key]
1191
 
        self._add_revision(rev)
1192
 
 
1193
 
    def _add_revision(self, revision):
1194
 
        text = self._serializer.write_revision_to_string(revision)
1195
 
        key = (revision.revision_id,)
1196
 
        parents = tuple((parent,) for parent in revision.parent_ids)
1197
 
        self.revisions.add_lines(key, parents, osutils.split_lines(text))
1198
 
 
1199
315
    def all_revision_ids(self):
1200
316
        """Returns a list of all the revision ids in the repository.
1201
317
 
1236
352
        # The old API returned a list, should this actually be a set?
1237
353
        return parent_map.keys()
1238
354
 
1239
 
    def _check_inventories(self, checker):
1240
 
        """Check the inventories found from the revision scan.
1241
 
        
1242
 
        This is responsible for verifying the sha1 of inventories and
1243
 
        creating a pending_keys set that covers data referenced by inventories.
1244
 
        """
1245
 
        bar = ui.ui_factory.nested_progress_bar()
1246
 
        try:
1247
 
            self._do_check_inventories(checker, bar)
1248
 
        finally:
1249
 
            bar.finished()
1250
 
 
1251
 
    def _do_check_inventories(self, checker, bar):
1252
 
        """Helper for _check_inventories."""
1253
 
        revno = 0
1254
 
        keys = {'chk_bytes':set(), 'inventories':set(), 'texts':set()}
1255
 
        kinds = ['chk_bytes', 'texts']
1256
 
        count = len(checker.pending_keys)
1257
 
        bar.update("inventories", 0, 2)
1258
 
        current_keys = checker.pending_keys
1259
 
        checker.pending_keys = {}
1260
 
        # Accumulate current checks.
1261
 
        for key in current_keys:
1262
 
            if key[0] != 'inventories' and key[0] not in kinds:
1263
 
                checker._report_items.append('unknown key type %r' % (key,))
1264
 
            keys[key[0]].add(key[1:])
1265
 
        if keys['inventories']:
1266
 
            # NB: output order *should* be roughly sorted - topo or
1267
 
            # inverse topo depending on repository - either way decent
1268
 
            # to just delta against. However, pre-CHK formats didn't
1269
 
            # try to optimise inventory layout on disk. As such the
1270
 
            # pre-CHK code path does not use inventory deltas.
1271
 
            last_object = None
1272
 
            for record in self.inventories.check(keys=keys['inventories']):
1273
 
                if record.storage_kind == 'absent':
1274
 
                    checker._report_items.append(
1275
 
                        'Missing inventory {%s}' % (record.key,))
1276
 
                else:
1277
 
                    last_object = self._check_record('inventories', record,
1278
 
                        checker, last_object,
1279
 
                        current_keys[('inventories',) + record.key])
1280
 
            del keys['inventories']
1281
 
        else:
1282
 
            return
1283
 
        bar.update("texts", 1)
1284
 
        while (checker.pending_keys or keys['chk_bytes']
1285
 
            or keys['texts']):
1286
 
            # Something to check.
1287
 
            current_keys = checker.pending_keys
1288
 
            checker.pending_keys = {}
1289
 
            # Accumulate current checks.
1290
 
            for key in current_keys:
1291
 
                if key[0] not in kinds:
1292
 
                    checker._report_items.append('unknown key type %r' % (key,))
1293
 
                keys[key[0]].add(key[1:])
1294
 
            # Check the outermost kind only - inventories || chk_bytes || texts
1295
 
            for kind in kinds:
1296
 
                if keys[kind]:
1297
 
                    last_object = None
1298
 
                    for record in getattr(self, kind).check(keys=keys[kind]):
1299
 
                        if record.storage_kind == 'absent':
1300
 
                            checker._report_items.append(
1301
 
                                'Missing %s {%s}' % (kind, record.key,))
1302
 
                        else:
1303
 
                            last_object = self._check_record(kind, record,
1304
 
                                checker, last_object, current_keys[(kind,) + record.key])
1305
 
                    keys[kind] = set()
1306
 
                    break
1307
 
 
1308
 
    def _check_record(self, kind, record, checker, last_object, item_data):
1309
 
        """Check a single text from this repository."""
1310
 
        if kind == 'inventories':
1311
 
            rev_id = record.key[0]
1312
 
            inv = self._deserialise_inventory(rev_id,
1313
 
                record.get_bytes_as('fulltext'))
1314
 
            if last_object is not None:
1315
 
                delta = inv._make_delta(last_object)
1316
 
                for old_path, path, file_id, ie in delta:
1317
 
                    if ie is None:
1318
 
                        continue
1319
 
                    ie.check(checker, rev_id, inv)
1320
 
            else:
1321
 
                for path, ie in inv.iter_entries():
1322
 
                    ie.check(checker, rev_id, inv)
1323
 
            if self._format.fast_deltas:
1324
 
                return inv
1325
 
        elif kind == 'chk_bytes':
1326
 
            # No code written to check chk_bytes for this repo format.
1327
 
            checker._report_items.append(
1328
 
                'unsupported key type chk_bytes for %s' % (record.key,))
1329
 
        elif kind == 'texts':
1330
 
            self._check_text(record, checker, item_data)
1331
 
        else:
1332
 
            checker._report_items.append(
1333
 
                'unknown key type %s for %s' % (kind, record.key))
1334
 
 
1335
 
    def _check_text(self, record, checker, item_data):
1336
 
        """Check a single text."""
1337
 
        # Check it is extractable.
1338
 
        # TODO: check length.
1339
 
        if record.storage_kind == 'chunked':
1340
 
            chunks = record.get_bytes_as(record.storage_kind)
1341
 
            sha1 = osutils.sha_strings(chunks)
1342
 
            length = sum(map(len, chunks))
1343
 
        else:
1344
 
            content = record.get_bytes_as('fulltext')
1345
 
            sha1 = osutils.sha_string(content)
1346
 
            length = len(content)
1347
 
        if item_data and sha1 != item_data[1]:
1348
 
            checker._report_items.append(
1349
 
                'sha1 mismatch: %s has sha1 %s expected %s referenced by %s' %
1350
 
                (record.key, sha1, item_data[1], item_data[2]))
1351
 
 
1352
355
    @staticmethod
1353
356
    def create(a_bzrdir):
1354
357
        """Construct the current default format repository in a_bzrdir."""
1359
362
 
1360
363
        :param _format: The format of the repository on disk.
1361
364
        :param a_bzrdir: The BzrDir of the repository.
 
365
        :param control_files: Control files to use for locking, etc.
1362
366
        """
1363
367
        # In the future we will have a single api for all stores for
1364
368
        # getting file texts, inventories and revisions, then
1371
375
        self._transport = control_files._transport
1372
376
        self.base = self._transport.base
1373
377
        # for tests
1374
 
        self._reconcile_does_inventory_gc = True
1375
 
        self._reconcile_fixes_text_parents = False
1376
 
        self._reconcile_backsup_inventory = True
1377
378
        self._write_group = None
1378
379
        # Additional places to query for data.
1379
380
        self._fallback_repositories = []
1380
 
        # An InventoryEntry cache, used during deserialization
1381
 
        self._inventory_entry_cache = fifo_cache.FIFOCache(10*1024)
1382
 
        # Is it safe to return inventory entries directly from the entry cache,
1383
 
        # rather copying them?
1384
 
        self._safe_to_return_from_cache = False
1385
381
 
1386
382
    @property
1387
383
    def user_transport(self):
1527
523
        if revid and committers:
1528
524
            result['committers'] = 0
1529
525
        if revid and revid != _mod_revision.NULL_REVISION:
 
526
            graph = self.get_graph()
1530
527
            if committers:
1531
528
                all_committers = set()
1532
 
            revisions = self.get_ancestry(revid)
1533
 
            # pop the leading None
1534
 
            revisions.pop(0)
1535
 
            first_revision = None
 
529
            revisions = [r for (r, p) in graph.iter_ancestry([revid])
 
530
                        if r != _mod_revision.NULL_REVISION]
 
531
            last_revision = None
1536
532
            if not committers:
1537
533
                # ignore the revisions in the middle - just grab first and last
1538
534
                revisions = revisions[0], revisions[-1]
1539
535
            for revision in self.get_revisions(revisions):
1540
 
                if not first_revision:
1541
 
                    first_revision = revision
 
536
                if not last_revision:
 
537
                    last_revision = revision
1542
538
                if committers:
1543
539
                    all_committers.add(revision.committer)
1544
 
            last_revision = revision
 
540
            first_revision = revision
1545
541
            if committers:
1546
542
                result['committers'] = len(all_committers)
1547
543
            result['firstrev'] = (first_revision.timestamp,
1548
544
                first_revision.timezone)
1549
545
            result['latestrev'] = (last_revision.timestamp,
1550
546
                last_revision.timezone)
1551
 
 
1552
 
        # now gather global repository information
1553
 
        # XXX: This is available for many repos regardless of listability.
1554
 
        if self.user_transport.listable():
1555
 
            # XXX: do we want to __define len__() ?
1556
 
            # Maybe the versionedfiles object should provide a different
1557
 
            # method to get the number of keys.
1558
 
            result['revisions'] = len(self.revisions.keys())
1559
 
            # result['size'] = t
1560
547
        return result
1561
548
 
1562
549
    def find_branches(self, using=False):
1597
584
        return ret
1598
585
 
1599
586
    @needs_read_lock
1600
 
    def search_missing_revision_ids(self, other, revision_id=None, find_ghosts=True):
 
587
    def search_missing_revision_ids(self, other,
 
588
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
 
589
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
590
            limit=None):
1601
591
        """Return the revision ids that other has that this does not.
1602
592
 
1603
593
        These are returned in topological order.
1604
594
 
1605
595
        revision_id: only return revision ids included by revision_id.
1606
596
        """
 
597
        if symbol_versioning.deprecated_passed(revision_id):
 
598
            symbol_versioning.warn(
 
599
                'search_missing_revision_ids(revision_id=...) was '
 
600
                'deprecated in 2.4.  Use revision_ids=[...] instead.',
 
601
                DeprecationWarning, stacklevel=3)
 
602
            if revision_ids is not None:
 
603
                raise AssertionError(
 
604
                    'revision_ids is mutually exclusive with revision_id')
 
605
            if revision_id is not None:
 
606
                revision_ids = [revision_id]
1607
607
        return InterRepository.get(other, self).search_missing_revision_ids(
1608
 
            revision_id, find_ghosts)
 
608
            find_ghosts=find_ghosts, revision_ids=revision_ids,
 
609
            if_present_ids=if_present_ids, limit=limit)
1609
610
 
1610
611
    @staticmethod
1611
612
    def open(base):
1653
654
    def suspend_write_group(self):
1654
655
        raise errors.UnsuspendableWriteGroup(self)
1655
656
 
1656
 
    def get_missing_parent_inventories(self, check_for_missing_texts=True):
1657
 
        """Return the keys of missing inventory parents for revisions added in
1658
 
        this write group.
1659
 
 
1660
 
        A revision is not complete if the inventory delta for that revision
1661
 
        cannot be calculated.  Therefore if the parent inventories of a
1662
 
        revision are not present, the revision is incomplete, and e.g. cannot
1663
 
        be streamed by a smart server.  This method finds missing inventory
1664
 
        parents for revisions added in this write group.
1665
 
        """
1666
 
        if not self._format.supports_external_lookups:
1667
 
            # This is only an issue for stacked repositories
1668
 
            return set()
1669
 
        if not self.is_in_write_group():
1670
 
            raise AssertionError('not in a write group')
1671
 
 
1672
 
        # XXX: We assume that every added revision already has its
1673
 
        # corresponding inventory, so we only check for parent inventories that
1674
 
        # might be missing, rather than all inventories.
1675
 
        parents = set(self.revisions._index.get_missing_parents())
1676
 
        parents.discard(_mod_revision.NULL_REVISION)
1677
 
        unstacked_inventories = self.inventories._index
1678
 
        present_inventories = unstacked_inventories.get_parent_map(
1679
 
            key[-1:] for key in parents)
1680
 
        parents.difference_update(present_inventories)
1681
 
        if len(parents) == 0:
1682
 
            # No missing parent inventories.
1683
 
            return set()
1684
 
        if not check_for_missing_texts:
1685
 
            return set(('inventories', rev_id) for (rev_id,) in parents)
1686
 
        # Ok, now we have a list of missing inventories.  But these only matter
1687
 
        # if the inventories that reference them are missing some texts they
1688
 
        # appear to introduce.
1689
 
        # XXX: Texts referenced by all added inventories need to be present,
1690
 
        # but at the moment we're only checking for texts referenced by
1691
 
        # inventories at the graph's edge.
1692
 
        key_deps = self.revisions._index._key_dependencies
1693
 
        key_deps.satisfy_refs_for_keys(present_inventories)
1694
 
        referrers = frozenset(r[0] for r in key_deps.get_referrers())
1695
 
        file_ids = self.fileids_altered_by_revision_ids(referrers)
1696
 
        missing_texts = set()
1697
 
        for file_id, version_ids in file_ids.iteritems():
1698
 
            missing_texts.update(
1699
 
                (file_id, version_id) for version_id in version_ids)
1700
 
        present_texts = self.texts.get_parent_map(missing_texts)
1701
 
        missing_texts.difference_update(present_texts)
1702
 
        if not missing_texts:
1703
 
            # No texts are missing, so all revisions and their deltas are
1704
 
            # reconstructable.
1705
 
            return set()
1706
 
        # Alternatively the text versions could be returned as the missing
1707
 
        # keys, but this is likely to be less data.
1708
 
        missing_keys = set(('inventories', rev_id) for (rev_id,) in parents)
1709
 
        return missing_keys
1710
 
 
1711
657
    def refresh_data(self):
1712
658
        """Re-read any data needed to synchronise with disk.
1713
659
 
1733
679
    def _resume_write_group(self, tokens):
1734
680
        raise errors.UnsuspendableWriteGroup(self)
1735
681
 
1736
 
    def fetch(self, source, revision_id=None, pb=None, find_ghosts=False,
 
682
    def fetch(self, source, revision_id=None, find_ghosts=False,
1737
683
            fetch_spec=None):
1738
684
        """Fetch the content required to construct revision_id from source.
1739
685
 
1773
719
                not _mod_revision.is_null(revision_id)):
1774
720
                self.get_revision(revision_id)
1775
721
            return 0, []
1776
 
        # if there is no specific appropriate InterRepository, this will get
1777
 
        # the InterRepository base class, which raises an
1778
 
        # IncompatibleRepositories when asked to fetch.
1779
722
        inter = InterRepository.get(source, self)
1780
 
        return inter.fetch(revision_id=revision_id, pb=pb,
 
723
        return inter.fetch(revision_id=revision_id,
1781
724
            find_ghosts=find_ghosts, fetch_spec=fetch_spec)
1782
725
 
1783
726
    def create_bundle(self, target, base, fileobj, format=None):
1785
728
 
1786
729
    def get_commit_builder(self, branch, parents, config, timestamp=None,
1787
730
                           timezone=None, committer=None, revprops=None,
1788
 
                           revision_id=None):
 
731
                           revision_id=None, lossy=False):
1789
732
        """Obtain a CommitBuilder for this repository.
1790
733
 
1791
734
        :param branch: Branch to commit to.
1796
739
        :param committer: Optional committer to set for commit.
1797
740
        :param revprops: Optional dictionary of revision properties.
1798
741
        :param revision_id: Optional revision id.
 
742
        :param lossy: Whether to discard data that can not be natively
 
743
            represented, when pushing to a foreign VCS
1799
744
        """
1800
 
        if self._fallback_repositories and not self._format.supports_chks:
1801
 
            raise errors.BzrError("Cannot commit directly to a stacked branch"
1802
 
                " in pre-2a formats. See "
1803
 
                "https://bugs.launchpad.net/bzr/+bug/375013 for details.")
1804
 
        result = self._commit_builder_class(self, parents, config,
1805
 
            timestamp, timezone, committer, revprops, revision_id)
1806
 
        self.start_write_group()
1807
 
        return result
 
745
        raise NotImplementedError(self.get_commit_builder)
1808
746
 
1809
747
    @only_raises(errors.LockNotHeld, errors.LockBroken)
1810
748
    def unlock(self):
1817
755
                    'Must end write groups before releasing write locks.')
1818
756
        self.control_files.unlock()
1819
757
        if self.control_files._lock_count == 0:
1820
 
            self._inventory_entry_cache.clear()
1821
758
            for repo in self._fallback_repositories:
1822
759
                repo.unlock()
1823
760
 
1888
825
                dest_repo = a_bzrdir.open_repository()
1889
826
        return dest_repo
1890
827
 
1891
 
    def _get_sink(self):
1892
 
        """Return a sink for streaming into this repository."""
1893
 
        return StreamSink(self)
1894
 
 
1895
 
    def _get_source(self, to_format):
1896
 
        """Return a source for streaming from this repository."""
1897
 
        return StreamSource(self, to_format)
1898
 
 
1899
828
    @needs_read_lock
1900
829
    def has_revision(self, revision_id):
1901
830
        """True if this repository has a copy of the revision."""
1908
837
        :param revision_ids: An iterable of revision_ids.
1909
838
        :return: A set of the revision_ids that were present.
1910
839
        """
1911
 
        parent_map = self.revisions.get_parent_map(
1912
 
            [(rev_id,) for rev_id in revision_ids])
1913
 
        result = set()
1914
 
        if _mod_revision.NULL_REVISION in revision_ids:
1915
 
            result.add(_mod_revision.NULL_REVISION)
1916
 
        result.update([key[0] for key in parent_map])
1917
 
        return result
 
840
        raise NotImplementedError(self.has_revisions)
1918
841
 
1919
842
    @needs_read_lock
1920
843
    def get_revision(self, revision_id):
1921
844
        """Return the Revision object for a named revision."""
1922
845
        return self.get_revisions([revision_id])[0]
1923
846
 
1924
 
    @needs_read_lock
1925
847
    def get_revision_reconcile(self, revision_id):
1926
848
        """'reconcile' helper routine that allows access to a revision always.
1927
849
 
1930
852
        be used by reconcile, or reconcile-alike commands that are correcting
1931
853
        or testing the revision graph.
1932
854
        """
1933
 
        return self._get_revisions([revision_id])[0]
 
855
        raise NotImplementedError(self.get_revision_reconcile)
1934
856
 
1935
 
    @needs_read_lock
1936
857
    def get_revisions(self, revision_ids):
1937
858
        """Get many revisions at once.
1938
859
        
1939
860
        Repositories that need to check data on every revision read should 
1940
861
        subclass this method.
1941
862
        """
1942
 
        return self._get_revisions(revision_ids)
1943
 
 
1944
 
    @needs_read_lock
1945
 
    def _get_revisions(self, revision_ids):
1946
 
        """Core work logic to get many revisions without sanity checks."""
1947
 
        revs = {}
1948
 
        for revid, rev in self._iter_revisions(revision_ids):
1949
 
            if rev is None:
1950
 
                raise errors.NoSuchRevision(self, revid)
1951
 
            revs[revid] = rev
1952
 
        return [revs[revid] for revid in revision_ids]
1953
 
 
1954
 
    def _iter_revisions(self, revision_ids):
1955
 
        """Iterate over revision objects.
1956
 
 
1957
 
        :param revision_ids: An iterable of revisions to examine. None may be
1958
 
            passed to request all revisions known to the repository. Note that
1959
 
            not all repositories can find unreferenced revisions; for those
1960
 
            repositories only referenced ones will be returned.
1961
 
        :return: An iterator of (revid, revision) tuples. Absent revisions (
1962
 
            those asked for but not available) are returned as (revid, None).
1963
 
        """
1964
 
        if revision_ids is None:
1965
 
            revision_ids = self.all_revision_ids()
1966
 
        else:
1967
 
            for rev_id in revision_ids:
1968
 
                if not rev_id or not isinstance(rev_id, basestring):
1969
 
                    raise errors.InvalidRevisionId(revision_id=rev_id, branch=self)
1970
 
        keys = [(key,) for key in revision_ids]
1971
 
        stream = self.revisions.get_record_stream(keys, 'unordered', True)
1972
 
        for record in stream:
1973
 
            revid = record.key[0]
1974
 
            if record.storage_kind == 'absent':
1975
 
                yield (revid, None)
1976
 
            else:
1977
 
                text = record.get_bytes_as('fulltext')
1978
 
                rev = self._serializer.read_revision_from_string(text)
1979
 
                yield (revid, rev)
 
863
        raise NotImplementedError(self.get_revisions)
1980
864
 
1981
865
    def get_deltas_for_revisions(self, revisions, specific_fileids=None):
1982
866
        """Produce a generator of revision deltas.
2037
921
        signature = gpg_strategy.sign(plaintext)
2038
922
        self.add_signature_text(revision_id, signature)
2039
923
 
2040
 
    @needs_write_lock
2041
924
    def add_signature_text(self, revision_id, signature):
2042
 
        self.signatures.add_lines((revision_id,), (),
2043
 
            osutils.split_lines(signature))
2044
 
 
2045
 
    def find_text_key_references(self):
2046
 
        """Find the text key references within the repository.
2047
 
 
2048
 
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
2049
 
            to whether they were referred to by the inventory of the
2050
 
            revision_id that they contain. The inventory texts from all present
2051
 
            revision ids are assessed to generate this report.
2052
 
        """
2053
 
        revision_keys = self.revisions.keys()
2054
 
        w = self.inventories
2055
 
        pb = ui.ui_factory.nested_progress_bar()
2056
 
        try:
2057
 
            return self._find_text_key_references_from_xml_inventory_lines(
2058
 
                w.iter_lines_added_or_present_in_keys(revision_keys, pb=pb))
2059
 
        finally:
2060
 
            pb.finished()
2061
 
 
2062
 
    def _find_text_key_references_from_xml_inventory_lines(self,
2063
 
        line_iterator):
2064
 
        """Core routine for extracting references to texts from inventories.
2065
 
 
2066
 
        This performs the translation of xml lines to revision ids.
2067
 
 
2068
 
        :param line_iterator: An iterator of lines, origin_version_id
2069
 
        :return: A dictionary mapping text keys ((fileid, revision_id) tuples)
2070
 
            to whether they were referred to by the inventory of the
2071
 
            revision_id that they contain. Note that if that revision_id was
2072
 
            not part of the line_iterator's output then False will be given -
2073
 
            even though it may actually refer to that key.
2074
 
        """
2075
 
        if not self._serializer.support_altered_by_hack:
2076
 
            raise AssertionError(
2077
 
                "_find_text_key_references_from_xml_inventory_lines only "
2078
 
                "supported for branches which store inventory as unnested xml"
2079
 
                ", not on %r" % self)
2080
 
        result = {}
2081
 
 
2082
 
        # this code needs to read every new line in every inventory for the
2083
 
        # inventories [revision_ids]. Seeing a line twice is ok. Seeing a line
2084
 
        # not present in one of those inventories is unnecessary but not
2085
 
        # harmful because we are filtering by the revision id marker in the
2086
 
        # inventory lines : we only select file ids altered in one of those
2087
 
        # revisions. We don't need to see all lines in the inventory because
2088
 
        # only those added in an inventory in rev X can contain a revision=X
2089
 
        # line.
2090
 
        unescape_revid_cache = {}
2091
 
        unescape_fileid_cache = {}
2092
 
 
2093
 
        # jam 20061218 In a big fetch, this handles hundreds of thousands
2094
 
        # of lines, so it has had a lot of inlining and optimizing done.
2095
 
        # Sorry that it is a little bit messy.
2096
 
        # Move several functions to be local variables, since this is a long
2097
 
        # running loop.
2098
 
        search = self._file_ids_altered_regex.search
2099
 
        unescape = _unescape_xml
2100
 
        setdefault = result.setdefault
2101
 
        for line, line_key in line_iterator:
2102
 
            match = search(line)
2103
 
            if match is None:
2104
 
                continue
2105
 
            # One call to match.group() returning multiple items is quite a
2106
 
            # bit faster than 2 calls to match.group() each returning 1
2107
 
            file_id, revision_id = match.group('file_id', 'revision_id')
2108
 
 
2109
 
            # Inlining the cache lookups helps a lot when you make 170,000
2110
 
            # lines and 350k ids, versus 8.4 unique ids.
2111
 
            # Using a cache helps in 2 ways:
2112
 
            #   1) Avoids unnecessary decoding calls
2113
 
            #   2) Re-uses cached strings, which helps in future set and
2114
 
            #      equality checks.
2115
 
            # (2) is enough that removing encoding entirely along with
2116
 
            # the cache (so we are using plain strings) results in no
2117
 
            # performance improvement.
2118
 
            try:
2119
 
                revision_id = unescape_revid_cache[revision_id]
2120
 
            except KeyError:
2121
 
                unescaped = unescape(revision_id)
2122
 
                unescape_revid_cache[revision_id] = unescaped
2123
 
                revision_id = unescaped
2124
 
 
2125
 
            # Note that unconditionally unescaping means that we deserialise
2126
 
            # every fileid, which for general 'pull' is not great, but we don't
2127
 
            # really want to have some many fulltexts that this matters anyway.
2128
 
            # RBC 20071114.
2129
 
            try:
2130
 
                file_id = unescape_fileid_cache[file_id]
2131
 
            except KeyError:
2132
 
                unescaped = unescape(file_id)
2133
 
                unescape_fileid_cache[file_id] = unescaped
2134
 
                file_id = unescaped
2135
 
 
2136
 
            key = (file_id, revision_id)
2137
 
            setdefault(key, False)
2138
 
            if revision_id == line_key[-1]:
2139
 
                result[key] = True
2140
 
        return result
2141
 
 
2142
 
    def _inventory_xml_lines_for_keys(self, keys):
2143
 
        """Get a line iterator of the sort needed for findind references.
2144
 
 
2145
 
        Not relevant for non-xml inventory repositories.
2146
 
 
2147
 
        Ghosts in revision_keys are ignored.
2148
 
 
2149
 
        :param revision_keys: The revision keys for the inventories to inspect.
2150
 
        :return: An iterator over (inventory line, revid) for the fulltexts of
2151
 
            all of the xml inventories specified by revision_keys.
2152
 
        """
2153
 
        stream = self.inventories.get_record_stream(keys, 'unordered', True)
2154
 
        for record in stream:
2155
 
            if record.storage_kind != 'absent':
2156
 
                chunks = record.get_bytes_as('chunked')
2157
 
                revid = record.key[-1]
2158
 
                lines = osutils.chunks_to_lines(chunks)
2159
 
                for line in lines:
2160
 
                    yield line, revid
2161
 
 
2162
 
    def _find_file_ids_from_xml_inventory_lines(self, line_iterator,
2163
 
        revision_keys):
2164
 
        """Helper routine for fileids_altered_by_revision_ids.
2165
 
 
2166
 
        This performs the translation of xml lines to revision ids.
2167
 
 
2168
 
        :param line_iterator: An iterator of lines, origin_version_id
2169
 
        :param revision_keys: The revision ids to filter for. This should be a
2170
 
            set or other type which supports efficient __contains__ lookups, as
2171
 
            the revision key from each parsed line will be looked up in the
2172
 
            revision_keys filter.
2173
 
        :return: a dictionary mapping altered file-ids to an iterable of
2174
 
        revision_ids. Each altered file-ids has the exact revision_ids that
2175
 
        altered it listed explicitly.
2176
 
        """
2177
 
        seen = set(self._find_text_key_references_from_xml_inventory_lines(
2178
 
                line_iterator).iterkeys())
2179
 
        parent_keys = self._find_parent_keys_of_revisions(revision_keys)
2180
 
        parent_seen = set(self._find_text_key_references_from_xml_inventory_lines(
2181
 
            self._inventory_xml_lines_for_keys(parent_keys)))
2182
 
        new_keys = seen - parent_seen
2183
 
        result = {}
2184
 
        setdefault = result.setdefault
2185
 
        for key in new_keys:
2186
 
            setdefault(key[0], set()).add(key[-1])
2187
 
        return result
 
925
        """Store a signature text for a revision.
 
926
 
 
927
        :param revision_id: Revision id of the revision
 
928
        :param signature: Signature text.
 
929
        """
 
930
        raise NotImplementedError(self.add_signature_text)
2188
931
 
2189
932
    def _find_parent_ids_of_revisions(self, revision_ids):
2190
933
        """Find all parent ids that are mentioned in the revision graph.
2199
942
        parent_ids.discard(_mod_revision.NULL_REVISION)
2200
943
        return parent_ids
2201
944
 
2202
 
    def _find_parent_keys_of_revisions(self, revision_keys):
2203
 
        """Similar to _find_parent_ids_of_revisions, but used with keys.
2204
 
 
2205
 
        :param revision_keys: An iterable of revision_keys.
2206
 
        :return: The parents of all revision_keys that are not already in
2207
 
            revision_keys
2208
 
        """
2209
 
        parent_map = self.revisions.get_parent_map(revision_keys)
2210
 
        parent_keys = set()
2211
 
        map(parent_keys.update, parent_map.itervalues())
2212
 
        parent_keys.difference_update(revision_keys)
2213
 
        parent_keys.discard(_mod_revision.NULL_REVISION)
2214
 
        return parent_keys
2215
 
 
2216
 
    def fileids_altered_by_revision_ids(self, revision_ids, _inv_weave=None):
 
945
    def fileids_altered_by_revision_ids(self, revision_ids):
2217
946
        """Find the file ids and versions affected by revisions.
2218
947
 
2219
948
        :param revisions: an iterable containing revision ids.
2220
 
        :param _inv_weave: The inventory weave from this repository or None.
2221
 
            If None, the inventory weave will be opened automatically.
2222
949
        :return: a dictionary mapping altered file-ids to an iterable of
2223
 
        revision_ids. Each altered file-ids has the exact revision_ids that
2224
 
        altered it listed explicitly.
 
950
            revision_ids. Each altered file-ids has the exact revision_ids
 
951
            that altered it listed explicitly.
2225
952
        """
2226
 
        selected_keys = set((revid,) for revid in revision_ids)
2227
 
        w = _inv_weave or self.inventories
2228
 
        return self._find_file_ids_from_xml_inventory_lines(
2229
 
            w.iter_lines_added_or_present_in_keys(
2230
 
                selected_keys, pb=None),
2231
 
            selected_keys)
 
953
        raise NotImplementedError(self.fileids_altered_by_revision_ids)
2232
954
 
2233
955
    def iter_files_bytes(self, desired_files):
2234
956
        """Iterate through file versions.
2241
963
        uniquely identify the file version in the caller's context.  (Examples:
2242
964
        an index number or a TreeTransform trans_id.)
2243
965
 
2244
 
        bytes_iterator is an iterable of bytestrings for the file.  The
2245
 
        kind of iterable and length of the bytestrings are unspecified, but for
2246
 
        this implementation, it is a list of bytes produced by
2247
 
        VersionedFile.get_record_stream().
2248
 
 
2249
966
        :param desired_files: a list of (file_id, revision_id, identifier)
2250
967
            triples
2251
968
        """
2252
 
        text_keys = {}
2253
 
        for file_id, revision_id, callable_data in desired_files:
2254
 
            text_keys[(file_id, revision_id)] = callable_data
2255
 
        for record in self.texts.get_record_stream(text_keys, 'unordered', True):
2256
 
            if record.storage_kind == 'absent':
2257
 
                raise errors.RevisionNotPresent(record.key, self)
2258
 
            yield text_keys[record.key], record.get_bytes_as('chunked')
2259
 
 
2260
 
    def _generate_text_key_index(self, text_key_references=None,
2261
 
        ancestors=None):
2262
 
        """Generate a new text key index for the repository.
2263
 
 
2264
 
        This is an expensive function that will take considerable time to run.
2265
 
 
2266
 
        :return: A dict mapping text keys ((file_id, revision_id) tuples) to a
2267
 
            list of parents, also text keys. When a given key has no parents,
2268
 
            the parents list will be [NULL_REVISION].
2269
 
        """
2270
 
        # All revisions, to find inventory parents.
2271
 
        if ancestors is None:
2272
 
            graph = self.get_graph()
2273
 
            ancestors = graph.get_parent_map(self.all_revision_ids())
2274
 
        if text_key_references is None:
2275
 
            text_key_references = self.find_text_key_references()
2276
 
        pb = ui.ui_factory.nested_progress_bar()
2277
 
        try:
2278
 
            return self._do_generate_text_key_index(ancestors,
2279
 
                text_key_references, pb)
2280
 
        finally:
2281
 
            pb.finished()
2282
 
 
2283
 
    def _do_generate_text_key_index(self, ancestors, text_key_references, pb):
2284
 
        """Helper for _generate_text_key_index to avoid deep nesting."""
2285
 
        revision_order = tsort.topo_sort(ancestors)
2286
 
        invalid_keys = set()
2287
 
        revision_keys = {}
2288
 
        for revision_id in revision_order:
2289
 
            revision_keys[revision_id] = set()
2290
 
        text_count = len(text_key_references)
2291
 
        # a cache of the text keys to allow reuse; costs a dict of all the
2292
 
        # keys, but saves a 2-tuple for every child of a given key.
2293
 
        text_key_cache = {}
2294
 
        for text_key, valid in text_key_references.iteritems():
2295
 
            if not valid:
2296
 
                invalid_keys.add(text_key)
2297
 
            else:
2298
 
                revision_keys[text_key[1]].add(text_key)
2299
 
            text_key_cache[text_key] = text_key
2300
 
        del text_key_references
2301
 
        text_index = {}
2302
 
        text_graph = graph.Graph(graph.DictParentsProvider(text_index))
2303
 
        NULL_REVISION = _mod_revision.NULL_REVISION
2304
 
        # Set a cache with a size of 10 - this suffices for bzr.dev but may be
2305
 
        # too small for large or very branchy trees. However, for 55K path
2306
 
        # trees, it would be easy to use too much memory trivially. Ideally we
2307
 
        # could gauge this by looking at available real memory etc, but this is
2308
 
        # always a tricky proposition.
2309
 
        inventory_cache = lru_cache.LRUCache(10)
2310
 
        batch_size = 10 # should be ~150MB on a 55K path tree
2311
 
        batch_count = len(revision_order) / batch_size + 1
2312
 
        processed_texts = 0
2313
 
        pb.update("Calculating text parents", processed_texts, text_count)
2314
 
        for offset in xrange(batch_count):
2315
 
            to_query = revision_order[offset * batch_size:(offset + 1) *
2316
 
                batch_size]
2317
 
            if not to_query:
2318
 
                break
2319
 
            for revision_id in to_query:
2320
 
                parent_ids = ancestors[revision_id]
2321
 
                for text_key in revision_keys[revision_id]:
2322
 
                    pb.update("Calculating text parents", processed_texts)
2323
 
                    processed_texts += 1
2324
 
                    candidate_parents = []
2325
 
                    for parent_id in parent_ids:
2326
 
                        parent_text_key = (text_key[0], parent_id)
2327
 
                        try:
2328
 
                            check_parent = parent_text_key not in \
2329
 
                                revision_keys[parent_id]
2330
 
                        except KeyError:
2331
 
                            # the parent parent_id is a ghost:
2332
 
                            check_parent = False
2333
 
                            # truncate the derived graph against this ghost.
2334
 
                            parent_text_key = None
2335
 
                        if check_parent:
2336
 
                            # look at the parent commit details inventories to
2337
 
                            # determine possible candidates in the per file graph.
2338
 
                            # TODO: cache here.
2339
 
                            try:
2340
 
                                inv = inventory_cache[parent_id]
2341
 
                            except KeyError:
2342
 
                                inv = self.revision_tree(parent_id).inventory
2343
 
                                inventory_cache[parent_id] = inv
2344
 
                            try:
2345
 
                                parent_entry = inv[text_key[0]]
2346
 
                            except (KeyError, errors.NoSuchId):
2347
 
                                parent_entry = None
2348
 
                            if parent_entry is not None:
2349
 
                                parent_text_key = (
2350
 
                                    text_key[0], parent_entry.revision)
2351
 
                            else:
2352
 
                                parent_text_key = None
2353
 
                        if parent_text_key is not None:
2354
 
                            candidate_parents.append(
2355
 
                                text_key_cache[parent_text_key])
2356
 
                    parent_heads = text_graph.heads(candidate_parents)
2357
 
                    new_parents = list(parent_heads)
2358
 
                    new_parents.sort(key=lambda x:candidate_parents.index(x))
2359
 
                    if new_parents == []:
2360
 
                        new_parents = [NULL_REVISION]
2361
 
                    text_index[text_key] = new_parents
2362
 
 
2363
 
        for text_key in invalid_keys:
2364
 
            text_index[text_key] = [NULL_REVISION]
2365
 
        return text_index
2366
 
 
2367
 
    def item_keys_introduced_by(self, revision_ids, _files_pb=None):
2368
 
        """Get an iterable listing the keys of all the data introduced by a set
2369
 
        of revision IDs.
2370
 
 
2371
 
        The keys will be ordered so that the corresponding items can be safely
2372
 
        fetched and inserted in that order.
2373
 
 
2374
 
        :returns: An iterable producing tuples of (knit-kind, file-id,
2375
 
            versions).  knit-kind is one of 'file', 'inventory', 'signatures',
2376
 
            'revisions'.  file-id is None unless knit-kind is 'file'.
2377
 
        """
2378
 
        for result in self._find_file_keys_to_fetch(revision_ids, _files_pb):
2379
 
            yield result
2380
 
        del _files_pb
2381
 
        for result in self._find_non_file_keys_to_fetch(revision_ids):
2382
 
            yield result
2383
 
 
2384
 
    def _find_file_keys_to_fetch(self, revision_ids, pb):
2385
 
        # XXX: it's a bit weird to control the inventory weave caching in this
2386
 
        # generator.  Ideally the caching would be done in fetch.py I think.  Or
2387
 
        # maybe this generator should explicitly have the contract that it
2388
 
        # should not be iterated until the previously yielded item has been
2389
 
        # processed?
2390
 
        inv_w = self.inventories
2391
 
 
2392
 
        # file ids that changed
2393
 
        file_ids = self.fileids_altered_by_revision_ids(revision_ids, inv_w)
2394
 
        count = 0
2395
 
        num_file_ids = len(file_ids)
2396
 
        for file_id, altered_versions in file_ids.iteritems():
2397
 
            if pb is not None:
2398
 
                pb.update("Fetch texts", count, num_file_ids)
2399
 
            count += 1
2400
 
            yield ("file", file_id, altered_versions)
2401
 
 
2402
 
    def _find_non_file_keys_to_fetch(self, revision_ids):
2403
 
        # inventory
2404
 
        yield ("inventory", None, revision_ids)
2405
 
 
2406
 
        # signatures
2407
 
        # XXX: Note ATM no callers actually pay attention to this return
2408
 
        #      instead they just use the list of revision ids and ignore
2409
 
        #      missing sigs. Consider removing this work entirely
2410
 
        revisions_with_signatures = set(self.signatures.get_parent_map(
2411
 
            [(r,) for r in revision_ids]))
2412
 
        revisions_with_signatures = set(
2413
 
            [r for (r,) in revisions_with_signatures])
2414
 
        revisions_with_signatures.intersection_update(revision_ids)
2415
 
        yield ("signatures", None, revisions_with_signatures)
2416
 
 
2417
 
        # revisions
2418
 
        yield ("revisions", None, revision_ids)
2419
 
 
2420
 
    @needs_read_lock
2421
 
    def get_inventory(self, revision_id):
2422
 
        """Get Inventory object by revision id."""
2423
 
        return self.iter_inventories([revision_id]).next()
2424
 
 
2425
 
    def iter_inventories(self, revision_ids, ordering=None):
2426
 
        """Get many inventories by revision_ids.
2427
 
 
2428
 
        This will buffer some or all of the texts used in constructing the
2429
 
        inventories in memory, but will only parse a single inventory at a
2430
 
        time.
2431
 
 
2432
 
        :param revision_ids: The expected revision ids of the inventories.
2433
 
        :param ordering: optional ordering, e.g. 'topological'.  If not
2434
 
            specified, the order of revision_ids will be preserved (by
2435
 
            buffering if necessary).
2436
 
        :return: An iterator of inventories.
2437
 
        """
2438
 
        if ((None in revision_ids)
2439
 
            or (_mod_revision.NULL_REVISION in revision_ids)):
2440
 
            raise ValueError('cannot get null revision inventory')
2441
 
        return self._iter_inventories(revision_ids, ordering)
2442
 
 
2443
 
    def _iter_inventories(self, revision_ids, ordering):
2444
 
        """single-document based inventory iteration."""
2445
 
        inv_xmls = self._iter_inventory_xmls(revision_ids, ordering)
2446
 
        for text, revision_id in inv_xmls:
2447
 
            yield self._deserialise_inventory(revision_id, text)
2448
 
 
2449
 
    def _iter_inventory_xmls(self, revision_ids, ordering):
2450
 
        if ordering is None:
2451
 
            order_as_requested = True
2452
 
            ordering = 'unordered'
2453
 
        else:
2454
 
            order_as_requested = False
2455
 
        keys = [(revision_id,) for revision_id in revision_ids]
2456
 
        if not keys:
2457
 
            return
2458
 
        if order_as_requested:
2459
 
            key_iter = iter(keys)
2460
 
            next_key = key_iter.next()
2461
 
        stream = self.inventories.get_record_stream(keys, ordering, True)
2462
 
        text_chunks = {}
2463
 
        for record in stream:
2464
 
            if record.storage_kind != 'absent':
2465
 
                chunks = record.get_bytes_as('chunked')
2466
 
                if order_as_requested:
2467
 
                    text_chunks[record.key] = chunks
2468
 
                else:
2469
 
                    yield ''.join(chunks), record.key[-1]
2470
 
            else:
2471
 
                raise errors.NoSuchRevision(self, record.key)
2472
 
            if order_as_requested:
2473
 
                # Yield as many results as we can while preserving order.
2474
 
                while next_key in text_chunks:
2475
 
                    chunks = text_chunks.pop(next_key)
2476
 
                    yield ''.join(chunks), next_key[-1]
2477
 
                    try:
2478
 
                        next_key = key_iter.next()
2479
 
                    except StopIteration:
2480
 
                        # We still want to fully consume the get_record_stream,
2481
 
                        # just in case it is not actually finished at this point
2482
 
                        next_key = None
2483
 
                        break
2484
 
 
2485
 
    def _deserialise_inventory(self, revision_id, xml):
2486
 
        """Transform the xml into an inventory object.
2487
 
 
2488
 
        :param revision_id: The expected revision id of the inventory.
2489
 
        :param xml: A serialised inventory.
2490
 
        """
2491
 
        result = self._serializer.read_inventory_from_string(xml, revision_id,
2492
 
                    entry_cache=self._inventory_entry_cache,
2493
 
                    return_from_cache=self._safe_to_return_from_cache)
2494
 
        if result.revision_id != revision_id:
2495
 
            raise AssertionError('revision id mismatch %s != %s' % (
2496
 
                result.revision_id, revision_id))
2497
 
        return result
2498
 
 
2499
 
    def get_serializer_format(self):
2500
 
        return self._serializer.format_num
2501
 
 
2502
 
    @needs_read_lock
2503
 
    def _get_inventory_xml(self, revision_id):
2504
 
        """Get serialized inventory as a string."""
2505
 
        texts = self._iter_inventory_xmls([revision_id], 'unordered')
2506
 
        try:
2507
 
            text, revision_id = texts.next()
2508
 
        except StopIteration:
2509
 
            raise errors.HistoryMissing(self, 'inventory', revision_id)
2510
 
        return text
 
969
        raise NotImplementedError(self.iter_files_bytes)
2511
970
 
2512
971
    def get_rev_id_for_revno(self, revno, known_pair):
2513
972
        """Return the revision id of a revno, given a later (revno, revid)
2544
1003
            raise AssertionError('_iter_for_revno returned too much history')
2545
1004
        return (True, partial_history[-1])
2546
1005
 
 
1006
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
2547
1007
    def iter_reverse_revision_history(self, revision_id):
2548
1008
        """Iterate backwards through revision ids in the lefthand history
2549
1009
 
2586
1046
 
2587
1047
        `revision_id` may be NULL_REVISION for the empty tree revision.
2588
1048
        """
2589
 
        revision_id = _mod_revision.ensure_null(revision_id)
2590
 
        # TODO: refactor this to use an existing revision object
2591
 
        # so we don't need to read it in twice.
2592
 
        if revision_id == _mod_revision.NULL_REVISION:
2593
 
            return RevisionTree(self, Inventory(root_id=None),
2594
 
                                _mod_revision.NULL_REVISION)
2595
 
        else:
2596
 
            inv = self.get_inventory(revision_id)
2597
 
            return RevisionTree(self, inv, revision_id)
 
1049
        raise NotImplementedError(self.revision_tree)
2598
1050
 
2599
1051
    def revision_trees(self, revision_ids):
2600
1052
        """Return Trees for revisions in this repository.
2602
1054
        :param revision_ids: a sequence of revision-ids;
2603
1055
          a revision-id may not be None or 'null:'
2604
1056
        """
2605
 
        inventories = self.iter_inventories(revision_ids)
2606
 
        for inv in inventories:
2607
 
            yield RevisionTree(self, inv, inv.revision_id)
2608
 
 
2609
 
    def _filtered_revision_trees(self, revision_ids, file_ids):
2610
 
        """Return Tree for a revision on this branch with only some files.
2611
 
 
2612
 
        :param revision_ids: a sequence of revision-ids;
2613
 
          a revision-id may not be None or 'null:'
2614
 
        :param file_ids: if not None, the result is filtered
2615
 
          so that only those file-ids, their parents and their
2616
 
          children are included.
2617
 
        """
2618
 
        inventories = self.iter_inventories(revision_ids)
2619
 
        for inv in inventories:
2620
 
            # Should we introduce a FilteredRevisionTree class rather
2621
 
            # than pre-filter the inventory here?
2622
 
            filtered_inv = inv.filter(file_ids)
2623
 
            yield RevisionTree(self, filtered_inv, filtered_inv.revision_id)
 
1057
        raise NotImplementedError(self.revision_trees)
2624
1058
 
2625
1059
    @needs_read_lock
 
1060
    @symbol_versioning.deprecated_method(
 
1061
        symbol_versioning.deprecated_in((2, 4, 0)))
2626
1062
    def get_ancestry(self, revision_id, topo_sorted=True):
2627
1063
        """Return a list of revision-ids integrated by a revision.
2628
1064
 
2632
1068
 
2633
1069
        This is topologically sorted.
2634
1070
        """
 
1071
        if 'evil' in debug.debug_flags:
 
1072
            mutter_callsite(2, "get_ancestry is linear with history.")
2635
1073
        if _mod_revision.is_null(revision_id):
2636
1074
            return [None]
2637
1075
        if not self.has_revision(revision_id):
2678
1116
 
2679
1117
    def get_parent_map(self, revision_ids):
2680
1118
        """See graph.StackedParentsProvider.get_parent_map"""
 
1119
        raise NotImplementedError(self.get_parent_map)
 
1120
 
 
1121
    def _get_parent_map_no_fallbacks(self, revision_ids):
 
1122
        """Same as Repository.get_parent_map except doesn't query fallbacks."""
2681
1123
        # revisions index works in keys; this just works in revisions
2682
1124
        # therefore wrap and unwrap
2683
1125
        query_keys = []
2689
1131
                raise ValueError('get_parent_map(None) is not valid')
2690
1132
            else:
2691
1133
                query_keys.append((revision_id ,))
 
1134
        vf = self.revisions.without_fallbacks()
2692
1135
        for ((revision_id,), parent_keys) in \
2693
 
                self.revisions.get_parent_map(query_keys).iteritems():
 
1136
                vf.get_parent_map(query_keys).iteritems():
2694
1137
            if parent_keys:
2695
1138
                result[revision_id] = tuple([parent_revid
2696
1139
                    for (parent_revid,) in parent_keys])
2699
1142
        return result
2700
1143
 
2701
1144
    def _make_parents_provider(self):
2702
 
        return self
 
1145
        if not self._format.supports_external_lookups:
 
1146
            return self
 
1147
        return graph.StackedParentsProvider(_LazyListJoin(
 
1148
            [self._make_parents_provider_unstacked()],
 
1149
            self._fallback_repositories))
 
1150
 
 
1151
    def _make_parents_provider_unstacked(self):
 
1152
        return graph.CallableToParentsProviderAdapter(
 
1153
            self._get_parent_map_no_fallbacks)
2703
1154
 
2704
1155
    @needs_read_lock
2705
1156
    def get_known_graph_ancestry(self, revision_ids):
2706
1157
        """Return the known graph for a set of revision ids and their ancestors.
2707
1158
        """
2708
 
        st = static_tuple.StaticTuple
2709
 
        revision_keys = [st(r_id).intern() for r_id in revision_ids]
2710
 
        known_graph = self.revisions.get_known_graph_ancestry(revision_keys)
2711
 
        return graph.GraphThunkIdsToKeys(known_graph)
 
1159
        raise NotImplementedError(self.get_known_graph_ancestry)
 
1160
 
 
1161
    def get_file_graph(self):
 
1162
        """Return the graph walker for files."""
 
1163
        raise NotImplementedError(self.get_file_graph)
2712
1164
 
2713
1165
    def get_graph(self, other_repository=None):
2714
1166
        """Return the graph walker for this repository format"""
2719
1171
                [parents_provider, other_repository._make_parents_provider()])
2720
1172
        return graph.Graph(parents_provider)
2721
1173
 
2722
 
    def _get_versioned_file_checker(self, text_key_references=None,
2723
 
        ancestors=None):
2724
 
        """Return an object suitable for checking versioned files.
2725
 
        
2726
 
        :param text_key_references: if non-None, an already built
2727
 
            dictionary mapping text keys ((fileid, revision_id) tuples)
2728
 
            to whether they were referred to by the inventory of the
2729
 
            revision_id that they contain. If None, this will be
2730
 
            calculated.
2731
 
        :param ancestors: Optional result from
2732
 
            self.get_graph().get_parent_map(self.all_revision_ids()) if already
2733
 
            available.
2734
 
        """
2735
 
        return _VersionedFileChecker(self,
2736
 
            text_key_references=text_key_references, ancestors=ancestors)
2737
 
 
2738
1174
    def revision_ids_to_search_result(self, result_set):
2739
1175
        """Convert a set of revision ids to a graph SearchResult."""
2740
1176
        result_parents = set()
2766
1202
 
2767
1203
    @needs_write_lock
2768
1204
    def sign_revision(self, revision_id, gpg_strategy):
2769
 
        plaintext = Testament.from_revision(self, revision_id).as_short_text()
 
1205
        testament = _mod_testament.Testament.from_revision(self, revision_id)
 
1206
        plaintext = testament.as_short_text()
2770
1207
        self.store_revision_signature(gpg_strategy, plaintext, revision_id)
2771
1208
 
2772
1209
    @needs_read_lock
 
1210
    def verify_revision(self, revision_id, gpg_strategy):
 
1211
        """Verify the signature on a revision.
 
1212
        
 
1213
        :param revision_id: the revision to verify
 
1214
        :gpg_strategy: the GPGStrategy object to used
 
1215
        
 
1216
        :return: gpg.SIGNATURE_VALID or a failed SIGNATURE_ value
 
1217
        """
 
1218
        if not self.has_signature_for_revision_id(revision_id):
 
1219
            return gpg.SIGNATURE_NOT_SIGNED, None
 
1220
        signature = self.get_signature_text(revision_id)
 
1221
 
 
1222
        testament = _mod_testament.Testament.from_revision(self, revision_id)
 
1223
        plaintext = testament.as_short_text()
 
1224
 
 
1225
        return gpg_strategy.verify(signature, plaintext)
 
1226
 
2773
1227
    def has_signature_for_revision_id(self, revision_id):
2774
1228
        """Query for a revision signature for revision_id in the repository."""
2775
 
        if not self.has_revision(revision_id):
2776
 
            raise errors.NoSuchRevision(self, revision_id)
2777
 
        sig_present = (1 == len(
2778
 
            self.signatures.get_parent_map([(revision_id,)])))
2779
 
        return sig_present
 
1229
        raise NotImplementedError(self.has_signature_for_revision_id)
2780
1230
 
2781
 
    @needs_read_lock
2782
1231
    def get_signature_text(self, revision_id):
2783
1232
        """Return the text for a signature."""
2784
 
        stream = self.signatures.get_record_stream([(revision_id,)],
2785
 
            'unordered', True)
2786
 
        record = stream.next()
2787
 
        if record.storage_kind == 'absent':
2788
 
            raise errors.NoSuchRevision(self, revision_id)
2789
 
        return record.get_bytes_as('fulltext')
 
1233
        raise NotImplementedError(self.get_signature_text)
2790
1234
 
2791
 
    @needs_read_lock
2792
1235
    def check(self, revision_ids=None, callback_refs=None, check_repo=True):
2793
1236
        """Check consistency of all history of given revision_ids.
2794
1237
 
2802
1245
        :param check_repo: If False do not check the repository contents, just 
2803
1246
            calculate the data callback_refs requires and call them back.
2804
1247
        """
2805
 
        return self._check(revision_ids, callback_refs=callback_refs,
 
1248
        return self._check(revision_ids=revision_ids, callback_refs=callback_refs,
2806
1249
            check_repo=check_repo)
2807
1250
 
2808
 
    def _check(self, revision_ids, callback_refs, check_repo):
2809
 
        result = check.Check(self, check_repo=check_repo)
2810
 
        result.check(callback_refs)
2811
 
        return result
 
1251
    def _check(self, revision_ids=None, callback_refs=None, check_repo=True):
 
1252
        raise NotImplementedError(self.check)
2812
1253
 
2813
1254
    def _warn_if_deprecated(self, branch=None):
 
1255
        if not self._format.is_deprecated():
 
1256
            return
2814
1257
        global _deprecation_warning_done
2815
1258
        if _deprecation_warning_done:
2816
1259
            return
2846
1289
                except UnicodeDecodeError:
2847
1290
                    raise errors.NonAsciiRevisionId(method, self)
2848
1291
 
2849
 
    def revision_graph_can_have_wrong_parents(self):
2850
 
        """Is it possible for this repository to have a revision graph with
2851
 
        incorrect parents?
2852
 
 
2853
 
        If True, then this repository must also implement
2854
 
        _find_inconsistent_revision_parents so that check and reconcile can
2855
 
        check for inconsistencies before proceeding with other checks that may
2856
 
        depend on the revision index being consistent.
2857
 
        """
2858
 
        raise NotImplementedError(self.revision_graph_can_have_wrong_parents)
2859
 
 
2860
 
 
2861
 
def install_revision(repository, rev, revision_tree):
2862
 
    """Install all revision data into a repository."""
2863
 
    install_revisions(repository, [(rev, revision_tree, None)])
2864
 
 
2865
 
 
2866
 
def install_revisions(repository, iterable, num_revisions=None, pb=None):
2867
 
    """Install all revision data into a repository.
2868
 
 
2869
 
    Accepts an iterable of revision, tree, signature tuples.  The signature
2870
 
    may be None.
2871
 
    """
2872
 
    repository.start_write_group()
2873
 
    try:
2874
 
        inventory_cache = lru_cache.LRUCache(10)
2875
 
        for n, (revision, revision_tree, signature) in enumerate(iterable):
2876
 
            _install_revision(repository, revision, revision_tree, signature,
2877
 
                inventory_cache)
2878
 
            if pb is not None:
2879
 
                pb.update('Transferring revisions', n + 1, num_revisions)
2880
 
    except:
2881
 
        repository.abort_write_group()
2882
 
        raise
2883
 
    else:
2884
 
        repository.commit_write_group()
2885
 
 
2886
 
 
2887
 
def _install_revision(repository, rev, revision_tree, signature,
2888
 
    inventory_cache):
2889
 
    """Install all revision data into a repository."""
2890
 
    present_parents = []
2891
 
    parent_trees = {}
2892
 
    for p_id in rev.parent_ids:
2893
 
        if repository.has_revision(p_id):
2894
 
            present_parents.append(p_id)
2895
 
            parent_trees[p_id] = repository.revision_tree(p_id)
2896
 
        else:
2897
 
            parent_trees[p_id] = repository.revision_tree(
2898
 
                                     _mod_revision.NULL_REVISION)
2899
 
 
2900
 
    inv = revision_tree.inventory
2901
 
    entries = inv.iter_entries()
2902
 
    # backwards compatibility hack: skip the root id.
2903
 
    if not repository.supports_rich_root():
2904
 
        path, root = entries.next()
2905
 
        if root.revision != rev.revision_id:
2906
 
            raise errors.IncompatibleRevision(repr(repository))
2907
 
    text_keys = {}
2908
 
    for path, ie in entries:
2909
 
        text_keys[(ie.file_id, ie.revision)] = ie
2910
 
    text_parent_map = repository.texts.get_parent_map(text_keys)
2911
 
    missing_texts = set(text_keys) - set(text_parent_map)
2912
 
    # Add the texts that are not already present
2913
 
    for text_key in missing_texts:
2914
 
        ie = text_keys[text_key]
2915
 
        text_parents = []
2916
 
        # FIXME: TODO: The following loop overlaps/duplicates that done by
2917
 
        # commit to determine parents. There is a latent/real bug here where
2918
 
        # the parents inserted are not those commit would do - in particular
2919
 
        # they are not filtered by heads(). RBC, AB
2920
 
        for revision, tree in parent_trees.iteritems():
2921
 
            if ie.file_id not in tree:
2922
 
                continue
2923
 
            parent_id = tree.inventory[ie.file_id].revision
2924
 
            if parent_id in text_parents:
2925
 
                continue
2926
 
            text_parents.append((ie.file_id, parent_id))
2927
 
        lines = revision_tree.get_file(ie.file_id).readlines()
2928
 
        repository.texts.add_lines(text_key, text_parents, lines)
2929
 
    try:
2930
 
        # install the inventory
2931
 
        if repository._format._commit_inv_deltas and len(rev.parent_ids):
2932
 
            # Cache this inventory
2933
 
            inventory_cache[rev.revision_id] = inv
2934
 
            try:
2935
 
                basis_inv = inventory_cache[rev.parent_ids[0]]
2936
 
            except KeyError:
2937
 
                repository.add_inventory(rev.revision_id, inv, present_parents)
2938
 
            else:
2939
 
                delta = inv._make_delta(basis_inv)
2940
 
                repository.add_inventory_by_delta(rev.parent_ids[0], delta,
2941
 
                    rev.revision_id, present_parents)
2942
 
        else:
2943
 
            repository.add_inventory(rev.revision_id, inv, present_parents)
2944
 
    except errors.RevisionAlreadyPresent:
2945
 
        pass
2946
 
    if signature is not None:
2947
 
        repository.add_signature_text(rev.revision_id, signature)
2948
 
    repository.add_revision(rev.revision_id, rev, inv)
2949
 
 
2950
1292
 
2951
1293
class MetaDirRepository(Repository):
2952
1294
    """Repositories in the new meta-dir layout.
2987
1329
        return not self._transport.has('no-working-trees')
2988
1330
 
2989
1331
 
2990
 
class MetaDirVersionedFileRepository(MetaDirRepository):
2991
 
    """Repositories in a meta-dir, that work via versioned file objects."""
 
1332
class RepositoryFormatRegistry(controldir.ControlComponentFormatRegistry):
 
1333
    """Repository format registry."""
2992
1334
 
2993
 
    def __init__(self, _format, a_bzrdir, control_files):
2994
 
        super(MetaDirVersionedFileRepository, self).__init__(_format, a_bzrdir,
2995
 
            control_files)
 
1335
    def get_default(self):
 
1336
        """Return the current default format."""
 
1337
        from bzrlib import bzrdir
 
1338
        return bzrdir.format_registry.make_bzrdir('default').repository_format
2996
1339
 
2997
1340
 
2998
1341
network_format_registry = registry.FormatRegistry()
3004
1347
"""
3005
1348
 
3006
1349
 
3007
 
format_registry = registry.FormatRegistry(network_format_registry)
 
1350
format_registry = RepositoryFormatRegistry(network_format_registry)
3008
1351
"""Registry of formats, indexed by their BzrDirMetaFormat format string.
3009
1352
 
3010
1353
This can contain either format instances themselves, or classes/factories that
3015
1358
#####################################################################
3016
1359
# Repository Formats
3017
1360
 
3018
 
class RepositoryFormat(object):
 
1361
class RepositoryFormat(controldir.ControlComponentFormat):
3019
1362
    """A repository format.
3020
1363
 
3021
1364
    Formats provide four things:
3056
1399
    # Does this format support CHK bytestring lookups. Set to True or False in
3057
1400
    # derived classes.
3058
1401
    supports_chks = None
3059
 
    # Should commit add an inventory, or an inventory delta to the repository.
3060
 
    _commit_inv_deltas = True
3061
 
    # What order should fetch operations request streams in?
3062
 
    # The default is unordered as that is the cheapest for an origin to
3063
 
    # provide.
3064
 
    _fetch_order = 'unordered'
3065
 
    # Does this repository format use deltas that can be fetched as-deltas ?
3066
 
    # (E.g. knits, where the knit deltas can be transplanted intact.
3067
 
    # We default to False, which will ensure that enough data to get
3068
 
    # a full text out of any fetch stream will be grabbed.
3069
 
    _fetch_uses_deltas = False
3070
1402
    # Should fetch trigger a reconcile after the fetch? Only needed for
3071
1403
    # some repository formats that can suffer internal inconsistencies.
3072
1404
    _fetch_reconcile = False
3078
1410
    # help), and for fetching when data won't have come from the same
3079
1411
    # compressor.
3080
1412
    pack_compresses = False
3081
 
    # Does the repository inventory storage understand references to trees?
 
1413
    # Does the repository storage understand references to trees?
3082
1414
    supports_tree_reference = None
3083
1415
    # Is the format experimental ?
3084
1416
    experimental = False
3085
 
    # Does this repository format escape funky characters, or does it create files with
3086
 
    # similar names as the versioned files in its contents on disk ?
3087
 
    supports_funky_characters = True
 
1417
    # Does this repository format escape funky characters, or does it create
 
1418
    # files with similar names as the versioned files in its contents on disk
 
1419
    # ?
 
1420
    supports_funky_characters = None
 
1421
    # Does this repository format support leaving locks?
 
1422
    supports_leaving_lock = None
 
1423
    # Does this format support the full VersionedFiles interface?
 
1424
    supports_full_versioned_files = None
 
1425
    # Does this format support signing revision signatures?
 
1426
    supports_revision_signatures = True
 
1427
    # Can the revision graph have incorrect parents?
 
1428
    revision_graph_can_have_wrong_parents = None
 
1429
    # Does this format support rich root data?
 
1430
    rich_root_data = None
 
1431
    # Does this format support explicitly versioned directories?
 
1432
    supports_versioned_directories = None
3088
1433
 
3089
1434
    def __repr__(self):
3090
1435
        return "%s()" % self.__class__.__name__
3115
1460
                                            kind='repository')
3116
1461
 
3117
1462
    @classmethod
 
1463
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3118
1464
    def register_format(klass, format):
3119
 
        format_registry.register(format.get_format_string(), format)
 
1465
        format_registry.register(format)
3120
1466
 
3121
1467
    @classmethod
 
1468
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3122
1469
    def unregister_format(klass, format):
3123
 
        format_registry.remove(format.get_format_string())
 
1470
        format_registry.remove(format)
3124
1471
 
3125
1472
    @classmethod
 
1473
    @symbol_versioning.deprecated_method(symbol_versioning.deprecated_in((2, 4, 0)))
3126
1474
    def get_default_format(klass):
3127
1475
        """Return the current default format."""
3128
 
        from bzrlib import bzrdir
3129
 
        return bzrdir.format_registry.make_bzrdir('default').repository_format
 
1476
        return format_registry.get_default()
3130
1477
 
3131
1478
    def get_format_string(self):
3132
1479
        """Return the ASCII format string that identifies this format.
3140
1487
        """Return the short description for this format."""
3141
1488
        raise NotImplementedError(self.get_format_description)
3142
1489
 
3143
 
    # TODO: this shouldn't be in the base class, it's specific to things that
3144
 
    # use weaves or knits -- mbp 20070207
3145
 
    def _get_versioned_file_store(self,
3146
 
                                  name,
3147
 
                                  transport,
3148
 
                                  control_files,
3149
 
                                  prefixed=True,
3150
 
                                  versionedfile_class=None,
3151
 
                                  versionedfile_kwargs={},
3152
 
                                  escaped=False):
3153
 
        if versionedfile_class is None:
3154
 
            versionedfile_class = self._versionedfile_class
3155
 
        weave_transport = control_files._transport.clone(name)
3156
 
        dir_mode = control_files._dir_mode
3157
 
        file_mode = control_files._file_mode
3158
 
        return VersionedFileStore(weave_transport, prefixed=prefixed,
3159
 
                                  dir_mode=dir_mode,
3160
 
                                  file_mode=file_mode,
3161
 
                                  versionedfile_class=versionedfile_class,
3162
 
                                  versionedfile_kwargs=versionedfile_kwargs,
3163
 
                                  escaped=escaped)
3164
 
 
3165
1490
    def initialize(self, a_bzrdir, shared=False):
3166
1491
        """Initialize a repository of this format in a_bzrdir.
3167
1492
 
3183
1508
        """
3184
1509
        return True
3185
1510
 
 
1511
    def is_deprecated(self):
 
1512
        """Is this format deprecated?
 
1513
 
 
1514
        Deprecated formats may trigger a user-visible warning recommending
 
1515
        the user to upgrade. They are still fully supported.
 
1516
        """
 
1517
        return False
 
1518
 
3186
1519
    def network_name(self):
3187
1520
        """A simple byte string uniquely identifying this format for RPC calls.
3188
1521
 
3227
1560
    rich_root_data = False
3228
1561
    supports_tree_reference = False
3229
1562
    supports_external_lookups = False
 
1563
    supports_leaving_lock = True
3230
1564
 
3231
1565
    @property
3232
1566
    def _matchingbzrdir(self):
3270
1604
        return self.get_format_string()
3271
1605
 
3272
1606
 
3273
 
# Pre-0.8 formats that don't have a disk format string (because they are
3274
 
# versioned by the matching control directory). We use the control directories
3275
 
# disk format string as a key for the network_name because they meet the
3276
 
# constraints (simple string, unique, immutable).
3277
 
network_format_registry.register_lazy(
3278
 
    "Bazaar-NG branch, format 5\n",
3279
 
    'bzrlib.repofmt.weaverepo',
3280
 
    'RepositoryFormat5',
3281
 
)
3282
 
network_format_registry.register_lazy(
3283
 
    "Bazaar-NG branch, format 6\n",
3284
 
    'bzrlib.repofmt.weaverepo',
3285
 
    'RepositoryFormat6',
3286
 
)
3287
 
 
3288
1607
# formats which have no format string are not discoverable or independently
3289
1608
# creatable on disk, so are not registered in format_registry.  They're
3290
 
# all in bzrlib.repofmt.weaverepo now.  When an instance of one of these is
 
1609
# all in bzrlib.repofmt.knitreponow.  When an instance of one of these is
3291
1610
# needed, it's constructed directly by the BzrDir.  Non-native formats where
3292
1611
# the repository is not separately opened are similar.
3293
1612
 
3294
1613
format_registry.register_lazy(
3295
 
    'Bazaar-NG Repository format 7',
3296
 
    'bzrlib.repofmt.weaverepo',
3297
 
    'RepositoryFormat7'
3298
 
    )
3299
 
 
3300
 
format_registry.register_lazy(
3301
1614
    'Bazaar-NG Knit Repository Format 1',
3302
1615
    'bzrlib.repofmt.knitrepo',
3303
1616
    'RepositoryFormatKnit1',
3320
1633
# NOTE: These are experimental in 0.92. Stable in 1.0 and above
3321
1634
format_registry.register_lazy(
3322
1635
    'Bazaar pack repository format 1 (needs bzr 0.92)\n',
3323
 
    'bzrlib.repofmt.pack_repo',
 
1636
    'bzrlib.repofmt.knitpack_repo',
3324
1637
    'RepositoryFormatKnitPack1',
3325
1638
    )
3326
1639
format_registry.register_lazy(
3327
1640
    'Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n',
3328
 
    'bzrlib.repofmt.pack_repo',
 
1641
    'bzrlib.repofmt.knitpack_repo',
3329
1642
    'RepositoryFormatKnitPack3',
3330
1643
    )
3331
1644
format_registry.register_lazy(
3332
1645
    'Bazaar pack repository format 1 with rich root (needs bzr 1.0)\n',
3333
 
    'bzrlib.repofmt.pack_repo',
 
1646
    'bzrlib.repofmt.knitpack_repo',
3334
1647
    'RepositoryFormatKnitPack4',
3335
1648
    )
3336
1649
format_registry.register_lazy(
3337
1650
    'Bazaar RepositoryFormatKnitPack5 (bzr 1.6)\n',
3338
 
    'bzrlib.repofmt.pack_repo',
 
1651
    'bzrlib.repofmt.knitpack_repo',
3339
1652
    'RepositoryFormatKnitPack5',
3340
1653
    )
3341
1654
format_registry.register_lazy(
3342
1655
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6.1)\n',
3343
 
    'bzrlib.repofmt.pack_repo',
 
1656
    'bzrlib.repofmt.knitpack_repo',
3344
1657
    'RepositoryFormatKnitPack5RichRoot',
3345
1658
    )
3346
1659
format_registry.register_lazy(
3347
1660
    'Bazaar RepositoryFormatKnitPack5RichRoot (bzr 1.6)\n',
3348
 
    'bzrlib.repofmt.pack_repo',
 
1661
    'bzrlib.repofmt.knitpack_repo',
3349
1662
    'RepositoryFormatKnitPack5RichRootBroken',
3350
1663
    )
3351
1664
format_registry.register_lazy(
3352
1665
    'Bazaar RepositoryFormatKnitPack6 (bzr 1.9)\n',
3353
 
    'bzrlib.repofmt.pack_repo',
 
1666
    'bzrlib.repofmt.knitpack_repo',
3354
1667
    'RepositoryFormatKnitPack6',
3355
1668
    )
3356
1669
format_registry.register_lazy(
3357
1670
    'Bazaar RepositoryFormatKnitPack6RichRoot (bzr 1.9)\n',
3358
 
    'bzrlib.repofmt.pack_repo',
 
1671
    'bzrlib.repofmt.knitpack_repo',
3359
1672
    'RepositoryFormatKnitPack6RichRoot',
3360
1673
    )
3361
1674
format_registry.register_lazy(
3369
1682
format_registry.register_lazy(
3370
1683
    ("Bazaar development format 2 with subtree support "
3371
1684
        "(needs bzr.dev from before 1.8)\n"),
3372
 
    'bzrlib.repofmt.pack_repo',
 
1685
    'bzrlib.repofmt.knitpack_repo',
3373
1686
    'RepositoryFormatPackDevelopment2Subtree',
3374
1687
    )
3375
1688
format_registry.register_lazy(
3391
1704
    InterRepository.get(other).method_name(parameters).
3392
1705
    """
3393
1706
 
3394
 
    _walk_to_common_revisions_batch_size = 50
3395
1707
    _optimisers = []
3396
1708
    """The available optimised InterRepository types."""
3397
1709
 
3412
1724
        self.target.fetch(self.source, revision_id=revision_id)
3413
1725
 
3414
1726
    @needs_write_lock
3415
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
 
1727
    def fetch(self, revision_id=None, find_ghosts=False,
3416
1728
            fetch_spec=None):
3417
1729
        """Fetch the content required to construct revision_id.
3418
1730
 
3420
1732
 
3421
1733
        :param revision_id: if None all content is copied, if NULL_REVISION no
3422
1734
                            content is copied.
3423
 
        :param pb: ignored.
3424
1735
        :return: None.
3425
1736
        """
3426
 
        ui.ui_factory.warn_experimental_format_fetch(self)
3427
 
        from bzrlib.fetch import RepoFetcher
3428
 
        # See <https://launchpad.net/bugs/456077> asking for a warning here
3429
 
        if self.source._format.network_name() != self.target._format.network_name():
3430
 
            ui.ui_factory.show_user_warning('cross_format_fetch',
3431
 
                from_format=self.source._format,
3432
 
                to_format=self.target._format)
3433
 
        f = RepoFetcher(to_repository=self.target,
3434
 
                               from_repository=self.source,
3435
 
                               last_revision=revision_id,
3436
 
                               fetch_spec=fetch_spec,
3437
 
                               find_ghosts=find_ghosts)
3438
 
 
3439
 
    def _walk_to_common_revisions(self, revision_ids):
3440
 
        """Walk out from revision_ids in source to revisions target has.
3441
 
 
3442
 
        :param revision_ids: The start point for the search.
3443
 
        :return: A set of revision ids.
3444
 
        """
3445
 
        target_graph = self.target.get_graph()
3446
 
        revision_ids = frozenset(revision_ids)
3447
 
        missing_revs = set()
3448
 
        source_graph = self.source.get_graph()
3449
 
        # ensure we don't pay silly lookup costs.
3450
 
        searcher = source_graph._make_breadth_first_searcher(revision_ids)
3451
 
        null_set = frozenset([_mod_revision.NULL_REVISION])
3452
 
        searcher_exhausted = False
3453
 
        while True:
3454
 
            next_revs = set()
3455
 
            ghosts = set()
3456
 
            # Iterate the searcher until we have enough next_revs
3457
 
            while len(next_revs) < self._walk_to_common_revisions_batch_size:
3458
 
                try:
3459
 
                    next_revs_part, ghosts_part = searcher.next_with_ghosts()
3460
 
                    next_revs.update(next_revs_part)
3461
 
                    ghosts.update(ghosts_part)
3462
 
                except StopIteration:
3463
 
                    searcher_exhausted = True
3464
 
                    break
3465
 
            # If there are ghosts in the source graph, and the caller asked for
3466
 
            # them, make sure that they are present in the target.
3467
 
            # We don't care about other ghosts as we can't fetch them and
3468
 
            # haven't been asked to.
3469
 
            ghosts_to_check = set(revision_ids.intersection(ghosts))
3470
 
            revs_to_get = set(next_revs).union(ghosts_to_check)
3471
 
            if revs_to_get:
3472
 
                have_revs = set(target_graph.get_parent_map(revs_to_get))
3473
 
                # we always have NULL_REVISION present.
3474
 
                have_revs = have_revs.union(null_set)
3475
 
                # Check if the target is missing any ghosts we need.
3476
 
                ghosts_to_check.difference_update(have_revs)
3477
 
                if ghosts_to_check:
3478
 
                    # One of the caller's revision_ids is a ghost in both the
3479
 
                    # source and the target.
3480
 
                    raise errors.NoSuchRevision(
3481
 
                        self.source, ghosts_to_check.pop())
3482
 
                missing_revs.update(next_revs - have_revs)
3483
 
                # Because we may have walked past the original stop point, make
3484
 
                # sure everything is stopped
3485
 
                stop_revs = searcher.find_seen_ancestors(have_revs)
3486
 
                searcher.stop_searching_any(stop_revs)
3487
 
            if searcher_exhausted:
3488
 
                break
3489
 
        return searcher.get_result()
 
1737
        raise NotImplementedError(self.fetch)
3490
1738
 
3491
1739
    @needs_read_lock
3492
 
    def search_missing_revision_ids(self, revision_id=None, find_ghosts=True):
 
1740
    def search_missing_revision_ids(self,
 
1741
            revision_id=symbol_versioning.DEPRECATED_PARAMETER,
 
1742
            find_ghosts=True, revision_ids=None, if_present_ids=None,
 
1743
            limit=None):
3493
1744
        """Return the revision ids that source has that target does not.
3494
1745
 
3495
1746
        :param revision_id: only return revision ids included by this
3496
 
                            revision_id.
 
1747
            revision_id.
 
1748
        :param revision_ids: return revision ids included by these
 
1749
            revision_ids.  NoSuchRevision will be raised if any of these
 
1750
            revisions are not present.
 
1751
        :param if_present_ids: like revision_ids, but will not cause
 
1752
            NoSuchRevision if any of these are absent, instead they will simply
 
1753
            not be in the result.  This is useful for e.g. finding revisions
 
1754
            to fetch for tags, which may reference absent revisions.
3497
1755
        :param find_ghosts: If True find missing revisions in deep history
3498
1756
            rather than just finding the surface difference.
 
1757
        :param limit: Maximum number of revisions to return, topologically
 
1758
            ordered
3499
1759
        :return: A bzrlib.graph.SearchResult.
3500
1760
        """
3501
 
        # stop searching at found target revisions.
3502
 
        if not find_ghosts and revision_id is not None:
3503
 
            return self._walk_to_common_revisions([revision_id])
3504
 
        # generic, possibly worst case, slow code path.
3505
 
        target_ids = set(self.target.all_revision_ids())
3506
 
        if revision_id is not None:
3507
 
            source_ids = self.source.get_ancestry(revision_id)
3508
 
            if source_ids[0] is not None:
3509
 
                raise AssertionError()
3510
 
            source_ids.pop(0)
3511
 
        else:
3512
 
            source_ids = self.source.all_revision_ids()
3513
 
        result_set = set(source_ids).difference(target_ids)
3514
 
        return self.source.revision_ids_to_search_result(result_set)
 
1761
        raise NotImplementedError(self.search_missing_revision_ids)
3515
1762
 
3516
1763
    @staticmethod
3517
1764
    def _same_model(source, target):
3538
1785
                "different serializers")
3539
1786
 
3540
1787
 
3541
 
class InterSameDataRepository(InterRepository):
3542
 
    """Code for converting between repositories that represent the same data.
3543
 
 
3544
 
    Data format and model must match for this to work.
3545
 
    """
3546
 
 
3547
 
    @classmethod
3548
 
    def _get_repo_format_to_test(self):
3549
 
        """Repository format for testing with.
3550
 
 
3551
 
        InterSameData can pull from subtree to subtree and from non-subtree to
3552
 
        non-subtree, so we test this with the richest repository format.
3553
 
        """
3554
 
        from bzrlib.repofmt import knitrepo
3555
 
        return knitrepo.RepositoryFormatKnit3()
3556
 
 
3557
 
    @staticmethod
3558
 
    def is_compatible(source, target):
3559
 
        return InterRepository._same_model(source, target)
3560
 
 
3561
 
 
3562
 
class InterDifferingSerializer(InterRepository):
3563
 
 
3564
 
    @classmethod
3565
 
    def _get_repo_format_to_test(self):
3566
 
        return None
3567
 
 
3568
 
    @staticmethod
3569
 
    def is_compatible(source, target):
3570
 
        """Be compatible with Knit2 source and Knit3 target"""
3571
 
        # This is redundant with format.check_conversion_target(), however that
3572
 
        # raises an exception, and we just want to say "False" as in we won't
3573
 
        # support converting between these formats.
3574
 
        if 'IDS_never' in debug.debug_flags:
3575
 
            return False
3576
 
        if source.supports_rich_root() and not target.supports_rich_root():
3577
 
            return False
3578
 
        if (source._format.supports_tree_reference
3579
 
            and not target._format.supports_tree_reference):
3580
 
            return False
3581
 
        if target._fallback_repositories and target._format.supports_chks:
3582
 
            # IDS doesn't know how to copy CHKs for the parent inventories it
3583
 
            # adds to stacked repos.
3584
 
            return False
3585
 
        if 'IDS_always' in debug.debug_flags:
3586
 
            return True
3587
 
        # Only use this code path for local source and target.  IDS does far
3588
 
        # too much IO (both bandwidth and roundtrips) over a network.
3589
 
        if not source.bzrdir.transport.base.startswith('file:///'):
3590
 
            return False
3591
 
        if not target.bzrdir.transport.base.startswith('file:///'):
3592
 
            return False
3593
 
        return True
3594
 
 
3595
 
    def _get_trees(self, revision_ids, cache):
3596
 
        possible_trees = []
3597
 
        for rev_id in revision_ids:
3598
 
            if rev_id in cache:
3599
 
                possible_trees.append((rev_id, cache[rev_id]))
3600
 
            else:
3601
 
                # Not cached, but inventory might be present anyway.
3602
 
                try:
3603
 
                    tree = self.source.revision_tree(rev_id)
3604
 
                except errors.NoSuchRevision:
3605
 
                    # Nope, parent is ghost.
3606
 
                    pass
3607
 
                else:
3608
 
                    cache[rev_id] = tree
3609
 
                    possible_trees.append((rev_id, tree))
3610
 
        return possible_trees
3611
 
 
3612
 
    def _get_delta_for_revision(self, tree, parent_ids, possible_trees):
3613
 
        """Get the best delta and base for this revision.
3614
 
 
3615
 
        :return: (basis_id, delta)
3616
 
        """
3617
 
        deltas = []
3618
 
        # Generate deltas against each tree, to find the shortest.
3619
 
        texts_possibly_new_in_tree = set()
3620
 
        for basis_id, basis_tree in possible_trees:
3621
 
            delta = tree.inventory._make_delta(basis_tree.inventory)
3622
 
            for old_path, new_path, file_id, new_entry in delta:
3623
 
                if new_path is None:
3624
 
                    # This file_id isn't present in the new rev, so we don't
3625
 
                    # care about it.
3626
 
                    continue
3627
 
                if not new_path:
3628
 
                    # Rich roots are handled elsewhere...
3629
 
                    continue
3630
 
                kind = new_entry.kind
3631
 
                if kind != 'directory' and kind != 'file':
3632
 
                    # No text record associated with this inventory entry.
3633
 
                    continue
3634
 
                # This is a directory or file that has changed somehow.
3635
 
                texts_possibly_new_in_tree.add((file_id, new_entry.revision))
3636
 
            deltas.append((len(delta), basis_id, delta))
3637
 
        deltas.sort()
3638
 
        return deltas[0][1:]
3639
 
 
3640
 
    def _fetch_parent_invs_for_stacking(self, parent_map, cache):
3641
 
        """Find all parent revisions that are absent, but for which the
3642
 
        inventory is present, and copy those inventories.
3643
 
 
3644
 
        This is necessary to preserve correctness when the source is stacked
3645
 
        without fallbacks configured.  (Note that in cases like upgrade the
3646
 
        source may be not have _fallback_repositories even though it is
3647
 
        stacked.)
3648
 
        """
3649
 
        parent_revs = set()
3650
 
        for parents in parent_map.values():
3651
 
            parent_revs.update(parents)
3652
 
        present_parents = self.source.get_parent_map(parent_revs)
3653
 
        absent_parents = set(parent_revs).difference(present_parents)
3654
 
        parent_invs_keys_for_stacking = self.source.inventories.get_parent_map(
3655
 
            (rev_id,) for rev_id in absent_parents)
3656
 
        parent_inv_ids = [key[-1] for key in parent_invs_keys_for_stacking]
3657
 
        for parent_tree in self.source.revision_trees(parent_inv_ids):
3658
 
            current_revision_id = parent_tree.get_revision_id()
3659
 
            parents_parents_keys = parent_invs_keys_for_stacking[
3660
 
                (current_revision_id,)]
3661
 
            parents_parents = [key[-1] for key in parents_parents_keys]
3662
 
            basis_id = _mod_revision.NULL_REVISION
3663
 
            basis_tree = self.source.revision_tree(basis_id)
3664
 
            delta = parent_tree.inventory._make_delta(basis_tree.inventory)
3665
 
            self.target.add_inventory_by_delta(
3666
 
                basis_id, delta, current_revision_id, parents_parents)
3667
 
            cache[current_revision_id] = parent_tree
3668
 
 
3669
 
    def _fetch_batch(self, revision_ids, basis_id, cache):
3670
 
        """Fetch across a few revisions.
3671
 
 
3672
 
        :param revision_ids: The revisions to copy
3673
 
        :param basis_id: The revision_id of a tree that must be in cache, used
3674
 
            as a basis for delta when no other base is available
3675
 
        :param cache: A cache of RevisionTrees that we can use.
3676
 
        :return: The revision_id of the last converted tree. The RevisionTree
3677
 
            for it will be in cache
3678
 
        """
3679
 
        # Walk though all revisions; get inventory deltas, copy referenced
3680
 
        # texts that delta references, insert the delta, revision and
3681
 
        # signature.
3682
 
        root_keys_to_create = set()
3683
 
        text_keys = set()
3684
 
        pending_deltas = []
3685
 
        pending_revisions = []
3686
 
        parent_map = self.source.get_parent_map(revision_ids)
3687
 
        self._fetch_parent_invs_for_stacking(parent_map, cache)
3688
 
        self.source._safe_to_return_from_cache = True
3689
 
        for tree in self.source.revision_trees(revision_ids):
3690
 
            # Find a inventory delta for this revision.
3691
 
            # Find text entries that need to be copied, too.
3692
 
            current_revision_id = tree.get_revision_id()
3693
 
            parent_ids = parent_map.get(current_revision_id, ())
3694
 
            parent_trees = self._get_trees(parent_ids, cache)
3695
 
            possible_trees = list(parent_trees)
3696
 
            if len(possible_trees) == 0:
3697
 
                # There either aren't any parents, or the parents are ghosts,
3698
 
                # so just use the last converted tree.
3699
 
                possible_trees.append((basis_id, cache[basis_id]))
3700
 
            basis_id, delta = self._get_delta_for_revision(tree, parent_ids,
3701
 
                                                           possible_trees)
3702
 
            revision = self.source.get_revision(current_revision_id)
3703
 
            pending_deltas.append((basis_id, delta,
3704
 
                current_revision_id, revision.parent_ids))
3705
 
            if self._converting_to_rich_root:
3706
 
                self._revision_id_to_root_id[current_revision_id] = \
3707
 
                    tree.get_root_id()
3708
 
            # Determine which texts are in present in this revision but not in
3709
 
            # any of the available parents.
3710
 
            texts_possibly_new_in_tree = set()
3711
 
            for old_path, new_path, file_id, entry in delta:
3712
 
                if new_path is None:
3713
 
                    # This file_id isn't present in the new rev
3714
 
                    continue
3715
 
                if not new_path:
3716
 
                    # This is the root
3717
 
                    if not self.target.supports_rich_root():
3718
 
                        # The target doesn't support rich root, so we don't
3719
 
                        # copy
3720
 
                        continue
3721
 
                    if self._converting_to_rich_root:
3722
 
                        # This can't be copied normally, we have to insert
3723
 
                        # it specially
3724
 
                        root_keys_to_create.add((file_id, entry.revision))
3725
 
                        continue
3726
 
                kind = entry.kind
3727
 
                texts_possibly_new_in_tree.add((file_id, entry.revision))
3728
 
            for basis_id, basis_tree in possible_trees:
3729
 
                basis_inv = basis_tree.inventory
3730
 
                for file_key in list(texts_possibly_new_in_tree):
3731
 
                    file_id, file_revision = file_key
3732
 
                    try:
3733
 
                        entry = basis_inv[file_id]
3734
 
                    except errors.NoSuchId:
3735
 
                        continue
3736
 
                    if entry.revision == file_revision:
3737
 
                        texts_possibly_new_in_tree.remove(file_key)
3738
 
            text_keys.update(texts_possibly_new_in_tree)
3739
 
            pending_revisions.append(revision)
3740
 
            cache[current_revision_id] = tree
3741
 
            basis_id = current_revision_id
3742
 
        self.source._safe_to_return_from_cache = False
3743
 
        # Copy file texts
3744
 
        from_texts = self.source.texts
3745
 
        to_texts = self.target.texts
3746
 
        if root_keys_to_create:
3747
 
            root_stream = _mod_fetch._new_root_data_stream(
3748
 
                root_keys_to_create, self._revision_id_to_root_id, parent_map,
3749
 
                self.source)
3750
 
            to_texts.insert_record_stream(root_stream)
3751
 
        to_texts.insert_record_stream(from_texts.get_record_stream(
3752
 
            text_keys, self.target._format._fetch_order,
3753
 
            not self.target._format._fetch_uses_deltas))
3754
 
        # insert inventory deltas
3755
 
        for delta in pending_deltas:
3756
 
            self.target.add_inventory_by_delta(*delta)
3757
 
        if self.target._fallback_repositories:
3758
 
            # Make sure this stacked repository has all the parent inventories
3759
 
            # for the new revisions that we are about to insert.  We do this
3760
 
            # before adding the revisions so that no revision is added until
3761
 
            # all the inventories it may depend on are added.
3762
 
            # Note that this is overzealous, as we may have fetched these in an
3763
 
            # earlier batch.
3764
 
            parent_ids = set()
3765
 
            revision_ids = set()
3766
 
            for revision in pending_revisions:
3767
 
                revision_ids.add(revision.revision_id)
3768
 
                parent_ids.update(revision.parent_ids)
3769
 
            parent_ids.difference_update(revision_ids)
3770
 
            parent_ids.discard(_mod_revision.NULL_REVISION)
3771
 
            parent_map = self.source.get_parent_map(parent_ids)
3772
 
            # we iterate over parent_map and not parent_ids because we don't
3773
 
            # want to try copying any revision which is a ghost
3774
 
            for parent_tree in self.source.revision_trees(parent_map):
3775
 
                current_revision_id = parent_tree.get_revision_id()
3776
 
                parents_parents = parent_map[current_revision_id]
3777
 
                possible_trees = self._get_trees(parents_parents, cache)
3778
 
                if len(possible_trees) == 0:
3779
 
                    # There either aren't any parents, or the parents are
3780
 
                    # ghosts, so just use the last converted tree.
3781
 
                    possible_trees.append((basis_id, cache[basis_id]))
3782
 
                basis_id, delta = self._get_delta_for_revision(parent_tree,
3783
 
                    parents_parents, possible_trees)
3784
 
                self.target.add_inventory_by_delta(
3785
 
                    basis_id, delta, current_revision_id, parents_parents)
3786
 
        # insert signatures and revisions
3787
 
        for revision in pending_revisions:
3788
 
            try:
3789
 
                signature = self.source.get_signature_text(
3790
 
                    revision.revision_id)
3791
 
                self.target.add_signature_text(revision.revision_id,
3792
 
                    signature)
3793
 
            except errors.NoSuchRevision:
3794
 
                pass
3795
 
            self.target.add_revision(revision.revision_id, revision)
3796
 
        return basis_id
3797
 
 
3798
 
    def _fetch_all_revisions(self, revision_ids, pb):
3799
 
        """Fetch everything for the list of revisions.
3800
 
 
3801
 
        :param revision_ids: The list of revisions to fetch. Must be in
3802
 
            topological order.
3803
 
        :param pb: A ProgressTask
3804
 
        :return: None
3805
 
        """
3806
 
        basis_id, basis_tree = self._get_basis(revision_ids[0])
3807
 
        batch_size = 100
3808
 
        cache = lru_cache.LRUCache(100)
3809
 
        cache[basis_id] = basis_tree
3810
 
        del basis_tree # We don't want to hang on to it here
3811
 
        hints = []
3812
 
        a_graph = None
3813
 
 
3814
 
        for offset in range(0, len(revision_ids), batch_size):
3815
 
            self.target.start_write_group()
3816
 
            try:
3817
 
                pb.update('Transferring revisions', offset,
3818
 
                          len(revision_ids))
3819
 
                batch = revision_ids[offset:offset+batch_size]
3820
 
                basis_id = self._fetch_batch(batch, basis_id, cache)
3821
 
            except:
3822
 
                self.source._safe_to_return_from_cache = False
3823
 
                self.target.abort_write_group()
3824
 
                raise
3825
 
            else:
3826
 
                hint = self.target.commit_write_group()
3827
 
                if hint:
3828
 
                    hints.extend(hint)
3829
 
        if hints and self.target._format.pack_compresses:
3830
 
            self.target.pack(hint=hints)
3831
 
        pb.update('Transferring revisions', len(revision_ids),
3832
 
                  len(revision_ids))
3833
 
 
3834
 
    @needs_write_lock
3835
 
    def fetch(self, revision_id=None, pb=None, find_ghosts=False,
3836
 
            fetch_spec=None):
3837
 
        """See InterRepository.fetch()."""
3838
 
        if fetch_spec is not None:
3839
 
            raise AssertionError("Not implemented yet...")
3840
 
        ui.ui_factory.warn_experimental_format_fetch(self)
3841
 
        if (not self.source.supports_rich_root()
3842
 
            and self.target.supports_rich_root()):
3843
 
            self._converting_to_rich_root = True
3844
 
            self._revision_id_to_root_id = {}
3845
 
        else:
3846
 
            self._converting_to_rich_root = False
3847
 
        # See <https://launchpad.net/bugs/456077> asking for a warning here
3848
 
        if self.source._format.network_name() != self.target._format.network_name():
3849
 
            ui.ui_factory.show_user_warning('cross_format_fetch',
3850
 
                from_format=self.source._format,
3851
 
                to_format=self.target._format)
3852
 
        revision_ids = self.target.search_missing_revision_ids(self.source,
3853
 
            revision_id, find_ghosts=find_ghosts).get_keys()
3854
 
        if not revision_ids:
3855
 
            return 0, 0
3856
 
        revision_ids = tsort.topo_sort(
3857
 
            self.source.get_graph().get_parent_map(revision_ids))
3858
 
        if not revision_ids:
3859
 
            return 0, 0
3860
 
        # Walk though all revisions; get inventory deltas, copy referenced
3861
 
        # texts that delta references, insert the delta, revision and
3862
 
        # signature.
3863
 
        if pb is None:
3864
 
            my_pb = ui.ui_factory.nested_progress_bar()
3865
 
            pb = my_pb
3866
 
        else:
3867
 
            symbol_versioning.warn(
3868
 
                symbol_versioning.deprecated_in((1, 14, 0))
3869
 
                % "pb parameter to fetch()")
3870
 
            my_pb = None
3871
 
        try:
3872
 
            self._fetch_all_revisions(revision_ids, pb)
3873
 
        finally:
3874
 
            if my_pb is not None:
3875
 
                my_pb.finished()
3876
 
        return len(revision_ids), 0
3877
 
 
3878
 
    def _get_basis(self, first_revision_id):
3879
 
        """Get a revision and tree which exists in the target.
3880
 
 
3881
 
        This assumes that first_revision_id is selected for transmission
3882
 
        because all other ancestors are already present. If we can't find an
3883
 
        ancestor we fall back to NULL_REVISION since we know that is safe.
3884
 
 
3885
 
        :return: (basis_id, basis_tree)
3886
 
        """
3887
 
        first_rev = self.source.get_revision(first_revision_id)
3888
 
        try:
3889
 
            basis_id = first_rev.parent_ids[0]
3890
 
            # only valid as a basis if the target has it
3891
 
            self.target.get_revision(basis_id)
3892
 
            # Try to get a basis tree - if it's a ghost it will hit the
3893
 
            # NoSuchRevision case.
3894
 
            basis_tree = self.source.revision_tree(basis_id)
3895
 
        except (IndexError, errors.NoSuchRevision):
3896
 
            basis_id = _mod_revision.NULL_REVISION
3897
 
            basis_tree = self.source.revision_tree(basis_id)
3898
 
        return basis_id, basis_tree
3899
 
 
3900
 
 
3901
 
InterRepository.register_optimiser(InterDifferingSerializer)
3902
 
InterRepository.register_optimiser(InterSameDataRepository)
3903
 
 
3904
 
 
3905
1788
class CopyConverter(object):
3906
1789
    """A repository conversion tool which just performs a copy of the content.
3907
1790
 
3950
1833
        pb.finished()
3951
1834
 
3952
1835
 
3953
 
_unescape_map = {
3954
 
    'apos':"'",
3955
 
    'quot':'"',
3956
 
    'amp':'&',
3957
 
    'lt':'<',
3958
 
    'gt':'>'
3959
 
}
3960
 
 
3961
 
 
3962
 
def _unescaper(match, _map=_unescape_map):
3963
 
    code = match.group(1)
3964
 
    try:
3965
 
        return _map[code]
3966
 
    except KeyError:
3967
 
        if not code.startswith('#'):
3968
 
            raise
3969
 
        return unichr(int(code[1:])).encode('utf8')
3970
 
 
3971
 
 
3972
 
_unescape_re = None
3973
 
 
3974
 
 
3975
 
def _unescape_xml(data):
3976
 
    """Unescape predefined XML entities in a string of data."""
3977
 
    global _unescape_re
3978
 
    if _unescape_re is None:
3979
 
        _unescape_re = re.compile('\&([^;]*);')
3980
 
    return _unescape_re.sub(_unescaper, data)
3981
 
 
3982
 
 
3983
 
class _VersionedFileChecker(object):
3984
 
 
3985
 
    def __init__(self, repository, text_key_references=None, ancestors=None):
3986
 
        self.repository = repository
3987
 
        self.text_index = self.repository._generate_text_key_index(
3988
 
            text_key_references=text_key_references, ancestors=ancestors)
3989
 
 
3990
 
    def calculate_file_version_parents(self, text_key):
3991
 
        """Calculate the correct parents for a file version according to
3992
 
        the inventories.
3993
 
        """
3994
 
        parent_keys = self.text_index[text_key]
3995
 
        if parent_keys == [_mod_revision.NULL_REVISION]:
3996
 
            return ()
3997
 
        return tuple(parent_keys)
3998
 
 
3999
 
    def check_file_version_parents(self, texts, progress_bar=None):
4000
 
        """Check the parents stored in a versioned file are correct.
4001
 
 
4002
 
        It also detects file versions that are not referenced by their
4003
 
        corresponding revision's inventory.
4004
 
 
4005
 
        :returns: A tuple of (wrong_parents, dangling_file_versions).
4006
 
            wrong_parents is a dict mapping {revision_id: (stored_parents,
4007
 
            correct_parents)} for each revision_id where the stored parents
4008
 
            are not correct.  dangling_file_versions is a set of (file_id,
4009
 
            revision_id) tuples for versions that are present in this versioned
4010
 
            file, but not used by the corresponding inventory.
4011
 
        """
4012
 
        local_progress = None
4013
 
        if progress_bar is None:
4014
 
            local_progress = ui.ui_factory.nested_progress_bar()
4015
 
            progress_bar = local_progress
4016
 
        try:
4017
 
            return self._check_file_version_parents(texts, progress_bar)
4018
 
        finally:
4019
 
            if local_progress:
4020
 
                local_progress.finished()
4021
 
 
4022
 
    def _check_file_version_parents(self, texts, progress_bar):
4023
 
        """See check_file_version_parents."""
4024
 
        wrong_parents = {}
4025
 
        self.file_ids = set([file_id for file_id, _ in
4026
 
            self.text_index.iterkeys()])
4027
 
        # text keys is now grouped by file_id
4028
 
        n_versions = len(self.text_index)
4029
 
        progress_bar.update('loading text store', 0, n_versions)
4030
 
        parent_map = self.repository.texts.get_parent_map(self.text_index)
4031
 
        # On unlistable transports this could well be empty/error...
4032
 
        text_keys = self.repository.texts.keys()
4033
 
        unused_keys = frozenset(text_keys) - set(self.text_index)
4034
 
        for num, key in enumerate(self.text_index.iterkeys()):
4035
 
            progress_bar.update('checking text graph', num, n_versions)
4036
 
            correct_parents = self.calculate_file_version_parents(key)
4037
 
            try:
4038
 
                knit_parents = parent_map[key]
4039
 
            except errors.RevisionNotPresent:
4040
 
                # Missing text!
4041
 
                knit_parents = None
4042
 
            if correct_parents != knit_parents:
4043
 
                wrong_parents[key] = (knit_parents, correct_parents)
4044
 
        return wrong_parents, unused_keys
4045
 
 
4046
 
 
4047
 
def _old_get_graph(repository, revision_id):
4048
 
    """DO NOT USE. That is all. I'm serious."""
4049
 
    graph = repository.get_graph()
4050
 
    revision_graph = dict(((key, value) for key, value in
4051
 
        graph.iter_ancestry([revision_id]) if value is not None))
4052
 
    return _strip_NULL_ghosts(revision_graph)
4053
 
 
4054
 
 
4055
1836
def _strip_NULL_ghosts(revision_graph):
4056
1837
    """Also don't use this. more compatibility code for unmigrated clients."""
4057
1838
    # Filter ghosts, and null:
4063
1844
    return revision_graph
4064
1845
 
4065
1846
 
4066
 
class StreamSink(object):
4067
 
    """An object that can insert a stream into a repository.
4068
 
 
4069
 
    This interface handles the complexity of reserialising inventories and
4070
 
    revisions from different formats, and allows unidirectional insertion into
4071
 
    stacked repositories without looking for the missing basis parents
4072
 
    beforehand.
4073
 
    """
4074
 
 
4075
 
    def __init__(self, target_repo):
4076
 
        self.target_repo = target_repo
4077
 
 
4078
 
    def insert_stream(self, stream, src_format, resume_tokens):
4079
 
        """Insert a stream's content into the target repository.
4080
 
 
4081
 
        :param src_format: a bzr repository format.
4082
 
 
4083
 
        :return: a list of resume tokens and an  iterable of keys additional
4084
 
            items required before the insertion can be completed.
4085
 
        """
4086
 
        self.target_repo.lock_write()
4087
 
        try:
4088
 
            if resume_tokens:
4089
 
                self.target_repo.resume_write_group(resume_tokens)
4090
 
                is_resume = True
4091
 
            else:
4092
 
                self.target_repo.start_write_group()
4093
 
                is_resume = False
4094
 
            try:
4095
 
                # locked_insert_stream performs a commit|suspend.
4096
 
                missing_keys = self.insert_stream_without_locking(stream,
4097
 
                                    src_format, is_resume)
4098
 
                if missing_keys:
4099
 
                    # suspend the write group and tell the caller what we is
4100
 
                    # missing. We know we can suspend or else we would not have
4101
 
                    # entered this code path. (All repositories that can handle
4102
 
                    # missing keys can handle suspending a write group).
4103
 
                    write_group_tokens = self.target_repo.suspend_write_group()
4104
 
                    return write_group_tokens, missing_keys
4105
 
                hint = self.target_repo.commit_write_group()
4106
 
                to_serializer = self.target_repo._format._serializer
4107
 
                src_serializer = src_format._serializer
4108
 
                if (to_serializer != src_serializer and
4109
 
                    self.target_repo._format.pack_compresses):
4110
 
                    self.target_repo.pack(hint=hint)
4111
 
                return [], set()
4112
 
            except:
4113
 
                self.target_repo.abort_write_group(suppress_errors=True)
4114
 
                raise
4115
 
        finally:
4116
 
            self.target_repo.unlock()
4117
 
 
4118
 
    def insert_stream_without_locking(self, stream, src_format,
4119
 
                                      is_resume=False):
4120
 
        """Insert a stream's content into the target repository.
4121
 
 
4122
 
        This assumes that you already have a locked repository and an active
4123
 
        write group.
4124
 
 
4125
 
        :param src_format: a bzr repository format.
4126
 
        :param is_resume: Passed down to get_missing_parent_inventories to
4127
 
            indicate if we should be checking for missing texts at the same
4128
 
            time.
4129
 
 
4130
 
        :return: A set of keys that are missing.
4131
 
        """
4132
 
        if not self.target_repo.is_write_locked():
4133
 
            raise errors.ObjectNotLocked(self)
4134
 
        if not self.target_repo.is_in_write_group():
4135
 
            raise errors.BzrError('you must already be in a write group')
4136
 
        to_serializer = self.target_repo._format._serializer
4137
 
        src_serializer = src_format._serializer
4138
 
        new_pack = None
4139
 
        if to_serializer == src_serializer:
4140
 
            # If serializers match and the target is a pack repository, set the
4141
 
            # write cache size on the new pack.  This avoids poor performance
4142
 
            # on transports where append is unbuffered (such as
4143
 
            # RemoteTransport).  This is safe to do because nothing should read
4144
 
            # back from the target repository while a stream with matching
4145
 
            # serialization is being inserted.
4146
 
            # The exception is that a delta record from the source that should
4147
 
            # be a fulltext may need to be expanded by the target (see
4148
 
            # test_fetch_revisions_with_deltas_into_pack); but we take care to
4149
 
            # explicitly flush any buffered writes first in that rare case.
4150
 
            try:
4151
 
                new_pack = self.target_repo._pack_collection._new_pack
4152
 
            except AttributeError:
4153
 
                # Not a pack repository
4154
 
                pass
4155
 
            else:
4156
 
                new_pack.set_write_cache_size(1024*1024)
4157
 
        for substream_type, substream in stream:
4158
 
            if 'stream' in debug.debug_flags:
4159
 
                mutter('inserting substream: %s', substream_type)
4160
 
            if substream_type == 'texts':
4161
 
                self.target_repo.texts.insert_record_stream(substream)
4162
 
            elif substream_type == 'inventories':
4163
 
                if src_serializer == to_serializer:
4164
 
                    self.target_repo.inventories.insert_record_stream(
4165
 
                        substream)
4166
 
                else:
4167
 
                    self._extract_and_insert_inventories(
4168
 
                        substream, src_serializer)
4169
 
            elif substream_type == 'inventory-deltas':
4170
 
                self._extract_and_insert_inventory_deltas(
4171
 
                    substream, src_serializer)
4172
 
            elif substream_type == 'chk_bytes':
4173
 
                # XXX: This doesn't support conversions, as it assumes the
4174
 
                #      conversion was done in the fetch code.
4175
 
                self.target_repo.chk_bytes.insert_record_stream(substream)
4176
 
            elif substream_type == 'revisions':
4177
 
                # This may fallback to extract-and-insert more often than
4178
 
                # required if the serializers are different only in terms of
4179
 
                # the inventory.
4180
 
                if src_serializer == to_serializer:
4181
 
                    self.target_repo.revisions.insert_record_stream(substream)
4182
 
                else:
4183
 
                    self._extract_and_insert_revisions(substream,
4184
 
                        src_serializer)
4185
 
            elif substream_type == 'signatures':
4186
 
                self.target_repo.signatures.insert_record_stream(substream)
4187
 
            else:
4188
 
                raise AssertionError('kaboom! %s' % (substream_type,))
4189
 
        # Done inserting data, and the missing_keys calculations will try to
4190
 
        # read back from the inserted data, so flush the writes to the new pack
4191
 
        # (if this is pack format).
4192
 
        if new_pack is not None:
4193
 
            new_pack._write_data('', flush=True)
4194
 
        # Find all the new revisions (including ones from resume_tokens)
4195
 
        missing_keys = self.target_repo.get_missing_parent_inventories(
4196
 
            check_for_missing_texts=is_resume)
4197
 
        try:
4198
 
            for prefix, versioned_file in (
4199
 
                ('texts', self.target_repo.texts),
4200
 
                ('inventories', self.target_repo.inventories),
4201
 
                ('revisions', self.target_repo.revisions),
4202
 
                ('signatures', self.target_repo.signatures),
4203
 
                ('chk_bytes', self.target_repo.chk_bytes),
4204
 
                ):
4205
 
                if versioned_file is None:
4206
 
                    continue
4207
 
                # TODO: key is often going to be a StaticTuple object
4208
 
                #       I don't believe we can define a method by which
4209
 
                #       (prefix,) + StaticTuple will work, though we could
4210
 
                #       define a StaticTuple.sq_concat that would allow you to
4211
 
                #       pass in either a tuple or a StaticTuple as the second
4212
 
                #       object, so instead we could have:
4213
 
                #       StaticTuple(prefix) + key here...
4214
 
                missing_keys.update((prefix,) + key for key in
4215
 
                    versioned_file.get_missing_compression_parent_keys())
4216
 
        except NotImplementedError:
4217
 
            # cannot even attempt suspending, and missing would have failed
4218
 
            # during stream insertion.
4219
 
            missing_keys = set()
4220
 
        return missing_keys
4221
 
 
4222
 
    def _extract_and_insert_inventory_deltas(self, substream, serializer):
4223
 
        target_rich_root = self.target_repo._format.rich_root_data
4224
 
        target_tree_refs = self.target_repo._format.supports_tree_reference
4225
 
        for record in substream:
4226
 
            # Insert the delta directly
4227
 
            inventory_delta_bytes = record.get_bytes_as('fulltext')
4228
 
            deserialiser = inventory_delta.InventoryDeltaDeserializer()
4229
 
            try:
4230
 
                parse_result = deserialiser.parse_text_bytes(
4231
 
                    inventory_delta_bytes)
4232
 
            except inventory_delta.IncompatibleInventoryDelta, err:
4233
 
                trace.mutter("Incompatible delta: %s", err.msg)
4234
 
                raise errors.IncompatibleRevision(self.target_repo._format)
4235
 
            basis_id, new_id, rich_root, tree_refs, inv_delta = parse_result
4236
 
            revision_id = new_id
4237
 
            parents = [key[0] for key in record.parents]
4238
 
            self.target_repo.add_inventory_by_delta(
4239
 
                basis_id, inv_delta, revision_id, parents)
4240
 
 
4241
 
    def _extract_and_insert_inventories(self, substream, serializer,
4242
 
            parse_delta=None):
4243
 
        """Generate a new inventory versionedfile in target, converting data.
4244
 
 
4245
 
        The inventory is retrieved from the source, (deserializing it), and
4246
 
        stored in the target (reserializing it in a different format).
4247
 
        """
4248
 
        target_rich_root = self.target_repo._format.rich_root_data
4249
 
        target_tree_refs = self.target_repo._format.supports_tree_reference
4250
 
        for record in substream:
4251
 
            # It's not a delta, so it must be a fulltext in the source
4252
 
            # serializer's format.
4253
 
            bytes = record.get_bytes_as('fulltext')
4254
 
            revision_id = record.key[0]
4255
 
            inv = serializer.read_inventory_from_string(bytes, revision_id)
4256
 
            parents = [key[0] for key in record.parents]
4257
 
            self.target_repo.add_inventory(revision_id, inv, parents)
4258
 
            # No need to keep holding this full inv in memory when the rest of
4259
 
            # the substream is likely to be all deltas.
4260
 
            del inv
4261
 
 
4262
 
    def _extract_and_insert_revisions(self, substream, serializer):
4263
 
        for record in substream:
4264
 
            bytes = record.get_bytes_as('fulltext')
4265
 
            revision_id = record.key[0]
4266
 
            rev = serializer.read_revision_from_string(bytes)
4267
 
            if rev.revision_id != revision_id:
4268
 
                raise AssertionError('wtf: %s != %s' % (rev, revision_id))
4269
 
            self.target_repo.add_revision(revision_id, rev)
4270
 
 
4271
 
    def finished(self):
4272
 
        if self.target_repo._format._fetch_reconcile:
4273
 
            self.target_repo.reconcile()
4274
 
 
4275
 
 
4276
 
class StreamSource(object):
4277
 
    """A source of a stream for fetching between repositories."""
4278
 
 
4279
 
    def __init__(self, from_repository, to_format):
4280
 
        """Create a StreamSource streaming from from_repository."""
4281
 
        self.from_repository = from_repository
4282
 
        self.to_format = to_format
4283
 
        self._record_counter = RecordCounter()
4284
 
 
4285
 
    def delta_on_metadata(self):
4286
 
        """Return True if delta's are permitted on metadata streams.
4287
 
 
4288
 
        That is on revisions and signatures.
4289
 
        """
4290
 
        src_serializer = self.from_repository._format._serializer
4291
 
        target_serializer = self.to_format._serializer
4292
 
        return (self.to_format._fetch_uses_deltas and
4293
 
            src_serializer == target_serializer)
4294
 
 
4295
 
    def _fetch_revision_texts(self, revs):
4296
 
        # fetch signatures first and then the revision texts
4297
 
        # may need to be a InterRevisionStore call here.
4298
 
        from_sf = self.from_repository.signatures
4299
 
        # A missing signature is just skipped.
4300
 
        keys = [(rev_id,) for rev_id in revs]
4301
 
        signatures = versionedfile.filter_absent(from_sf.get_record_stream(
4302
 
            keys,
4303
 
            self.to_format._fetch_order,
4304
 
            not self.to_format._fetch_uses_deltas))
4305
 
        # If a revision has a delta, this is actually expanded inside the
4306
 
        # insert_record_stream code now, which is an alternate fix for
4307
 
        # bug #261339
4308
 
        from_rf = self.from_repository.revisions
4309
 
        revisions = from_rf.get_record_stream(
4310
 
            keys,
4311
 
            self.to_format._fetch_order,
4312
 
            not self.delta_on_metadata())
4313
 
        return [('signatures', signatures), ('revisions', revisions)]
4314
 
 
4315
 
    def _generate_root_texts(self, revs):
4316
 
        """This will be called by get_stream between fetching weave texts and
4317
 
        fetching the inventory weave.
4318
 
        """
4319
 
        if self._rich_root_upgrade():
4320
 
            return _mod_fetch.Inter1and2Helper(
4321
 
                self.from_repository).generate_root_texts(revs)
4322
 
        else:
4323
 
            return []
4324
 
 
4325
 
    def get_stream(self, search):
4326
 
        phase = 'file'
4327
 
        revs = search.get_keys()
4328
 
        graph = self.from_repository.get_graph()
4329
 
        revs = tsort.topo_sort(graph.get_parent_map(revs))
4330
 
        data_to_fetch = self.from_repository.item_keys_introduced_by(revs)
4331
 
        text_keys = []
4332
 
        for knit_kind, file_id, revisions in data_to_fetch:
4333
 
            if knit_kind != phase:
4334
 
                phase = knit_kind
4335
 
                # Make a new progress bar for this phase
4336
 
            if knit_kind == "file":
4337
 
                # Accumulate file texts
4338
 
                text_keys.extend([(file_id, revision) for revision in
4339
 
                    revisions])
4340
 
            elif knit_kind == "inventory":
4341
 
                # Now copy the file texts.
4342
 
                from_texts = self.from_repository.texts
4343
 
                yield ('texts', from_texts.get_record_stream(
4344
 
                    text_keys, self.to_format._fetch_order,
4345
 
                    not self.to_format._fetch_uses_deltas))
4346
 
                # Cause an error if a text occurs after we have done the
4347
 
                # copy.
4348
 
                text_keys = None
4349
 
                # Before we process the inventory we generate the root
4350
 
                # texts (if necessary) so that the inventories references
4351
 
                # will be valid.
4352
 
                for _ in self._generate_root_texts(revs):
4353
 
                    yield _
4354
 
                # we fetch only the referenced inventories because we do not
4355
 
                # know for unselected inventories whether all their required
4356
 
                # texts are present in the other repository - it could be
4357
 
                # corrupt.
4358
 
                for info in self._get_inventory_stream(revs):
4359
 
                    yield info
4360
 
            elif knit_kind == "signatures":
4361
 
                # Nothing to do here; this will be taken care of when
4362
 
                # _fetch_revision_texts happens.
4363
 
                pass
4364
 
            elif knit_kind == "revisions":
4365
 
                for record in self._fetch_revision_texts(revs):
4366
 
                    yield record
4367
 
            else:
4368
 
                raise AssertionError("Unknown knit kind %r" % knit_kind)
4369
 
 
4370
 
    def get_stream_for_missing_keys(self, missing_keys):
4371
 
        # missing keys can only occur when we are byte copying and not
4372
 
        # translating (because translation means we don't send
4373
 
        # unreconstructable deltas ever).
4374
 
        keys = {}
4375
 
        keys['texts'] = set()
4376
 
        keys['revisions'] = set()
4377
 
        keys['inventories'] = set()
4378
 
        keys['chk_bytes'] = set()
4379
 
        keys['signatures'] = set()
4380
 
        for key in missing_keys:
4381
 
            keys[key[0]].add(key[1:])
4382
 
        if len(keys['revisions']):
4383
 
            # If we allowed copying revisions at this point, we could end up
4384
 
            # copying a revision without copying its required texts: a
4385
 
            # violation of the requirements for repository integrity.
4386
 
            raise AssertionError(
4387
 
                'cannot copy revisions to fill in missing deltas %s' % (
4388
 
                    keys['revisions'],))
4389
 
        for substream_kind, keys in keys.iteritems():
4390
 
            vf = getattr(self.from_repository, substream_kind)
4391
 
            if vf is None and keys:
4392
 
                    raise AssertionError(
4393
 
                        "cannot fill in keys for a versioned file we don't"
4394
 
                        " have: %s needs %s" % (substream_kind, keys))
4395
 
            if not keys:
4396
 
                # No need to stream something we don't have
4397
 
                continue
4398
 
            if substream_kind == 'inventories':
4399
 
                # Some missing keys are genuinely ghosts, filter those out.
4400
 
                present = self.from_repository.inventories.get_parent_map(keys)
4401
 
                revs = [key[0] for key in present]
4402
 
                # Get the inventory stream more-or-less as we do for the
4403
 
                # original stream; there's no reason to assume that records
4404
 
                # direct from the source will be suitable for the sink.  (Think
4405
 
                # e.g. 2a -> 1.9-rich-root).
4406
 
                for info in self._get_inventory_stream(revs, missing=True):
4407
 
                    yield info
4408
 
                continue
4409
 
 
4410
 
            # Ask for full texts always so that we don't need more round trips
4411
 
            # after this stream.
4412
 
            # Some of the missing keys are genuinely ghosts, so filter absent
4413
 
            # records. The Sink is responsible for doing another check to
4414
 
            # ensure that ghosts don't introduce missing data for future
4415
 
            # fetches.
4416
 
            stream = versionedfile.filter_absent(vf.get_record_stream(keys,
4417
 
                self.to_format._fetch_order, True))
4418
 
            yield substream_kind, stream
4419
 
 
4420
 
    def inventory_fetch_order(self):
4421
 
        if self._rich_root_upgrade():
4422
 
            return 'topological'
4423
 
        else:
4424
 
            return self.to_format._fetch_order
4425
 
 
4426
 
    def _rich_root_upgrade(self):
4427
 
        return (not self.from_repository._format.rich_root_data and
4428
 
            self.to_format.rich_root_data)
4429
 
 
4430
 
    def _get_inventory_stream(self, revision_ids, missing=False):
4431
 
        from_format = self.from_repository._format
4432
 
        if (from_format.supports_chks and self.to_format.supports_chks and
4433
 
            from_format.network_name() == self.to_format.network_name()):
4434
 
            raise AssertionError(
4435
 
                "this case should be handled by GroupCHKStreamSource")
4436
 
        elif 'forceinvdeltas' in debug.debug_flags:
4437
 
            return self._get_convertable_inventory_stream(revision_ids,
4438
 
                    delta_versus_null=missing)
4439
 
        elif from_format.network_name() == self.to_format.network_name():
4440
 
            # Same format.
4441
 
            return self._get_simple_inventory_stream(revision_ids,
4442
 
                    missing=missing)
4443
 
        elif (not from_format.supports_chks and not self.to_format.supports_chks
4444
 
                and from_format._serializer == self.to_format._serializer):
4445
 
            # Essentially the same format.
4446
 
            return self._get_simple_inventory_stream(revision_ids,
4447
 
                    missing=missing)
4448
 
        else:
4449
 
            # Any time we switch serializations, we want to use an
4450
 
            # inventory-delta based approach.
4451
 
            return self._get_convertable_inventory_stream(revision_ids,
4452
 
                    delta_versus_null=missing)
4453
 
 
4454
 
    def _get_simple_inventory_stream(self, revision_ids, missing=False):
4455
 
        # NB: This currently reopens the inventory weave in source;
4456
 
        # using a single stream interface instead would avoid this.
4457
 
        from_weave = self.from_repository.inventories
4458
 
        if missing:
4459
 
            delta_closure = True
4460
 
        else:
4461
 
            delta_closure = not self.delta_on_metadata()
4462
 
        yield ('inventories', from_weave.get_record_stream(
4463
 
            [(rev_id,) for rev_id in revision_ids],
4464
 
            self.inventory_fetch_order(), delta_closure))
4465
 
 
4466
 
    def _get_convertable_inventory_stream(self, revision_ids,
4467
 
                                          delta_versus_null=False):
4468
 
        # The two formats are sufficiently different that there is no fast
4469
 
        # path, so we need to send just inventorydeltas, which any
4470
 
        # sufficiently modern client can insert into any repository.
4471
 
        # The StreamSink code expects to be able to
4472
 
        # convert on the target, so we need to put bytes-on-the-wire that can
4473
 
        # be converted.  That means inventory deltas (if the remote is <1.19,
4474
 
        # RemoteStreamSink will fallback to VFS to insert the deltas).
4475
 
        yield ('inventory-deltas',
4476
 
           self._stream_invs_as_deltas(revision_ids,
4477
 
                                       delta_versus_null=delta_versus_null))
4478
 
 
4479
 
    def _stream_invs_as_deltas(self, revision_ids, delta_versus_null=False):
4480
 
        """Return a stream of inventory-deltas for the given rev ids.
4481
 
 
4482
 
        :param revision_ids: The list of inventories to transmit
4483
 
        :param delta_versus_null: Don't try to find a minimal delta for this
4484
 
            entry, instead compute the delta versus the NULL_REVISION. This
4485
 
            effectively streams a complete inventory. Used for stuff like
4486
 
            filling in missing parents, etc.
4487
 
        """
4488
 
        from_repo = self.from_repository
4489
 
        revision_keys = [(rev_id,) for rev_id in revision_ids]
4490
 
        parent_map = from_repo.inventories.get_parent_map(revision_keys)
4491
 
        # XXX: possibly repos could implement a more efficient iter_inv_deltas
4492
 
        # method...
4493
 
        inventories = self.from_repository.iter_inventories(
4494
 
            revision_ids, 'topological')
4495
 
        format = from_repo._format
4496
 
        invs_sent_so_far = set([_mod_revision.NULL_REVISION])
4497
 
        inventory_cache = lru_cache.LRUCache(50)
4498
 
        null_inventory = from_repo.revision_tree(
4499
 
            _mod_revision.NULL_REVISION).inventory
4500
 
        # XXX: ideally the rich-root/tree-refs flags would be per-revision, not
4501
 
        # per-repo (e.g.  streaming a non-rich-root revision out of a rich-root
4502
 
        # repo back into a non-rich-root repo ought to be allowed)
4503
 
        serializer = inventory_delta.InventoryDeltaSerializer(
4504
 
            versioned_root=format.rich_root_data,
4505
 
            tree_references=format.supports_tree_reference)
4506
 
        for inv in inventories:
4507
 
            key = (inv.revision_id,)
4508
 
            parent_keys = parent_map.get(key, ())
4509
 
            delta = None
4510
 
            if not delta_versus_null and parent_keys:
4511
 
                # The caller did not ask for complete inventories and we have
4512
 
                # some parents that we can delta against.  Make a delta against
4513
 
                # each parent so that we can find the smallest.
4514
 
                parent_ids = [parent_key[0] for parent_key in parent_keys]
4515
 
                for parent_id in parent_ids:
4516
 
                    if parent_id not in invs_sent_so_far:
4517
 
                        # We don't know that the remote side has this basis, so
4518
 
                        # we can't use it.
4519
 
                        continue
4520
 
                    if parent_id == _mod_revision.NULL_REVISION:
4521
 
                        parent_inv = null_inventory
4522
 
                    else:
4523
 
                        parent_inv = inventory_cache.get(parent_id, None)
4524
 
                        if parent_inv is None:
4525
 
                            parent_inv = from_repo.get_inventory(parent_id)
4526
 
                    candidate_delta = inv._make_delta(parent_inv)
4527
 
                    if (delta is None or
4528
 
                        len(delta) > len(candidate_delta)):
4529
 
                        delta = candidate_delta
4530
 
                        basis_id = parent_id
4531
 
            if delta is None:
4532
 
                # Either none of the parents ended up being suitable, or we
4533
 
                # were asked to delta against NULL
4534
 
                basis_id = _mod_revision.NULL_REVISION
4535
 
                delta = inv._make_delta(null_inventory)
4536
 
            invs_sent_so_far.add(inv.revision_id)
4537
 
            inventory_cache[inv.revision_id] = inv
4538
 
            delta_serialized = ''.join(
4539
 
                serializer.delta_to_lines(basis_id, key[-1], delta))
4540
 
            yield versionedfile.FulltextContentFactory(
4541
 
                key, parent_keys, None, delta_serialized)
4542
 
 
4543
 
 
4544
1847
def _iter_for_revno(repo, partial_history_cache, stop_index=None,
4545
1848
                    stop_revision=None):
4546
1849
    """Extend the partial history to include a given index
4556
1859
        it is encountered, history extension will stop.
4557
1860
    """
4558
1861
    start_revision = partial_history_cache[-1]
4559
 
    iterator = repo.iter_reverse_revision_history(start_revision)
 
1862
    graph = repo.get_graph()
 
1863
    iterator = graph.iter_lefthand_ancestry(start_revision,
 
1864
        (_mod_revision.NULL_REVISION,))
4560
1865
    try:
4561
 
        #skip the last revision in the list
 
1866
        # skip the last revision in the list
4562
1867
        iterator.next()
4563
1868
        while True:
4564
1869
            if (stop_index is not None and
4572
1877
        # No more history
4573
1878
        return
4574
1879
 
 
1880
 
 
1881
class _LazyListJoin(object):
 
1882
    """An iterable yielding the contents of many lists as one list.
 
1883
 
 
1884
    Each iterator made from this will reflect the current contents of the lists
 
1885
    at the time the iterator is made.
 
1886
    
 
1887
    This is used by Repository's _make_parents_provider implementation so that
 
1888
    it is safe to do::
 
1889
 
 
1890
      pp = repo._make_parents_provider()      # uses a list of fallback repos
 
1891
      pp.add_fallback_repository(other_repo)  # appends to that list
 
1892
      result = pp.get_parent_map(...)
 
1893
      # The result will include revs from other_repo
 
1894
    """
 
1895
 
 
1896
    def __init__(self, *list_parts):
 
1897
        self.list_parts = list_parts
 
1898
 
 
1899
    def __iter__(self):
 
1900
        full_list = []
 
1901
        for list_part in self.list_parts:
 
1902
            full_list.extend(list_part)
 
1903
        return iter(full_list)